text
stringlengths
8
6.88M
#include "Actor.h" #include "StudentWorld.h" // Students: Add code to this file (if you wish), Actor.h, StudentWorld.h, and StudentWorld.cpp /**************************** Actor Implementation *****************************/ Actor:: Actor(int imageID, int startX, int startY,StudentWorld* world, Direction dir, double size,unsigned int depth) :GraphObject(imageID, startX, startY, dir, size, depth),m_world(world),m_alive(true),m_ID(imageID){ setVisible(true); } Actor::~Actor(){ setVisible(false); } bool Actor::isAlive(){ return m_alive; } void Actor::setDead(){ m_alive=false; } StudentWorld* Actor::getWorld() const { return m_world; } unsigned int Actor::getID() const { return m_ID; } void Actor::playSound(int soundID){ m_world->playSound(soundID); }; Actor::Direction Actor::randDir(){ Direction dir[4]={ up, down, left, right }; return dir[rand()%4]; } void Actor::moveInDir(Direction dir){ switch (dir) { case left: if (getX()-1>=0&&!getWorld()->dirtThere(getX()-1, getY())&&!getWorld()->actorThere(getX()-1,getY(),IID_BOULDER)) { moveTo(getX()-1, getY()); // move one square to the left } break; case right: if (getX()+1<=60&&!getWorld()->dirtThere(getX()+1, getY())&&!getWorld()->actorThere(getX()+1,getY(),IID_BOULDER)) { moveTo(getX()+1, getY()); // move one square to the right } break; case up: if (getY()+1<=60&&!getWorld()->dirtThere(getX(), getY()+1)&&!getWorld()->actorThere(getX(),getY()+1,IID_BOULDER)) { moveTo(getX(), getY()+1); // move one square to the up } break; case down: if (getY()-1>=0&&!getWorld()->dirtThere(getX(), getY()-1)&&!getWorld()->actorThere(getX(),getY()-1,IID_BOULDER)) { moveTo(getX(), getY()-1); // move one square to the down } break; default:break; } } bool Actor::canMoveInDir(Direction dir){ switch (dir) { case left: if (getX()-1>=0&&!getWorld()->dirtThere(getX()-1, getY())&&!getWorld()->actorThere(getX()-1,getY(),IID_BOULDER)) {// can move one square to the left return true; } break; case right: if (getX()+1<=60&&!getWorld()->dirtThere(getX()+1, getY())&&!getWorld()->actorThere(getX()+1,getY(),IID_BOULDER)) { // can move one square to the right return true; } break; case up: if (getY()+1<=60&&!getWorld()->dirtThere(getX(), getY()+1)&&!getWorld()->actorThere(getX(),getY()+1,IID_BOULDER)) {// can move one square to the up return true; } break; case down: if (getY()-1>=0&&!getWorld()->dirtThere(getX(), getY()-1)&&!getWorld()->actorThere(getX(),getY()-1,IID_BOULDER)) {// can move one square to the down return true; } break; default:break; } return false; } bool Actor::isAtIntersection(Direction dir){ switch (dir) { case left: case right: if (getY()+1<=60&&!getWorld()->dirtThere(getX(), getY()+1)&&!getWorld()->actorThere(getX(),getY()+1,IID_BOULDER)) //can move one square to the up return true; if (getY()-1>=0&&!getWorld()->dirtThere(getX(), getY()-1)&&!getWorld()->actorThere(getX(),getY()-1,IID_BOULDER)) // can move one square to the down return true; break; case up: case down: if (getX()-1>=0&&!getWorld()->dirtThere(getX()-1, getY())&&!getWorld()->actorThere(getX()-1,getY(),IID_BOULDER)) // can move one square to the left return true; if (getX()+1<=60&&!getWorld()->dirtThere(getX()+1, getY())&&!getWorld()->actorThere(getX()+1,getY(),IID_BOULDER)) // can move one square to the right return true; break; default:break; } return false; } Actor::Direction Actor::pickViablePerpendicularDir(Direction dir){ bool l=false, r=false, u=false, d=false; Direction d1[2]={ up, down }; Direction d2[2]={ left, right }; switch (dir) { case left: case right: if (getY()+1<=60&&!getWorld()->dirtThere(getX(), getY()+1)&&!getWorld()->actorThere(getX(),getY()+1,IID_BOULDER)) //can move one square to the up u=true; if (getY()-1>=0&&!getWorld()->dirtThere(getX(), getY()-1)&&!getWorld()->actorThere(getX(),getY()-1,IID_BOULDER)) // can move one square to the down d=true; break; case up: case down: if (getX()-1>=0&&!getWorld()->dirtThere(getX()-1, getY())&&!getWorld()->actorThere(getX()-1,getY(),IID_BOULDER)) // can move one square to the left l=true; if (getX()+1<=60&&!getWorld()->dirtThere(getX()+1, getY())&&!getWorld()->actorThere(getX()+1,getY(),IID_BOULDER)) // can move one square to the right r=true; break; default:break; } if(u&&d) return d1[rand()%2]; else if(u) return up; else if(d) return down; if(l&&r) return d2[rand()%2]; else if(l) return left; else if(r) return right; return none; } /**************************** Dirt Implementation *****************************/ Dirt::Dirt(int X, int Y, StudentWorld* world): Actor(IID_DIRT, X, Y, world,right,0.25,3){ } Dirt:: ~Dirt(){ } /**************************** Frackman Implementation *****************************/ FrackMan::FrackMan(StudentWorld* world): Actor(IID_PLAYER, 30, 60, world,right,1.0,0){ hit_points=10; water_units=5; sonar_charge=1; gold_nuggets=0; } FrackMan:: ~FrackMan(){ } int FrackMan::getHealth(){ float health=hit_points/10.0*100; return health; } int FrackMan::getWaterUnits(){ return water_units; } int FrackMan::getSonarCharge(){ return sonar_charge; } int FrackMan::getGoldNuggets(){ return gold_nuggets; } void FrackMan::incGold(){ gold_nuggets++; } void FrackMan::incSonar(){ sonar_charge+=2; } void FrackMan::incWater(){ water_units+=5; } void FrackMan::getAnnoyed(int points){ hit_points=hit_points-points; if (hit_points<=0) { setDead(); getWorld()->decLives(); } } void FrackMan::doSomething(){ int ch; if (!isAlive()) return; if (getWorld()->getKey(ch) == true) { // user hit a key this tick! switch (ch) { case KEY_PRESS_LEFT: if(getDirection()!=left) setDirection(left); else{ if (getX()-1>=0&&!getWorld()->actorThere(getX()-1,getY(),IID_BOULDER)) { moveTo(getX()-1, getY()); // move one square to the left if(getWorld()->dirtThere(getX(), getY())){ getWorld()->deleteDirt(getX(), getY()); playSound(SOUND_DIG); } } } break; case KEY_PRESS_RIGHT: if(getDirection()!=right) setDirection(right); else{ if (getX()+1<=60&&!getWorld()->actorThere(getX()+1,getY(),IID_BOULDER)) { moveTo(getX()+1, getY()); // move one square to the right if(getWorld()->dirtThere(getX()+3, getY())){ getWorld()->deleteDirt(getX()+3, getY()); playSound(SOUND_DIG); } } } break; case KEY_PRESS_UP: if(getDirection()!=up) setDirection(up); else{ if (getY()+1<=60&&!getWorld()->actorThere(getX(),getY()+1,IID_BOULDER)) { moveTo(getX(), getY()+1); // move one square to the up if(getWorld()->dirtThere(getX(), getY()+3)){ getWorld()->deleteDirt(getX(), getY()+3); playSound(SOUND_DIG); } } } break; case KEY_PRESS_DOWN: if(getDirection()!=down) setDirection(down); else{ if (getY()-1>=0&&!getWorld()->actorThere(getX(),getY()-1,IID_BOULDER)) { moveTo(getX(), getY()-1); // move one square to the down if(getWorld()->dirtThere(getX(), getY())){ getWorld()->deleteDirt(getX(), getY()); playSound(SOUND_DIG); } } } break; case KEY_PRESS_SPACE: if(water_units>0){ switch (getDirection()) { case right: getWorld()->addSquirt(getX() + 4, getY(), right); break; case left: getWorld()->addSquirt(getX() - 4, getY(), left); break; case up: getWorld()->addSquirt(getX(), getY() + 4, up); break; case down: getWorld()->addSquirt(getX(), getY() - 4, down); break; default:break; } getWorld()->playSound(SOUND_PLAYER_SQUIRT); water_units--; } break; case KEY_PRESS_TAB: if(gold_nuggets>0){ getWorld()->addTempGold(getX(), getY()); gold_nuggets--; } break; case 'Z': case 'z': if (sonar_charge > 0) { sonar_charge--; getWorld()->useSonar(getX(), getY()); getWorld()->playSound(SOUND_SONAR); } break; case KEY_PRESS_ESCAPE: setDead(); break; } } } /**************************** Boulders Implementation *****************************/ Boulders::Boulders(int X, int Y, StudentWorld* world): Actor(IID_BOULDER, X, Y, world,down,1.0,1){ wait_time=30; is_falling = true; } Boulders:: ~Boulders(){ } void Boulders::doSomething(){ if (!isAlive()) return; if(getWorld()->dirtBelow(getX(), getY())) return; wait_time--; if(wait_time<=0){ if(is_falling){ playSound(SOUND_FALLING_ROCK); is_falling=false; } if (getWorld()->boulderCollision(getX(), getY()-1)){ setDead(); //set the boulder to dead return; } else moveTo(getX(), getY()-1); // move one square down getWorld()->boulderAnnoyActor(getX(), getY()); } } /**************************** Squirt Implementation *****************************/ Squirt::Squirt(int X, int Y, StudentWorld* world, Direction dir): Actor(IID_WATER_SPURT, X, Y, world,dir,1.0,1){ travel_distance=4; } Squirt::~Squirt(){ } void Squirt::doSomething(){ if(!isAlive()) return; if(travel_distance>0){ switch (getDirection()) { case GraphObject::left: if (getX()-1>=0&&!getWorld()->dirtThere(getX()-1, getY())&&!getWorld()->actorThere(getX()-1, getY(), IID_BOULDER)) { moveTo(getX()-1, getY()); // move one square to the left travel_distance--; }else setDead(); break; case GraphObject::right: if (getX()+1<=60&&!getWorld()->dirtThere(getX()+1, getY())&&!getWorld()->actorThere(getX()+1, getY(), IID_BOULDER)) { moveTo(getX()+1, getY()); // move one square to the right travel_distance--; }else setDead(); break; case GraphObject::up: if (getY()+1<=60&&!getWorld()->dirtThere(getX(), getY()+1)&&!getWorld()->actorThere(getX(), getY()+1, IID_BOULDER)) { moveTo(getX(), getY()+1); // move one square to the up travel_distance--; }else setDead(); break; case GraphObject::down: if (getY()-1>=0&&!getWorld()->dirtThere(getX(), getY()-1)&&!getWorld()->actorThere(getX(), getY()-1, IID_BOULDER)) { moveTo(getX(), getY()-1); // move one square to the down travel_distance--; }else setDead(); break; default:break; } }else { getWorld()->attackProtester(getX(), getY()); setDead(); } return; } /**************************** Barrel of Oil Implementation *****************************/ BarrelsOfOil::BarrelsOfOil(int X, int Y, StudentWorld* world):Actor(IID_BARREL, X, Y, world,right,1.0,2){ setVisible(false); } BarrelsOfOil::~BarrelsOfOil(){ } void BarrelsOfOil::doSomething(){ if(!isAlive()) return; if(!isVisible()&&getWorld()->frackmanThere(getX(), getY(),4)){ setVisible(true); return; } if(getWorld()->frackmanThere(getX(), getY(),3)){ setDead(); playSound(SOUND_FOUND_OIL); getWorld()->increaseScore(1000); getWorld()->decreaseOil(); } } /**************************** Gold Nuggets Implementation *****************************/ GoldNuggets::GoldNuggets(int X, int Y, StudentWorld* world, bool permanent):Actor(IID_GOLD, X, Y, world,right,1.0,2){ life_time=100; is_permanent=permanent; if (is_permanent) setVisible(false); else setVisible(true); } GoldNuggets::~GoldNuggets(){ } void GoldNuggets::doSomething(){ if(!isAlive()) return; if(is_permanent){ if(!isVisible()&&getWorld()->frackmanThere(getX(), getY(),4)){ setVisible(true); return; } if(getWorld()->frackmanThere(getX(), getY(),3)){ setDead(); playSound(SOUND_GOT_GOODIE); getWorld()->increaseScore(10); getWorld()->increaseGold(); } } else{ if (life_time>0) { if(getWorld()->pickUpGold(getX(),getY())) setDead(); life_time--; }else setDead(); } } /**************************** Sonar Kit Implementation *****************************/ SonarKit::SonarKit(StudentWorld* world):Actor(IID_SONAR, 0, 60, world,right,1.0,2){ life_time=100>(300-10*getWorld()->getLevel())?100:300-10*getWorld()->getLevel(); } SonarKit::~SonarKit(){ } void SonarKit::doSomething(){ if(!isAlive()) return; if (life_time>0) { if(getWorld()->frackmanThere(getX(), getY(),3)){ setDead(); playSound(SOUND_GOT_GOODIE); getWorld()->increaseSonar(); getWorld()->increaseScore(75); } life_time--; }else setDead(); } /**************************** Water Pool Implementation *****************************/ WaterPool::WaterPool(int X, int Y, StudentWorld* world):Actor(IID_WATER_POOL, X, Y, world,right,1.0,2){ life_time=100>(300-10*getWorld()->getLevel())?100:300-10*getWorld()->getLevel(); } WaterPool::~WaterPool(){ } void WaterPool::doSomething(){ if(!isAlive()) return; if (life_time>0) { if(getWorld()->frackmanThere(getX(), getY(),3)){ setDead(); playSound(SOUND_GOT_GOODIE); getWorld()->increaseWater(); getWorld()->increaseScore(100); } life_time--; }else setDead(); } /**************************** Regular Protester Implementation *****************************/ RegularProtester::RegularProtester(int IID,StudentWorld* world): Actor(IID, 60, 60, world,left,1.0,0){ if (IID==IID_PROTESTER) { hit_points=5; }else if (IID==IID_HARD_CORE_PROTESTER) { hit_points=20; } leaveOilField=false; ticksToWaitBetweenMoves = 0>int(3-getWorld()->getLevel()/4)? 0:int(3-getWorld()->getLevel()/4); ticksToWaitBetweenShouts = 15; ticksToMakePerpendicularTurn= 200; ticksToBeFreezed=0; calLeavePath=false; numSquaresToMoveInCurrentDirection=getWorld()->randInt(8, 60); } RegularProtester:: ~RegularProtester(){ } void RegularProtester::doSomething(){ if(ticksToBeFreezed<=0) { if(ticksToWaitBetweenMoves<0) { if(!isAlive()) return; if(leaveOilField) { if(getX()==60&&getY()==60) { setDead(); return; }else { if(!calLeavePath) { leavepath = getWorld()->calLeavePath(getX(), getY()); calLeavePath=true; } if(leavepath.size()>0) { vector<Coord>::reverse_iterator rp=leavepath.rbegin(); int nx=(*rp).c(); int ny=(*rp).r(); if(getX()==nx) { if(getY()<ny) { setDirection(up); }else { setDirection(down); } } if(getY()==ny) { if(getX()<nx) { setDirection(right); }else { setDirection(left); } } moveTo(nx, ny); leavepath.pop_back(); setTicksToWait(); return; } } }else { if(getWorld()->frackmanThere(getX(), getY(), 4)) //&&getDirection()==getWorld()->directionToFrackMan(getX(), getY())) { if(ticksToWaitBetweenShouts<0) { playSound(SOUND_PROTESTER_YELL); getWorld()->annoyFrackman(2); ticksToWaitBetweenShouts=15; setTicksToWait(); return; }else ticksToWaitBetweenShouts--; } if(trackFrackman()) return; if(getWorld()->lineOfSightToFrackMan(getX(), getY())&&!getWorld()->frackmanThere(getX(), getY(), 4)) { setDirection(getWorld()->directionToFrackMan(getX(), getY())); moveInDir(getDirection()); numSquaresToMoveInCurrentDirection=0; setTicksToWait(); return; } if(numSquaresToMoveInCurrentDirection<=0) { if(!getWorld()->lineOfSightToFrackMan(getX(), getY())) { setDirection(randDir()); while (!canMoveInDir(getDirection())) setDirection(randDir()); numSquaresToMoveInCurrentDirection=getWorld()->randInt(8, 60); } } if(ticksToMakePerpendicularTurn<=0&&isAtIntersection(getDirection())) { setDirection(pickViablePerpendicularDir(getDirection())); ticksToMakePerpendicularTurn=200; numSquaresToMoveInCurrentDirection=getWorld()->randInt(8, 60); }else ticksToMakePerpendicularTurn--; if (canMoveInDir(getDirection())) { moveInDir(getDirection()); numSquaresToMoveInCurrentDirection--; }else numSquaresToMoveInCurrentDirection=0; } setTicksToWait(); }else ticksToWaitBetweenMoves--; }else ticksToBeFreezed--; } void RegularProtester::getAnnoyed(int points){ hit_points=hit_points-points; if (hit_points>0) { getWorld()->playSound(SOUND_PROTESTER_ANNOYED); getFreezed(); }else { leaveOilField=true; getWorld()->playSound(SOUND_PROTESTER_GIVE_UP); ticksToWaitBetweenMoves=-1; } } void RegularProtester::pickUpGold(){ leaveOilField=true; getWorld()->playSound(SOUND_PROTESTER_FOUND_GOLD); getWorld()->increaseScore(25); } bool RegularProtester::trackFrackman(){ return false; } void RegularProtester::getFreezed(){ ticksToBeFreezed = 50>(100-getWorld()->getLevel() * 10)?50:100-getWorld()->getLevel() * 10; } void RegularProtester::setTicksToWait(){ ticksToWaitBetweenMoves = 0>int(3-getWorld()->getLevel()/4)? 0:int(3-getWorld()->getLevel()/4); } /**************************** Hardcore Protester Implementation *****************************/ HardcoreProtester::HardcoreProtester(int IID,StudentWorld* world): RegularProtester(IID,world){ } HardcoreProtester:: ~HardcoreProtester(){ } void HardcoreProtester::pickUpGold(){ getFreezed(); getWorld()->playSound(SOUND_PROTESTER_FOUND_GOLD); getWorld()->increaseScore(50); } bool HardcoreProtester::trackFrackman(){ int M = 16 + getWorld()->getLevel() * 2; if(!getWorld()->frackmanThere(getX(), getY(), 4)&&getWorld()->senseFrackman(getX(), getY(), M)) { Coord trackpath = getWorld()->calTrackPath(getX(), getY()); int nx=trackpath.c(); int ny=trackpath.r(); if(getX()==nx) { if(getY()<ny) { setDirection(up); }else { setDirection(down); } } if(getY()==ny) { if(getX()<nx) { setDirection(right); }else { setDirection(left); } } moveTo(nx, ny); setTicksToWait(); return true; } return false; }
/* Copyright 2017 Istio Authors. 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. */ #include "service_context.h" #include "include/istio/utils/attribute_names.h" #include "src/istio/control/http/attributes_builder.h" using ::istio::mixer::v1::Attributes; using ::istio::mixer::v1::config::client::ServiceConfig; namespace istio { namespace control { namespace http { ServiceContext::ServiceContext(std::shared_ptr<ClientContext> client_context, const ServiceConfig *config) : client_context_(client_context) { if (config) { service_config_.reset(new ServiceConfig(*config)); } BuildParsers(); } void ServiceContext::BuildParsers() { if (!service_config_) { return; } // Build quota parser for (const auto &quota : service_config_->quota_spec()) { quota_parsers_.push_back( ::istio::quota_config::ConfigParser::Create(quota)); } } // Add static mixer attributes. void ServiceContext::AddStaticAttributes( ::istio::mixer::v1::Attributes *attributes) const { client_context_->AddLocalNodeAttributes(attributes); if (client_context_->config().has_mixer_attributes()) { attributes->MergeFrom(client_context_->config().mixer_attributes()); } if (service_config_ && service_config_->has_mixer_attributes()) { attributes->MergeFrom(service_config_->mixer_attributes()); } } // Inject a header that contains the static forwarded attributes. void ServiceContext::InjectForwardedAttributes( HeaderUpdate *header_update) const { Attributes attributes; client_context_->AddLocalNodeForwardAttribues(&attributes); if (client_context_->config().has_forward_attributes()) { attributes.MergeFrom(client_context_->config().forward_attributes()); } if (service_config_ && service_config_->has_forward_attributes()) { attributes.MergeFrom(service_config_->forward_attributes()); } if (!attributes.attributes().empty()) { AttributesBuilder::ForwardAttributes(attributes, header_update); } } // Add quota requirements from quota configs. void ServiceContext::AddQuotas( ::istio::mixer::v1::Attributes *attributes, std::vector<::istio::quota_config::Requirement> &quotas) const { for (const auto &parser : quota_parsers_) { parser->GetRequirements(*attributes, &quotas); } } } // namespace http } // namespace control } // namespace istio
# include <stdio.h> # define WEIGHT_A 3.5 # define WEIGHT_B 7.5 int main() { double A, B, avg; scanf("%lf", &A); scanf("%lf", &B); avg = (A * WEIGHT_A + B * WEIGHT_B) / (WEIGHT_A + WEIGHT_B); printf("MEDIA = %.5lf\n", avg); return 0; }
//========================================================================== // LOGBUFFER.H - part of // // OMNeT++/OMNEST // Discrete System Simulation in C++ // //========================================================================== /*--------------------------------------------------------------* Copyright (C) 1992-2008 Andras Varga Copyright (C) 2006-2008 OpenSim Ltd. This file is distributed WITHOUT ANY WARRANTY. See the file `license' for details on this and other legal matters. *--------------------------------------------------------------*/ #ifndef __LOGBUFFER_H #define __LOGBUFFER_H #include <string> #include <list> #include <vector> #include <set> #include "simtime_t.h" #include "tkutil.h" #include "circularbuffer.h" NAMESPACE_BEGIN class cModule; class LogBuffer; class ILogBufferListener { public: virtual ~ILogBufferListener() {} virtual void logEntryAdded() = 0; virtual void logLineAdded() = 0; virtual void messageSendAdded() = 0; }; /** * Stores textual debug output from modules. */ class TKENV_API LogBuffer { public: struct Line { int contextComponentId; const char *prefix; // Tcl quoted const char *line; // including newline; Tcl quoted Line(int contextComponentId, const char *prefix, const char *line) : contextComponentId(contextComponentId), prefix(prefix), line(line) {} }; struct MessageSend { cMessage *msg; std::vector<int> hopModuleIds; //TODO also: txStartTime, propagationDelay, duration for each hop }; struct Entry { eventnumber_t eventNumber; // 0 for initialization, >0 afterwards simtime_t simtime; int moduleId; // 0 for info log lines, -1 for channels (TODO only until 5.0) //TODO msg name, class, kind, previousEventNumber const char *banner; std::vector<Line> lines; std::vector<MessageSend> msgs; Entry() {eventNumber=0; simtime=0; moduleId=0; banner=NULL;} ~Entry(); }; protected: std::vector<ILogBufferListener*> listeners; circular_buffer<Entry*> entries; int maxNumEntries; int entriesDiscarded; protected: void discardEventsIfLimitExceeded(); void fillEntry(Entry *entry, eventnumber_t e, simtime_t t, cModule *mod, const char *banner); public: LogBuffer(); ~LogBuffer(); void addListener(ILogBufferListener *l); void removeListener(ILogBufferListener *l); void addInitialize(cComponent *component, const char *banner); void addEvent(eventnumber_t e, simtime_t t, cModule *moduleIds, const char *banner); void addLogLine(const char *prefix, const char *text); void addLogLine(const char *prefix, const char *text, int len); void addInfo(const char *text); void addInfo(const char *text, int len); void beginSend(cMessage *msg); void messageSendDirect(cMessage *msg, cGate *toGate, simtime_t propagationDelay, simtime_t transmissionDelay); void messageSendHop(cMessage *msg, cGate *srcGate); void messageSendHop(cMessage *msg, cGate *srcGate, simtime_t propagationDelay, simtime_t transmissionDelay); void endSend(cMessage *msg); void setMaxNumEntries(int limit); // when exceeded, oldest entries are discarded int getMaxNumEntries() {return maxNumEntries;} const circular_buffer<Entry*>& getEntries() const {return entries;} int getNumEntries() const {return entries.size();} int getNumEntriesDiscarded() const {return entriesDiscarded;} int findEntryByEventNumber(eventnumber_t eventNumber); Entry *getEntryByEventNumber(eventnumber_t eventNumber); void clear(); void dump() const; }; NAMESPACE_END #endif
// This file has been generated by Py++. #ifndef WindowFactoryManager_hpp__pyplusplus_wrapper #define WindowFactoryManager_hpp__pyplusplus_wrapper void register_WindowFactoryManager_class(); #endif//WindowFactoryManager_hpp__pyplusplus_wrapper
#include "sensor.h" using namespace std; void interrupt() { cout<< "l'interruption a eu lieu\n"; } PI_THREAD (myThread) { while (1) { wiringPiISR(3, INT_EDGE_RISING, interrupt); waitForInterrupt(3, -1); cout <<"allumé\n"; wiringPiISR(3, INT_EDGE_FALLING, interrupt); waitForInterrupt(3, -1); cout <<"éteind\n"; } } int main() { if (wiringPiSetup() == -1) { cout << "erreur\n"; return 0; } Led led(0,"PWM_OUTPUT"); TouchSensor touchSensor(3); led.lightOn(1000); /*int x = piThreadCreate(myThread); if (x != 0) cout << "problem\n"; else cout << "thread thrown\n";*/ delay(300); /* int i(0); while (1) { if (touchSensor.getGpioValue() == 1 && i ==0) { led.lightOn(); i=1; } else if (touchSensor.getGpioValue() == 0 && i==1) { led.lightOff(); i=0; } }*/ return 0; }
#include <string> #include "Bank.hpp" /************************************************ ** Member function definitions ************************************************/ // PLEASE ADD IMPLEMENTATIONS OF ALL FUNCTION MEMBERS OF CLASS BANK Bank::Bank( const std::string & name, const double & starting, const double & salary) : name_(name), amount_starting_(starting), amount_salary_(salary) {}
/** * Utility for converting a binary on/off image to * a signed distance field image. */ #ifndef FISHY_DISTANCE_FIELD_H #define FISHY_DISTANCE_FIELD_H #include <CORE/types.h> #include <vector> /** * Conversion utility for computing the signed distance field * representation of an input black and white image. */ class DistanceGrid { public: /** * Initialize a grid converter for a fixed image size and * distance scaling factor. * * @param sx horizontal width * @param sy vertical height * @param scale distance scaling factor */ DistanceGrid(const u32 sx, const u32 sy, const f32 scale); /** * Perform a conversion * * @param pImageDataIn the input black-and-white image * @param pImageDataOut teh output greyscale image with 128 as the midpoint * color. */ void convertToSdf(const u8 *pImageDataIn, u8 *pImageDataOut); private: struct DistancePoint { f32 m_dx; f32 m_dy; DistancePoint() : m_dx(0.0f), m_dy(0.0f) {} DistancePoint(f32 dx, f32 dy) : m_dx(dx), m_dy(dy) {} f32 dist() const { return m_dx * m_dx + m_dy * m_dy; } }; s32 m_szx; s32 m_szy; f32 m_scale; std::vector< DistancePoint > m_gridInside; std::vector< DistancePoint > m_gridOutside; void fromRgba(const u8 *pImageData); void toRgba(u8 *pImageData); void computeSdf(std::vector< DistancePoint > &); int index(int x, int y) const; DistancePoint compare( const std::vector< DistancePoint > &, const DistancePoint &p, int x, int y) const; }; #endif
/* * Wrapper class for eureqa::server_info * * Created on: Nov 21, 2010 * Author: MF */ #ifndef SERVERINFO_H_ #define SERVERINFO_H_ #include <eureqa/server_info.h> class ServerInfo { private: eureqa::server_info instance; public: // Wrapper for default constructor ServerInfo() {} // Constructor taking eureqa::server_info as the parameter (C++ usage) ServerInfo(const eureqa::server_info& instance) {this->instance = instance;} // Getter for the eureqa::server_info's instance (C++ usage) const eureqa::server_info& GetInstance() {return instance;} // Wrapper for function testing if info is entered and in range bool IsValid() {return instance.is_valid();} // Wrapper for function returning a short text summary of the server info std::string Summary() {return instance.summary();} // Getters and setters for eureqa::server_info's public members int GetCpuCores() const {return instance.cpu_cores_;} void SetCpuCores(int cpu_cores) {instance.cpu_cores_ = cpu_cores;} double GetEureqaVersion() const {return instance.eureqa_version_;} void SetEureqaVersion(double eureqa_version) {instance.eureqa_version_ = eureqa_version;} std::string GetHostname() const {return instance.hostname_;} void SetHostname(std::string hostname) {instance.hostname_ = hostname;} std::string GetOperatingSystem() const {return instance.operating_system_;} void SetOperatingSystem(std::string operating_system) {instance.operating_system_ = operating_system;} }; #endif /* SERVERINFO_H_ */
#include "mainwindow.h" #include "ui_mainwindow.h" #include "basicheaders.h" void MainWindow::setUpUI() { qDebug() << "UI set up started" << endl; // creates actual widget instances // from QtDesigner ui->setupUi(this); // working zone - main widget QWidget *canvas = new QWidget; QVBoxLayout *layout = new QVBoxLayout; canvas->setLayout(layout); // sets the stretch factor at position index // and aligning of main widget layout->setStretch(1, 2); layout->setAlignment(Qt::AlignCenter); // set main widget of window canvas->setStyleSheet("QWidget { background: white; }"); setCentralWidget(canvas); // set up table of values and conditions QGridLayout *valuesInfoLayout = new QGridLayout(); isBstTree->setStyleSheet("color: black;"); labelIsBsdTree->setStyleSheet("color: black;"); isBinHeap->setStyleSheet("color: black;"); labelIsBinHeap->setStyleSheet("color: black;"); maxNode->setStyleSheet("color: black;"); labelMaxNode->setStyleSheet("color: black;"); minNode->setStyleSheet("color: black;"); labelMinNode->setStyleSheet("color: black;"); valuesInfoLayout->addWidget(labelIsBsdTree, 0, 0, Qt::AlignLeft); valuesInfoLayout->addWidget(isBstTree, 0, 1, Qt::AlignHCenter); valuesInfoLayout->addWidget(labelIsBinHeap, 1, 0, Qt::AlignLeft); valuesInfoLayout->addWidget(isBinHeap, 1, 1, Qt::AlignHCenter); valuesInfoLayout->addWidget(labelMaxNode, 2, 0, Qt::AlignLeft); valuesInfoLayout->addWidget(maxNode, 2, 1, Qt::AlignHCenter); valuesInfoLayout->addWidget(labelMinNode, 3, 0, Qt::AlignLeft); valuesInfoLayout->addWidget(minNode, 3, 1, Qt::AlignHCenter); labelIsBsdTree->setText("Is BST tree: "); labelIsBinHeap->setText("Is Bin Heap: "); labelMaxNode->setText("Max node: "); labelMinNode->setText("Min node: "); // default parameters isBstTree->setText("-"); isBinHeap->setText("-"); maxNode->setText("-"); minNode->setText("-"); // set up steps buttons and check switchers stepImplSwitch->setText("Step mode"); nextStep->setText("Next step"); checkBst->setText("Check BST"); checkBinHeap->setText("Check Bin heap"); QGridLayout *stepsButtonsLayout = new QGridLayout(); stepsButtonsLayout->addWidget(stepImplSwitch, 0, 0, Qt::AlignHCenter); stepsButtonsLayout->addWidget(nextStep, 1, 0, Qt::AlignCenter); stepsButtonsLayout->addWidget(checkBst, 2, 0, Qt::AlignLeft); stepsButtonsLayout->addWidget(checkBinHeap, 3, 0, Qt::AlignLeft); // setup input line inputLine->setLabel("Enter binary tree in bracket representation:"); inputLine->setTextColor(QColor::fromRgb(0, 0, 0)); inputLine->setValidator(new QRegExpValidator(QRegExp("[0-9()\\s]*"), inputLine)); // set up full buttons layout runButton->setText("Run"); fileOpen->setText("Open file"); QHBoxLayout *allButtonsLayout = new QHBoxLayout(); allButtonsLayout->addWidget(runButton); allButtonsLayout->addWidget(fileOpen); allButtonsLayout->addWidget(inputLine); allButtonsLayout->addLayout(stepsButtonsLayout); allButtonsLayout->addLayout(valuesInfoLayout); // main layout setup layout->addLayout(allButtonsLayout); layout->addWidget(mainGraphicsView); // default conditions nextStep->setDisabled(true); stepImplSwitch->setChecked(false); checkBst->setEnabled(false); checkBinHeap->setEnabled(false); _root = nullptr; /* SIGNALS AND SLOTS CONNECTIONS */ connect(stepImplSwitch, SIGNAL(toggled(bool)), this, SLOT(changeActivitiStepBut(bool))); connect(runButton, SIGNAL(clicked()), this, SLOT(onRunButtonClicked())); connect(fileOpen, SIGNAL(clicked()), this, SLOT(onFileOpenButtonClicked())); }
#include "invalidageofcarexception.h" InvalidAgeOfCarException::InvalidAgeOfCarException(string message) { this->message = message; } string InvalidAgeOfCarException::getMessage() { return this->message; }
#ifndef __TEST_FIXED_FLOAT_H__ #define __TEST_FIXED_FLOAT_H__ #include <iostream> #include <cstdlib> #include "physics.h" using namespace std; using namespace physics; class TestFixedFloat { public: static void doTest(); static void doTestSpeed(); }; #endif
// // Created by wojtekreg on 15.01.18. // #ifndef PYRAPORTFEL_KONTRAKT_H #define PYRAPORTFEL_KONTRAKT_H #include "Aktywa.h" class Kontrakt : public Aktywa{ private: int czasTrwania; void setCzasTrwania(int czasTrwania); public: Kontrakt(std::string opis, double wartosc, int czasTrwania); virtual void wyswietlInformacje() override; virtual double wartoscWMiesiacu(int miesiac) override; virtual void edytuj() override; virtual std::string serializuj() override; }; #endif //PYRAPORTFEL_KONTRAKT_H
#pragma once #include <map> #include <vector> #include "UpdateOperation.h" class DSM { public: DSM(int world_size, int process_id, std::map<char, int> variables); ~DSM(); bool available = true; void assignUpdate(char variable, int value); void updateVariable(char variable, int value); void setValue(char variable, int value); void updateSubscribers(char variable, UpdateOperation updateOperation); void xChangeValue(char variable, int old_value, int new_value); void subscribeMe(char variable); void subscribe(int other_process_id, char variable); bool isSubscribedTo(int process_id, char variable); int getValue(char variable); bool contains(char variable); void close(); int getVariableIndex(char variable); char getVariableChar(int index); private: // Number of processes / nodes running int world_size; // Process ID int process_id; //// Variables in the systems mapped to their values //int a, b, c; // Subsribers to the variables // • std::string is the string name of the variable // • int in vector are ids of the nodes std::map<char, std::vector<int>> subscribers; // Variable values std::map<char, int> variables; std::vector<char> vars; };
#include<stdio.h>//**打印函数的头文件** #include<stdlib.h> #include<time.h>//**电脑生成随机数的time函数头文件** #define ROW 3//**此处用define定义3行3列的棋盘** #define COL 3 void game(); void menu(); void InitBoard(char Board[ROW][COL],int row,int col);//**定义棋盘的函数声明** void DisplayBoard(char Board[ROW][COL],int row,int col);//**打印棋盘的函数的声明** void Computermove(char Board[ROW][COL],int row,int col);//**电脑移动的函数声明** void Playermove(char Board[ROW][COL],int row,int col);//**玩家移动的函数声明** char IsWin(char Board[ROW][COL],int row,int col);//**判断电脑或者玩家有没有获得游戏胜利的函数声明** int IsFull(char Board[ROW][COL],int row,int col);//**判断是否平局的函数声明** /*—————————————————————————————————————————— 以上我们就实现了头文件和游戏大体逻辑部分,接下来我们则要实现最重要的游戏部分,头文件中的自定义函数声明我们都将在game.c中一一实现。 —————————————————————————————————————————————— 首先来看定义的第一个函数,InitBoard函数,此函数将完成我们九个格子的初始化,我们将格子全部初始化为空格:*/ //首先编写一个简单的游戏逻辑 int main() { int input; srand((unsigned int)time(NULL)); //**实现电脑生成随机数后面讲解** do { menu();//**游戏进入先打印一个菜单** scanf("%d",&input); switch(input) { case 1: game();//**实现游戏的函数** break; case 0: printf("游戏退出\n"); break; default: printf("输入有误,请重新输入\n"); break; } }while(input); return 0; } /*—————————————————————————— 以下部分放置于主函数之上即可 完成简单逻辑后我们应完成菜单的打印以及game()函数的部分:*/ void menu() { printf("******************\n"); printf("***1.游戏开始*****\n"); printf("***0.游戏退出*****\n"); printf("******************\n"); } void game()//**函数部分将在game.c部分进行进一步讲解** { char Board[ROW][COL]={0}; char ret; InitBoard(Board,ROW,COL); DisplayBoard(Board,ROW,COL); while(1) { Computermove(Board,ROW,COL); ret=IsWin(Board,ROW,COL); if(ret !=' ') break; DisplayBoard(Board,ROW,COL); Playermove(Board,ROW,COL); ret=IsWin(Board,ROW,COL); if(ret !=' ') break; DisplayBoard(Board,ROW,COL); } if(ret=='X') { printf("电脑赢\n"); } else if(ret=='0') { printf("玩家赢\n"); } else if(ret=='q') { printf("平局\n"); } DisplayBoard(Board,ROW,COL); } void InitBoard(char Board[ROW][COL],int row,int col) //**空型函数,Board[ROW][COL]接受指针,row,col为接受的形式参数** { int i=0;//**使用简单的循环语句** for(i=0; i<row; i++) { int j=0; for(j=0; j<col; j++) Board[i][j]=' '; } } /*实际上我们还可以使用更方便的memset函数: { memset(&board[0][0],' ',col*row*board[0][0]);//此处不做过多的介绍 }*/ /*—————————————————————————————— 接着打印我们的棋盘的分割线 —————————————————————————————— */ void DisplayBoard(char Board[ROW][COL],int row,int col) { int i=0; for(i=0; i<row; i++) { int j=0; for(j=0; j<col; j++) { printf(" %c ",Board[i][j]); if(j<col-1) printf("|"); } printf("\n"); if(i<row-1) { for(j=0; j<col; j++) { printf("---"); if(j<col-1) printf("|"); } printf("\n");} } } /*———————————————————————————————————— 紧接着我们就要开始完成人机对战的逻辑 ————————————————————————————————————-*/ //电脑移动 void Computermove(char Board[ROW][COL],int row,int col) { int x=0; int y=0; printf("电脑走\n"); while(1) { x=rand()%row;//**rand()即为让电脑生成随机数** y=rand()%col; if(Board[x][y]==' ') { Board[x][y]='X'; break; } } } //玩家移动 void Playermove(char Board[ROW][COL],int row,int col) { int x=0; int y=0; printf("玩家走\n");//**此处为玩家自行输入坐标完成操作** while(1) { printf("请输入坐标\n"); scanf("%d%d",&x,&y); if(x>=1&&x<=row&&y>=1&&y<=col) { if(Board[x-1][y-1]==' ') { Board[x-1][y-1]='0'; break; } else { printf("坐标被占用请重新输入\n"); } } else { printf("输入有误请重新输入\n"); } } } char IsWin(char Board[ROW][COL],int row,int col) { int i=0; for(i=0; i<row; i++) { if(Board[i][0]==Board[i][1]&&Board[i][1]==Board[i][2]&&Board[i][0]!=' ')//**行3个相连** return Board[i][0];//**只要不返回空格游戏继续** } for(i=0; i<col; i++) { if(Board[0][i]==Board[1][i]&&Board[1][i]==Board[2][i]&&Board[0][i]!=' ')//**列3个相连** return Board[0][i]; } if(Board[0][0]==Board[1][1]&&Board[1][1]==Board[2][2]&&Board[2][2]!=' ')//**对角线相连** { return Board[1][1]; } if(Board[0][2]==Board[1][1]&&Board[1][1]==Board[2][0]&&Board[2][0]!=' ') { return Board[1][1]; } if(IsFull(Board,row,col))//**这里判断是否出现平局** { return 'Q'; } return ' ';} int IsFull(char Board[ROW][COL],int row,int col) { int i=0; for(i=0; i<row; i++) { int j=0; for(j=0; j<col; j++) { if(Board[i][j]==' ') return 0; } } return 1; }
#pragma once #include "FRAlgorithm.h" #include <opencv2\nonfree\features2d.hpp> #include <opencv2/nonfree/gpu.hpp> using namespace gpu; class FRSurfGpu : public FRAlgorithm{ private: int m_minHessian; SurfFeatureDetector m_detector; SurfDescriptorExtractor m_extractor; SURF_GPU surf; public: FRSurfGpu(void); FRSurfGpu(int minHessian); ~FRSurfGpu(void); void setMinHessian(int minHessian); int getMinHessian(); virtual ImageFeatures* detect(GpuMat* img); };
#ifndef CELLO_SEQUENCE_MANAGER #define CELLO_SEQUENCE_MANAGER #include <vector> #include <util/ActionSequence.h> using std::vector; namespace cello { class SequenceManager { public: ~SequenceManager() { for (ActionSequence* sequence : _sequences) { delete sequence; } for (ActionSequence* sequence : _sequencesToBeAdded) { delete sequence; } } void addSequence(ActionSequence* sequence) { // We add new sequences to a temporary queue rather than directly into the list of sequences. // This is to avoid iterator corruption due to adding new sequences while iterating through // the current ones. This can happen when methods are executed as part of a sequence which // add a new sequence _sequencesToBeAdded.push_back(sequence); } void update(float elapsedTime) { _sequences.insert(_sequences.end(), _sequencesToBeAdded.begin(), _sequencesToBeAdded.end()); _sequencesToBeAdded.clear(); for (auto it = _sequences.begin(); it != _sequences.end(); ) { ActionSequence* sequence = *it; sequence->update(elapsedTime); if (sequence->isFinished()) { it = _sequences.erase(it); delete sequence; } else { ++it; } } } private: vector <ActionSequence*> _sequencesToBeAdded; vector <ActionSequence*> _sequences; }; } #endif
// // Created by wqy on 19-11-17. // #ifndef VERIFIER_BEAGLETRANSLATOR_H #define VERIFIER_BEAGLETRANSLATOR_H #include "Translator.h" #include "../BeagleModel/BeagleModel.h" #include <stdio.h> #include <string> #include <vector> using std::string; using std::vector; namespace esc { class BeagleTranslator : public Translator { private: BeagleModel* beagleModel; vector<string> beagleModelFile; public: BeagleTranslator(); void generateBeagle(); void makeHeader(); void makeModules(); void makeProperties(); void generateBeagleModelFile(); void setModel(Model* _model); bool saveInFile(string path); }; } #endif //VERIFIER_BEAGLETRANSLATOR_H
#include <bits/stdc++.h> using namespace std; const int MAX_INT = std::numeric_limits<int>::max(); const int MIN_INT = std::numeric_limits<int>::min(); const int INF = 1000000000; const int NEG_INF = -1000000000; #define max(a,b)(a>b?a:b) #define min(a,b)(a<b?a:b) #define MEM(arr,val)memset(arr,val, sizeof arr) #define PI acos(0)*2.0 #define eps 1.0e-9 #define are_equal(a,b)fabs(a-b)<eps #define LS(b)(b& (-b)) // Least significant bit #define DEG_to_RAD(a)((a*PI)/180.0) // convert to radians typedef long long ll; typedef pair<int,int> ii; typedef pair<int,char> ic; typedef pair<long,char> lc; typedef vector<int> vi; typedef vector<ii> vii; int gcd(int a,int b){return b == 0 ? a : gcd(b,a%b);} int lcm(int a,int b){return a*(b/gcd(a,b));} vi dfs_num, dfs_low, dfs_parent; vector<bool> articulation_vertex; map<int, vi> adj; vii criticalEdges; int dfsNumberCounter, dfsRoot, rootChildren; void articulationPoint(int u){ dfs_low[u] = dfs_num[u] = dfsNumberCounter++; for (int j = 0; j < (int)adj[u].size(); j++){ int v = adj[u][j]; if (dfs_num[v] == 0){ dfs_parent[v] = u; if (u == dfsRoot) rootChildren++; articulationPoint(v); if (dfs_low[v] >= dfs_num[u]){ // cout << u << ", " << v << endl; articulation_vertex[u] = true; } if (dfs_low[v] > dfs_num[u]){ // cout << 2 << endl; if (u < v) criticalEdges.push_back(ii(u, v)); else criticalEdges.push_back(ii(v, u)); } dfs_low[u] = min(dfs_low[u], dfs_low[v]); } else if (v != dfs_parent[u]) dfs_low[u] = min(dfs_low[u], dfs_num[v]); } } int main(){ int n; while (scanf("%d\n", &n) == 1){ string line; adj.clear(); for (int i = 0; i < n; i++){ getline(cin, line); // cout << line <<endl; if (line == "0") break; stringstream ss; ss.str(line); int a, b; char c, d; ss >> a >> c >> b >> d; // cout << a << ": "; while (ss >> b){ adj[a].push_back(b); adj[b].push_back(a); // cout << b << " "; } // cout << endl; } dfsNumberCounter = 1; dfs_num.assign(n+1, 0); dfs_low.assign(n+1, 0); dfs_parent.assign(n+1, 0); articulation_vertex.assign(n, false); criticalEdges.clear(); for (int i = 0; i < n; i++){ // cout << i << ", " << dfs_num[i] << endl; if (dfs_num[i] == 0){ dfsRoot = i; // cout << i << endl; rootChildren = 0; articulationPoint(i); articulation_vertex[dfsRoot] = (rootChildren > 1); // cout << dfsRoot << ", " << rootChildren << ", " << articulation_vertex[dfsRoot] << endl; } } cout << criticalEdges.size() << " critical links" << endl; sort(criticalEdges.begin(), criticalEdges.end()); // cout << 1 << endl; for (int i = 0; i < criticalEdges.size(); i++){ // cout << i << ", " << dfs_num[i] << ", " << dfs_low[i] << ", " << articulation_vertex[i] << endl; cout << criticalEdges[i].first << " - " << criticalEdges[i].second << endl; } cout << endl; } return 0; }
#include <Arduino.h> #include <ESPEssentials.h> #include "Animation.h" #include "Config.h" #include "Fade.h" #include "Hardware.h" #include "WebSocket.h" #include "Webserver.h" // Include animations here: #include "Animations/rainbow.h" #include "Animations/color.h" #include "Animations/colorBlend.h" #include "Animations/fader.h" #include "Animations/colorRider.h" #include "Animations/rbWave.h" #include "Animations/rgbWave.h" void setup() { initESPEssentials("Lightstrip"); Config.init(); initHardware(); if (WiFi.status() == WL_CONNECTED) { initWebsocket(); initWebserverCommands(); initFade(); } // Register animations here: registerAnimation(new Color("Color")); registerAnimation(new ColorBlend("Color Blend")); registerAnimation(new ColorRider("Color Rider")); registerAnimation(new Fader("Fader")); registerAnimation(new Rainbow("Rainbow")); registerAnimation(new RbWave("RB Wave")); registerAnimation(new RgbWave("RGB Wave")); if (Config.startupAnimation != "") getAnimation(Config.startupAnimation)->begin(); } void loop() { if (status == RUNNING && currentAnimation) currentAnimation->loop(); handleESPEssentials(); handleFade(); webSocket.loop(); }
#include<iostream> using namespace std; class Node{ public : int data,key; Node *next; Node(){ data=0; key=0; next=NULL; } Node(int k, int d){ key=k; data=d; next=NULL; } }; class CircularLinkedList{ public : Node *head; CircularLinkedList(){ head=NULL; } CircularLinkedList(Node *n){ head=n; n->next=head; } // 1. CHeck if node exists using key value Node * nodeExists(int k) { Node *ptr=head; Node *temp=NULL; if(head==NULL){ return temp; } else { do{ if(ptr->key==k){ temp=ptr; ptr=head; } else{ ptr=ptr->next; } }while(ptr!=head); return temp; } } // 2. Append a node to the list void appendNode(Node * n) { if(nodeExists(n->key)!=NULL){ printf("\n\t duplicate key entry "); return ; } else { if(head==NULL){ head=n; head->next=n; printf("\n\t Node is append as a head Node "); } else { Node *ptr=head; while(ptr->next!=head){ ptr=ptr->next; } n->next=head; ptr->next=n; printf("\n\t Node Appended"); } } } // 3. Prepend Node - Attach a node at the start void prependNode(Node * n) { if(nodeExists(n->key)!=NULL){ printf("\n\t duplicate key entry "); } else { if(head==NULL){ head=n; head->next=n; printf("\n\t Node is prepend as a head Node "); } else{ Node *ptr=head; while(ptr->next!=head){ ptr=ptr->next; } ptr->next=n; n->next=head; head=n; printf("\n\t Node Prepended"); } } } // 4. Insert a Node after a particular node in the list void insertNodeAfter(int k, Node * n) { Node *ptr=nodeExists(k); if(ptr==NULL){ printf("\n\t invalid key , insert a node after a praticular key is failed "); } else { if(nodeExists(n->key)!=NULL){ printf("\n\t duplicate key entry "); } else { // if the ptr is single || if the ptr is at end if(ptr->next==head){ n->next=head; ptr->next=n; printf("\n\t Node Inserted at the End"); } // if the ptr is at middle else { n->next=ptr->next; ptr->next=n; printf("\n\t Node Inserted in between"); } } } } // 5. Delete node by unique key void deleteNodeByKey(int k) { Node *ptr=nodeExists(k); if(ptr==NULL){ printf("\n\t invalid key , insert a node after a praticular key is failed "); } else { Node *cptr=head; while(cptr->next!=ptr){ cptr=cptr->next; } Node *lNode=head; while(lNode->next!=head){ lNode=lNode->next; } // ptr is a single node if(ptr->next==head && head->next==head){ printf("\n\t only a single Node present i.e Head Node, deleted "); delete head; head=NULL; } // if the node is to deleted as a 1st Ndde and remaing node are left as is it else if(head->key==k){ Node *t=head; head=head->next; lNode->next=head; delete t; } // if ptr is a last Node else if(ptr->next==head){ cptr->next=head; delete ptr; } // if ptr is a middle node else { cptr->next=ptr->next; delete ptr; } } } // 6th update node void updateNodeByKey(int k, int new_data) { Node *ptr=nodeExists(k); if(ptr==NULL){ printf("\n\t invalid key , updating a Node is failed "); } else{ ptr->data=new_data; } } // 7th printing void printList() { if(head==NULL){ printf("\n\t list is empty "); } else{ Node *ptr=head; printf("\n\t "); while(ptr->next!=head){ printf(" ( %d, %d ) --> ",ptr->key,ptr->data); ptr=ptr->next; } printf(" ( %d, %d ) --> NULL ",ptr->key,ptr->data); } } }; int main() { CircularLinkedList obj; int option; int key1, k1, data1; do { cout << "\nWhat operation do you want to perform? Select Option number. Enter 0 to exit." << endl; cout << "1. appendNode()" << endl; cout << "2. prependNode()" << endl; cout << "3. insertNodeAfter()" << endl; cout << "4. deleteNodeByKey()" << endl; cout << "5. updateNodeByKey()" << endl; cout << "6. print()" << endl; cout << "7. Clear Screen" << endl << endl; cin >> option; Node * n1 = new Node(); //Node n1; switch (option) { case 0: break; case 1: cout << "Append Node Operation \nEnter key & data of the Node to be Appended" << endl; cin >> key1; cin >> data1; n1 -> key = key1; n1 -> data = data1; obj.appendNode(n1); //cout<<n1.key<<" = "<<n1.data<<endl; break; case 2: cout << "Prepend Node Operation \nEnter key & data of the Node to be Prepended" << endl; cin >> key1; cin >> data1; n1 -> key = key1; n1 -> data = data1; obj.prependNode(n1); break; case 3: cout << "Insert Node After Operation \nEnter key of existing Node after which you want to Insert this New node: " << endl; cin >> k1; cout << "Enter key & data of the New Node first: " << endl; cin >> key1; cin >> data1; n1 -> key = key1; n1 -> data = data1; obj.insertNodeAfter(k1, n1); break; case 4: cout << "Delete Node By Key Operation - \nEnter key of the Node to be deleted: " << endl; cin >> k1; obj.deleteNodeByKey(k1); break; case 5: cout << "Update Node By Key Operation - \nEnter key & NEW data to be updated" << endl; cin >> key1; cin >> data1; obj.updateNodeByKey(key1, data1); break; case 6: obj.printList(); break; case 7: system("cls"); break; default: cout << "Enter Proper Option number " << endl; } } while (option != 0); return 0; }
#include "head.h" //具体类 class BinarySplitter : public ISplitter { void split() override { } }; class TxtSplitter : public ISplitter { void split() override { } }; class PictureSplitter : public ISplitter { void split() override { } }; class VideoSplitter : public ISplitter { void split() override { } };
#pragma once #include <rpc/msgpack.hpp> #include <string> #include <vector> struct ObjectState { std::string objectName; float x, y, z; float qw, qx, qy, qz; ObjectState() {} ObjectState(std::string objectName, float x, float y, float z, float qw, float qx, float qy, float qz) :objectName(objectName), x(x), y(y), z(z), qw(qw), qx(qx), qy(qy), qz(qz) {} ObjectState(std::string objectName) :objectName(objectName), x(0), y(0), z(0), qw(1), qx(0), qy(0), qz(0) {} MSGPACK_DEFINE_ARRAY(objectName, x, y, z, qw, qx, qy, qz) }; struct GroupState { std::string groupName; std::vector<ObjectState> objectStates; GroupState() {} GroupState(std::string groupName) :groupName(groupName) {} GroupState(std::string groupName, int nObj) :groupName(groupName), objectStates(nObj) {} MSGPACK_DEFINE_ARRAY(groupName, objectStates) }; struct FrameState { double duration; std::vector<GroupState> groups; MSGPACK_DEFINE_ARRAY(duration, groups) };
#include "Game.h" #include <iostream> #include <Windows.h> Game::Game( ) { m_currentScore = 0; m_currentGameState = GameStates::mainMenu; m_scoreFilename = "HighScore.txt"; m_highScoreFile.open( m_scoreFilename ); m_highScoreFile >> m_highScore; m_highScoreFile.close( ); } void Game::renderGameOver( ) { //Clears all text from the screen system( "cls" ); //Displays text on the screen to inform the player of how to proceed std::cout << "You died!"; std::cout << "Your score was: " << m_currentScore << "\n\n"; std::cout << "Press any key to play again!\n"; } void Game::renderMenu( ) { //Clears the screen of all text system( "cls" ); //Prints some welcome text to inform the player how to proceed std::cout << "Welcome to Snake!\n"; std::cout << "Press any key to begin!\n\n"; std::cout << "High Score: " << m_highScore; } void Game::runGame( ) { system( "cls" ); std::cout << "The game will go here, I promise!\n"; } void Game::update( ) { while ( true ) { switch ( m_currentGameState ) { case GameStates::mainMenu: renderMenu( ); break; case GameStates::gameRunning: runGame( ); break; case GameStates::gameOver: renderGameOver( ); break; } Sleep( 250 ); } }
#include<bits/stdc++.h> using namespace std; int findparent(int* parent,int n,int index) { if(parent[index]==index) { return index; } return findparent(parent,n,parent[index]); } int solve(int* arr,int n) { int large = 0; // using union find algorithm for(int i=0;i<n;i++) { large = max(large,arr[i]); } int* parent = new int[large+1]; for(int i=0;i<=large;i++) { parent[i]=i; } // find prime factors for(int i=0;i<n;i++) { for(int j=2;j<=sqrt(arr[i]);j++) { if(arr[i]%j == 0) { int x = findparent(parent,n,arr[i]); int y = findparent(parent,n,j); parent[x]=y;// belong to same set int temp = arr[i]/j; y = findparent(parent,n,temp); x = findparent(parent,n,arr[i]); parent[x]=y; } } } map<int,int> hash; for(int i=0;i<n;i++) { int x = findparent(parent,n,arr[i]); hash[x]+=1; } map<int,int> :: iterator it = hash.begin(); int max_len = 0; for(it=hash.begin();it!=hash.end();it++) { max_len = max(max_len,it->second); } return max_len; } int main() { int n; cin >> n; int* arr = new int[n]; for(int i=0;i<n;i++) { cin >> arr[i]; } cout << solve(arr,n) << endl; }
/* * Copyright (C) 2014-2016 Open Source Robotics Foundation * * 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. * */ /* * Author: Jennifer Buehler */ #ifndef COLLISION_BENCHMARK_TEST_STEPGUI_H #define COLLISION_BENCHMARK_TEST_STEPGUI_H #include <gazebo/common/Plugin.hh> #include <gazebo/gui/GuiPlugin.hh> #ifndef Q_MOC_RUN // See: https://bugreports.qt-project.org/browse/QTBUG-22829 # include <gazebo/transport/transport.hh> # include <gazebo/gui/gui.hh> #endif #include <string> /** * \brief Creates a GUI with "Next" and "Prev" button * for debugging between update steps. * * Communication with the server works via gazebo::Any messages. * An integer of -1 is sent for "Prev", an integer of 1 for "Next". * * \author Jennifer Buehler * \date December 2017 */ class GAZEBO_VISIBLE StepGui : public gazebo::GUIPlugin { Q_OBJECT /// \brief Constructor /// \param[in] _parent Parent widget public: StepGui(); /// \brief Destructor public: virtual ~StepGui(); /// \brief Callback trigged when the button "Prev" is pressed. protected slots: void OnButtonPrev(); /// \brief Callback trigged when the button "Next" is pressed. protected slots: void OnButtonNext(); /// \brief Node used to establish communication with gzserver. private: gazebo::transport::NodePtr node; /// \brief Publisher for "next" and "prev" world setting private: gazebo::transport::PublisherPtr pub; /// \brief minimum size of the widget, set by the buttons width and height private: QSize minSize; }; #endif
class IProgess { public: virtual void DoProgress(float value) = 0; ~IProgess(); }; class FileSplitter { public: FileSplitter(const string& filePath,int fileNumber,IProgess* m_iprogress):m_filePath(filePath),m_fileNumber(fileNumber),m_iprogessBar(iprogress) { } ~FileSplitter(); void split() { //1、读取大文件 //2、分批次向小文件写入 for(int i = 0; i < m_fileNumber; i++) { //... float progessValue = m_fileNumber; progessValue = (i+1)/progessValue onProgress(progessValue);// 更新进度条 } } protected: void onProgress(float value) { if (m_iprogess != nullptr ) { m_iprogress->DoProgress(value); } } private: string m_filePath; int m_fileNumber; // ProgressBar *m_progessBar;//分割进度条 扮演了一个通知者的角色 IProgess* m_iprogress; //抽象的通知机制 };
//  Created by Frank M. Carrano and Timothy M. Henry. //  Copyright (c) 2017 Pearson Education, Hoboken, New Jersey. /** ADT stack: Link-based implementation. Listing 7-3. @file LinkedStack.h */ #ifndef LINKED_STACK_ #define LINKED_STACK_ #include "StackInterface.h" #include "Node.h" template<class ItemType> class LinkedStack : public StackInterface<ItemType> { private: Node<ItemType>* topPtr; // Pointer to first node in the chain; // this node contains the stack's top public: // Constructors and destructor: LinkedStack(); // Default constructor LinkedStack(const LinkedStack<ItemType>& aStack);// Copy constructor virtual ~LinkedStack(); // Destructor // Stack operations: bool isEmpty() const; bool push(const ItemType& newItem); bool pop(); ItemType peek() const; }; // end LinkedStack #include "LinkedStack.cpp" #endif
#pragma once #ifdef _WIN32 #include <afxmt.h> typedef CCriticalSection CRIT_SECTION; #else #include <pthread.h> typedef pthread_mutex_t CRIT_SECTION; #endif // _WIN32 class CCSGuardian { CRIT_SECTION &m_CS; public: CCSGuardian(CRIT_SECTION &CS); ~CCSGuardian(void); };
/*************************************************************************** Copyright (c) 2020 Philip Fortier This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ***************************************************************************/ #pragma once #include "Types.h" struct CodeResult { public: CodeResult(WORD wBytes, SpeciesIndex wType) : _wBytes(wBytes), _type(wType) {} CodeResult(WORD wBytes) : _wBytes(wBytes), _type(DataTypeNone) {} CodeResult() : _wBytes(0), _type(DataTypeNone) {} WORD GetBytes() const { return _wBytes; } SpeciesIndex GetType() const { return _type; } private: WORD _wBytes; // Number of bytes pushed onto the stack SpeciesIndex _type; // Data type }; namespace sci { enum class ValueType : uint32_t { String = 0x00000000, Said = 0x00000001, Number = 0x00000002, Token = 0x00000003, Selector = 0x00000004, Pointer = 0x00000005, None = 0x00000006, ResourceString = 0x00000007, // Not available in SCIStudio syntax ArraySize = 0x00000008, // e.g. &sizeof MyArray - should get converted in prescan #ifdef ENABLE_EXISTS ParameterIndex = 0x00000010, // the 0-based numerical index of the parameter #endif #ifdef ENABLE_LDMSTM Deref = 0x00000020, #endif }; }
#include <iostream> #include <string> #include <vector> using namespace std; //solution to the bit++ codeforces problem //http://codeforces.com/contest/282/problem/A int get_value(vector<string> operations, int n){ int x = 0; for (int i = 0; i < n; i++){ if ( (operations.at(i).at(1)) == '+' ) x += 1; else x -= 1; } return x; } int main(int argc, char *argv[]) { short n; vector<string> operations (150); cin >> n; for (int i = 0; i < n; i++){ cin >> operations.at(i); } cout << get_value(operations, n); return 0; }
#pragma once namespace logger { void init_logger(); void close_logger(); void write_entry(size_t hash, std::wstring text); }
// // Created by zlc on 2021/6/24. // #ifndef _MY_SLAM_GMAPPING_LIDAR_UNDISTORTION_H_ #define _MY_SLAM_GMAPPING_LIDAR_UNDISTORTION_H_ #include "ros/ros.h" #include "sensor_msgs/LaserScan.h" #include "std_msgs/Float64.h" #include "nav_msgs/GetMap.h" #include "tf/transform_listener.h" #include "tf/transform_broadcaster.h" #include "message_filters/subscriber.h" #include "tf/message_filter.h" #include <iostream> #include <dirent.h> // dirent.h是用于目录操作的头文件,linux 默认在/usr/include目录下(会自动包含其他文件),常见的方法如下: // 1. opendir(): 打开目录,并返回句柄 // 2. readdir(): 读取句柄,返回dirent结构体 // 3. telldir(): 返回当前指针的位置,表示第几个元素 // 4. close(): 关闭句柄 #include <fstream> #include <string> /******************************************************************************************************* * 2D 激光雷达运动畸变去除 * *****************************************************************************************************/ // 雷达运动畸变去除类 class LidarMotionCalibrator { public: // 构造函数 LidarMotionCalibrator(std::string scan_frame_name, std::string odom_name); // 析构函数 ~LidarMotionCalibrator(); // 激光雷达运动畸变去除函数 void lidarCalibration(std::vector<double>& ranges, std::vector<double>& angles, ros::Time startTime, ros::Time endTime, tf::TransformListener* tf_); // 从tf缓存数据中,寻找对应时间戳的里程计位姿 bool getLaserPose(tf::Stamped<tf::Pose>& odom_pose, ros::Time dt, tf::TransformListener* tf_); // 根据传入参数,对任意一个分段进行插值 void lidarMotionCalibration(tf::Stamped<tf::Pose> frame_base_pose, tf::Stamped<tf::Pose> frame_start_pose, tf::Stamped<tf::Pose> frame_end_pose, std::vector<double>& ranges, std::vector<double>& angles, int startIndex, int& beam_number); public: // 针对各自的情况需要更改的名字,自行更改 std::string scan_frame_name_; // 扫描帧 名字 std::string odom_name_; // 里程计 名字 }; #endif // _MY_SLAM_GMAPPING_LIDAR_UNDISTORTION_H_
//OtherNoteApp.cpp #include "OtherNoteApp.h" #include "OtherNoteForm.h" #include "Note.h" #include "PageForm.h" #include "resource1.h" //#include <crtdbg.h>//메모리 릭 체크 BOOL OtherNoteApp::InitInstance() { OtherNoteForm *otherNoteForm = new OtherNoteForm(new Note); otherNoteForm->Create("otherNote", "제목없음 - OtherNote" , WS_OVERLAPPEDWINDOW | WS_MAXIMIZE, CFrameWnd::rectDefault, NULL, (LPCTSTR)IDR_MENU_MAIN, 0, NULL); otherNoteForm->ShowWindow(SW_SHOW); otherNoteForm->UpdateWindow(); otherNoteForm->GetTabCtrl()->DrawTabItem(); this->m_pMainWnd = otherNoteForm; //_CrtDumpMemoryLeaks(); 메모리 릭 체크 return TRUE; } OtherNoteApp otherNoteApp;
#include "OMJunctionGenerator.h" #include <Const.h> #include <Utils/GeneralizedCylinder.h> /* void OMJunctionGenerator::SampleSegmentBoundary(const TreeHypergraph::Branch &branch,float t,unsigned int sample_id_begin,VertexData destination[]) { GeneralizedCylinder BranchCylinder(*branch.Curve,branch.Up,branch.Width); float dAngle = 2.0 * PI / SegmentWidth; for(unsigned int i=0;i < SegmentWidth;i++) { float ParamX = t; float ParamY = i*dAngle; destination[i].Vertex = BranchCylinder.GetPoint(ParamX,ParamY); ParamX /= (branch.t_End - branch.t_Begin); ParamY /= 2.0*PI; destination[i].TexCoord = vec4(ParamX,ParamY); destination[i].SegmentId = branch.Id; destination[i].SampleId = sample_id_begin + i; } } */ void OMJunctionGenerator::SampleJunction() { unsigned int NumVertices = Junction.Children.size()*SegmentWidth; // if(Junction.Root != nullptr) {NumVertices += SegmentWidth;} // std::vector<VertexData> Vertices(NumVertices); // unsigned int j=0; if(Junction.Root != nullptr) { SampleSegmentBoundary(*Junction.Root,Junction.Root->t_End,(SegmentHeight - 1)*SegmentWidth,&Vertices[0]); } // unsigned int I = 0; if(Junction.Root != nullptr) {I = 1;} // for(TreeHypergraph::Branch *B : Junction.Children) { SampleSegmentBoundary(*B,B->t_Begin,0,&Vertices[I * SegmentWidth]); I++; } // Quickhull(&Vertices[0],Vertices.size(),JunctionMesh); }
#include "WorkerThreadPool.h" WorkerThreadPool::WorkerThreadPool (size_t low_mark, size_t high_mark) : ACE_Task_Base () , task_mutex_ () , task_condition_ (task_mutex_) , handler_ () , queue_ (low_mark, high_mark) , state_ (ST_INIT) , num_threads_ (0) , active_threads_ (0) { } WorkerThreadPool::~WorkerThreadPool() { stopAndWait (); ACE_ASSERT ( state_ == ST_STOPPED); } bool WorkerThreadPool::putq (Job *job) { return queue_.put (obj); } bool WorkerThreadPool::start (int num_threads, const HANDLER & runHandler) { { ACE_GUARD_RETURN (Mutex, guard, task_mutex_, false); if (num_threads == 0) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) WorkerThreadPool::start - invalid parameter\n"))); return false; } switch (state_) { case ST_INIT: case ST_STOPPED: break; default: ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) WorkerThreadPool::start - already started or requested to stop\n"))); return false; } state_ = ST_ACTIVE; handler_ = runHandler; } queue_.activate (Queue::READABLE); // activate "numThreads" if (this->activate (THR_NEW_LWP| THR_JOINABLE, num_threads) < 0) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) WorkerThreadPool::start - unable to activate\n"))); this->stopAndWait (); return false; } { ACE_GUARD_RETURN (Mutex, guard, task_mutex_, false); while (num_threads_ != num_threads) { task_condition_.wait(); } } queue_.activate (Queue::WRITABLE); return true; } inline bool WorkerThreadPool <OBJECT, HANDLER, CONTAINER>::stop () { queue_.deactivate (Queue::READABLE | Queue::WRITABLE); { ACE_GUARD_RETURN (Mutex, guard, task_mutex_, false); switch (state_) { case ST_INIT: state_ = ST_STOPPED; return true; case ST_STOPPED: return true; case ST_CANCEL: break; case ST_ACTIVE: break; default: break; } state_ = ST_CANCEL; } return true; } inline bool WorkerThreadPool <OBJECT, HANDLER, CONTAINER>::stopAndWait () { this->stop (); int rc = this->wait (); if (rc < 0) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) ThreadPool_t::stop - unable to deactivate\n"))); return false; } { ACE_GUARD_RETURN (Mutex, guard, task_mutex_, false); num_threads_ = 0; state_ = ST_STOPPED; } return true; } inline bool WorkerThreadPool <OBJECT, HANDLER, CONTAINER>::purgeQueue (const HANDLER & purgeHandler) { { ACE_GUARD_RETURN (Mutex, guard, task_mutex_, false); if (state_ != ST_STOPPED) return false; } OBJECT msg; while (queue_.pop(msg)) { try { purgeHandler(msg); } catch (std::exception & e ) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) WorkerThreadPool::purgeQueue() caught exception: %s\n"), e.what())); } catch (...) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) WorkerThreadPool::purgeQueue() caught unknown exception\n"))); } } return true; } inline int WorkerThreadPool <OBJECT, HANDLER, CONTAINER>::svc () { int thrNum = 0; { ACE_GUARD_RETURN (Mutex, guard, task_mutex_, -1); thrNum = active_threads_ = ++num_threads_; task_condition_.signal (); ACE_ERROR ((LM_INFO, ACE_TEXT ("(%t) WorkerThreadPool::svc() thread=%d started\n"), thrNum)); } OBJECT msg; while (queue_.get(msg)) { try { handler_(msg); } catch (std::exception & e ) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) WorkerThreadPool::svc() thread=%d caught exception: %s\n"), thrNum, e.what())); } catch (...) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) WorkerThreadPool::svc() thread=%d caught unknown exception\n"), thrNum)); } } { ACE_GUARD_RETURN (Mutex, guard, task_mutex_, -1); --active_threads_; ACE_ERROR ((LM_INFO, ACE_TEXT ("(%t) WorkerThreadPool::svc() thread=%d finished\n"), thrNum)); } return 0; } #endif // THREAD_POOL_T
#include "rectangle.h" Rectangle::Rectangle(int length, int width) { this->length = length; this->width = width; area = length * width; placed = false; } int Rectangle::getLength() { return length; } int Rectangle::getWidth() { return width; } int Rectangle::getArea() { return area; } void Rectangle::setPlaced(bool b) { placed = b; } bool Rectangle::getPlaced() { return placed; } void Rectangle::reverseLW() { int temp = length; length = width; width = temp; } bool Rectangle::operator < (const Rectangle &r1) const { if (r1.length != length) { return length < r1.length; } else { return width < r1.width; } } bool Rectangle::operator == (const Rectangle &r1) const { return (r1.length == length && r1.width == width) || (r1.length == width && r1.width == length); } bool operator == (std::set<std::set<Rectangle>> r, std::set<std::set<Rectangle>> s) { if (r.size() != s.size()) { return false; } else { auto rIt = r.begin(), sIt = s.begin(); while (rIt != r.end()) { if (*rIt != *sIt) { return false; } rIt++; sIt++; } return true; } }
//想要sort()按照从大到小排列,则需要加入第三个参数cmp //处理double型数据 #include<stdio.h> #include<algorithm> using namespace std; bool cmp(double a,double b) { return a>b;//按照从大到小排列,注意与priority_queue的写法是相反的 } int main(){ double a[]={2.66,5.88,-89.1,-55.25,67}; for(int i=0;i<5;i++) printf("%f ",a[i]); printf("\n"); sort(a,a+5);//不加compare参数的话就是默认从小到大排列 for(int i=0;i<5;i++) printf("%f ",a[i]); printf("\n"); sort(a,a+5,cmp);//不加compare参数的话就是默认从小到大排列 for(int i=0;i<5;i++) printf("%f ",a[i]); printf("\n"); return 0; }
#include "ros/ros.h" #include "std_msgs/String.h" #include "math.h" #include <algorithm> // std::sort //Librerias propias usadas #include "constantes.hpp" #include "camina4/v_repConst.h" // Used data structures: #include "camina4/InfoMapa.h" #include "camina4/CinversaParametros.h" #include "camina4/UbicacionRobot.h" #include "camina4/PlanificadorParametros.h" #include "camina4/SenalesCambios.h" // Used API services: #include "vrep_common/VrepInfo.h" // Definiciones #define MAX_CICLOS 5 //Clientes y Servicios ros::ServiceClient client_Cinversa1; camina4::CinversaParametros srv_Cinversa1; //-- Variables Globales bool simulationRunning=true; bool sensorTrigger=false; float simulationTime=0.0f; //-- Log de planificador FILE *fp2; //-- Entrada int Tripode=0, tripode[Npatas], Tripode1[Npatas/2], Tripode2[Npatas/2]; float velocidad_Apoyo=0.0, beta=0.0, phi[Npatas], alfa=0.0; //-- Variables de mapa camina4::InfoMapa infoMapa; std::vector<int> coordenadaObstaculo_i(1000,0), coordenadaObstaculo_j(1000,0); bool matrizMapa[100][100]; int nCeldas_i=0, nCeldas_j=0; float LongitudCeldaY=0, LongitudCeldaX=0; //-- Variables de ubicacion robot double tiempo_ahora=0.0, tiempo_anterior=0.0; float ajuste_Vel=vel_esperada/vel_teorica; float velocidadCuerpo_y=0.0, delta_x=0.0, delta_y=0.0, x_anterior=0.0, y_anterior=0.0, x_actual=0.0, y_actual=0.0; float posicionActualPata_y[Npatas], posicionActualPata_x[Npatas], posicionActualPata_z[Npatas]; float posicionActualPataSistemaPata_y[Npatas],posicionActualPataSistemaPata_x[Npatas],posicionActualPataSistemaPata_z[Npatas]; float teta_CuerpoRobot=0.0; //-- Envio de señal de stop ros::Publisher chatter_pub1; camina4::SenalesCambios senales; //-- Generales //int k=0; ros::Publisher chatter_pub2; //-- Funciones void transformacion_yxTOij(int *ptr_ij, float y, float x); void FilePrint_matrizMapa(); void Limpiar_matrizMapa(); int Construye_matrizMapa(std::string fileName); void print_matrizMapa(); //-- Topic subscriber callbacks: void infoCallback(const vrep_common::VrepInfo::ConstPtr& info) { simulationTime=info->simulationTime.data; simulationRunning=(info->simulatorState.data&1)!=0; } void ubicacionRobCallback(camina4::UbicacionRobot msgUbicacionRobot) { float vel_aux=0.0; teta_CuerpoRobot = msgUbicacionRobot.orientacionCuerpo_yaw; vel_aux = msgUbicacionRobot.velocidadCuerpo_y; if(vel_aux>velocidad_Apoyo){ //-- la velocidad no puede ser mayor a la esperada velocidadCuerpo_y = velocidad_Apoyo; } else { velocidadCuerpo_y = vel_aux; } velocidadCuerpo_y= ajuste_Vel*velocidadCuerpo_y; for(int k=0; k<Npatas;k++) { posicionActualPata_x[k] = msgUbicacionRobot.coordenadaPata_x[k]; posicionActualPata_y[k] = msgUbicacionRobot.coordenadaPata_y[k]; posicionActualPata_z[k] = msgUbicacionRobot.coordenadaPata_z[k]; posicionActualPataSistemaPata_x[k] = msgUbicacionRobot.coordenadaPataSistemaPata_x[k]; posicionActualPataSistemaPata_y[k] = msgUbicacionRobot.coordenadaPataSistemaPata_y[k]; posicionActualPataSistemaPata_z[k] = msgUbicacionRobot.coordenadaPataSistemaPata_z[k]; } } bool PlanificadorPisada(camina4::PlanificadorParametros::Request &req, camina4::PlanificadorParametros::Response &res) { // ROS_INFO("Llamado a servicio planificador"); // fprintf(fp2,"\ntiempo de simulacion: %.3f\t",simulationTime); //-- Datos para envio de mensajes res.modificacion_T = 0.0; res.modificacion_lambda = 0.0; res.result = 0; //-- Variables locales int Tripode_Apoyo[Npatas/2]; int PisadaProxima_i=0, PisadaProxima_j=0, PisadaActual_i=0, PisadaActual_j=0; bool PisadaInvalida[Npatas/2], TodasPisadasOk, cinversaOK; float PisadaProxima_x=0.0, PisadaProxima_y=0.0, PisadaProxima_z=0.0; float delta_x_S0=0.0, delta_y_S0=0.0, delta_x=0.0, delta_y=0.0; float modificacion_lambda[Npatas/2]; float T_actual=0.0; int ij[2]={0,0}, *p_ij; //Apuntadores a arreglos de coordenadas e indices p_ij = ij; // Inicialización de apuntador Tripode=req.Tripode; ROS_INFO("server_Plan::T[%d] v_y=%.3f",Tripode,velocidadCuerpo_y); fprintf(fp2,"\ntiempo de simulacion: %.3f\n",simulationTime); fprintf(fp2,"server_Plan::T[%d]: Inicio Plan - v_y=%.3f\n",Tripode,velocidadCuerpo_y); if (req.Tripode == 1){ for(int k=0;k<Npatas/2;k++) Tripode_Apoyo[k] = Tripode1[k]; } else{ for(int k=0;k<Npatas/2;k++) Tripode_Apoyo[k] = Tripode2[k]; } T_actual = req.T; TodasPisadasOk = true; // Todas las pisadas se asumen bien a la primera for(int k=0;k<Npatas/2;k++){ ros::spinOnce(); // ROS_INFO("server_Plan: revisando pata [%d]", Tripode_Apoyo[k]); //-- Calculamos proximo movimiento en el sistema de pata delta_x_S0 = -lambda_maximo*cos(alfa); delta_y_S0 = lambda_maximo*sin(alfa); delta_x = delta_x_S0*cos(phi[Tripode_Apoyo[k]]+alfa)-delta_y_S0*sin(phi[Tripode_Apoyo[k]]+alfa); delta_y = delta_x_S0*sin(phi[Tripode_Apoyo[k]]+alfa)+delta_y_S0*cos(phi[Tripode_Apoyo[k]]+alfa); PisadaProxima_x=posicionActualPataSistemaPata_x[Tripode_Apoyo[k]] + delta_x; PisadaProxima_y=posicionActualPataSistemaPata_y[Tripode_Apoyo[k]] + delta_y; PisadaProxima_z=posicionActualPataSistemaPata_z[Tripode_Apoyo[k]]; //-- Verificamos que pisada sea factible // ROS_INFO("server_Plan: revisando cinversa"); srv_Cinversa1.request.x = PisadaProxima_x; srv_Cinversa1.request.y = PisadaProxima_y; srv_Cinversa1.request.z = PisadaProxima_z; if (client_Cinversa1.call(srv_Cinversa1)){ //-- Funciona servicio cinversaOK=true; } else { ROS_ERROR("server_PlanificadorPisada: servicio de Cinversa no funciona\n"); cinversaOK=false; } if (cinversaOK){ // ROS_INFO("server_Plan: cinversaOK"); ros::spinOnce(); //-- Calculamos proximo movimiento en el sistema mundo transformacion_yxTOij(p_ij, posicionActualPata_y[Tripode_Apoyo[k]], posicionActualPata_x[Tripode_Apoyo[k]]); PisadaActual_i = ij[0]; PisadaActual_j = ij[1]; PisadaProxima_y=posicionActualPata_y[Tripode_Apoyo[k]] + (lambda_maximo+velocidadCuerpo_y*(1-beta)*T_actual)*cos((teta_CuerpoRobot-teta_Offset)+alfa); PisadaProxima_x=posicionActualPata_x[Tripode_Apoyo[k]] + (lambda_maximo+velocidadCuerpo_y*(1-beta)*T_actual)*sin((teta_CuerpoRobot-teta_Offset)+alfa); transformacion_yxTOij(p_ij, PisadaProxima_y, PisadaProxima_x); PisadaProxima_i=ij[0]; PisadaProxima_j=ij[1]; PisadaInvalida[k] = false; // ROS_INFO("Pisada revisar: i=%d,j=%d",PisadaProxima_i,PisadaProxima_j); if(matrizMapa[PisadaProxima_i][PisadaProxima_j]){ //-- La pisada COINCIDE con obstaculo ROS_WARN("server_PlanificadorPisada: pata [%d] coincide con obstaculo [%d][%d]",Tripode_Apoyo[k]+1,PisadaProxima_i,PisadaProxima_j); fprintf(fp2,"tiempo de simulacion: %.3f\n",simulationTime); fprintf(fp2,"pata [%d] coincide con obstaculo[%d][%d]\n",Tripode_Apoyo[k]+1,PisadaProxima_i,PisadaProxima_j); PisadaInvalida[k] = true; TodasPisadasOk = false; // break; } if(!PisadaInvalida[k]){ // ROS_INFO("TripodeOK"); //-- Todo salio bien! Esta proxima_pisada es valida! :D modificacion_lambda[k] = lambda_maximo; //-- Pisada maxima infoMapa.coordenadaAjuste_i[Tripode_Apoyo[k]] = PisadaProxima_i; infoMapa.coordenadaAjuste_j[Tripode_Apoyo[k]] = PisadaProxima_j; infoMapa.coordenadaPreAjuste_i[Tripode_Apoyo[k]] = PisadaActual_i; infoMapa.coordenadaPreAjuste_j[Tripode_Apoyo[k]] = PisadaActual_j; } } else { ROS_WARN("server_PlanificadorPisada: pata [%d] error cinversa",k+1); fprintf(fp2,"tiempo de simulacion: %.3f\n",simulationTime); fprintf(fp2,"pata [%d] error cinversa\n",Tripode_Apoyo[k]+1); PisadaInvalida[k] = true; TodasPisadasOk = false; } } // Fin de revision de pisadas infoMapa.correccion=false; //---> Aqui va codigo para arreglar pisadas invalidas float lambda_Correccion=0.0, T_Correccion=0.0, lambda_paso=0.0; int ciclosContraccion=0; while (ciclosContraccion<MAX_CICLOS && !TodasPisadasOk){ infoMapa.correccion=true; ROS_WARN("server_PlanificadorPisada: Correccion de pisada ciclo: %d",ciclosContraccion); fprintf(fp2,"tiempo de simulacion: %.3f\n",simulationTime); fprintf(fp2,"server_PlanificadorPisada: Correccion de pisada ciclo: %d\n",ciclosContraccion); ciclosContraccion++; TodasPisadasOk = true; //-- Se corrige en tamaños de celda lambda_paso = lambda_paso+0.02; lambda_Correccion = lambda_maximo-lambda_paso; ROS_WARN("server_PlanificadorPisada: lambda_Correccion: %.3f",lambda_Correccion); fprintf(fp2,"tiempo de simulacion: %.3f\n",simulationTime); fprintf(fp2,"lambda_Correccion: %.3f\n",lambda_Correccion); T_Correccion = lambda_Correccion/(beta*velocidad_Apoyo); for (int k=0;k<Npatas/2;k++){ ros::spinOnce(); if(PisadaInvalida[k]){ ROS_WARN("server_PlanificadorPisada: revisando pata[%d]",Tripode_Apoyo[k]+1); fprintf(fp2,"tiempo de simulacion: %.3f\n",simulationTime); fprintf(fp2,"revisando pata[%d]\n",Tripode_Apoyo[k]+1); //-- Calculamos proximo movimiento en el sistema de pata delta_x_S0 = -lambda_Correccion*cos(alfa); delta_y_S0 = lambda_Correccion*sin(alfa); delta_x = delta_x_S0*cos(phi[Tripode_Apoyo[k]]+alfa)-delta_y_S0*sin(phi[Tripode_Apoyo[k]]+alfa); delta_y = delta_x_S0*sin(phi[Tripode_Apoyo[k]]+alfa)+delta_y_S0*cos(phi[Tripode_Apoyo[k]]+alfa); PisadaProxima_x=posicionActualPataSistemaPata_x[Tripode_Apoyo[k]] + delta_x; PisadaProxima_y=posicionActualPataSistemaPata_y[Tripode_Apoyo[k]] + delta_y; PisadaProxima_z=posicionActualPataSistemaPata_z[Tripode_Apoyo[k]]; //-- Verificamos que pisada sea factible srv_Cinversa1.request.x = PisadaProxima_x; srv_Cinversa1.request.y = PisadaProxima_y; srv_Cinversa1.request.z = PisadaProxima_z; if (client_Cinversa1.call(srv_Cinversa1)){ //-- Funciona servicio cinversaOK=true; } else { ROS_ERROR("server_PlanificadorPisada: servicio de Cinversa no funciona\n"); cinversaOK=false; } if (cinversaOK){ ros::spinOnce(); //-- Calculamos proximo movimiento en el sistema mundo transformacion_yxTOij(p_ij, posicionActualPata_y[Tripode_Apoyo[k]], posicionActualPata_x[Tripode_Apoyo[k]]); PisadaActual_i = ij[0]; PisadaActual_j = ij[1]; PisadaProxima_y=posicionActualPata_y[Tripode_Apoyo[k]] + (lambda_Correccion+velocidadCuerpo_y*(1-beta)*T_Correccion)*cos((teta_CuerpoRobot-teta_Offset)+alfa); PisadaProxima_x=posicionActualPata_x[Tripode_Apoyo[k]] + (lambda_Correccion+velocidadCuerpo_y*(1-beta)*T_Correccion)*sin((teta_CuerpoRobot-teta_Offset)+alfa); transformacion_yxTOij(p_ij, PisadaProxima_y, PisadaProxima_x); PisadaProxima_i=ij[0]; PisadaProxima_j=ij[1]; PisadaInvalida[k] = false; if(matrizMapa[PisadaProxima_i][PisadaProxima_j]){ //-- La pisada COINCIDE con obstaculo ROS_WARN("server_PlanificadorPisada: pata [%d] coincide con obstaculo [%d][%d]",Tripode_Apoyo[k]+1,PisadaProxima_i,PisadaProxima_j); fprintf(fp2,"tiempo de simulacion: %.3f\n",simulationTime); fprintf(fp2,"pata [%d] coincide con obstaculo [%d][%d]\n",Tripode_Apoyo[k]+1,PisadaProxima_i,PisadaProxima_j); PisadaInvalida[k] = true; TodasPisadasOk = false; break; } if(!PisadaInvalida[k]){ //-- Todo salio bien! Esta proxima_pisada es valida! :D modificacion_lambda[k] = lambda_Correccion; //-- Pisada corregida infoMapa.coordenadaAjuste_i[Tripode_Apoyo[k]] = PisadaProxima_i; infoMapa.coordenadaAjuste_j[Tripode_Apoyo[k]] = PisadaProxima_j; infoMapa.coordenadaPreAjuste_i[Tripode_Apoyo[k]] = PisadaActual_i; infoMapa.coordenadaPreAjuste_j[Tripode_Apoyo[k]] = PisadaActual_j; } } else { //-- La pisada no es factible ROS_ERROR("server_PlanificadorPisada: pata [%d] error cinversa",Tripode_Apoyo[k]+1); fprintf(fp2,"tiempo de simulacion: %.3f\n",simulationTime); fprintf(fp2,"pata [%d] error cinversa\n",Tripode_Apoyo[k]+1); PisadaInvalida[k] = true; TodasPisadasOk = false; } }// Fin if(pisadaInvalida) } // Fin de for } // Fin while ciclos && !TodasPisadasOk //-- Si hay alguna pisada invalida detengo la planificacion for(int k=0;k<Npatas/2;k++) { if(PisadaInvalida[k]){ ROS_ERROR("server_PlanificadorPisada: No se pudo corregir pisada pata[%d]",Tripode_Apoyo[k]+1); fprintf(fp2,"tiempo de simulacion: %.3f\n",simulationTime); fprintf(fp2,"No se pudo corregir pisada pata[%d]\n",Tripode_Apoyo[k]+1); senales.Stop=true; chatter_pub1.publish(senales); // fclose(fp2); ROS_INFO("Adios_server_PlanificadorPisada!"); // ros::shutdown(); // res.result = -1; // return -1; } } //-- Escojo el largo de pisada mas corto y lo impongo a todas las patas del tripode // ROS_INFO("server_Plan: final PlanificadorPisada"); std::sort (modificacion_lambda, modificacion_lambda+3); if(modificacion_lambda[0]<lambda_minimo){ res.modificacion_lambda = lambda_minimo; } else { res.modificacion_lambda = modificacion_lambda[0]; } res.modificacion_T = res.modificacion_lambda/(beta*velocidad_Apoyo); //-- Envio trayectoria planificada D: chanchanchaaaaaan // ROS_INFO("server_PlanificadorPisada: Tripode=%d, landa_correccion=%.3f, T_correccion=%.3f",req.Tripode,res.modificacion_lambda,res.modificacion_T); //-- Envio datos de planificacion al mapa fprintf(fp2,"\ntiempo de simulacion: %.3f\n",simulationTime); fprintf(fp2,"server_PlanificadorPisada: Tripode=%d, landa_correccion=%.3f, T_correccion=%.3f",req.Tripode,res.modificacion_lambda,res.modificacion_T); // fprintf(fp2,"Envio datos de mapa"); chatter_pub2.publish(infoMapa); return 1; } int main(int argc, char **argv) { int Narg=0, cuentaObs=0; std::string fileName; Narg=20; if (argc>=Narg) { beta = atof(argv[1]); velocidad_Apoyo = atof(argv[2]); alfa = atof(argv[3])*pi/180.0; fileName = argv[4]; nCeldas_i = atoi(argv[5]); nCeldas_j = atoi(argv[6]); LongitudCeldaY = atof(argv[7]); LongitudCeldaX = atof(argv[8]); for(int k=0;k<Npatas;k++) phi[k] = atof(argv[9+k])*pi/180.0; for(int k=0;k<Npatas;k++) tripode[k] = atoi(argv[9+Npatas+k]); } else{ ROS_ERROR("server_PlanificadorPisada: Indique argumentos completos!\n"); return (0); } /*Inicio nodo de ROS*/ ros::init(argc, argv, "server_PlanificadorPisada"); ros::NodeHandle node; ROS_INFO("server_PlanificadorPisada just started\n"); //-- Topicos susbcritos y publicados chatter_pub1=node.advertise<camina4::SenalesCambios>("Senal", 100); chatter_pub2=node.advertise<camina4::InfoMapa>("Plan", 100); ros::Subscriber sub1=node.subscribe("/vrep/info",100,infoCallback); ros::Subscriber sub2=node.subscribe("UbicacionRobot",100,ubicacionRobCallback); //-- Clientes y Servicios ros::ServiceServer service = node.advertiseService("PlanificadorPisada", PlanificadorPisada); client_Cinversa1=node.serviceClient<camina4::CinversaParametros>("Cinversa"); /* Log de planificador */ fp2 = fopen("../fuerte_workspace/sandbox/TesisMaureen/ROS/camina4/datos/LogPlanificador.txt","w+"); for(int k=0;k<Npatas;k++) { infoMapa.coordenadaPreAjuste_i.push_back(0); infoMapa.coordenadaPreAjuste_j.push_back(0); infoMapa.coordenadaAjuste_i.push_back(0); infoMapa.coordenadaAjuste_j.push_back(0); } //-- Patas de [0-5] int cuenta_T1=0, cuenta_T2=0; for(int k=0;k<Npatas;k++) { if(tripode[k]==1){ Tripode1[cuenta_T1]=k; cuenta_T1++; } else { Tripode2[cuenta_T2]=k; cuenta_T2++; } } Limpiar_matrizMapa(); cuentaObs = Construye_matrizMapa(fileName); // print_matrizMapa(nCeldas_i,nCeldas_j); // ROS_INFO("Nobstaculos=%d",cuentaObs); // ROS_INFO("variables de mapa: Ni=%d,Nj=%d,LY=%.3f,LX=%.3f",nCeldas_i,nCeldas_j,LongitudCeldaY,LongitudCeldaX); ROS_INFO("server_PlanificadorPisada: Tripode1[%d,%d,%d] - Tripode2[%d,%d,%d]",Tripode1[0]+1,Tripode1[1]+1,Tripode1[2]+1,Tripode2[0]+1,Tripode2[1]+1,Tripode2[2]+1); while (ros::ok() && simulationRunning){ ros::spinOnce(); } fclose(fp2); ROS_INFO("Adios_server_PlanificadorPisada!"); ros::shutdown(); return 0; } /*En matriz de mapa las coordenadas van de i=[0,99], j=[0,19] */ void transformacion_yxTOij(int *ptr_ij, float y, float x){ ptr_ij[0] = (int) (nCeldas_i/2 - floor(y/LongitudCeldaY)-1); ptr_ij[1] = (int) (nCeldas_j/2 + floor(x/LongitudCeldaX)); } void Limpiar_matrizMapa(){ int i=0, j=0; for(i=0;i<nCeldas_i;i++){ for(j=0;j<nCeldas_j;j++){ matrizMapa[i][j]=false; } } } int Construye_matrizMapa(std::string fileName){ //--- Construccion de mapa mediante lectura de archivo // printf ("%s \n", fileName.c_str()); FILE *fp; int int_aux=0, i=0, j=0, cuentaObs=0; fp = fopen(fileName.c_str(), "r"); if(fp!=NULL){ printf("\n"); for(i=0;i<nCeldas_i;i++){ for(j=0;j<nCeldas_j;j++){ fscanf(fp, "%d", &int_aux); if (int_aux==0) matrizMapa[i][j]=false; if (int_aux==1) { matrizMapa[i][j]=true; cuentaObs++; // ROS_INFO("obstaculo_i: %d",i); } } } // printf("Mapa inicial\n"); // print_matrizMapa(nCeldas_i,nCeldas_j); } fclose(fp); return (cuentaObs); } void print_matrizMapa(){ printf("\n"); for(int i=0;i<nCeldas_i;i++){ for(int j=0;j<nCeldas_j;j++){ if (matrizMapa[i][j]){ printf ("o."); } else { printf("-."); } } printf("\n"); } }
#pragma once #include <vector> #include "Edge.h" class GameStatus { public: int stage, score, cont_stage; int ini_score; bool isPlay; int max_Edges; std::vector<Edge*> edges; GameStatus(); };
#include<bits/stdc++.h> using namespace std; stack<bool> sta; char ch; int main() { scanf("%c", &ch); if (ch == ')') { printf("NO\n"); return 0; } while (ch != '@') { if (ch == '(') sta.push(true); if (ch == ')') { if (sta.empty()) { printf("NO\n"); return 0; } sta.pop(); } scanf("%c", &ch); } if (sta.empty()) printf("YES\n"); else printf("NO\n"); return 0; }
#include <bits/stdc++.h> using namespace std; const int MAX_INT = std::numeric_limits<int>::max(); const int MIN_INT = std::numeric_limits<int>::min(); const int INF = 1000000000; const int NEG_INF = -1000000000; #define max(a,b)(a>b?a:b) #define min(a,b)(a<b?a:b) #define MEM(arr,val)memset(arr,val, sizeof arr) #define PI acos(0)*2.0 #define eps 1.0e-9 #define are_equal(a,b)fabs(a-b)<eps #define LS(b)(b& (-b)) // Least significant bit #define DEG_to_RAD(a)((a*PI)/180.0) // convert to radians typedef long long ll; typedef pair<int,int> ii; typedef pair<int,char> ic; typedef pair<long,char> lc; typedef vector<int> vi; typedef vector<ii> vii; int gcd(int a,int b){return b == 0 ? a : gcd(b,a%b);} int lcm(int a,int b){return a*(b/gcd(a,b));} ll _sieve_size; bitset<10000010> bs; vi primes; void sieve(ll upperbound){ _sieve_size = upperbound + 1; bs.set(); bs[0] = bs[1] = 0; for (ll i = 2; i <= _sieve_size; i++) if (bs[i]){ for (ll j = i * i; j <= _sieve_size; j+=i) bs[j] = 0; primes.push_back((int)i); } } vi primeFactors(ll N) { vi factors; ll PF_idx = 0, PF = primes[PF_idx]; while (PF * PF <= N){ while (N % PF == 0){ N /= PF; factors.push_back(PF); } PF = primes[++PF_idx]; } if (N != 1) factors.push_back(N); return factors; } int main(){ sieve(1000000); vi r = primeFactors(2147483647); for (vi::iterator i = r.begin(); i != r.end(); i++) printf("> %d\n", *i); r = primeFactors(136117223861LL); for (vi::iterator i = r.begin(); i != r.end(); i++) printf("> %d\n", *i); r = primeFactors(142391208960LL); for (vi::iterator i = r.begin(); i != r.end(); i++) printf("> %d\n", *i); }
#ifndef KEYWORD_SUGGESTION_SERVER_INCLUDE_ONLINE_THREAD_H_ #define KEYWORD_SUGGESTION_SERVER_INCLUDE_ONLINE_THREAD_H_ #include <pthread.h> #include <functional> #include <string> #include "noncopyable.h" namespace keyword_suggestion { namespace current_thread { extern __thread const char *name; } class Thread : public Noncopyable { public: using ThreadCallback = std::function<void()>; Thread(ThreadCallback &&callback, const std::string &name = std::string()); ~Thread(); void Start(); void Join(); pthread_t thread_id() const { return thread_id_; } std::string name() const { return name_; } private: static void *ThreadFunction(void *arg); pthread_t thread_id_; bool is_running_; ThreadCallback callback_; std::string name_; }; } // namespace keyword_suggestion #endif
/* * F1FrameGrabManager.cpp * * Created on: Dec 4, 2018 * Author: ttw2xk */ #include "f1_datalogger/image_logging/f1_framegrab_manager.h" #include "f1_datalogger/image_logging/utils/opencv_utils.h" //#include "image_logging/utils/screencapture_lite_utils.h" #include <algorithm> #include <iostream> namespace scl = SL::Screen_Capture; namespace deepf1 { scl::Window findWindow(const std::string& search_string) { std::string srchterm(search_string); // convert to lower case for easier comparisons std::transform(srchterm.begin(), srchterm.end(), srchterm.begin(), ::tolower); std::vector<scl::Window> filtereditems; std::vector<scl::Window> windows = SL::Screen_Capture::GetWindows(); // @suppress("Function cannot be resolved") for (unsigned int i = 0; i < windows.size(); i++) { scl::Window a = windows[i]; std::string name = a.Name; //std::cout << name << std::endl; std::transform(name.begin(), name.end(), name.begin(), ::tolower); if (name.find(srchterm) != std::string::npos) { filtereditems.push_back(a); } } for (int i = 0; i < filtereditems.size(); i++) { scl::Window a = filtereditems[i]; std::string name(&(a.Name[0])); std::cout<<"Enter " << i << " for " << name << std::endl; } std::string input; std::cin >> input; int selected_index; scl::Window selected_window; try { selected_index = std::atoi( (const char*) input.c_str() ); selected_window = filtereditems.at(selected_index); } catch (std::out_of_range &oor) { std::stringstream ss; ss << "Selected index (" << selected_index << ") is >= than the number of windows" << std::endl; ss << "Underlying exception message: " << std::endl << std::string(oor.what()) << std::endl; std::runtime_error ex(ss.str().c_str()); throw ex; } catch (std::runtime_error &e) { std::stringstream ss; ss << "Could not grab selected window " << selected_index << std::endl; ss << "Underlying exception message " << std::string(e.what()) << std::endl; std::runtime_error ex(ss.str().c_str()); throw ex; } return selected_window; } F1FrameGrabManager::F1FrameGrabManager(std::shared_ptr<std::chrono::high_resolution_clock> clock, std::shared_ptr<IF1FrameGrabHandler> capture_handler, const std::string& search_string) { capture_handler_ = capture_handler; clock_ = clock; std::cout << "Looking for an application with the search string " << search_string << std::endl; window_ = findWindow(search_string); capture_config_ = scl::CreateCaptureConfiguration( (scl::WindowCallback)std::bind(&F1FrameGrabManager::get_windows_, this)); capture_config_->onNewFrame((scl::WindowCaptureCallback)std::bind(&F1FrameGrabManager::onNewFrame_, this, std::placeholders::_1, std::placeholders::_2)); } F1FrameGrabManager::~F1FrameGrabManager() { stop(); } std::vector<scl::Window> F1FrameGrabManager::get_windows_() { return std::vector<scl::Window> {window_}; } void F1FrameGrabManager::onNewFrame_(const scl::Image &img, const scl::Window &monitor) { if(capture_handler_->isReady()) { TimestampedImageData timestamped_image; timestamped_image.image = deepf1::OpenCVUtils::toCV(img); timestamped_image.timestamp = clock_->now(); capture_handler_->handleData(timestamped_image); } } void F1FrameGrabManager::stop() { capture_manager_.reset(); capture_config_.reset(); } void F1FrameGrabManager::start(double capture_frequency) { capture_manager_ = capture_config_->start_capturing(); unsigned int ms = (unsigned int)(std::round(((double)1E3)/capture_frequency)); capture_manager_->setFrameChangeInterval(std::chrono::milliseconds(ms)); } } /* namespace deepf1 */
/*! * \file KaiXinApp_StatusFaceList.cpp * \author GoZone * \date * \brief 解析与UI: 获取用户状态列表 * * \ref CopyRight * =======================================================================<br> * Copyright ? 2010-2012 GOZONE <br> * All Rights Reserved.<br> * The file is generated by Kaixin_Component Wizard for Tranzda Mobile Platform <br> * =======================================================================<br> */ #include "KaiXinAPICommon.h" void* KaiXinAPI_StatusFaceList_JsonParse(char *text) { cJSON *json; cJSON *pTemp0; tResponseStatusFaceList* Response = new tResponseStatusFaceList; memset(Response, 0 , sizeof(tResponseStatusFaceList)); json = cJSON_Parse(text); pTemp0 = cJSON_GetObjectItem(json,"ret"); if (pTemp0) { Response->ret = pTemp0->valueint; } //Success if(Response->ret == 1) { pTemp0 = cJSON_GetObjectItem(json, "uid"); if(pTemp0) { Response->uid = pTemp0->valueint; } pTemp0 = cJSON_GetObjectItem(json, "faces"); if(pTemp0) { int nSize1 = 0, i = 0; nSize1 = cJSON_GetArraySize(pTemp0); Response->nSize_faces = nSize1; if( nSize1 != 0 ) { Response->faces = NULL; Response->faces = (StatusFaceList_faces*) malloc(sizeof( StatusFaceList_faces ) * nSize1 ); memset(Response->faces, 0 , sizeof(StatusFaceList_faces) * nSize1 ); } for ( i = 0; i < nSize1; i++ ) { cJSON *Item1 = NULL, *pTemp1 = NULL; Item1 = cJSON_GetArrayItem(pTemp0,i); pTemp1 = cJSON_GetObjectItem(Item1, "sface"); if(pTemp1) { Response->faces[i].sface = pTemp1->valueint; } pTemp1 = cJSON_GetObjectItem(Item1, "slogo"); if(pTemp1) { STRCPY_Ex(Response->faces[i].slogo, pTemp1->valuestring); } pTemp1 = cJSON_GetObjectItem(Item1, "ntype"); if(pTemp1) { Response->faces[i].ntype = pTemp1->valueint; } } } } //Failue else { //pTemp0 = cJSON_GetObjectItem(json,"msg"); //if (pTemp0) //{ // strcpy(Response->msg, pTemp0 ->valuestring); //} } cJSON_Delete(json); return Response; } // 构造函数 TStatusFaceListForm::TStatusFaceListForm(TApplication* pApp):TWindow(pApp) { //Create(APP_KA_ID_KaiXinHomePage); } // 析构函数 TStatusFaceListForm::~TStatusFaceListForm(void) { } // 窗口事件处理 Boolean TStatusFaceListForm::EventHandler(TApplication * pApp, EventType * pEvent) { Boolean bHandled = FALSE; switch (pEvent->eType) { case EVENT_WinInit: { _OnWinInitEvent(pApp, pEvent); bHandled = TRUE; break; } case EVENT_WinClose: { _OnWinClose(pApp, pEvent); break; } case EVENT_WinEraseClient: { TDC dc(this); WinEraseClientEventType *pEraseEvent = reinterpret_cast< WinEraseClientEventType* >( pEvent ); TRectangle rc(pEraseEvent->rc); TRectangle rcBack(5, 142, 310, 314); this->GetBounds(&rcBack); // 擦除 dc.EraseRectangle(&rc, 0); dc.DrawBitmapsH(TResource::LoadConstBitmap(APP_KA_ID_BITMAP_title_bg), 0, 0, SCR_W, GUI_API_STYLE_ALIGNMENT_LEFT); //dc.DrawBitmapsH(TResource::LoadConstBitmap(APP_KA_ID_BITMAP_bottom_bg), 0, rcBack.Bottom()-68, //320, GUI_API_STYLE_ALIGNMENT_LEFT|GUI_API_STYLE_ALIGNMENT_TOP); pEraseEvent->result = 1; bHandled = TRUE; } break; case EVENT_CtrlSelect: { bHandled = _OnCtrlSelectEvent(pApp, pEvent); break; } default: break; } if (!bHandled) { bHandled = TWindow::EventHandler(pApp, pEvent); } return bHandled; } // 窗口初始化 Boolean TStatusFaceListForm::_OnWinInitEvent(TApplication * pApp, EventType * pEvent) { return TRUE; } // 关闭窗口时,保存设置信息 Boolean TStatusFaceListForm::_OnWinClose(TApplication * pApp, EventType * pEvent) { return TRUE; } // 控件点击事件处理 Boolean TStatusFaceListForm::_OnCtrlSelectEvent(TApplication * pApp, EventType * pEvent) { Boolean bHandled; bHandled = FALSE; switch(pEvent->sParam1) { case 0: { break; } default: break; } return bHandled; }
#include "buff.h" Buff::Buff() { } Buff::Buff(BattleController* battleController, uint8 idBuff, uint8 owner, uint8 carrier) { _params.battleController = battleController; _params.owner = owner; _params.carrier = carrier; init(idBuff); } Buff::~Buff() { } bool Buff::isActive() const { return _params.settings & Settings::IsActive; } void Buff::action(const Signal signalType, SignalStruct& signalStruct) { if (!isActive()) return; if (signalType == Signal::Death && signalStruct.idOwner == _params.carrier) setInActive(); if (signalType == Signal::BeforeGloabalTick) if (_params.time-- <= 0) setInActive(); if (!isSubscribe(signalType)) return; activateString(false); } bool Buff::dispel(uint8 level) { if (!isActive()) return false; if (auto neededDispelLevel = getNeededDispelLevel()) { if (level >= neededDispelLevel) { setInActive(); actionAfterDead(); return true; } } return false; } const Buff::Params& Buff::getParams() const { return _params; } void Buff::init(uint8 id) { if (!idIsValid(id)) return; //TODO: загрузка из бд/контроллера парамметров баффа } void Buff::actionAfterDead() { if (!isActive()) return; activateString(false); } bool Buff::isSubscribe(const Signal signalType) const { return _params.subscribes | signalType; } uint8 Buff::getNeededDispelLevel() const { return _params.settings >> 2 & 0x3; } void Buff::setInActive() { _params.settings |= Settings::IsActive; }
/*********************************************************************** created: Tue Mar 7 2006 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #ifndef _CEGUIDynamicModule_h_ #define _CEGUIDynamicModule_h_ #include "CEGUI/Base.h" #include "CEGUI/String.h" #if defined(__WIN32__) || defined(_WIN32) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #ifndef NOMINMAX #define NOMINMAX #endif #include <windows.h> #endif namespace CEGUI { #if defined(__WIN32__) || defined(_WIN32) typedef HMODULE DYNLIB_HANDLE; typedef PROC ModuleFuncHandle; #elif defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__) || \ defined(__CYGWIN__) typedef void* DYNLIB_HANDLE; typedef void* ModuleFuncHandle; #endif /*! \brief Class that wraps and gives access to a dynamically linked module (.dll, .so, etc...) */ class CEGUIEXPORT DynamicModule { public: /*! \brief Construct the DynamicModule object by loading the dynamic loadable module specified. \param name String object holding the name of a loadable module. */ DynamicModule(const String& name); /*! \brief Destroys the DynamicModule object and unloads the associated loadable module. */ ~DynamicModule(); /*! \brief Return a String containing the name of the dynamic module. */ const String& getModuleName() const; /*! \brief Return the address of the specified symbol. \param symbol String holding the symbol to look up in the module. \return Pointer to the requested symbol. \exception InvalidRequestException thrown if the symbol does not exist. */ ModuleFuncHandle getSymbolAddress(const String& symbol) const; private: struct Impl; Impl* d_pimpl; }; } #endif
/******************************************************************************* * include/generators/barabassi/barabassi.h * * Copyright (C) 2016-2017 Christian Schulz <christian.schulz@ira.uka.de> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #ifndef _BARABASSI_H_ #define _BARABASSI_H_ #include <iostream> #include <vector> #include "definitions.h" #include "generator_config.h" #include "generator_io.h" #include "hash.hpp" namespace kagen { template <typename EdgeCallback> class Barabassi { public: Barabassi(PGeneratorConfig &config, const PEID rank, const EdgeCallback &cb) : config_(config), rank_(rank), io_(config), cb_(cb), min_degree_(config_.min_degree), total_degree_(2 * config_.min_degree) { PEID size; MPI_Comm_size(MPI_COMM_WORLD, &size); // Init variables from_ = rank * ceil(config_.n / (LPFloat)size); to_ = std::min((SInt)((rank + 1) * ceil(config_.n / (LPFloat)size) - 1), config_.n - 1); std::cout << "f " << from_ << " t " << to_ << std::endl; } void Generate() { GenerateEdges(); // Additional stats if (rank_ == ROOT) { HPFloat terra_bytes = 128 * config_.n * min_degree_; terra_bytes /= (8); terra_bytes /= (1024); terra_bytes /= (1024); terra_bytes /= (1024); terra_bytes /= (1024); std::cout << "memory of graph in tera bytes " << std::setprecision(40) << terra_bytes << std::endl; } } void Output() const { #ifdef OUTPUT_EDGES io_.OutputEdges(); #else io_.OutputDist(); #endif } std::pair<SInt, SInt> GetVertexRange() { return std::make_pair(from_, to_); } SInt NumberOfEdges() const { return io_.NumEdges(); } private: // Config PGeneratorConfig &config_; PEID rank_; // I/O GeneratorIO<> io_; EdgeCallback cb_; // Constants and variables SInt min_degree_; SInt total_degree_; SInt from_, to_; void GenerateEdges() { for (SInt v = from_; v <= to_; v++) { for (SInt i = 0; i < min_degree_; i++) { SInt r = 2 * (v * min_degree_ + i) + 1; do { // compute hash h(r) SInt hash = sampling::Spooky::hash(config_.seed + r); r = hash % r; } while (r % 2 == 1); SInt w = r / total_degree_; cb_(v, w); #ifdef OUTPUT_EDGES io_.PushEdge(v, w); #else io_.UpdateDist(v); #endif } } }; }; } #endif
#include <windows.h> #include <iomanip> #include <iostream> void main() { setlocale(LC_CTYPE, "Russian"); using namespace std; char c, probel; probel = ' '; long long x = 1, y = 20; cout << "Введите символ "; cin >> c; cout << setw(y) << setfill(probel) << probel; cout << setw(x) << setfill(c) << c << endl; cout << setw(y -= 1) << setfill(probel) << probel; cout << setw(x += 2) << setfill(c) << c << endl; cout << setw(y -= 2) << setfill(probel) << probel; cout << setw(x += 4) << setfill(c) << c << endl; cout << setw(y -= 2) << setfill(probel) << probel; cout << setw(x += 4) << setfill(c) << c << endl; cout << setw(y -= 2) << setfill(probel) << probel; cout << setw(x += 4) << setfill(c) << c << endl; cout << setw(y -= 2) << setfill(probel) << probel; cout << setw(x += 4) << setfill(c) << c << endl; cout << setw(y -= 2) << setfill(probel) << probel; cout << setw(x += 4) << setfill(c) << c << endl; cout << setw(y=19) << setfill(probel) << probel; cout << setw(x=3) << setfill(c) << c << endl; cout << setw(y -= 2) << setfill(probel) << probel; cout << setw(x += 4) << setfill(c) << c << endl; cout << setw(y -= 2) << setfill(probel) << probel; cout << setw(x += 4) << setfill(c) << c << endl; cout << setw(y -= 2) << setfill(probel) << probel; cout << setw(x += 4) << setfill(c) << c << endl; cout << setw(y -= 2) << setfill(probel) << probel; cout << setw(x += 4) << setfill(c) << c << endl; cout << setw(y -= 2) << setfill(probel) << probel; cout << setw(x += 4) << setfill(c) << c << endl; cout << setw(y = 19) << setfill(probel) << probel; cout << setw(x = 3) << setfill(c) << c << endl; cout << setw(y -= 2) << setfill(probel) << probel; cout << setw(x += 4) << setfill(c) << c << endl; cout << setw(y -= 2) << setfill(probel) << probel; cout << setw(x += 4) << setfill(c) << c << endl; cout << setw(y -= 2) << setfill(probel) << probel; cout << setw(x += 4) << setfill(c) << c << endl; cout << setw(y -= 2) << setfill(probel) << probel; cout << setw(x += 4) << setfill(c) << c << endl; cout << setw(y -= 2) << setfill(probel) << probel; cout << setw(x += 4) << setfill(c) << c << endl; cout << setw(y = 19) << setfill(probel) << probel; cout << setw(x = 3) << setfill(c) << c << endl; cout << setw(y = 19) << setfill(probel) << probel; cout << setw(x = 3) << setfill(c) << c << endl; cout << setw(y = 19) << setfill(probel) << probel; cout << setw(x = 3) << setfill(c) << c << endl; cout << setw(y = 19) << setfill(probel) << probel; cout << setw(x = 3) << setfill(c) << c << endl; }
#include "BitSet.h" #include <iostream> BitSet::BitSet() { this->bitSetSize = 0; } BitSet::BitSet(int initialSize) { this->bitSetSize = 0; this->array.push_back(0); for (int i = 0; i < initialSize; i++) this->push_back(false); } unsigned int BitSet::getBlock(unsigned int x) const { return x >> BITSET_SIZE_LOG; } unsigned int BitSet::getRem(unsigned int x) const { return x & ((1 << BITSET_SIZE_LOG) - 1); } bool BitSet::at(unsigned int i) const { unsigned int blk = this->getBlock(i); unsigned int pos = this->getRem(i); return this->array[blk] & (1 << pos); } void BitSet::set(bool x, unsigned int i) { unsigned int blk = this->getBlock(i); unsigned int pos = this->getRem(i); this->array[blk] |= (1 << pos); if (x == false) this->array[blk] ^= (1 << pos); } void BitSet::push_back(bool value) { if (this->getRem(this->bitSetSize) == 0) { this->array.push_back(0); if (this->array.size() != this->array.capacity()) this->array.shrink_to_fit(); } this->set(value, this->bitSetSize); this->bitSetSize++; } void BitSet::pop_back() { this->bitSetSize--; } unsigned int BitSet::size() const { return this->bitSetSize; } void BitSet::print() const { for (unsigned int i = 0; i < this->size(); i++) std::cout << this->at(i) << ' '; std::cout << std::endl; }
#ifndef LIBNDGPP_TYPE_TRAITS_CHAR_NUMERIC_TYPE_HPP #define LIBNDGPP_TYPE_TRAITS_CHAR_NUMERIC_TYPE_HPP namespace ndgpp { /// Type trait class that returns a numeric type suitable for a char template <class T> struct char_numeric_type; template <> struct char_numeric_type<signed char> { using type = signed short; }; template <> struct char_numeric_type<unsigned char> { using type = unsigned short; }; template <> struct char_numeric_type<char> { using type = typename std::conditional<std::is_signed<char>::value, signed short, unsigned short>::type; }; } #endif
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include "beventure.h" int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine; Beventure beventure (NULL, &engine); // Initialize engine.load(QUrl(QStringLiteral("qrc:///Main.qml"))); QObject* rootObject = engine.rootObjects().first(); QObject::connect(rootObject->findChild<QObject*>("addAnswer"), SIGNAL(myClicked(QString)), &beventure, SLOT(addAnswer(QString))); QObject::connect(rootObject->findChild<QObject*>("clearAnswer"), SIGNAL(clicked()), &beventure, SLOT(clear())); QObject::connect(rootObject->findChild<QObject*>("bestChoiceBtn"), SIGNAL(clicked()), &beventure, SLOT(bestAnswer())); return app.exec(); }
/* NO WARRANTY * * BECAUSE THE PROGRAM IS IN THE PUBLIC DOMAIN, THERE IS NO * WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE * LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE AUTHORS * AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT * WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO * THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD * THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL * NECESSARY SERVICING, REPAIR OR CORRECTION. * * IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN * WRITING WILL ANY AUTHOR, OR ANY OTHER PARTY WHO MAY MODIFY * AND/OR REDISTRIBUTE THE PROGRAM, BE LIABLE TO YOU FOR DAMAGES, * INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL * DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM * (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING * RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES * OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER * PROGRAMS), EVEN IF SUCH AUTHOR OR OTHER PARTY HAS BEEN ADVISED * OF THE POSSIBILITY OF SUCH DAMAGES. */ #include <stdio.h> #include <iostream> #include <string.h> #include <iomanip> #include "stdafx.h" #include "Autofont.h" #include "Context.h" CWinApp theApp; #define LINKAGE __declspec(dllexport) //---------------------------------------------------------------------------- int Context::doConfigure(HWND view, char* param){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); // 0 => display the generic DigitalSimulator Dialog // 1 => no display neccessary.....display your own dialog in this function return 0; } // return the min/max of possible input pins // //---------------------------------------------------------------------------- CSize Context::getInputCountRange(){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); // BEGIN_TODO // return CSize(3,3); // END_TODO }; // return the min/max of the possible output pins // //---------------------------------------------------------------------------- CSize Context::getOutputCountRange(){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); // BEGIN_TODO // return CSize(10,10); // END_TODO }; // Return the dimension of the object. // This is required for the DragDrap actions and painting // //---------------------------------------------------------------------------- CSize Context::getSize(long inputCount, long outputCount){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); // BEGIN_TODO // return CSize(200,70*max(outputCount,inputCount)); // END_TODO }; // Return the bytes of additional persistent memory. This memory array will // be saved/loaded with the object itself // //---------------------------------------------------------------------------- long Context::getParamCount(){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); // BEGIN_TODO // return 1; // END_TODO } // Return a short description of this object // //---------------------------------------------------------------------------- char* Context::getDescription(){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); // BEGIN_TODO // return "I am only a template object......\r\n\r\n" "and I do nothing."; // END_TODO } // Return the name of the group in which this object will // be insert (see in extended dialog) // //---------------------------------------------------------------------------- char* Context::getGroup(){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); // BEGIN_TODO // return "Sonstiges"; // END_TODO } // Unique key for the internal hash map // //---------------------------------------------------------------------------- char* Context::getKey(){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); // BEGIN_TODO // return "template object"; // END_TODO } // Display name of this object // //---------------------------------------------------------------------------- char* Context::getName(){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); // BEGIN_TODO // return "template object"; // END_TODO } // .....****... // //---------------------------------------------------------------------------- char * Context::getProgrammerName(){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); // BEGIN_TODO // return "Andreas Herz"; // END_TODO } // .....****... // //---------------------------------------------------------------------------- char * Context::getProgrammerURL(){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); // BEGIN_TODO // return "http://www.FreeGroup.de"; // END_TODO } // .....****... // //---------------------------------------------------------------------------- char * Context::getProgrammerMail(){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); // BEGIN_TODO // return "A.Herz@FreeGroup.de"; // END_TODO } // Version of this DLL/PlugIn // //---------------------------------------------------------------------------- char * Context::getVersion(){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); // BEGIN_TODO // return "0.3"; // END_TODO } // unused at this moment // //---------------------------------------------------------------------------- char * Context::getLabel(){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); // BEGIN_TODO // return "unused"; // END_TODO } // called befor the simulation starts. This is usefull to allocate/block // some resources (like COM-Ports or somthing else) // //---------------------------------------------------------------------------- void Context::onStartCalculate(char* param){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); // BEGIN_TODO // // END_TODO } // Called after the simulation has stoped // Release the resources which are allocated in onStartCalculation(...) // //---------------------------------------------------------------------------- void Context::onStopCalculate(char* param){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); // BEGIN_TODO // // END_TODO } // Initial call of a new object. You can init your additial memory // (see on getPAramCount() ) // //---------------------------------------------------------------------------- void Context::initParam(char* param){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); // BEGIN_TODO // // END_TODO } // If you have stored some pointers in this memory array is this the time // to release them. DON'T delete 'param' this will done by the framework // //---------------------------------------------------------------------------- void Context::cleanupParam(char* param){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); // BEGIN_TODO // // END_TODO } // calculate your output values // //---------------------------------------------------------------------------- int Context::calculate(char *input ,char* lastInput,long inputCount, char* output, long outputCount, char* param){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); CSize s = getInputCountRange(); if( inputCount<s.cx || inputCount>s.cy ) return 0; // BEGIN_TODO // return 0; // if no redraw of the object are necessary //return 1; // if a redraw of the object necessary return 1 // END_TODO } // layout our output pins // the left/top point of the object is 0/0 // x increases to the left // y decreases to the bottom // //---------------------------------------------------------------------------- void Context::layoutOutput(long* xPositions, long* yPositions, long inputCount, long outputCount, char* param){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); float yBegin; float yOffset; int loop; CSize size = getSize(inputCount, outputCount) // BEGIN_TODO // yOffset = size.cy/ (outputCount+1); yBegin = yOffset/2; for( loop=0; loop <outputCount; loop++) { int xPos = size.cx; int yPos = yBegin + yOffset*(loop); xPositions[loop] = xPos; yPositions[loop] = -yPos; } // END_TODO } // layout our input pins // the left/top point of the object is 0/0 // x increases to the left // y decreases to the bottom // //---------------------------------------------------------------------------- void Context::layoutInput(long* xPositions, long* yPositions, long inputCount, long outputCount, char* param){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); float yBegin; float yOffset; CSize size = getSize(inputCount, outputCount) // BEGIN_TODO // yOffset = size.cy/ (inputCount+1); yBegin = yOffset/2; for( loop=0; loop <inputCount; loop++) { int xPos = -15; int yPos = yBegin + yOffset*(loop); xPositions[loop] = xPos; yPositions[loop] = -yPos; } // END_TODO } // draw the object to the device context // the left/top point of the object is 0/0 // x increases to the left // y decreases to the bottom // //---------------------------------------------------------------------------- bool Context::paint(CDC* pDC, CPoint location, long inputCount, long outputCount, char* param){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); m_bigFont.SetDC(pDC->m_hDC); m_smallFont.SetDC(pDC->m_hDC); // BEGIN_TODO // long xSize = getSize(inputCount,outputCount).cx; long ySize = getSize(inputCount,outputCount).cy; long yOffsetOut = ySize/outputCount; long yOffsetIn = ySize/inputCount; pDC->SetBkMode(TRANSPARENT); // Rahmen zeichnen // pDC->Rectangle(location.x,location.y,location.x + xSize,location.y- ySize); // ...in den Rahmen die Bezeichnung GND eintragen // CFont*oldFont=pDC->SelectObject(&m_smallFont); pDC->TextOut( location.x+10, location.y-10 ,"XXX"); pDC->SelectObject(oldFont); // return true; // The parent object draw nothing (no ports, .....) // You must handle all the painting here. return false; // the parent object draw additional objects like the ports. // // END_TODO } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // DON'T TOUCH THIS CODE // //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //---------------------------------------------------------------------------- extern "C" bool LINKAGE cf_create_interface(const char *iid,IPluginBase **iface){ //---------------------------------------------------------------------------- *iface = NULL; Context *ptr; try { ptr = new Context; ptr->QueryInterface(iid, iface); ptr->Destroy(); } catch(...){ (*iface ) = NULL; } return (*iface ) != NULL; } //---------------------------------------------------------------------------- Context::Context(void): m_bigFont("Arial"), m_smallFont("Arial") { //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); m_bigFont.SetHeight(BIG_FONT); m_smallFont.SetHeight(SMALL_FONT); m_refCount = 1; } //---------------------------------------------------------------------------- bool Context::QueryInterface(const char *iid, IPluginBase **iface){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); *iface = NULL; if (::strcmp(iid, "IObjectInfo") == 0) *iface = static_cast<IObjectInfo*>(this); else if (::strcmp(iid, "IObjectWorker") == 0) *iface = static_cast<IObjectWorker*>(this); else if (::strcmp(iid, "IObjectContext") == 0) *iface = (IPluginBase*)(IObjectInfo*)this; else if (::strcmp(iid, "IPluginBase") == 0) *iface = static_cast<IObjectInfo*>(this); if (*iface != NULL) m_refCount++; return *iface != NULL; } //---------------------------------------------------------------------------- void Context::Destroy(void){ //---------------------------------------------------------------------------- AFX_MANAGE_STATE(AfxGetStaticModuleState( )); if (--m_refCount == 0){ delete this; } } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
#pragma once #include <frc/WPILib.h> class OI { public: OI(); frc::Joystick& GetJoystick(); frc::Joystick m_joystick{0}; frc::JoystickButton m_button1{&m_joystick, 1}; frc::JoystickButton m_button2{&m_joystick, 2}; frc::JoystickButton m_button3{&m_joystick, 3}; frc::JoystickButton m_button4{&m_joystick, 4}; frc::JoystickButton m_button5{&m_joystick, 5}; frc::JoystickButton m_button6{&m_joystick, 6}; frc::JoystickButton m_button7{&m_joystick, 7}; frc::JoystickButton m_button8{&m_joystick, 8}; frc::JoystickButton m_button9{&m_joystick, 9}; frc::JoystickButton m_button10{&m_joystick, 10}; frc::JoystickButton m_button11{&m_joystick, 11}; frc::JoystickButton m_button12{&m_joystick, 12}; };
//************************************************************************** //** //** See jlquake.txt for copyright info. //** //** This program is free software; you can redistribute it and/or //** modify it under the terms of the GNU General Public License //** as published by the Free Software Foundation; either version 3 //** of the License, or (at your option) any later version. //** //** This program is distributed in the hope that it will be useful, //** but WITHOUT ANY WARRANTY; without even the implied warranty of //** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //** included (gnu.txt) GNU General Public License for more details. //** //************************************************************************** #include "local.h" #include "../../common/Common.h" #include "../../common/common_defs.h" #include "../../common/strings.h" #include "../../common/command_buffer.h" #include "../../client/public.h" #include "../worldsector.h" static int SVQ2_FindIndex( const char* name, int start, int max ) { if ( !name || !name[ 0 ] ) { return 0; } int i; for ( i = 1; i < max && sv.q2_configstrings[ start + i ][ 0 ]; i++ ) { if ( !String::Cmp( sv.q2_configstrings[ start + i ], name ) ) { return i; } } if ( i == max ) { common->Error( "*Index: overflow" ); } String::NCpy( sv.q2_configstrings[ start + i ], name, sizeof ( sv.q2_configstrings[ i ] ) ); if ( sv.state != SS_LOADING ) { // send the update to everyone sv.multicast.Clear(); sv.multicast.WriteChar( q2svc_configstring ); sv.multicast.WriteShort( start + i ); sv.multicast.WriteString2( name ); SVQ2_Multicast( oldvec3_origin, Q2MULTICAST_ALL_R ); } return i; } int SVQ2_ModelIndex( const char* name ) { return SVQ2_FindIndex( name, Q2CS_MODELS, MAX_MODELS_Q2 ); } int SVQ2_SoundIndex( const char* name ) { return SVQ2_FindIndex( name, Q2CS_SOUNDS, MAX_SOUNDS_Q2 ); } int SVQ2_ImageIndex( const char* name ) { return SVQ2_FindIndex( name, Q2CS_IMAGES, MAX_IMAGES_Q2 ); } // Entity baselines are used to compress the update messages // to the clients -- only the fields that differ from the // baseline will be transmitted static void SVQ2_CreateBaseline() { for ( int entnum = 1; entnum < ge->num_edicts; entnum++ ) { q2edict_t* svent = Q2_EDICT_NUM( entnum ); if ( !svent->inuse ) { continue; } if ( !svent->s.modelindex && !svent->s.sound && !svent->s.effects ) { continue; } svent->s.number = entnum; // // take current state as baseline // VectorCopy( svent->s.origin, svent->s.old_origin ); sv.q2_baselines[ entnum ] = svent->s; } } static void SVQ2_CheckForSavegame() { if ( svq2_noreload->value ) { return; } if ( Cvar_VariableValue( "deathmatch" ) ) { return; } char name[ MAX_OSPATH ]; String::Sprintf( name, sizeof ( name ), "save/current/%s.sav", sv.name ); if ( !FS_FileExists( name ) ) { // no savegame return; } SV_ClearWorld(); // get configstrings and areaportals SVQ2_ReadLevelFile(); if ( !sv.loadgame ) { // coming back to a level after being in a different // level, so run it for ten seconds // rlava2 was sending too many lightstyles, and overflowing the // reliable data. temporarily changing the server state to loading // prevents these from being passed down. serverState_t previousState = sv.state; sv.state = SS_LOADING; for ( int i = 0; i < 100; i++ ) { ge->RunFrame(); } sv.state = previousState; } } // Change the server to a new map, taking all connected // clients along with it. static void SVQ2_SpawnServer( const char* server, const char* spawnpoint, serverState_t serverstate, bool attractloop, bool loadgame ) { if ( attractloop ) { Cvar_SetLatched( "paused", "0" ); } common->Printf( "------- Server Initialization -------\n" ); common->DPrintf( "SpawnServer: %s\n",server ); if ( sv.q2_demofile ) { FS_FCloseFile( sv.q2_demofile ); } svs.spawncount++; // any partially connected client will be // restarted sv.state = SS_DEAD; ComQ2_SetServerState( sv.state ); // wipe the entire per-level structure Com_Memset( &sv, 0, sizeof ( sv ) ); svs.realtime = 0; sv.loadgame = loadgame; sv.q2_attractloop = attractloop; // save name for levels that don't set message String::Cpy( sv.q2_configstrings[ Q2CS_NAME ], server ); if ( Cvar_VariableValue( "deathmatch" ) ) { sprintf( sv.q2_configstrings[ Q2CS_AIRACCEL ], "%g", svq2_airaccelerate->value ); pmq2_airaccelerate = svq2_airaccelerate->value; } else { String::Cpy( sv.q2_configstrings[ Q2CS_AIRACCEL ], "0" ); pmq2_airaccelerate = 0; } sv.multicast.InitOOB( sv.multicastBuffer, MAX_MSGLEN_Q2 ); String::Cpy( sv.name, server ); // leave slots at start for clients only for ( int i = 0; i < sv_maxclients->value; i++ ) { // needs to reconnect if ( svs.clients[ i ].state > CS_CONNECTED ) { svs.clients[ i ].state = CS_CONNECTED; } svs.clients[ i ].q2_lastframe = -1; } sv.q2_time = 1000; String::Cpy( sv.name, server ); String::Cpy( sv.q2_configstrings[ Q2CS_NAME ], server ); int checksum; if ( serverstate != SS_GAME ) { CM_LoadMap( "", false, &checksum ); // no real map } else { String::Sprintf( sv.q2_configstrings[ Q2CS_MODELS + 1 ],sizeof ( sv.q2_configstrings[ Q2CS_MODELS + 1 ] ), "maps/%s.bsp", server ); CM_LoadMap( sv.q2_configstrings[ Q2CS_MODELS + 1 ], false, &checksum ); } sv.models[ 1 ] = 0; String::Sprintf( sv.q2_configstrings[ Q2CS_MAPCHECKSUM ],sizeof ( sv.q2_configstrings[ Q2CS_MAPCHECKSUM ] ), "%i", ( unsigned )checksum ); // // clear physics interaction links // SV_ClearWorld(); for ( int i = 1; i < CM_NumInlineModels(); i++ ) { String::Sprintf( sv.q2_configstrings[ Q2CS_MODELS + 1 + i ], sizeof ( sv.q2_configstrings[ Q2CS_MODELS + 1 + i ] ), "*%i", i ); sv.models[ i + 1 ] = CM_InlineModel( i ); } // // spawn the rest of the entities on the map // // precache and static commands can be issued during // map initialization sv.state = SS_LOADING; ComQ2_SetServerState( sv.state ); // load and spawn all other entities ge->SpawnEntities( sv.name, CM_EntityString(), spawnpoint ); // run two frames to allow everything to settle ge->RunFrame(); ge->RunFrame(); // all precaches are complete sv.state = serverstate; ComQ2_SetServerState( sv.state ); // create a baseline for more efficient communications SVQ2_CreateBaseline(); // check for a savegame SVQ2_CheckForSavegame(); // set serverinfo variable Cvar_Get( "mapname", "", CVAR_SERVERINFO | CVAR_INIT ); Cvar_Set( "mapname", sv.name ); common->Printf( "-------------------------------------\n" ); } // A brand new game has been started void SVQ2_InitGame() { int i; q2edict_t* ent; if ( svs.initialized ) { // cause any connected clients to reconnect SVQ2_Shutdown( "Server restarted\n", true ); } else { // make sure the client is down CLQ2_Drop(); SCRQ2_BeginLoadingPlaque( false ); } // get any latched variable changes (maxclients, etc) Cvar_GetLatchedVars(); svs.initialized = true; if ( Cvar_VariableValue( "coop" ) && Cvar_VariableValue( "deathmatch" ) ) { common->Printf( "Deathmatch and Coop both set, disabling Coop\n" ); Cvar_Set( "coop", "0" ); } // dedicated servers are can't be single player and are usually DM // so unless they explicity set coop, force it to deathmatch if ( com_dedicated->value ) { if ( !Cvar_VariableValue( "coop" ) ) { Cvar_Set( "deathmatch", "1" ); } } // init clients if ( Cvar_VariableValue( "deathmatch" ) ) { if ( sv_maxclients->value <= 1 ) { Cvar_Set( "maxclients", "8" ); } else if ( sv_maxclients->value > MAX_CLIENTS_Q2 ) { Cvar_Set( "maxclients", va( "%i", MAX_CLIENTS_Q2 ) ); } } else if ( Cvar_VariableValue( "coop" ) ) { if ( sv_maxclients->value <= 1 || sv_maxclients->value > 4 ) { Cvar_Set( "maxclients", "4" ); } } else { // non-deathmatch, non-coop is one player Cvar_Set( "maxclients", "1" ); } svs.spawncount = rand(); svs.clients = ( client_t* )Mem_ClearedAlloc( sizeof ( client_t ) * sv_maxclients->value ); svs.q2_num_client_entities = sv_maxclients->value * UPDATE_BACKUP_Q2 * 64; svs.q2_client_entities = ( q2entity_state_t* )Mem_ClearedAlloc( sizeof ( q2entity_state_t ) * svs.q2_num_client_entities ); // init network stuff NET_Config( ( sv_maxclients->value > 1 ) ); // heartbeats will always be sent to the id master svs.q2_last_heartbeat = -99999; // send immediately SOCK_StringToAdr( "192.246.40.37", &master_adr[ 0 ], Q2PORT_MASTER ); // init game SVQ2_InitGameProgs(); for ( i = 0; i < sv_maxclients->value; i++ ) { ent = Q2_EDICT_NUM( i + 1 ); ent->s.number = i + 1; svs.clients[ i ].q2_edict = ent; Com_Memset( &svs.clients[ i ].q2_lastUsercmd, 0, sizeof ( svs.clients[ i ].q2_lastUsercmd ) ); } } // the full syntax is: // // map [*]<map>$<startspot>+<nextserver> // // command from the console or progs. // Map can also be a.cin, .pcx, or .dm2 file // Nextserver is used to allow a cinematic to play, then proceed to // another level: // // map tram.cin+jail_e3 void SVQ2_Map( bool attractloop, const char* levelstring, bool loadgame ) { char level[ MAX_QPATH ]; char* ch; int l; char spawnpoint[ MAX_QPATH ]; sv.loadgame = loadgame; sv.q2_attractloop = attractloop; if ( sv.state == SS_DEAD && !sv.loadgame ) { SVQ2_InitGame(); // the game is just starting } String::Cpy( level, levelstring ); // if there is a + in the map, set nextserver to the remainder ch = strstr( level, "+" ); if ( ch ) { *ch = 0; Cvar_SetLatched( "nextserver", va( "gamemap \"%s\"", ch + 1 ) ); } else { Cvar_SetLatched( "nextserver", "" ); } //ZOID special hack for end game screen in coop mode if ( Cvar_VariableValue( "coop" ) && !String::ICmp( level, "victory.pcx" ) ) { Cvar_SetLatched( "nextserver", "gamemap \"*base1\"" ); } // if there is a $, use the remainder as a spawnpoint ch = strstr( level, "$" ); if ( ch ) { *ch = 0; String::Cpy( spawnpoint, ch + 1 ); } else { spawnpoint[ 0 ] = 0; } // skip the end-of-unit flag if necessary if ( level[ 0 ] == '*' ) { memmove( level, level + 1, String::Length( level ) ); } l = String::Length( level ); if ( l > 4 && !String::Cmp( level + l - 4, ".cin" ) ) { SCRQ2_BeginLoadingPlaque( false ); // for local system SVQ2_BroadcastCommand( "changing\n" ); SVQ2_SpawnServer( level, spawnpoint, SS_CINEMATIC, attractloop, loadgame ); } else if ( l > 4 && !String::Cmp( level + l - 4, ".dm2" ) ) { SCRQ2_BeginLoadingPlaque( false ); // for local system SVQ2_BroadcastCommand( "changing\n" ); SVQ2_SpawnServer( level, spawnpoint, SS_DEMO, attractloop, loadgame ); } else if ( l > 4 && !String::Cmp( level + l - 4, ".pcx" ) ) { SCRQ2_BeginLoadingPlaque( false ); // for local system SVQ2_BroadcastCommand( "changing\n" ); SVQ2_SpawnServer( level, spawnpoint, SS_PIC, attractloop, loadgame ); } else { SCRQ2_BeginLoadingPlaque( false ); // for local system SVQ2_BroadcastCommand( "changing\n" ); SVQ2_SendClientMessages(); SVQ2_SpawnServer( level, spawnpoint, SS_GAME, attractloop, loadgame ); Cbuf_CopyToDefer(); } SVQ2_BroadcastCommand( "reconnect\n" ); }
#ifndef ELECTRICCELL_H #define ELECTRICCELL_H #include <cmath> #include <vector> #include <fstream> #include <ctime> using namespace std; #include "particle.h" #include "toner_particle.h" #include "wall.h" /*//////////////////////////////////////////////////// ElectricCell構造体 粒子占有領域判定及び電界計算用メッシュの構造体. ////////////////////////////////////////////////////*/ struct ElectricCell{ int ID; //cell番号 double Pos[3]; //cellの中心座標 int XYZnum[3]; //cellの整数座標番号 int Condition; //0:空間,1:粒子,2:現像器, 3:感光体 double RelElePerm; //このeleCellにおける比誘電率 double Potential; //このeleCellの中心におけるポテンシャル double ChargeDensity; //このeleCellおける電荷密度.各時間ステップごとに初期化.粒子の移動に追従しない. double PolChargeDensity;//このeleCellおける分極電荷密度.各時間ステップごとに初期化.粒子の移動に追従しない. int Adress[2]; //eleCellが粒子内にある場合に利用.Adress[0]==属してる粒子番号,Adress[1]==その粒子内のvectorコンテナの番号 int SurEleCellID[6]; //このeleCellの周囲のeleCellの番号.[0]:+x,[1]:-x,[2]:+y,[3]:-y,[4]:+z,[5]:-z 方向のeleCell番号. //eleCellが領域の端の場合,その方向の番号は自分の番号を入れている.これにより仮の境界条件を作っている. double ElectricFieldIndensity;//このセルにおける電界強度 double SQRElectricFieldIndensity;//電界強度の2乗 }; /*//////////////////////////////////////////////////// EleCellinParticle構造体 注目粒子内に含有されているeleCellの情報を所持した構造体. これをvectorコンテナで利用. ////////////////////////////////////////////////////*/ struct EleCellinParticle{ int ReXYZnum[3]; //粒子中心があるeleCellの整数座標に対する注目eleCellの相対整数座標 double Rexyz[3]; //粒子中心があるeleCell座標からの相対座標.トルク計算に使用. double ChargeDensity;//注目eleCellにおける電荷密度.時間ステップごとの初期化はしない.粒子が移動してもこれは保持される. }; /*//////////////////////////////////////////////////// ParticleInformation構造体 電界計算に必要な粒子の情報を格納した構造体. これを配列として利用する.配列番号は粒子番号と一致. ////////////////////////////////////////////////////*/ struct ParticleInformation{ int eleCellID; //注目粒子の中心がいるeleCellのID double ElectricForce[3]; //この粒子にかかる力 double ElectricTorque[3]; //この粒子にかかるトルク std::vector<EleCellinParticle> eleCellinPtcl_v; //注目粒子内に含まれる複数のeleCellに関するEleCellinParticle構造体をvectorコンテナに格納 }; /*//////////////////////////////////////////////////// ElectricCellArrayクラス 定義部 領域分割法を実装したクラス.Cell構造体を用いる. ////////////////////////////////////////////////////*/ class ElectricCellArray{ private: ParticleArray* ptclArray; //関連付けられたParticleArrayクラスへのポインタ Toner_ParticleArray* t_ptclArray; //関連付けられたToner_ParticleArrayクラスへのポインタ CylinderArray* cyldArray; //関連付けられたCylinderArrayクラスへのポインタ ElectricCell* eleCell; //ElectricCellCell構造体の配列へのポインタ ParticleInformation *ptclInfo; //ParticleInformation構造体の配列へのポインタ.配列番号と粒子番号が一致. ParticleInformation *t_ptclInfo; //ParticleInformation構造体の配列へのポインタ.配列番号と粒子番号が一致. double spElePerm; //真空の誘電率.MSKA単位系. double carriorRelElePerm; //キャリアの比誘電率 double tonerRelElePerm; //トナーの比誘電率 int ptclNum; //粒子数 int t_ptclNum; //トナー粒子数 int cyldNum; //円筒の総数 int eleCellNumSum; //Cellの総数 int widthEleCellNum; //x方向のCellの数 int depthEleCellNum; //y方向のCellの数 int heightEleCellNum; //z方向のCellの数 double eleCellArrayOrigin[3]; //Cell配列の原点 double areaWidth; //Cellで区切る領域の,x方向長さ double areaDepth; //Cellで区切る領域の,y方向長さ double areaHeight; //Cellで区切る領域の,z方向長さ double eleCellSize; //Cellのサイズ double PI; int EleArrayNumConvert( //Cellのx,y,z位置からcell番号に変換する関数.戻り値はcell番号. int Xnum, //Cellのx方向位置 int Ynum, //Cellのy方向位置 int Znum); //Cellのz方向位置 public: ElectricCellArray(); //コンストラクタ ~ElectricCellArray(); //デストラクタ void Associate( //ParticleArrayクラスを関連付けるための関数 ParticleArray* particleArray); //関連付けをするParticleArrayクラスへのポインタ void Associate( //Toner_ParticleArrayクラスを関連付けるための関数 Toner_ParticleArray* toner_particleArray); //関連付けをするToner_ParticleArrayクラスへのポインタ void Associate( //CylinderArrayクラスを関連付けるための関数 CylinderArray* cylinderArray); //関連付けをするCylinderArrayクラスへのポインタ void SetEleCellSize(double ElecellCoeff); //eleCellの大きさを決定する関数 double GetEleCellSize(); //eleCellの大きさを取得する関数 void EleCellAlloc( //指定した領域に対してCellを配置させる関数 double AreaWidth, //Cellを配置する領域のx方向長さ double AreaDepth, //Cellを配置する領域のy方向長さ double AreaHeight); //Cellを配置する領域のz方向長さ int GetEleCellNum(int Xnum, int Ynum, int Znum); //指定したx,y,z整数座標からCellのIDを取得する関数 int GetEleCellNumSum(); //eleCellの総数を取得する関数を取得する関数 int GetWidthEleCellNum(); //領域内のeleCellの幅方向の個数を取得する関数 int GetDepthEleCellNum(); //領域内のeleCellの奥行き方向の個数を取得する関数 int GetHeightEleCellNum(); //領域内のeleCellの高さ方向の個数を取得する関数 int GetCondition(int ID); //eleCellのメンバConditionの値を取得する関数を取得する関数 double GetPotential(int ID); //指定したeleCellのポテンシャルを取得する関数 double GetElectricIndensity(int ID); //指定したelecellの電場強度を取得する関数 double GetChargeDensity(int ID); //指定したeleCellの電荷密度を取得する関数 double GetAllChargeDensity(int ID); double GetRelElePerm(int ID); void EleCellInicialize(); //粒子内に含まれていたeleCellを開放して初期化する関数 void EleForceInicialize(); //粒子にかかっていた力,トルクを0に初期化する関数 void SetSurEleCellFill(); //粒子内に含まれるeleCellの情報を設定する関数 void SetInicialCharge(); //粒子生成時に粒子中心のあるセルに初期帯電量を埋め込む関数 void FillEleCell2(); //粒子内に含まれるeleCellのConditionを1:粒子に塗り潰し,必要な情報をeleCellに格納する関数 void FillEleCellCylinder(double DSPotential,double PHPotential); //円筒内に含まれるeleCellのConditionを現像器:2か感光体:3に塗りつぶす関数 void PutinEleCell(); //eleCell内に粒子を所属させる関数 void t_PutinEleCell(); //eleCell内にトナー粒子を所属させる関数 void CalcPotential(double TFC,double SOR); //ポテンシャルの計算をする関数 void CalcChargeDensity(double TimeStep,double R); //電荷密度の計算をする関数 void CalcElectricForce(); //電界による力を計算する関数 void CalcDielectricForce(); //誘電体にかかる力を計算する関数 void AddElectricForce(); //計算した力,トルクを加算する関数 void SetCarriorRelElePerm(double CarriorRelElePerm); //キャリア粒子の比誘電率を取得 void SetTonerRelElePerm(double TonerRelElePerm); //キャリア粒子の比誘電率を取得 void CalcPolChargeDensity(); /* void Debug(); */ }; #endif
#include <vector> #include <fstream> #include <cstdint> #include <iostream> #define DATA_FILE_IO_GOOD 1 #define DATA_FILE_IO_BAD 0 namespace DataFileIO { /* Loads the bytes that were stored using DataFileIO::Save and returns it in Returns a pointer that you MUST call delete to Takes a reference to an int that stores the size of the buffer */ template<typename T> T* Load(const char* filepath, unsigned int* size = nullptr); /* Stores contiguous blocks of data onto the disk Size parameter takes the number of bytes to be saved, NOT the number of elements */ bool Save(const char* filepath, const void* data, size_t size, bool append = false); } #ifdef _DEBUG #define DATA_FILE_IO_DEBUG_PRINT(x) std::cout<<x<<std::endl #else #define DEBUG_PRINT(x) #endif #define DATA_FILE_IO_PREFIX "DATA_FILE_IO ERROR: " template<typename T> T* DataFileIO::Load(const char* filepath, unsigned int* size/*= nullptr*/) { std::ifstream infile(filepath, std::ios_base::binary); if (infile.bad() || infile.fail()) { DATA_FILE_IO_DEBUG_PRINT(DATA_FILE_IO_PREFIX << "Error opening file"); return nullptr; } infile.seekg(0, std::ios_base::end); size_t fileSize = infile.tellg(); /*Gets the total size of the file in bytes*/ infile.seekg(0, std::ios_base::beg); if (fileSize < 1) // If file is empty { DATA_FILE_IO_DEBUG_PRINT(DATA_FILE_IO_PREFIX << "File is empty"); infile.close(); return nullptr; } unsigned char* buffer = new unsigned char[fileSize]; infile.read((char*)buffer, fileSize); if (size != nullptr) *size = fileSize / sizeof(T); infile.close(); return reinterpret_cast<T*>(buffer); } bool DataFileIO::Save(const char* filepath, const void* data, size_t size, bool append/*= false*/) { int writeMode = append ? std::ios_base::app : std::ios_base::trunc; // Determines if the user wants to either append, or truncate the file std::ofstream outfile(filepath, std::ios_base::binary | writeMode); if (outfile.bad()) { DATA_FILE_IO_DEBUG_PRINT(DATA_FILE_IO_PREFIX << "Error saving to file"); return DATA_FILE_IO_BAD; } outfile.write((const char*)data, size); // Writes the individual bytes into the file outfile.close(); return DATA_FILE_IO_GOOD; }
#include<stdio.h> int pratition(int a[],int i,int j) { int pivot, temp, k; k = i + 1; int pivot1 = a[i]; while (k <= j) { while (a[k] <= pivot1) k++; while (a[j] > pivot1) j--; if (k < j) { temp = a[k]; a[k] = a[j]; a[j] = temp; } } temp = a[j]; a[j] =a[i] ; a[i] = temp; return j; } void quicksort(int a[],int start,int end) { if (end > start) { int index = pratition(a, start, end); quicksort(a, start, index - 1); quicksort(a, index + 1, end); } } int main() { int i, j, n; int a[10000]; scanf("%d", &n); for (i = 0; i < n; i++) scanf("%d", &a[i]); quicksort(a, 0, n - 1); for (i = 0; i < n; i++) printf("%d ",a[i]); return 0; }
#pragma once #include <iostream> #include <vector> using namespace std; #define vertexRadius 4.f #define TriangleSize 12.0f /******************************************************************** Struct: point Description: each point contains x, y coordinate ********************************************************************/ struct Point { public: Point() : x(0.0f),y(0.0f){} ~Point(){} float x, y; void setxy(float x2, float y2) { x = x2; y = y2; } bool getMouseIn(float _x, float _y) { bool bx = _x > x - 10 && _x < x + 10; bool by = _y > y - 10 && _y < y + 10; float i = pow((_x - x), 2) + pow((_y - y), 2); float j = pow(vertexRadius * 2, 2); if (pow((_x - x), 2) + pow((_y - y), 2) < pow(vertexRadius * 2, 2)) { return true; } else { return false; } } }; /******************************************************************** Struct: triangle Description: each triangle contains three points ********************************************************************/ struct Triangle { public: Point Point1; Point Point2; Point Point3; void setTriangle(Point _p1, Point _p2, Point _p3) { Point1 = _p1; Point2 = _p2; Point3 = _p3; } void setTriangle(Point p, float topX, float topY, float offsetXL, float offsetXR, float offsetYL, float offsetYR) { Point1.setxy(p.x + topX, p.y + topY); Point2.setxy(p.x + offsetXL, p.y + offsetYL); Point3.setxy(p.x + offsetXR, p.y + offsetYR); } }; /******************************************************************** Struct: line Description: each line contains a set of point, and the origin point and the end point of the line, and a triangle which display at end point of the line ********************************************************************/ struct Line { public: vector<Point> allPoint; Point startPoint; Point endPoint; Triangle endTriangle; void setSegPoint(Point _p1, Point _p2) { startPoint = _p1; endPoint = _p2; } // compute the control point of the cubic-bezier line void computeBeizerCtrlPoint(Point* _points) { // Four points would decide the shape of cubic-bezier line Point bPoint[4]; bPoint[0] = _points[0]; bPoint[1] = _points[1]; // compute the slope K of the line float tanX = 0; float tanY = 0; float k; tanX = abs(bPoint[0].x - bPoint[1].x); tanY = abs(bPoint[0].y - bPoint[1].y); k = tanY / tanX; bPoint[3] = bPoint[1]; // if the slope K <= 1.0, then drawing the end triangle horizontally if (k <= 1.0) { // The triangle toward left or right if (bPoint[0].x <= bPoint[3].x) { bPoint[1].x = (bPoint[3].x + bPoint[0].x) / 2; bPoint[1].y = (bPoint[0].y); bPoint[2].x = (bPoint[0].x + bPoint[3].x) / 2; bPoint[2].y = (bPoint[3].y); endTriangle.setTriangle(bPoint[3], TriangleSize, 0, 0, 0, -TriangleSize, TriangleSize); } else { bPoint[1].x = (bPoint[3].x + bPoint[0].x) / 2; bPoint[1].y = (bPoint[0].y); bPoint[2].x = (bPoint[0].x + bPoint[3].x) / 2; bPoint[2].y = (bPoint[3].y); endTriangle.setTriangle(bPoint[3], -TriangleSize, 0, 0, 0, -TriangleSize, TriangleSize); } } // if the slope K > 1.0, then drawing the end triangle vertically else { // The triangle toward up or down if (bPoint[0].y <= bPoint[3].y) { bPoint[1].x = bPoint[0].x; bPoint[1].y = (bPoint[0].y + bPoint[3].y) / 2; bPoint[2].x = bPoint[3].x; bPoint[2].y = (bPoint[3].y + bPoint[0].y) / 2; endTriangle.setTriangle(bPoint[3], 0, TriangleSize, -TriangleSize, TriangleSize, 0, 0); } else { bPoint[1].x = (bPoint[0].x); bPoint[1].y = (bPoint[0].y + bPoint[3].y) / 2; bPoint[2].x = (bPoint[3].x); bPoint[2].y = (bPoint[3].y + bPoint[0].y) / 2; endTriangle.setTriangle(bPoint[3], 0, -TriangleSize, TriangleSize, -TriangleSize, 0, 0); } } for (int i = 0; i < 4; i++) { _points[i] = bPoint[i]; } } // generalize all cubic-bezier point through control point void bezierGeneralized(Point* ctrlPoints) { Point p1 = ctrlPoints[0]; Point p2; Line tempLine; allPoint.clear(); tempLine.setSegPoint(ctrlPoints[0], ctrlPoints[3]); allPoint.push_back(p1); // compute each segment of the curve.Make t increment in smaller amounts for a more detailed curve. for (double t = 0.0; t <= 1.02; t += 0.02) { p2 = _computeBezierPoints(ctrlPoints, t); p1 = p2; allPoint.push_back(p2); } int i = 1; } private: Point _computeBezierPoints(Point* PT, double t) { Point P; P.x = 0; P.y = 0; double a1 = pow((1 - t), 3); double a2 = pow((1 - t), 2) * 3 * t; double a3 = 3 * t*t*(1 - t); double a4 = t*t*t; P.x = a1 * PT[0].x + a2 * PT[1].x + a3 * PT[2].x + a4 * PT[3].x; P.y = a1 * PT[0].y + a2 * PT[1].y + a3 * PT[2].y + a4 * PT[3].y; return P; } };
#include "GameObject.h" GameObject::GameObject( const GameObject& ref ) : mPosition( ref.mPosition ), mRotation( ref.mRotation ), mpMesh( ref.mpMesh ), mpTexture( ref.mpTexture ) { } GameObject::GameObject() : mPosition( 0.0f ), mRotation( 0.0f, 0.0f, 0.0f, 0.0f ), mpMesh( nullptr ), mpTexture( nullptr ) { } GameObject::~GameObject() { }
/* utils.h -*- C++ -*- Rémi Attab (remi.attab@gmail.com), 14 Apr 2015 FreeBSD-style copyright and disclaimer apply */ #pragma once namespace reflect { namespace json { /******************************************************************************/ /* BIT OPS */ /******************************************************************************/ size_t clz(char value) { return __builtin_clz(uint32_t(value) << 24); } } // namespace json } // namespace reflect
//tcp_cli_test.cpp #include "connector_co.h" #include <iostream> using namespace arsee::net; using namespace std; struct CoTask{ struct promise_type { CoTask get_return_object() { return {}; } std::suspend_never initial_suspend() { return {}; } std::suspend_never final_suspend() noexcept { return {}; } void return_void() {} void unhandled_exception() {} }; }; CoTask loop(Connector_co4::peer_t& tcp) { cout<<"enter loop coroutine\n"; while(true){ MsgSt msg("hello", 6); int w = co_await tcp.async_write(msg); cout<<"write size["<<msg.size()<<"]"<<endl; auto msgr = co_await tcp.async_read(); cout<<"read size["<<msgr.size()<<"]"<<endl; } cout<<"leave loop coroutine\n"; } int main(int argc, char** argv) { int port=10010; EventQueueEpoll eq; Connector_co4 c(&eq, 0); auto peer = c.connect({"127.0.0.1", 10010}); if(!peer.is_valid() ){ return 1; } loop(peer); //co_spawn(loop(tcp)); //CoExeScope scope; //co_spawn(scope, loop(tcp)); cout<<"after loop\n"; while(true){ eq.process(); } return 0; }
#include "Mixovnik.hpp" Mixovnik::Mixovnik() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS) {} void Mixovnik::step() { float SUM_L = 0.0; float SUM_R = 0.0; float SUM_AUX1_L = 0.0; float SUM_AUX1_R = 0.0; float SUM_AUX2_L = 0.0; float SUM_AUX2_R = 0.0; float cvVolumeRatio[16]; //First Solo test bool soloTest = false; int step = 0; do { if (params[SOLO_PARAM + step].value == 1) soloTest = true; step++; } while (!soloTest && step < 16); //Anti Pop Mix antiPopMixLeft -= (params[MIX_L_MUTE].value ==1) ? antiPopSpeed : -antiPopSpeed; if (antiPopMixLeft <0 ) antiPopMixLeft = 0; if (antiPopMixLeft >1 ) antiPopMixLeft = 1; antiPopMixRight -= (params[MIX_R_MUTE].value ==1) ? antiPopSpeed : -antiPopSpeed; if (antiPopMixRight <0 ) antiPopMixRight = 0; if (antiPopMixRight >1 ) antiPopMixRight = 1; //Anti Pop Auxes antiPopAux1 -= (params[AUX1_MUTE].value ==1) ? antiPopSpeed : -antiPopSpeed; if (antiPopAux1 <0 ) antiPopAux1 = 0; if (antiPopAux1 >1 ) antiPopAux1 = 1; antiPopAux2 -= (params[AUX2_MUTE].value ==1) ? antiPopSpeed : -antiPopSpeed; if (antiPopAux2 <0 ) antiPopAux2 = 0; if (antiPopAux2 >1 ) antiPopAux2 = 1; // Main loop for (int i = 0; i < 16; i++) { //Get signal float INPUT_SIGNAL = 0; cvVolumeRatio[i] = 1; if (inputs[STRIPE_CV_VOL_INPUT + i].active) cvVolumeRatio[i] = inputs[STRIPE_CV_VOL_INPUT + i].value/10; bool nieparzystyStripe = (i%2 == 0) ? true : false; bool linkActive = (params[LINK_PARAM + ((i-1)/2)].value == 1) ? true : false; //stripes 1,3,5,7,9,11,13,15 if (nieparzystyStripe) { INPUT_SIGNAL = inputs[STRIPE_INPUT + i].value * cvVolumeRatio[i] * params[VOLUME_PARAM + i].value; //stripes 2,4,6,8,10,12,14,16 } else { //link with left stripes? if (linkActive) { INPUT_SIGNAL = inputs[STRIPE_INPUT + i].value * cvVolumeRatio[i-1] * params[VOLUME_PARAM + (i - 1)].value ; } else { INPUT_SIGNAL = inputs[STRIPE_INPUT + i].value * cvVolumeRatio[i] * params[VOLUME_PARAM + i].value; } } //MUTE SOLO test for Anti Pop //SOLO if (soloTest) { if (nieparzystyStripe) { antiPopCurrentSpeed[i] = (params[MUTE_PARAM + i].value == 0 && params[SOLO_PARAM + i].value == 1) ? +antiPopSpeed : -antiPopSpeed; } else { if (linkActive) { antiPopCurrentSpeed[i] = (params[MUTE_PARAM + i -1].value == 0 && params[SOLO_PARAM + i -1].value == 1) ? +antiPopSpeed : -antiPopSpeed; } else { antiPopCurrentSpeed[i] = (params[MUTE_PARAM + i].value == 0 && params[SOLO_PARAM + i].value == 1) ? +antiPopSpeed : -antiPopSpeed; } } //NO SOLO } else { if (nieparzystyStripe) { antiPopCurrentSpeed[i] = (params[MUTE_PARAM + i].value == 1) ? -antiPopSpeed : +antiPopSpeed; } else { if (linkActive) { antiPopCurrentSpeed[i] = (params[MUTE_PARAM + i -1].value == 1) ? -antiPopSpeed : +antiPopSpeed; } else { antiPopCurrentSpeed[i] = (params[MUTE_PARAM + i].value == 1) ? -antiPopSpeed : +antiPopSpeed; } } } //Anti Pop final if (!inputs[STRIPE_INPUT + i].active) antiPopCurrentSpeed[i] = -antiPopSpeed; antiPop[i] += antiPopCurrentSpeed[i]; if (antiPop[i] <0 ) antiPop[i] = 0; if (antiPop[i] >1 ) antiPop[i] = 1; INPUT_SIGNAL *= antiPop[i]; //Constant-power panning float KNOB_PAN_POS = params[PAN_PARAM + i].value + (inputs[STRIPE_CV_PAN_INPUT + i].value / 5); //Anti invert phase if (KNOB_PAN_POS < -1) KNOB_PAN_POS = -1; if (KNOB_PAN_POS > 1) KNOB_PAN_POS = 1; double angle = KNOB_PAN_POS * PI_4; float GAIN_SIGNAL_L = (float) (SQRT2_2 * (cos(angle) - sin(angle))); float GAIN_SIGNAL_R = (float) (SQRT2_2 * (cos(angle) + sin(angle))); SUM_L += INPUT_SIGNAL * GAIN_SIGNAL_L; SUM_R += INPUT_SIGNAL * GAIN_SIGNAL_R; //AUX1 stripe send float KNOB_AUX1_POS = params[AUX1_PARAM + i].value; SUM_AUX1_L += KNOB_AUX1_POS * INPUT_SIGNAL * GAIN_SIGNAL_L ; SUM_AUX1_R += KNOB_AUX1_POS * INPUT_SIGNAL * GAIN_SIGNAL_R; //AUX2 stripe send float KNOB_AUX2_POS = params[AUX2_PARAM + i].value; SUM_AUX2_L += KNOB_AUX2_POS * INPUT_SIGNAL * GAIN_SIGNAL_L; SUM_AUX2_R += KNOB_AUX2_POS * INPUT_SIGNAL * GAIN_SIGNAL_R; //Lights float SIGNAL_LEVEL_ABS = fabs(INPUT_SIGNAL); if (SIGNAL_LEVEL_ABS == 0) { lights[SIGNAL_LIGHT_NORMAL + i*2 +0].value = 0; lights[SIGNAL_LIGHT_NORMAL + i*2 +1].value = 0; } if (SIGNAL_LEVEL_ABS > 0 && SIGNAL_LEVEL_ABS < 5.0) { lights[SIGNAL_LIGHT_NORMAL + i*2 +0].value = 1; lights[SIGNAL_LIGHT_NORMAL + i*2 +1].value = 0; } if (SIGNAL_LEVEL_ABS > 5) { lights[SIGNAL_LIGHT_NORMAL + i*2 +0].value = 0; lights[SIGNAL_LIGHT_NORMAL + i*2 +1].value = 1; } } //AUX1 and AUX2 sends outputs[AUX1_OUTPUT_L].value = SUM_AUX1_L; outputs[AUX1_OUTPUT_R].value = SUM_AUX1_R; outputs[AUX2_OUTPUT_L].value = SUM_AUX2_L; outputs[AUX2_OUTPUT_R].value = SUM_AUX2_R; //AUX1 and AUX2 returns float AUX1_SUM_L = inputs[AUX1_INPUT_L].value * params[AUX1_VOLUME].value * antiPopAux1; float AUX1_SUM_R = inputs[AUX1_INPUT_R].value * params[AUX1_VOLUME].value * antiPopAux1; float AUX2_SUM_L = inputs[AUX2_INPUT_L].value * params[AUX2_VOLUME].value * antiPopAux2; float AUX2_SUM_R = inputs[AUX2_INPUT_R].value * params[AUX2_VOLUME].value * antiPopAux2; SUM_L += AUX1_SUM_L + AUX2_SUM_L; SUM_R += AUX1_SUM_R + AUX2_SUM_R; //Exteranal mix SUM_L += inputs[STEREO_INPUT_L].value; SUM_R += inputs[STEREO_INPUT_R].value; //Mix sliders SUM_L *= params[MIX_L_VOLUME].value; SUM_R *= ((params[MIX_LINK].value == 0) ? params[MIX_R_VOLUME].value : params[MIX_L_VOLUME].value); //Final mix with mute switches SUM_L *= antiPopMixLeft; if (params[MIX_LINK].value == 1) { SUM_R *= antiPopMixLeft; } else { SUM_R *= antiPopMixRight; } //Final out outputs[STEREO_OUTPUT_L].value = SUM_L; outputs[STEREO_OUTPUT_R].value = SUM_R; //Mix lights lights[MIX_LIGHT_L].value = (fabs(SUM_L) > 5) ? 1.0 : 0.0; lights[MIX_LIGHT_R].value = (fabs(SUM_R) > 5) ? 1.0 : 0.0; lights[AUX1_LIGHT].value = (fabs(AUX1_SUM_L) > 5 || fabs(AUX1_SUM_R) > 5) ? 1.0 : 0.0; lights[AUX2_LIGHT].value = (fabs(AUX2_SUM_L) > 5 || fabs(AUX2_SUM_R) > 5) ? 1.0 : 0.0; } /////////////////////////////////////////////////////////////////////////////// // Store variables /////////////////////////////////////////////////////////////////////////////// json_t *Mixovnik::toJson() { json_t *rootJ = json_object(); json_object_set_new(rootJ, "panelStyle", json_integer(panelStyle)); return rootJ; } void Mixovnik::fromJson(json_t *rootJ) { json_t *j_panelStyle = json_object_get(rootJ, "panelStyle"); panelStyle = json_integer_value(j_panelStyle); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////// GUI /////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// MixovnikWidget::MixovnikWidget(Mixovnik *module) : ModuleWidget(module){ box.size = Vec(58 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT); { DynamicPanelWidget *panel = new DynamicPanelWidget(); panel->addPanel(SVG::load(assetPlugin(plugin, "res/Mixovnik-Dark.svg"))); panel->addPanel(SVG::load(assetPlugin(plugin, "res/Mixovnik-Light.svg"))); box.size = panel->box.size; panel->mode = &module->panelStyle; addChild(panel); } //Set base position float xPos = 17; float yPos = 20; float xDelta = 40; //AUX1 inputs and outputs addInput(Port::create<PJ301MPort>(Vec(694, yPos +7), Port::INPUT, module, Mixovnik::AUX1_INPUT_L)); addInput(Port::create<PJ301MPort>(Vec(733, yPos +7), Port::INPUT, module, Mixovnik::AUX1_INPUT_R)); addOutput(Port::create<PJ301MPort>(Vec(780, yPos +7), Port::OUTPUT, module, Mixovnik::AUX1_OUTPUT_L)); addOutput(Port::create<PJ301MPort>(Vec(815, yPos +7), Port::OUTPUT, module, Mixovnik::AUX1_OUTPUT_R)); //AUX2 inputs and outputs addInput(Port::create<PJ301MPort>(Vec(694, yPos + 45), Port::INPUT, module, Mixovnik::AUX2_INPUT_L)); addInput(Port::create<PJ301MPort>(Vec(733, yPos + 45), Port::INPUT, module, Mixovnik::AUX2_INPUT_R)); addOutput(Port::create<PJ301MPort>(Vec(780, yPos + 45), Port::OUTPUT, module, Mixovnik::AUX2_OUTPUT_L)); addOutput(Port::create<PJ301MPort>(Vec(815, yPos + 45), Port::OUTPUT, module, Mixovnik::AUX2_OUTPUT_R)); //External stereo inputs addInput(Port::create<PJ301MPort>(Vec(699, yPos + 285), Port::INPUT, module, Mixovnik::STEREO_INPUT_L)); addInput(Port::create<PJ301MPort>(Vec(733, yPos + 285), Port::INPUT, module, Mixovnik::STEREO_INPUT_R)); //Stereo mix outputs addOutput(Port::create<PJ301MPort>(Vec(782, yPos + 285), Port::OUTPUT, module, Mixovnik::STEREO_OUTPUT_L)); addOutput(Port::create<PJ301MPort>(Vec(816, yPos + 285), Port::OUTPUT, module, Mixovnik::STEREO_OUTPUT_R)); //Stripes elements for (int i = 0; i < 16; i++) { addChild(ModuleLightWidget::create<SmallLight<GreenRedLight>> (Vec(xPos + 27 + i*xDelta, yPos + 110), module, Mixovnik::SIGNAL_LIGHT_NORMAL + i*2)); addParam(ParamWidget::create<Koralfx_RoundBlackKnob> (Vec(xPos - 0.5 + i*xDelta, yPos - 0.5), module, Mixovnik::AUX1_PARAM + i, 0, 1, 0.0)); addParam(ParamWidget::create<Koralfx_RoundBlackKnob> (Vec(xPos - 0.5 + i*xDelta, yPos + 36.5), module, Mixovnik::AUX2_PARAM + i, 0, 1, 0.0)); addParam(ParamWidget::create<Koralfx_RoundBlackKnob> (Vec(xPos - 0.5 + i*xDelta, yPos + 75.5), module, Mixovnik::PAN_PARAM + i, -1, 1, 0.0)); addParam(ParamWidget::create<Koralfx_SliderPot> (Vec(xPos + 3 + i*xDelta, yPos + 110), module, Mixovnik::VOLUME_PARAM + i, 0.0f, 1.0f, 0.9f)); addParam(ParamWidget::create<Koralfx_Switch_Red> (Vec(xPos + 8 + i*xDelta, yPos + 228), module, Mixovnik::MUTE_PARAM + i, 0.0, 1.0, 0.0)); if (i%2 == 0) addParam(ParamWidget::create<Koralfx_Switch_Blue>(Vec(xPos + 8 + (i+0.5)*xDelta, yPos + 228), module, Mixovnik::LINK_PARAM + (i/2), 0.0, 1.0, 0.0)); addInput(Port::create<PJ301MPort> (Vec(xPos + 3 + i*xDelta, yPos + 266), Port::INPUT, module, Mixovnik::STRIPE_INPUT + i)); addInput(Port::create<PJ301MPort> (Vec(xPos + 3 + i*xDelta, yPos + 292), Port::INPUT, module, Mixovnik::STRIPE_CV_PAN_INPUT + i)); addInput(Port::create<PJ301MPort> (Vec(xPos + 3 + i*xDelta, yPos + 318), Port::INPUT, module, Mixovnik::STRIPE_CV_VOL_INPUT + i)); addParam(ParamWidget::create<Koralfx_Switch_Green> (Vec(xPos + 8 + i*xDelta, yPos + 245), module, Mixovnik::SOLO_PARAM + i, 0.0, 1.0, 0.0)); } //Final volume sliders addParam(ParamWidget::create<Koralfx_SliderPot>(Vec(xPos - 2 + 17*xDelta, yPos + 110), module, Mixovnik::AUX1_VOLUME, 0.0f, 1.0f, 0.9f)); addParam(ParamWidget::create<Koralfx_SliderPot>(Vec(xPos - 2 + 18*xDelta, yPos + 110), module, Mixovnik::AUX2_VOLUME, 0.0f, 1.0f, 0.9f)); addParam(ParamWidget::create<Koralfx_SliderPot>(Vec(xPos + 3 + 19*xDelta, yPos + 110), module, Mixovnik::MIX_L_VOLUME, 0.0f, 1.0f, 0.9f)); addParam(ParamWidget::create<Koralfx_SliderPot>(Vec(xPos + 1 + 20*xDelta, yPos + 110), module, Mixovnik::MIX_R_VOLUME, 0.0f, 1.0f, 0.9f)); //Final mute switches addParam(ParamWidget::create<Koralfx_Switch_Red>(Vec(xPos + 3 + 17*xDelta, yPos + 227), module, Mixovnik::AUX1_MUTE, 0, 1, 0)); addParam(ParamWidget::create<Koralfx_Switch_Red>(Vec(xPos + 3 + 18*xDelta, yPos + 227), module, Mixovnik::AUX2_MUTE, 0, 1, 0)); addParam(ParamWidget::create<Koralfx_Switch_Red>(Vec(xPos + 8 + 19*xDelta, yPos + 227), module, Mixovnik::MIX_L_MUTE, 0, 1, 0)); addParam(ParamWidget::create<Koralfx_Switch_Red>(Vec(xPos + 6 + 20*xDelta, yPos + 227), module, Mixovnik::MIX_R_MUTE, 0, 1, 0)); //Stereo mix link switch addParam(ParamWidget::create<Koralfx_Switch_Blue>(Vec(xPos + 7 + 19.5*xDelta, yPos + 227), module, Mixovnik::MIX_LINK, 0, 1, 0)); //Final mix lights addChild(ModuleLightWidget::create<SmallLight<RedLight>> (Vec(703,120), module, Mixovnik::AUX1_LIGHT)); addChild(ModuleLightWidget::create<SmallLight<RedLight>> (Vec(743,120), module, Mixovnik::AUX2_LIGHT)); addChild(ModuleLightWidget::create<SmallLight<RedLight>> (Vec(788,120), module, Mixovnik::MIX_LIGHT_L)); addChild(ModuleLightWidget::create<SmallLight<RedLight>> (Vec(826,120), module, Mixovnik::MIX_LIGHT_R)); } //////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////// Context Menu /////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// //Context menu code is adapted from The Dexter by Dale Johnson //https://github.com/ValleyAudio struct MixovnikPanelStyleItem : MenuItem { Mixovnik* module; int panelStyle; void onAction(EventAction &e) override { module->panelStyle = panelStyle; } void step() override { rightText = (module->panelStyle == panelStyle) ? "✔" : ""; MenuItem::step(); } }; void MixovnikWidget::appendContextMenu(Menu *menu) { Mixovnik *module = dynamic_cast<Mixovnik*>(this->module); assert(module); // Panel style menu->addChild(construct<MenuLabel>()); menu->addChild(construct<MenuLabel>(&MenuLabel::text, "Frame of mind")); menu->addChild(construct<MixovnikPanelStyleItem>(&MenuItem::text, "Dark Calm Night", &MixovnikPanelStyleItem::module, module, &MixovnikPanelStyleItem::panelStyle, 0)); menu->addChild(construct<MixovnikPanelStyleItem>(&MenuItem::text, "Happy Bright Day", &MixovnikPanelStyleItem::module, module, &MixovnikPanelStyleItem::panelStyle, 1)); } //////////////////////////////////////////////////////////////////////////////////////////////////// Model *modelMixovnik = Model::create<Mixovnik, MixovnikWidget>("Koralfx-Modules", "Mixovnik", "Mixovnik", MIXER_TAG);
#include <exception> #include "Amount.h" bool Amount::in_domain(Integral num) { return num != infinite_value; } void Amount::assert_in_domain(Integral num) { if (!in_domain(num)) throw std::domain_error("amount " + std::to_string(num) + " not within domain"); } void Amount::assure_addable(Integral a, Integral b) { if (!(highest_value % 2) ? ((a > add_treshold && b >= add_treshold) || (a >= add_treshold && b > add_treshold)) : (a > add_treshold && b > add_treshold)) throw std::domain_error("addition exceeds amount limit"); } void Amount::assure_subtractable(Integral a, Integral b) { if (b > a) throw std::domain_error("amount cannot go negative"); } Amount::Amount(): value_(0) {}; Amount::Amount(Integral amount): value_(amount) { assert_in_domain(amount); } Amount Amount::infinity() { Amount amount; amount.value_ = infinite_value; return amount; } Amount Amount::operator+(const Amount amount) { assure_addable(value_, amount.value_); return Amount(value_ + amount); } Amount Amount::operator-(const Amount amount) { assure_subtractable(value_, amount.value_); return Amount(value_ - amount.value_); } Amount Amount::operator=(const Amount amount) { value_ = amount.value_; return *this; } bool Amount::infinite() const { return value_ == infinite_value; } bool Amount::finite() const { return !infinite(); } Amount::operator Integral() const { assert_in_domain(value_); return value_; } Amount::operator std::string() const { return infinite() ? "unlimited" : std::to_string(value_); } std::istream& operator>>(std::istream& in, Amount& amount) { std::string text; in >> text; if (text == "unlimited") { amount = std::numeric_limits<Amount>::infinity(); return in; } unsigned int raw_int(std::stoi(text)); if (!Amount::in_domain(raw_int)) { if (in.exceptions()) throw std::ios_base::failure("could not convert to amount"); else { in.setstate(std::ios_base::failbit); return in; } } amount.value_ = raw_int; return in; }
#include <iostream> using namespace std; class User { private: int m_us_ID; string m_full_name; string m_email; string m_username; string m_password; string m_picture; // Constructors public: User(string full_name, string email, string username, string password, string picture); User(const User& us ); ~User(); User &operator= (const User& us); //functions public: void Add_User(); void Edit_User(); void Display(); // some containers may be list or vector public: list <document> docsOfUser; list <workspace> workspaceOfUser; list <coments> comentsOfUser; }; class Document { //membeers private: int m_doc_ID; string m_doc_title; string m_doc_path; string m_doc_extention; string m_doc_size; string m_doc_user; string m_doc_version; int m_doc_workspace_ID; string m_vizibility; // Constructors public: Document(int doc_ID, string doc_title, string doc_path, int workspace_ID, int user_ID ); Document(const Document& doc); ~Document(); Document &operator= (const Document& doc); // Functions public: void Add_Doc(string doc_path); void Edit(string doc_title); void Update(string doc_title); void Print(); // Dont work normaly void Rename(string doc_title); void Move(int workplace_ID); Document Search(string doc_title, string doc_visibility, int doc_size, int workspace_ID ); void Share(int us_ID, string doc_visibility); void Archive(string doc_ID); void Display(string doc_title, int doc_ID); void DDrope(); // for drug an drope // containers public: list <comment> comentsOfDocument; list <int> UserIDAcssesOfDoc; }; class Workplace { private: int m_workplace_ID; string m_wname; public: Workplace( string wname, int workplace_ID, int us_ID,); Workplace( const Workplace& wp); ~Workplace(); Workplace &operator= (const Workplace& wp); public: void Create(); void Rename(string wname); void Delete(); void Union(int workspace_ID); // union of 2 workspaces public: list <document> DocsInWorkspace; }; class Comments { private: int m_comment_ID; string m_c_text; int m_doc_ID; int m_us_ID; public: Comments(int doc_ID, string c_text, int comment_ID, int us_ID); Comments(const Comments& com); ~Comments(); Comments &operator= (const Comments& com); public: void CommentOnDoc(int doc_ID); void Delete_Comm(int Com_ID); void Display(); }; class Notification { private: int m_notification_ID; int m_us_ID; bool m_not_type; int m_doc_ID; //constructors public: Notification(int us_ID, int doc_ID); Notification(); ~Notification(); Notification &operator= (const Notification& not); //functions public: void Create(); void Display(); public: list <int> notificationList; }; class Settings { private: int m_settings_ID; int m_us_ID; //Constructors public: Settings(); Settings(); ~Settings(); Settings &operator= (const Settings& stting); public: bool AutoHelp(); void Language(); //??????? };
#include <glad/glad.h> #include <GLFW/glfw3.h> #include <iostream> #include <ShaderProgram.hpp> #include <Shader.hpp> #include <glm/gtc/type_ptr.hpp> ShaderProgram::ShaderProgram() : id(glCreateProgram()) { } ShaderProgram::ShaderProgram(const std::vector<Shader> &s) : id(glCreateProgram()) { for(auto i=s.begin(); i!=s.end(); ++i){ this->attach(*i); } } ShaderProgram::~ShaderProgram() { glDeleteProgram(this->id); } void ShaderProgram::attach(const Shader &shader) { if(shader.usable()) glAttachShader(this->id, shader.id()); else throw std::runtime_error("ShaderProgram::ERROR::attach: Shader was already deleted"); } void ShaderProgram::link() { this->linkShaderProgramWithError(this->id); } void ShaderProgram::use() { glUseProgram(this->id); } void ShaderProgram::linkShaderProgramWithError(const GLuint program) { glLinkProgram(program); int success; char infoLog[512]; glGetProgramiv(program, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(program, 512, NULL, infoLog); std::cerr << "ERROR::PROGRAM::LINK\n" << infoLog << std::endl; glfwTerminate(); exit(EXIT_FAILURE); } } // int void ShaderProgram::setUniform1i(const std::string &name, GLint v) { GLuint location = glGetUniformLocation(this->id, name.c_str()); glUniform1i(location, v); } void ShaderProgram::setUniform2i(const std::string &name, GLint v0, GLint v1) { GLuint location = glGetUniformLocation(this->id, name.c_str()); glUniform2i(location, v0, v1); } void ShaderProgram::setUniform3i(const std::string &name, GLint v0, GLint v1, GLint v2) { GLuint location = glGetUniformLocation(this->id, name.c_str()); glUniform3i(location, v0, v1, v2); } void ShaderProgram::setUniform4i(const std::string &name, GLint v0, GLint v1, GLint v2, GLint v3) { GLuint location = glGetUniformLocation(this->id, name.c_str()); glUniform4i(location, v0, v1, v2, v3); } // unsigned int void ShaderProgram::setUniform1ui(const std::string &name, GLuint v) { GLuint location = glGetUniformLocation(this->id, name.c_str()); glUniform1ui(location, v); } void ShaderProgram::setUniform2ui(const std::string &name, GLuint v0, GLuint v1) { GLuint location = glGetUniformLocation(this->id, name.c_str()); glUniform2ui(location, v0, v1); } void ShaderProgram::setUniform3ui(const std::string &name, GLuint v0, GLuint v1, GLuint v2) { GLuint location = glGetUniformLocation(this->id, name.c_str()); glUniform3ui(location, v0, v1, v2); } void ShaderProgram::setUniform4ui(const std::string &name, GLuint v0, GLuint v1, GLuint v2, GLuint v3) { GLuint location = glGetUniformLocation(this->id, name.c_str()); glUniform4ui(location, v0, v1, v2, v3); } // Floats void ShaderProgram::setUniform1f(const std::string &name, GLfloat v) { GLuint location = glGetUniformLocation(this->id, name.c_str()); glUniform1f(location, v); } void ShaderProgram::setUniform2f(const std::string &name, GLfloat v0, GLfloat v1) { GLuint location = glGetUniformLocation(this->id, name.c_str()); glUniform2f(location, v0, v1); } void ShaderProgram::setUniform3f(const std::string &name, GLfloat v0, GLfloat v1, GLfloat v2) { GLuint location = glGetUniformLocation(this->id, name.c_str()); glUniform3f(location, v0, v1, v2); } void ShaderProgram::setUniform4f(const std::string &name, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3) { GLuint location = glGetUniformLocation(this->id, name.c_str()); glUniform4f(location, v0, v1, v2, v3); } void ShaderProgram::setUniformMatrix(const std::string& name, glm::mat4 v, bool transpose) { GLuint location = glGetUniformLocation(this->id, name.c_str()); glUniformMatrix4fv(location, 1, transpose, glm::value_ptr(v)); }
#include<bits/stdc++.h> using namespace std; struct node { int data; struct node* left = NULL; struct node* right = NULL; }; typedef struct node Node; Node* create_node(int value) { Node* temp = new Node(); temp->data = value; temp->left = NULL; temp->right = NULL; return temp; } void leaf_nodes(Node* root) { if(root==NULL) { return ; } if(root->left==NULL && root->right==NULL) { cout << root->data << " "; return ; } // print all leaf nodes in left leaf_nodes(root->left); // print all leaf nodes in right leaf_nodes(root->right); } void boundary_left(Node* root) { if(root==NULL) { return ; } if(root->left!=NULL) { cout << root->data << " "; boundary_left(root->left); } else if(root->right!=NULL) { cout << root->data << " "; boundary_left(root->right); } // to avoid duplicating we are not considering leaf nodes return ; } void boundary_right(Node* root) { if(root==NULL) { return ; } if(root->right!=NULL) { boundary_right(root->right); cout << root->data << " "; } else if(root->left!=NULL) { boundary_right(root->left); cout << root->data << " "; } // to avoid duplicating we are not considering leaf nodes return ; } void boundary(Node* root) { if(root==NULL) { return ; } cout << root->data << " "; //left boundary boundary_left(root->left); //leaf nodes leaf_nodes(root); //right boundary boundary_right(root->right); cout << endl; return ; } int main() { Node* root = NULL; root = create_node(5); root->left = create_node(6); root->right = create_node(3); root->right->left = create_node(4); root->right->right = create_node(2); boundary(root); return 0; }
#include "player.h" void Player::createVariables() { this ->animationStates = PLAYER_ANIMATION_STATES::IDLE; } void Player::createTexture() { if(!this->textureSheet.loadFromFile("Images/postac_animacje_prawo.png")) { std::cout<<"Halo prosze wczytac gracza!"<< std::endl; } } void Player::createSprite() { this->sprite.setTexture(this->textureSheet); this->currentFrame = sf::IntRect(0,0,32,64); this->sprite.setTextureRect(this->currentFrame); this->sprite.setScale(2.f,2.f); } void Player::createView() { this->view.reset(sf::FloatRect(0.f,0.f,1000.f,800.f)); this->view.setCenter(this->sprite.getPosition().x + this->sprite.getGlobalBounds().width / 2.f, this->sprite.getPosition().y + this->sprite.getGlobalBounds().height - 368.f); } void Player::createAnimation() { this->animationTime.restart(); } void Player::createPhysics() { this->velMax = 5.f; this->velMin = 1.f; this->acceleration = 1.5f; this->drag = 0.8f; this->gravity = 4.f; this->velocityMaxY = 15.f; this->attackCooldownMax = 10; this->attackCooldown = this->attackCooldownMax; this->hpMax = 100; this->hp = this->hpMax; } Player::Player() { this->createVariables(); this->createTexture(); this->createSprite(); this->createView(); this->createAnimation(); this->createPhysics(); } Player::~Player() { } const sf::Vector2f Player::getPosition() const { return this->sprite.getPosition(); } const sf::FloatRect Player::getGlobalBounds() const { return this->sprite.getGlobalBounds(); } int Player::getHp() const { return this->hp; } int Player::getHpMax() const { return this->hpMax; } void Player::setPosition(const float x, const float y) { this->sprite.setPosition(x,y); } void Player::resetVelocityY() { this->velocity.y = 0.f; } void Player::resetVelocityX() { this->velocity.x = 0.f; } void Player::setHp(const int hp_) { this->hp = hp_; } void Player::loseHp(const int value_) { this->hp -= value_; if(this->hp < 0) { this->hp = 0; } } void Player::pickUpHp(const int givehp_) { this->hp += givehp_; if(this->hp > this->hpMax) { this->hp = this->hpMax; } } bool Player::canAttack() { if(this->attackCooldown >= this->attackCooldownMax) { this->attackCooldown = 0; return true; } return false; } void Player::move(const float direction_x, const float direction_y) { //Acceleration this->velocity.x += direction_x * this->acceleration; //Limit vel if(std::abs(this->velocity.x) > this->velMax) { this->velocity.x = this->velMax * ((this->velocity.x) < 0.f ? -1.f : 1.f); } } void Player::speed() { this->velMax = 15.f; if(sf::Keyboard::isKeyPressed(sf::Keyboard::Key::A)) //left this->move(-1.f,0.f); if(sf::Keyboard::isKeyPressed(sf::Keyboard::Key::D)) //right this->move(1.f,0.f); } void Player::updatePhysics() { //Gravity this->velocity.y += 1.0 * this->gravity; if(std::abs(this->velocity.y) > this->velocityMaxY) { this->velocity.y = this->velocityMaxY * ((this->velocity.y) < 0.f ? -1.f : 1.f); } //Deceleration this->velocity *= this->drag; //Limit deceleceration if(std::abs(this->velocity.x) < this->velMin) { this->velocity.x = 0.f; } if(std::abs(this->velocity.y) < this->velMin) { this->velocity.y = 0.f; } this->sprite.move(this->velocity); } void Player::updateAttack() { if(this->attackCooldown < this->attackCooldownMax) { this->attackCooldown += 0.5; } } void Player::updateMovement() { this->animationStates = PLAYER_ANIMATION_STATES::IDLE; //X Axis movement if(sf::Keyboard::isKeyPressed(sf::Keyboard::Key::A)) //left { this->move(-1.f,0.f); this->animationStates = PLAYER_ANIMATION_STATES::MOVING_LEFT; } else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Key::D)) //right { this->move(1.f,0.f); this->animationStates = PLAYER_ANIMATION_STATES::MOVING_RIGHT; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Key::LShift)) { this->speed(); } } void Player::updateAnimation() { if(this->animationStates == PLAYER_ANIMATION_STATES::IDLE) { if(this->animationTime.getElapsedTime().asSeconds() >= 0.5f) { this->currentFrame.top = 0.f; this->currentFrame.left += 32.f; if(this->currentFrame.left >= 128.f) this->currentFrame.left = 0; this->animationTime.restart(); this->sprite.setTextureRect(this->currentFrame); } } else if(this->animationStates == PLAYER_ANIMATION_STATES::MOVING_RIGHT) { if(this->animationTime.getElapsedTime().asSeconds() >= 0.3f) { this->currentFrame.top = 64.f; this->currentFrame.left += 32.f; if(this->currentFrame.left >= 128.f) this->currentFrame.left = 0; this->animationTime.restart(); this->sprite.setTextureRect(this->currentFrame); this->sprite.setScale(2.f,2.f); this->sprite.setOrigin(0.f,0.f); } } else if(this->animationStates == PLAYER_ANIMATION_STATES::MOVING_LEFT) { if(this->animationTime.getElapsedTime().asSeconds() >= 0.3f) { this->currentFrame.top = 64.f; this->currentFrame.left += 32.f; if(this->currentFrame.left >= 128.f) this->currentFrame.left = 0; this->animationTime.restart(); this->sprite.setTextureRect(this->currentFrame); this->sprite.setScale(-2.f,2.f); this->sprite.setOrigin(this->sprite.getGlobalBounds().width/2.f, 0); } } else this->animationTime.restart(); } void Player::update() { this->updateMovement(); this->updateAnimation(); this->createView(); this->updatePhysics(); this->updateAttack(); } void Player::render(sf::RenderTarget &target) { target.draw(this->sprite); }
#include "registration.h" #include "ui_registration.h" #include "QMessageBox" #include "mainwindow.h" #include "total_main.h" registration::registration(QWidget *parent) : QDialog(parent), ui(new Ui::registration) { ui->setupUi(this); socket = new QTcpSocket(this); connect(socket,SIGNAL(readyRead()),this,SLOT(sockReady())); connect(socket,SIGNAL(disconnected()),this,SLOT(sockDisc())); socket->connectToHost("127.0.0.1.",5555); } registration::~registration() { delete ui; } // Кнопка РЕЄСТРАЦІЯ + перевірка реєстрації void registration::on_reg_in_clicked() { QString login_r = ui->login_r->text(); QString password_r = ui->pass_r->text(); QMessageBox *log_info = new QMessageBox(); log_info->setStyleSheet("background-color:rgb(0, 0, 120); color:white;"); if(login_r == "TEST" && password_r == "1234") { log_info->setWindowTitle("Успіх"); log_info->setText("Успішна реєстрація"); log_info->open(); }else { log_info->setWindowTitle("Помилка"); log_info->setText("Помилка реєстрації"); log_info->open(); } } // Кнопка НАЗАД void registration::on_pushButton_back_clicked() { hide(); } void registration::sockDisc() { socket->deleteLater(); } void registration::sockReady() { }
/** * **** Code generated by the RIDL Compiler **** * RIDL has been developed by: * Remedy IT * Westervoort, GLD * The Netherlands * http://www.remedy.nl */ #ifndef __RIDL_TESTC_H_BEJIHBBJ_INCLUDED__ #define __RIDL_TESTC_H_BEJIHBBJ_INCLUDED__ #pragma once #include /**/ "ace/pre.h" #include "tao/x11/stddef.h" #include "tao/x11/basic_traits.h" #include "tao/x11/corba.h" #include "tao/x11/system_exception.h" #include "tao/x11/orb.h" #include "tao/x11/object.h" #include "tao/x11/corba_ostream.h" #include /**/ "tao/x11/versionx11.h" #if TAOX11_MAJOR_VERSION != 1 || TAOX11_MINOR_VERSION != 7 || TAOX11_MICRO_VERSION != 1 #error This file was generated with another RIDL C++11 backend version (1.7.1). Please re-generate. #endif using namespace TAOX11_NAMESPACE; // generated from StubHeaderWriter#enter_module /// @copydoc test.idl::Test namespace Test { // generated from c++11/templates/cli/hdr/typedef.erb /// @copydoc test.idl::Test::F typedef std::array< float, 10 > F; // generated from c++11/templates/cli/hdr/typedef.erb /// @copydoc test.idl::Test::V typedef std::array< std::string, 10 > V; // generated from c++11/templates/cli/hdr/typedef.erb /// @copydoc test.idl::Test::M typedef std::array< std::array< std::array< std::string, 3 >, 2 >, 1 > M; // generated from StubHeaderWriter#enter_interface // generated from c++11/templates/cli/hdr/interface_fwd.erb #if !defined (_INTF_TEST_FOO_FWD_) #define _INTF_TEST_FOO_FWD_ class Foo; class Foo_proxy; typedef Foo_proxy* Foo_proxy_ptr; #endif // !_INTF_TEST_FOO_FWD_ // generated from Base::CodeWriter#at_global_scope } // namespace Test // entering Base::CodeWriter#at_global_scope // generated from c++11/templates/cli/hdr/interface_object_traits.erb #if !defined (_INTF_TEST_FOO_TRAITS_DECL_) #define _INTF_TEST_FOO_TRAITS_DECL_ namespace TAOX11_NAMESPACE { namespace CORBA { template<> object_traits< ::Test::Foo>::shared_ptr_type object_traits< ::Test::Foo>::lock_shared ( ::Test::Foo* p); template<> object_traits< ::Test::Foo>::ref_type object_traits< ::Test::Foo>::narrow ( object_traits<TAOX11_NAMESPACE::CORBA::Object>::ref_type); } // namespace CORBA namespace IDL { template<> struct traits < ::Test::Foo> : public IDL::common_byval_traits <CORBA::object_reference < ::Test::Foo>>, public CORBA::object_traits < ::Test::Foo> { /// std::false_type or std::true_type type indicating whether /// this interface is declared as local typedef std::false_type is_local; /// std::false_type or std::true_type type indicating whether /// this interface is declared as abstract typedef std::false_type is_abstract; template <typename OStrm_, typename Formatter = formatter< ::Test::Foo, OStrm_>> static inline OStrm_& write_on( OStrm_& os_, in_type val_, Formatter fmt_ = Formatter ()) { return fmt_ (os_, val_); } template <typename Formatter = std::false_type> static inline __Writer<Formatter> write (in_type val) { return {val}; } }; } // namespace IDL } // namespace TAOX11_NAMESPACE #endif // !_INTF_TEST_FOO_TRAITS_DECL_ // leaving Base::CodeWriter#at_global_scope namespace Test { // generated from c++11/templates/cli/hdr/interface_pre.erb /// @copydoc test.idl::Test::Foo class Foo : public virtual TAOX11_NAMESPACE::CORBA::Object { public: template <typename T> friend struct TAOX11_CORBA::object_traits; /// @name Member types //@{ typedef TAOX11_IDL::traits< Foo> _traits_type; /// Strong reference type typedef TAOX11_IDL::traits< Foo>::ref_type _ref_type; //@} // generated from c++11/templates/cli/hdr/operation.erb /// @copydoc test.idl::Test::Foo::op virtual void op ( const ::Test::F& p1, ::Test::V& p2, ::Test::M& p3); // generated from c++11/templates/cli/hdr/interface_post.erb protected: typedef std::shared_ptr<Foo> _shared_ptr_type; template <typename _Tp1, typename, typename ...Args> friend TAOX11_CORBA::object_reference<_Tp1> TAOX11_CORBA::make_reference(Args&& ...args); explicit Foo (Foo_proxy_ptr p, bool inherited = false); /// Default constructor Foo () = default; /// Destructor ~Foo () = default; private: /** @name Illegal to be called. Deleted explicitly to let the compiler detect any violation */ //@{ Foo(const Foo&) = delete; Foo(Foo&&) = delete; Foo& operator=(const Foo&) = delete; Foo& operator=(Foo&&) = delete; //@} Foo_proxy_ptr foo_proxy_ {}; }; // class Foo } // namespace Test // generated from StubHeaderIDLTraitsWriter#pre_visit namespace TAOX11_NAMESPACE { namespace IDL { // generated from c++11/templates/cli/hdr/array_idl_traits.erb // Unaliased type : std::array< float, 10 > // MD5 : ABF04919D09ABF9A218FEAC04AA202DD #if !defined(_ALIAS_ABF04919D09ABF9A218FEAC04AA202DD_TRAITS_DECL_) #define _ALIAS_ABF04919D09ABF9A218FEAC04AA202DD_TRAITS_DECL_ template<> struct traits < ::Test::F> : IDL::common_traits< ::Test::F> { /// IDL::traits<> for the element of the array typedef IDL::traits< float> element_traits; /// std::integral_constant type of value_type uint32_t /// indicating the number of dimensions of the array typedef std::integral_constant<uint32_t, 1> dimensions; template <typename OStrm_, typename Formatter = formatter< ::Test::F, OStrm_> > static inline OStrm_& write_on( OStrm_& os_, in_type val_, Formatter fmt_ = Formatter ()) { return fmt_ (os_, val_); } template <typename Formatter = std::false_type> static inline __Writer<Formatter> write (in_type val) { return {val}; } }; template <typename OStrm_, typename Fmt> inline OStrm_& operator <<( OStrm_& os, IDL::traits< ::Test::F>::__Writer<Fmt> w) { typedef IDL::traits< ::Test::F>::__Writer<Fmt> writer_t; typedef typename std::conditional< std::is_same< typename writer_t::formatter_t, std::false_type>::value, formatter< ::Test::F, OStrm_>, typename writer_t::formatter_t>::type formatter_t; return IDL::traits< ::Test::F>::write_on ( os, w.val_, formatter_t ()); } #endif // generated from c++11/templates/cli/hdr/array_idl_traits.erb // Unaliased type : std::array< std::string, 10 > // MD5 : 0586A70043E3B0103619F928C5EC3EA6 #if !defined(_ALIAS_0586A70043E3B0103619F928C5EC3EA6_TRAITS_DECL_) #define _ALIAS_0586A70043E3B0103619F928C5EC3EA6_TRAITS_DECL_ template<> struct traits < ::Test::V> : IDL::common_traits< ::Test::V> { /// IDL::traits<> for the element of the array typedef IDL::traits< std::string> element_traits; /// std::integral_constant type of value_type uint32_t /// indicating the number of dimensions of the array typedef std::integral_constant<uint32_t, 1> dimensions; template <typename OStrm_, typename Formatter = formatter< ::Test::V, OStrm_> > static inline OStrm_& write_on( OStrm_& os_, in_type val_, Formatter fmt_ = Formatter ()) { return fmt_ (os_, val_); } template <typename Formatter = std::false_type> static inline __Writer<Formatter> write (in_type val) { return {val}; } }; template <typename OStrm_, typename Fmt> inline OStrm_& operator <<( OStrm_& os, IDL::traits< ::Test::V>::__Writer<Fmt> w) { typedef IDL::traits< ::Test::V>::__Writer<Fmt> writer_t; typedef typename std::conditional< std::is_same< typename writer_t::formatter_t, std::false_type>::value, formatter< ::Test::V, OStrm_>, typename writer_t::formatter_t>::type formatter_t; return IDL::traits< ::Test::V>::write_on ( os, w.val_, formatter_t ()); } #endif // generated from c++11/templates/cli/hdr/array_idl_traits.erb // Unaliased type : std::array< std::array< std::array< std::string, 3 >, 2 >, 1 > // MD5 : BA0460710F246455F8D8DCE031B10605 #if !defined(_ALIAS_BA0460710F246455F8D8DCE031B10605_TRAITS_DECL_) #define _ALIAS_BA0460710F246455F8D8DCE031B10605_TRAITS_DECL_ template<> struct traits < ::Test::M> : IDL::common_traits< ::Test::M> { /// IDL::traits<> for the element of the array typedef IDL::traits< std::string> element_traits; /// std::integral_constant type of value_type uint32_t /// indicating the number of dimensions of the array typedef std::integral_constant<uint32_t, 3> dimensions; template <typename OStrm_, typename Formatter = formatter< ::Test::M, OStrm_> > static inline OStrm_& write_on( OStrm_& os_, in_type val_, Formatter fmt_ = Formatter ()) { return fmt_ (os_, val_); } template <typename Formatter = std::false_type> static inline __Writer<Formatter> write (in_type val) { return {val}; } }; template <typename OStrm_, typename Fmt> inline OStrm_& operator <<( OStrm_& os, IDL::traits< ::Test::M>::__Writer<Fmt> w) { typedef IDL::traits< ::Test::M>::__Writer<Fmt> writer_t; typedef typename std::conditional< std::is_same< typename writer_t::formatter_t, std::false_type>::value, formatter< ::Test::M, OStrm_>, typename writer_t::formatter_t>::type formatter_t; return IDL::traits< ::Test::M>::write_on ( os, w.val_, formatter_t ()); } #endif // generated from c++11/templates/cli/hdr/interface_idl_traits.erb #if !defined (_INTF_FMT_TEST_FOO_TRAITS_DECL_) #define _INTF_FMT_TEST_FOO_TRAITS_DECL_ template <typename OStrm_> struct formatter< ::Test::Foo, OStrm_> { OStrm_& operator ()( OStrm_& , IDL::traits< ::Test::Foo>::ref_type); }; template <typename OStrm_, typename Fmt> OStrm_& operator <<( OStrm_&, IDL::traits< ::Test::Foo>::__Writer<Fmt>); #endif // !_INTF_FMT_TEST_FOO_TRAITS_DECL_ } // namespace IDL } // namespace TAOX11_NAMESPACE // generated from StubHeaderIDLTraitsDefWriter#pre_visit namespace TAOX11_NAMESPACE { namespace IDL { // generated from c++11/templates/cli/hdr/interface_idl_traits_def.erb template <typename OStrm_> inline OStrm_& formatter< ::Test::Foo, OStrm_>::operator ()( OStrm_& os_, IDL::traits< ::Test::Foo>::ref_type val_) { os_ << IDL::traits<TAOX11_CORBA::Object>::_dump ( std::move (val_), "Test::Foo"); return os_; } template <typename OStrm_, typename Fmt> inline OStrm_& operator <<( OStrm_& os, IDL::traits< ::Test::Foo>::__Writer<Fmt> w) { typedef IDL::traits< ::Test::Foo>::__Writer<Fmt> writer_t; typedef typename std::conditional< std::is_same< typename writer_t::formatter_t, std::false_type>::value, formatter< ::Test::Foo, OStrm_>, typename writer_t::formatter_t>::type formatter_t; return IDL::traits< ::Test::Foo>::write_on ( os, w.val_, formatter_t ()); } } // namespace IDL } // namespace TAOX11_NAMESPACE // generated from c++11/templates/cli/hdr/array_os.erb // Unaliased type : std::array< float, 10 > // MD5 : ABF04919D09ABF9A218FEAC04AA202DD #if !defined (_ALIAS_OSTREAM_ABF04919D09ABF9A218FEAC04AA202DD_DECL_) #define _ALIAS_OSTREAM_ABF04919D09ABF9A218FEAC04AA202DD_DECL_ inline std::ostream& operator<< ( std::ostream& strm, const ::Test::F& _v) { return IDL::traits< ::Test::F>::write_on (strm, _v); } #endif // _ALIAS_OSTREAM_ABF04919D09ABF9A218FEAC04AA202DD_DECL_ // generated from c++11/templates/cli/hdr/array_os.erb // Unaliased type : std::array< std::string, 10 > // MD5 : 0586A70043E3B0103619F928C5EC3EA6 #if !defined (_ALIAS_OSTREAM_0586A70043E3B0103619F928C5EC3EA6_DECL_) #define _ALIAS_OSTREAM_0586A70043E3B0103619F928C5EC3EA6_DECL_ inline std::ostream& operator<< ( std::ostream& strm, const ::Test::V& _v) { return IDL::traits< ::Test::V>::write_on (strm, _v); } #endif // _ALIAS_OSTREAM_0586A70043E3B0103619F928C5EC3EA6_DECL_ // generated from c++11/templates/cli/hdr/array_os.erb // Unaliased type : std::array< std::array< std::array< std::string, 3 >, 2 >, 1 > // MD5 : BA0460710F246455F8D8DCE031B10605 #if !defined (_ALIAS_OSTREAM_BA0460710F246455F8D8DCE031B10605_DECL_) #define _ALIAS_OSTREAM_BA0460710F246455F8D8DCE031B10605_DECL_ inline std::ostream& operator<< ( std::ostream& strm, const ::Test::M& _v) { return IDL::traits< ::Test::M>::write_on (strm, _v); } #endif // _ALIAS_OSTREAM_BA0460710F246455F8D8DCE031B10605_DECL_ // generated from c++11/templates/cli/hdr/interface_os.erb inline std::ostream& operator<< ( std::ostream& strm, IDL::traits< ::Test::Foo>::ref_type _v) { return IDL::traits< ::Test::Foo>::write_on (strm, std::move(_v)); } // generated from c++11/templates/cli/hdr/post.erb #if defined (__TAOX11_INCLUDE_STUB_PROXY__) #include "testCP.h" #endif #include /**/ "ace/post.h" #endif /* __RIDL_TESTC_H_BEJIHBBJ_INCLUDED__ */ // -*- END -*-
/** * File name: ffsnetd.cpp * Desc: daemon process for FusionFS network transfer * Author: dzhao8@hawk.iit.edu * Known issues: the default port number is 9000; and is not changable * * Update history: * - 01/15/2013: add parent directory if necessary for upload mode. * - 07/18/2012: add mkdir(), this is not being used for now. It's not been tested either. * - 07/17/2012: add rmfile() * - 07/07/2012: better error handling - close file handle and iofs if failure occurs * - 06/18/2012: initial development * * To compile this single file: * g++ ffsnetd.cpp -o ffsnetd -I../src -L../src -ludt -lstdc++ -lpthread * NOTE: -I../src (similarly to -L../src) means to include the directory of the udt library, i.e. libudt.so * * You may also need to update the environment variable as: * export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:../src */ #include <cstdlib> #include <netdb.h> #include <fstream> #include <iostream> #include <cstring> #include <unistd.h> #include <udt.h> #include <linux/limits.h> #include <sys/stat.h> #include <cerrno> using namespace std; void* transfile(void*); int main(int argc, char* argv[]) { /* usage: ffsd [server_port] */ if ((2 < argc) || ((2 == argc) && (0 == atoi(argv[1])))) { cout << "usage: ffsd [server_port]" << endl; return 0; } /* use this function to initialize the UDT library */ UDT::startup(); addrinfo hints; addrinfo *res; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_flags = AI_PASSIVE; hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; //DFZ: I know this is a bad practice... string service("9000"); /* default server port */ if (2 == argc) service = argv[1]; if (0 != getaddrinfo(NULL, service.c_str(), &hints, &res)) { cout << "illegal port number or port is busy.\n" << endl; return 0; } UDTSOCKET serv = UDT::socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (UDT::ERROR == UDT::bind(serv, res->ai_addr, res->ai_addrlen)) { cout << "bind: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } freeaddrinfo(res); cout << "FusionFS file transfer is ready at port: " << service << endl; UDT::listen(serv, 10); sockaddr_storage clientaddr; int addrlen = sizeof(clientaddr); UDTSOCKET fhandle; while (true) { if (UDT::INVALID_SOCK == (fhandle = UDT::accept(serv, (sockaddr*)&clientaddr, &addrlen))) { cout << "accept: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } char clienthost[NI_MAXHOST]; char clientservice[NI_MAXSERV]; getnameinfo((sockaddr *)&clientaddr, addrlen, clienthost, sizeof(clienthost), clientservice, sizeof(clientservice), NI_NUMERICHOST|NI_NUMERICSERV); /* cout << "new connection: " << clienthost << ":" << clientservice << endl; */ pthread_t filethread; pthread_create(&filethread, NULL, transfile, new UDTSOCKET(fhandle)); pthread_detach(filethread); } UDT::close(serv); /* use this function to release the UDT library */ UDT::cleanup(); return 0; } /** * Thread to accept file request: download or upload */ void* transfile(void* usocket) { UDTSOCKET fhandle = *(UDTSOCKET*)usocket; delete (UDTSOCKET*)usocket; /* aquiring file name information from client */ char file[1024]; int len; int is_recv; /* 0: download, 1: upload, 2: remove file, 3: make dir */ /* get the request type: download or upload */ if (UDT::ERROR == UDT::recv(fhandle, (char*)&is_recv, sizeof(int), 0)) { cout << "recv: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } /* * The following is for upload */ if (1 == is_recv) { // so the format is to size+content if (UDT::ERROR == UDT::recv(fhandle, (char*)&len, sizeof(int), 0)) { UDT::close(fhandle); cout << "recv: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } if (UDT::ERROR == UDT::recv(fhandle, file, len, 0)) { UDT::close(fhandle); cout << "recv: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } file[len] = '\0'; /*create the parent paths if necessary*/ char pathname[PATH_MAX] = {0}; const char *pch = strrchr(file, '/'); strncpy(pathname, file, pch - file); if (access(pathname, F_OK)) { char cmd[PATH_MAX] = {0}; strcpy(cmd, "mkdir -p "); strcat(cmd, pathname); system(cmd); } /* open the file to write */ fstream ofs(file, ios::out | ios::binary | ios::trunc); int64_t recvsize; int64_t offset = 0; /* get size information */ int64_t size; // receives the file size if (UDT::ERROR == UDT::recv(fhandle, (char*)&size, sizeof(int64_t), 0)) { UDT::close(fhandle); ofs.close(); cout << "send: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } if (size < 0) { UDT::close(fhandle); ofs.close(); cout << "cannot open file " << file << " on the server\n"; return 0; } /* receive the file content */ if (UDT::ERROR == (recvsize = UDT::recvfile(fhandle, ofs, offset, size))) { UDT::close(fhandle); ofs.close(); cout << "recvfile: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } ofs.close(); } /* * the following is for download */ if (0 == is_recv) { /*get the length of the filename*/ if (UDT::ERROR == UDT::recv(fhandle, (char*)&len, sizeof(int), 0)) { UDT::close(fhandle); cout << "recv: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } /*get the file content */ if (UDT::ERROR == UDT::recv(fhandle, file, len, 0)) { UDT::close(fhandle); cout << "recv: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } file[len] = '\0'; /* open the file to read */ fstream ifs(file, ios::in | ios::binary); ifs.seekg(0, ios::end); int64_t size = ifs.tellg(); ifs.seekg(0, ios::beg); /* send file size information */ if (UDT::ERROR == UDT::send(fhandle, (char*)&size, sizeof(int64_t), 0)) { UDT::close(fhandle); ifs.close(); cout << "send: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } UDT::TRACEINFO trace; UDT::perfmon(fhandle, &trace); /* send the file */ int64_t offset = 0; if (UDT::ERROR == UDT::sendfile(fhandle, ifs, offset, size)) { /* DFZ: This error might be triggered if the file size is zero, which is fine. */ UDT::close(fhandle); ifs.close(); cout << "sendfile: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } UDT::perfmon(fhandle, &trace); /* cout << "speed = " << trace.mbpsSendRate << "Mbits/sec" << endl; */ ifs.close(); } /* * The following is for remove files */ if (2 == is_recv) { /*receive the length of the filename to be removed*/ if (UDT::ERROR == UDT::recv(fhandle, (char*)&len, sizeof(int), 0)) { UDT::close(fhandle); cout << "rmfile: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } /*receive the filename string*/ if (UDT::ERROR == UDT::recv(fhandle, file, len, 0)) { UDT::close(fhandle); cout << "rmfile: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } file[len] = '\0'; /*remove the file*/ int stat = unlink(file); if (stat < 0) { UDT::close(fhandle); cout << "rmfile: " << UDT::getlasterror().getErrorMessage() << endl; } /*send return status: success or fail*/ int success = (stat < 0)? 1: 0; if (UDT::ERROR == UDT::send(fhandle, (char*)&success, sizeof(int), 0)) { cout << "rmfile: " << UDT::getlasterror().getErrorMessage() << endl; UDT::close(fhandle); return 0; } } /* * The following is to make a physical directory on the local node */ if (3 == is_recv) { /*receive the length of the directory name to be created*/ if (UDT::ERROR == UDT::recv(fhandle, (char*)&len, sizeof(int), 0)) { UDT::close(fhandle); cout << "rmfile: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } /*receive the directory name*/ if (UDT::ERROR == UDT::recv(fhandle, file, len, 0)) { UDT::close(fhandle); cout << "rmfile: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } file[len] = '\0'; /*create the directory*/ struct stat info; int retstat = lstat(file, &info); if (retstat && (ENOENT == errno)) /*does the pathname exist?*/ { char cmd[PATH_MAX] = {0}; strcpy(cmd, "mkdir -p "); strcat(cmd, file); system(cmd); /*reset the status*/ retstat = 0; } /*send return status: success or fail*/ int success = (retstat < 0)? 1: 0; if (UDT::ERROR == UDT::send(fhandle, (char*)&success, sizeof(int), 0)) { cout << "rmfile: " << UDT::getlasterror().getErrorMessage() << endl; UDT::close(fhandle); return 0; } } /*clean up*/ UDT::close(fhandle); return NULL; }
#include "SDL2DemoFramework.h" #include <DemoUtils/DemoTexture.h> #include <Demo/DemoCollection.h> #include <Demo/Demo3D/DeterministicTree.h> #include "Camera3D.h" int main(int argc,char *argv[]) { unsigned int TreeResX = 6; unsigned int TreeResY = 6; SDL2DemoFramework DemoFramework(800,600,nullptr,new Camera3D); GLuint DummyTexture = CreateTexture(); GLuint BarkTexId = LoadBarkTexture(); DemoFramework.SetDemo( new DemoCollection({ new DeterministicTree(TreeResX,TreeResY,DummyTexture), new DeterministicTree(TreeResX,TreeResY,BarkTexId) }) ); DemoFramework.Loop(); glDeleteTextures(1,&DummyTexture); glDeleteTextures(1,&BarkTexId); return 0; }
#include <iostream> #include <stdio.h> #include <vector> #include <algorithm> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int k; cin >> k; vector<int> v; // stact vector<int> output; for(int i=0; i<k; i++) { string str; int n; cin >> str; if(str == "push") { cin >> n; v.push_back(n); } else if (str == "pop") { if(v.size() ==0) output.push_back(-1); else { output.push_back(v.back()); v.pop_back(); } } else if (str == "top") { if(v.size() ==0) output.push_back(-1); else output.push_back(v.back()); } else if (str == "size") { int tmp = v.size(); output.push_back(tmp); } else if (str == "empty") { if(v.size()==0) output.push_back(1); else output.push_back(0); } } for(int i=0; i<output.size(); i++) { printf("%d\n", output[i]); } return 0; } /* 14 push 1 push 2 top size empty pop pop pop size empty pop push 3 empty top */
#ifndef DiceInterface_h #define DiceInterface_h #include "Config.h" class DiceInterface { public: virtual void showDigit(int digit) = 0; }; DiceInterface* createDice(int kind); class traditional: public DiceInterface { public: void showDigit(int digit); private: void printDigit(int pins[], int size); void clearLED(); static const int digit1[]; static const int digit2[]; static const int digit3[]; static const int digit4[]; static const int digit5[]; static const int digit6[]; static const int allLED[]; }; class sevenSegment: public DiceInterface { public: void showDigit(int digit); private: void printDigit(int pins[], int size); void clearLED(); static const int digit1[]; static const int digit2[]; static const int digit3[]; static const int digit4[]; static const int digit5[]; static const int digit6[]; static const int allLED[]; }; class binary: public DiceInterface { public: void showDigit(int digit); private: void printDigit(int pins[], int size); void clearLED(); static const int digit1[]; static const int digit2[]; static const int digit3[]; static const int digit4[]; static const int digit5[]; static const int digit6[]; static const int allLED[]; }; #endif
#include <iostream> int operate (int a, int b) { return a*b; } float operate (float a, float b) { return a/b; } int main() { int x=5, y=2; float n=5.0, m=2.0; std::cout << "Function 1: >" << operate (x,y) << "\n"; std::cout << "\n"; std::cout << "Function 2: >" << operate (n,m) << "\n"; std::cin.get(); std::cin.get(); return 0; }
#pragma once class ASystemInfo { public: ASystemInfo(); ~ASystemInfo(); int NumberOfProcessors; };
#ifndef _neuron_ #define _neuron_ #include <stdio.h> #include <stdlib.h> #include <iostream> #include <string> #include "windows.h" #include <vector> using namespace std; static class neuron { public: int tips, memb; string name; int mas;//вес нейрона vector <int> memTips; vector <int> memMemb;//память нейрона void loadMem(string neuname);//загружает память нейрона void comp();//расчитывает вес нейрона void save();//сохраняет новый опыт }; #endif
// -*- C++ -*- // // Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory, // Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC // // This file is part of FreePOOMA. // // FreePOOMA is free software; you can redistribute it and/or modify it // under the terms of the Expat license. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Expat // license for more details. // // You should have received a copy of the Expat license along with // FreePOOMA; see the file LICENSE. // //----------------------------------------------------------------------------- // Classes: // ConstantFunction - Tag class for defining a constant-function-engine. // Engine - Specialization for ConstantFunction // NewEngine - Specializations for ConstantFunction //----------------------------------------------------------------------------- #ifndef POOMA_ENGINE_CONSTANTFUNCTIONENGINE_H #define POOMA_ENGINE_CONSTANTFUNCTIONENGINE_H /** @file * @ingroup Engine * @brief * Constant-function-engine objects provide a way to make a scalar behave like * an array. */ //----------------------------------------------------------------------------- // Includes: //----------------------------------------------------------------------------- #include "Domain/SliceDomain.h" #include "Engine/Engine.h" #include "Layout/INode.h" #include "Layout/DomainLayout.h" #include "PETE/ErrorType.h" /** * ConstantFunction is just a tag class for the constant-function engine, * which makes a scalar look like an Array. */ struct ConstantFunction { }; /** * Engine<Dim, T, ConstantFunction> is a specialization of Engine for * ConstantFunction. * * This does all of the usual Engine things: * - Typedefs for the tag, element types, domain and dimensions. * - Operator() with integers to evaluate elements quickly. * - Operator() with a domain to subset. * - Accessor for the domain. */ template<int Dim, class T> class Engine<Dim, T, ConstantFunction> { public: //--------------------------------------------------------------------------- // Exported typedefs and constants typedef ConstantFunction Tag_t; typedef Engine<Dim, T, ConstantFunction> This_t; typedef This_t Engine_t; typedef Interval<Dim> Domain_t; typedef DomainLayout<Dim> Layout_t; typedef T Element_t; typedef ErrorType ElementRef_t; enum { dimensions = Dim }; enum { hasDataObject = false }; enum { dynamic = false }; enum { zeroBased = false }; enum { multiPatch = false }; //--------------------------------------------------------------------------- // Default constructor. Engine() { } //--------------------------------------------------------------------------- // Construct from a domain object. explicit Engine(const Domain_t &domain, T val = T()) : val_m(val), domain_m(domain) { for (int d = 0; d < Dim; ++d) firsts_m[d] = domain[d].first(); } template<class Layout> explicit Engine(const Layout &layout, T val = T()) : val_m(val), domain_m(layout.domain()) { for (int d = 0; d < Dim; ++d) firsts_m[d] = domain_m[d].first(); } //--------------------------------------------------------------------------- // Copy constructor. Engine(const Engine<Dim, T, ConstantFunction> &model) : val_m(model.constant()), domain_m(model.domain()) { for (int d = 0; d < Dim; ++d) { firsts_m[d] = model.firsts_m[d]; } } //--------------------------------------------------------------------------- // Construct from various sorts of domains (e.g., take a view). template<class DT> Engine(const Engine<Dim, T, ConstantFunction> &e, const Domain<Dim, DT> &dom) : val_m(e.constant()), domain_m(Pooma::NoInit()) { const typename DT::Domain_t &domain = dom.unwrap(); for (int d = 0; d < Dim; ++d) { domain_m[d] = Interval<1>(domain[d].length()); firsts_m[d] = 0; } } template<int Dim2, class DT> Engine(const Engine<Dim2, T, ConstantFunction> &e, const SliceDomain<DT> &dom) : val_m(e.constant()), domain_m(Pooma::NoInit()) { // The domain's dimension should match ours. CTAssert(DT::sliceDimensions == Dim); CTAssert(DT::dimensions == Dim2); const typename DT::SliceDomain_t &domain = dom.sliceDomain(); for (int d = 0; d < Dim; ++d) { domain_m[d] = Interval<1>(domain[d].length()); firsts_m[d] = 0; } } template<class Domain> Engine(const Engine<Dim, T, ConstantFunction> &e, const Node<Domain> &node) : val_m(e.constant()), domain_m(Pooma::NoInit()) { // The nodes's dimension should match ours. CTAssert(Domain::dimensions == Dim); const Domain &domain = node.domain(); for (int d = 0; d < Dim; ++d) { domain_m[d] = Interval<1>(domain[d].length()); firsts_m[d] = 0; } } Engine(const Engine<Dim, T, ConstantFunction> &e, const INode<Dim> &inode) : val_m(e.constant()), domain_m(Pooma::NoInit()) { const typename INode<Dim>::Domain_t &domain = inode.domain(); for (int d = 0; d < Dim; ++d) { domain_m[d] = Interval<1>(domain[d].length()); firsts_m[d] = 0; } } //--------------------------------------------------------------------------- // Element access via ints for speed. // We only need read() functions since this engine should only be used in // a read-only array. inline Element_t read(int) const { return val_m; } inline Element_t read(int, int) const { return val_m; } inline Element_t read(int, int, int) const { return val_m; } inline Element_t read(int, int, int, int) const { return val_m; } inline Element_t read(int, int, int, int, int) const { return val_m; } inline Element_t read(int, int, int, int, int, int) const { return val_m; } inline Element_t read(int, int, int, int, int, int, int) const { return val_m; } inline Element_t read(const Loc<Dim> &) const { return val_m; } //--------------------------------------------------------------------------- // Return the domain. const Domain_t &domain() const { return domain_m; } //--------------------------------------------------------------------------- // Return a layout. inline Layout_t layout() const { return Layout_t(domain_m); } // Return the first value for the specified direction. inline int first(int i) const { PAssert(i >= 0 && i < Dim); return firsts_m[i]; } //--------------------------------------------------------------------------- // Accessors/modifiers. T constant() const { return val_m; } void setConstant(T val) { val_m = val; } private: T val_m; Domain_t domain_m; int firsts_m[Dim]; }; /** * NewEngine<Engine,SubDomain> * * Specializations of NewEngine for subsetting a constant-function-engine with * an arbitrary domain. */ template <int Dim, class T> struct NewEngine<Engine<Dim, T, ConstantFunction>, Interval<Dim> > { typedef Engine<Dim, T, ConstantFunction> Type_t; }; template <int Dim, class T> struct NewEngine<Engine<Dim, T, ConstantFunction>, Range<Dim> > { typedef Engine<Dim, T, ConstantFunction> Type_t; }; template <int Dim, class T, int SliceDim> struct NewEngine<Engine<Dim,T,ConstantFunction>, SliceInterval<Dim,SliceDim> > { typedef Engine<SliceDim,T,ConstantFunction> Type_t; }; template <int Dim, class T, int SliceDim> struct NewEngine<Engine<Dim,T,ConstantFunction>, SliceRange<Dim,SliceDim> > { typedef Engine<SliceDim,T,ConstantFunction> Type_t; }; template <int Dim, class T, class Domain> struct NewEngine<Engine<Dim, T, ConstantFunction>, Node<Domain> > { typedef Engine<Dim, T, ConstantFunction> Type_t; }; template <int Dim, class T> struct NewEngine<Engine<Dim, T, ConstantFunction>, INode<Dim> > { typedef Engine<Dim, T, ConstantFunction> Type_t; }; #endif // POOMA_ENGINE_CONSTANTFUNCTIONENGINE_H // ACL:rcsinfo // ---------------------------------------------------------------------- // $RCSfile: ConstantFunctionEngine.h,v $ $Author: richard $ // $Revision: 1.21 $ $Date: 2004/11/01 18:16:37 $ // ---------------------------------------------------------------------- // ACL:rcsinfo
#include<bits/stdc++.h> using namespace std; int pokes[1000100]; int desaf[1000100]; int main(){ int n; scanf("%d", &n); for(int i=0;i<n;i++){ scanf("%d", &desaf[i]); } int m; scanf("%d", &m); for(int i=0;i<m;i++){ scanf("%d", &pokes[i]); } sort(desaf, desaf+n); sort(pokes, pokes+m); int i=0, j=0; long long soma = 0; while(true){ if(i>=m) break; if(j>=n) break; if( pokes[i] >= desaf[j] ){ soma+=pokes[i]; j++; } i++; } if(j>=n){ printf("%d\n", soma); }else{ printf("impossivel\n"); } }
/*************************************************************************** qcanvas.h - description ------------------- begin : Tue Jul 23 2002 copyright : (C) 2002 by Marco Bubke email : marco@bubke.de ***************************************************************************/ /*************************************************************************** * * * This program 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; version 2.1 of * * the License. * * * ***************************************************************************/ #ifndef QCANVAS_H #define QCANVAS_H #include <qgl.h> #include "canvas.h" /** *@author Marco Bubke */ namespace Ah { class QCanvas : public Canvas, public QGLWidget{ public: QCanvas(QWidget* parent); ~QCanvas(); virtual void initilizeGL(); virtual void paintGL(); virtual void resizeGL(int width, int height); protected: //!only for testing virtual void keyPressEvent(QKeyEvent* e); virtual void mouseReleaseEvent(QMouseEvent* e); virtual void postdraw(); private: Node* element; }; }; #endif
#pragma once #include "data/cursor.h" namespace data { struct cursor_iterator: std::iterator<std::random_access_iterator_tag, double> { double get_value() const { data::pcursor_t cursor(master_->clone(index)); if (cursor->is_valid()) { return cursor->get_time(); } return 0.0; } double operator*() const { return get_value(); } bool operator<(const cursor_iterator &d) const { return index < d.index; } bool operator==(const cursor_iterator &d) const { return index == d.index; } cursor_iterator &operator++() { ++index; return *this; } cursor_iterator operator++(int) { cursor_iterator temp(*this); ++temp; return temp; } cursor_iterator &operator--() { --index; return *this; } cursor_iterator operator--(int) { cursor_iterator temp(*this); --temp; return temp; } cursor_iterator &operator+=(int z) { index+=z; return *this; } cursor_iterator operator+(int z) const { return cursor_iterator(master_, index+z); } cursor_iterator operator-(int z) const { return cursor_iterator(master_, index-z); } size_t operator-(const cursor_iterator &l) const { return index-l.index; } cursor_iterator() : master_(), index(0) {} cursor_iterator(const cursor_iterator &l) : master_(l.master_), index(l.index) {} cursor_iterator(data::pcursor_t cur, int i=0) : master_(cur), index(i<0 ? cur->rest() : i) {} private: data::pcursor_t master_; int index; }; }
/***************************************************************** * Filename: food.h * * Author: Patrick Cook * Start Date: 9-23-2020 * * Description: Interface for Food class. * *****************************************************************/ #ifndef FOOD_H #define FOOD_H #include <QImage> #include <QGraphicsRectItem> #include <QObject> class Food : public QGraphicsRectItem { public: explicit Food(); void setFood(QPointF pos = QPointF(0,0)); void advance(int phase); void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); QRectF boundingRect() const; private: QString foodImgPath; }; #endif // FOOD_H
#include "HeroPuppeteer.h" #include <SFML/Graphics.hpp> constexpr unsigned WINDOW_WIDHT = 800; constexpr unsigned WINDOW_HEIGHT = 600; // Функция создаёт окно определённого размера с определённым заголовком. void createWindow(sf::RenderWindow& window) { sf::VideoMode videoMode(WINDOW_WIDHT, WINDOW_HEIGHT); const std::string title = "Controlling Hero: Animated Sprite + Puppeteer"; sf::ContextSettings settings; settings.antialiasingLevel = 4; window.create(videoMode, title, sf::Style::Default, settings); } void pollEvents(sf::RenderWindow& window) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } } } void update(sf::Clock& clock, HeroPuppeteer& puppeteer) { float dt = clock.restart().asSeconds(); puppeteer.update(dt); } void drawFrame(sf::RenderWindow& window, AnimatedSprite& heroSprite) { // Рисуем анимированный спрайт как обычный спрайт: вызовом window.draw. window.clear(sf::Color(0x20, 0x20, 0x20)); window.draw(heroSprite); window.display(); } int main() { sf::RenderWindow window; createWindow(window); sf::Clock clock; AnimatedSprite heroSprite; if (!heroSprite.loadFromFiles("man_hero.png", "man_hero.atlas")) { return 1; } heroSprite.setPosition({0.1f * float(WINDOW_WIDHT), 0.9f * float(WINDOW_HEIGHT)}); HeroPuppeteer heroPuppeteer(heroSprite); while (window.isOpen()) { pollEvents(window); update(clock, heroPuppeteer); drawFrame(window, heroSprite); } }
//C++ program showing inheritance #include<iostream> using namespace std; #include<conio.h> class Person { private: int personid,age; string name; public: void read1() { cout<<"Enter the name,id and age of the person"; getline(cin,name); cin>>personid; cin>>age; } void print1() { cout<<'\n'<<"******Details Entered******"<<endl; cout<<"Name of poerson "<<name<<endl; cout<<"ID of the person "<<personid<<endl; cout<<"Age of the perosn "<<age<<endl; } }; class address:public Person { private: int hno; string hname,sname,po; public: void read2() { read1(); cout<<"Enter the house number house name,street name,post office"; cin>>hno; getline(cin,hname); getline(cin,sname); getline(cin,po); } void print2() { print1(); cout<<"The address of the person is "<<endl; cout<<"House number: "<<hno<<endl; cout<<"House name: "<<hname<<endl; cout<<"Street name: "<<sname<<endl; cout<<"Post Office: "<<po<<endl; } }; int main() { address A; A.read2(); A.print2(); getch(); return 0; }
/**************************************************************************** ** Meta object code from reading C++ file 'mainwindow.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.10.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../Ejemplo3/mainwindow.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'mainwindow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.10.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_MainWindow_t { QByteArrayData data[14]; char stringdata0[247]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = { { QT_MOC_LITERAL(0, 0, 10), // "MainWindow" QT_MOC_LITERAL(1, 11, 6), // "fTimer" QT_MOC_LITERAL(2, 18, 0), // "" QT_MOC_LITERAL(3, 19, 21), // "on_pushButton_clicked" QT_MOC_LITERAL(4, 41, 15), // "teclado_pressed" QT_MOC_LITERAL(5, 57, 19), // "on_Bderecha_pressed" QT_MOC_LITERAL(6, 77, 20), // "on_Bderecha_released" QT_MOC_LITERAL(7, 98, 21), // "on_Bizquierda_pressed" QT_MOC_LITERAL(8, 120, 22), // "on_Bizquierda_released" QT_MOC_LITERAL(9, 143, 20), // "on_Badelante_pressed" QT_MOC_LITERAL(10, 164, 21), // "on_Badelante_released" QT_MOC_LITERAL(11, 186, 17), // "on_Batras_pressed" QT_MOC_LITERAL(12, 204, 18), // "on_Batras_released" QT_MOC_LITERAL(13, 223, 23) // "on_push_punto_2_clicked" }, "MainWindow\0fTimer\0\0on_pushButton_clicked\0" "teclado_pressed\0on_Bderecha_pressed\0" "on_Bderecha_released\0on_Bizquierda_pressed\0" "on_Bizquierda_released\0on_Badelante_pressed\0" "on_Badelante_released\0on_Batras_pressed\0" "on_Batras_released\0on_push_punto_2_clicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_MainWindow[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 12, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 74, 2, 0x0a /* Public */, 3, 0, 75, 2, 0x08 /* Private */, 4, 0, 76, 2, 0x08 /* Private */, 5, 0, 77, 2, 0x08 /* Private */, 6, 0, 78, 2, 0x08 /* Private */, 7, 0, 79, 2, 0x08 /* Private */, 8, 0, 80, 2, 0x08 /* Private */, 9, 0, 81, 2, 0x08 /* Private */, 10, 0, 82, 2, 0x08 /* Private */, 11, 0, 83, 2, 0x08 /* Private */, 12, 0, 84, 2, 0x08 /* Private */, 13, 0, 85, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0 // eod }; void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { MainWindow *_t = static_cast<MainWindow *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->fTimer(); break; case 1: _t->on_pushButton_clicked(); break; case 2: _t->teclado_pressed(); break; case 3: _t->on_Bderecha_pressed(); break; case 4: _t->on_Bderecha_released(); break; case 5: _t->on_Bizquierda_pressed(); break; case 6: _t->on_Bizquierda_released(); break; case 7: _t->on_Badelante_pressed(); break; case 8: _t->on_Badelante_released(); break; case 9: _t->on_Batras_pressed(); break; case 10: _t->on_Batras_released(); break; case 11: _t->on_push_punto_2_clicked(); break; default: ; } } Q_UNUSED(_a); } const QMetaObject MainWindow::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow.data, qt_meta_data_MainWindow, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *MainWindow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *MainWindow::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0)) return static_cast<void*>(const_cast< MainWindow*>(this)); return QMainWindow::qt_metacast(_clname); } int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 12) qt_static_metacall(this, _c, _id, _a); _id -= 12; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 12) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 12; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
/* * stopwatch.hpp * * Created on: Jul 12, 2020 12:07 * Description: * * Source: * [1] https://github.com/sailormoon/stopwatch * [2] https://github.com/rxdu/stopwatch * * Copyright (c) 2019 sailormoon <http://unlicense.org> * Copyright (c) 2020 Weston Robot Pte. Ltd. * * License: <http://unlicense.org> */ #ifndef STOPWATCH_HPP #define STOPWATCH_HPP #include <array> #include <chrono> #include <cstdint> #include <algorithm> #include <thread> namespace westonrobot { // only supported on x86 processors #if (defined __x86_64__) || (defined __i386) // An implementation of the 'TrivialClock' concept using the rdtscp instruction. struct rdtscp_clock { using rep = std::uint64_t; using period = std::ratio<1>; using duration = std::chrono::duration<rep, period>; using time_point = std::chrono::time_point<rdtscp_clock, duration>; static time_point now() noexcept { std::uint32_t hi, lo; __asm__ __volatile__("rdtscp" : "=d"(hi), "=a"(lo)); return time_point(duration((static_cast<std::uint64_t>(hi) << 32) | lo)); } }; // A timer using the specified clock. template <class Clock = std::chrono::system_clock> struct timer { using time_point = typename Clock::time_point; using duration = typename Clock::duration; timer(const duration duration) : expiry(Clock::now() + duration) {} timer(const time_point expiry) : expiry(expiry) {} bool done() const { return done(Clock::now()); } bool done(const time_point now) const { return now >= expiry; } duration remaining() const { return remaining(Clock::now()); }; duration remaining(const time_point now) const { return expiry - now; } const time_point expiry; }; template <class Clock = std::chrono::system_clock> constexpr timer<Clock> make_timer(const typename Clock::duration duration) { return timer<Clock>(duration); } // Times how long it takes a function to execute using the specified clock. template <class Clock = rdtscp_clock, class Func> typename Clock::duration time_func(Func &&function) { const auto start = Clock::now(); function(); return Clock::now() - start; } // Samples the given function N times using the specified clock. template <std::size_t N, class Clock = rdtscp_clock, class Func> std::array<typename Clock::duration, N> sample(Func &&function) { std::array<typename Clock::duration, N> samples; for (std::size_t i = 0u; i < N; ++i) { samples[i] = time_func<Clock>(function); } std::sort(samples.begin(), samples.end()); return samples; } #endif /* __x86_64__ or __i386 */ struct StopWatch { using Clock = std::chrono::high_resolution_clock; using time_point = typename Clock::time_point; using duration = typename Clock::duration; StopWatch() { tic_point = Clock::now(); }; time_point tic_point; void tic() { tic_point = Clock::now(); }; double toc() { return std::chrono::duration_cast<std::chrono::microseconds>(Clock::now() - tic_point) .count() / 1000000.0; }; // toc() in different units double stoc() { return std::chrono::duration_cast<std::chrono::seconds>(Clock::now() - tic_point) .count(); }; double mtoc() { return std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - tic_point) .count(); }; double utoc() { return std::chrono::duration_cast<std::chrono::microseconds>(Clock::now() - tic_point) .count(); }; double ntoc() { return std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now() - tic_point) .count(); }; }; struct Timer { using Clock = std::chrono::high_resolution_clock; using time_point = typename Clock::time_point; using duration = typename Clock::duration; Timer() { tic_point = Clock::now(); }; time_point tic_point; void reset() { tic_point = Clock::now(); }; // you have to call reset() before calling sleep functions void sleep_until_ms(int64_t period_ms) { int64_t duration = period_ms - std::chrono::duration_cast<std::chrono::milliseconds>( Clock::now() - tic_point) .count(); if (duration > 0) std::this_thread::sleep_for(std::chrono::milliseconds(duration)); }; void sleep_until_us(int64_t period_us) { int64_t duration = period_us - std::chrono::duration_cast<std::chrono::microseconds>( Clock::now() - tic_point) .count(); if (duration > 0) std::this_thread::sleep_for(std::chrono::microseconds(duration)); }; }; } // namespace westonrobot #endif // STOPWATCH_HPP
#ifndef _HS_SFM_BUNDLE_ADJUSTMENT_BA_GCP_CONSTRAINED_ANALYTICAL_JACOBIAN_MATRIX_CALCULATOR_HPP_ #define _HS_SFM_BUNDLE_ADJUSTMENT_BA_GCP_CONSTRAINED_ANALYTICAL_JACOBIAN_MATRIX_CALCULATOR_HPP_ #include "hs_sfm/bundle_adjustment/ba_naive_analytical_jacobian_matrix_calculator.hpp" #include "hs_sfm/bundle_adjustment/ba_gcp_constrained_vector_function.hpp" #include "hs_sfm/bundle_adjustment/ba_gcp_constrained_jacobian_matrix.hpp" namespace hs { namespace sfm { namespace ba { template <typename _VectorFunction> class BAGCPConstrainedAnalyticalJacobianMatrixCalculator; template <typename _Scalar> class BAGCPConstrainedAnalyticalJacobianMatrixCalculator< BAGCPConstrainedVectorFunction<_Scalar> > { public: typedef _Scalar Scalar; typedef int Err; typedef BAGCPConstrainedVectorFunction<Scalar> VectorFunction; typedef BANaiveVectorFunction<Scalar> NaiveVectorFunction; typedef BANaiveAnalyticalJacobianMatrixCalculator<NaiveVectorFunction> NaiveJacobianMatrixCalculator; typedef typename VectorFunction::XVector XVector; typedef typename VectorFunction::YVector YVector; typedef typename VectorFunction::Index Index; typedef BAGCPConstrainedJacobianMatrix<Scalar, Index, VectorFunction::params_per_feature_, VectorFunction::params_per_camera_, VectorFunction::params_per_point_> JacobianMatrix; public: Err operator() (const VectorFunction& vector_function, const XVector& x, JacobianMatrix& jacobian_matrix) const { jacobian_matrix.set_number_of_gcps(vector_function.number_of_gcps()); return naive_jacobian_matrix_calculator_( NaiveVectorFunction(vector_function), x, jacobian_matrix.naive_jacobian_matrix()); } private: NaiveJacobianMatrixCalculator naive_jacobian_matrix_calculator_; }; } } } #endif
#pragma once class GameTimer { public: GameTimer(); //~GameTimer(void); float TotalTime() const; float DeltaTime() const; void Reset(); void Start(); void Stop(); void Tick(); private: double mSecondsPerCount;//每秒计时次数 double mDeltaTime; __int64 mBaseTime;//各个编译器对int4支持不一样,__int64是win支持的64longlong类型 __int64 mPausedTime; __int64 mStopTime; __int64 mPrevTime;//上一帧时间 __int64 mCurrTime; bool mStopped; };
//cpp #include "tic_tac_toe_manager.h" TicTacToeManager::TicTacToeManager(TicTacToeData& d) { games = d.get_games(); for (int i = 0; i < games.size(); i++) { update_winner_count(games.at(i)->get_winner()); } } void TicTacToeManager::save_game(std::unique_ptr<TicTacToe> &game) { update_winner_count(game->get_winner()); games.push_back(std::move(game)); data.save_games(games); } void TicTacToeManager::update_winner_count(std::string winner) { if (winner == "X") { x_wins++; } else if (winner == "O") { o_wins++; } else if (winner == "C") { ties++; } } std::ostream& operator<<(std::ostream& out, const TicTacToeManager& m) { for (auto& game : m.games) { out << *game; out << "Winner of last game: " <<game->get_winner() << "\n"; } out << "Win History"; out << "\nO wins: " << m.o_wins << "\n"; out << "X wins: " << m.x_wins << "\n"; out << "Ties: " << m.ties << "\n"; return out; }
/** * @file motor.cpp * @date 2019/04/20 22:38 * * @author <a href="mailto:shuke.wang@memblaze.com">shuke.wang@memblaze.com</a> * * @brief motor * @note */ #include "motor.h" CondomMotor condomMotor; void CondomMotor::init(void) { } void CondomMotor::deinit(void) { } void CondomMotor::pushOut(PathType_e pathType) { } void CondomMotor::openDoor(PathType_e pathType) { } void CondomMotor::pullBack(PathType_e pathType) { } void CondomMotor::closeDoor(PathType_e pathType) { } void CondomMotor::test(void) { }
// This file has been generated by Py++. #ifndef KeyFrame_hpp__pyplusplus_wrapper #define KeyFrame_hpp__pyplusplus_wrapper void register_KeyFrame_class(); #endif//KeyFrame_hpp__pyplusplus_wrapper
#include<bits/stdc++.h> using namespace std; int n, m; string s[550]; bool existe(int i, int j){ return (i>=0) && (j>= 0) && (i < n) && (j < m) && (s[i][j] == '*'); } int main(){ std::ios_base::sync_with_stdio(false); cin.tie(); cout.tie(); long long marcadas = 0; cin >> n >> m; for(int i = 0; i < n; i++){ cin >> s[i]; for(auto c : s[i]){ if(c == '*') marcadas++; } } // for(int i=0; i < n ; i++){ // for(int j =0; j < m ; j++){ // printf("%c", s[i][j]); // } // printf("\n"); // } long long passei = 1; for(int i = 0; i < n; i++){ for(int j =0; j < m ; j++){ if(s[i][j] == '*'){ if(existe(i-1, j) && existe(i, j-1) && existe(i+1, j) && existe(i, j+1)){ //cout << "centro: (" << i << ", " << j << ")" << endl; int k = i; while(k > 0){ k--; if(s[k][j] != '*') break; else passei++; } k = j; while(k > 0){ k--; if(s[i][k] != '*') break; else passei++; } k = i; while(k < n-1){ k++; if(s[k][j] != '*') break; else passei++; } k = j; while(k < m-1){ k++; if(s[i][k] != '*') break; else passei++; } if(passei == marcadas) cout << "YES" << endl; else cout << "NO" << endl; return 0; } } } } cout << "NO" << endl; //cout << "passei: " << passei << " marcadas: " << marcadas << endl; }
/** * * @file ModelBase.cpp * @author Naoki Takahashi * **/ #include "ModelBase.hpp" namespace Kinematics { namespace Model { ModelBase::ModelBase(const std::string &new_model_file_name) { model_file_name = new_model_file_name; access_model_mutex = std::make_unique<std::mutex>(); } ModelBase::~ModelBase() { } std::mutex &ModelBase::get_access_model_mutex() { return *access_model_mutex; } std::string ModelBase::model_file() { return model_file_name; } } }
#include "CRPGServer.h" #pragma comment (lib , "ws2_32.lib") #pragma comment (lib , "winmm.lib") int main() { CRPGServer* zoneServer = new CRPGServer(); if (!zoneServer->Init(".\\ServerInfo.ini")) return -1; zoneServer->Run(); zoneServer->Cleanup(); SAFE_DELETE(zoneServer); system("pause"); return 0; }
class Solution { public: int maxProfit(vector<int>& prices) { if(prices.empty() || prices.size() == 1) return 0; int smallest = prices[0]; int profit = 0; for(int i = 1; i < prices.size(); i++) { profit = max(profit, prices[i] - smallest); smallest = min(smallest, prices[i]); } return profit; } };
// CGlutPlayDialog.cpp : implementation file // #include "stdafx.h" #include "ComputerizedDanceClassroomApplication.h" #include "GlutPlayDialog.h" #include "afxdialogex.h" #include "SampleViewer.h" #include "PlayDialog.h" #include "NiTE.h" #include "ErrorDialog.h" #include "ComputerizedDanceClassroomApplicationDlg.h" #include "ExitDialog.h" //IMPLEMENT_DYNAMIC(CGlutPlayDialog, CDialogEx) CGlutPlayDialog::CGlutPlayDialog(CWnd* pParent /*=NULL*/) : CDialogEx(CGlutPlayDialog::IDD, pParent) { } CGlutPlayDialog::~CGlutPlayDialog() { } void CGlutPlayDialog::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CGlutPlayDialog, CDialogEx) ON_BN_CLICKED(IDC_BUTTON1_GLUT_BACK, &CGlutPlayDialog::OnBnClickedButton1) ON_BN_CLICKED(IDC_RADIO1, &CGlutPlayDialog::OnBnClickedRadio1) ON_BN_CLICKED(IDC_RADIO2, &CGlutPlayDialog::OnBnClickedRadio2) ON_BN_CLICKED(IDC_RADIO12, &CGlutPlayDialog::OnBnClickedRadio12) ON_BN_CLICKED(IDC_RADIO13, &CGlutPlayDialog::OnBnClickedRadio13) ON_BN_CLICKED(IDC_RADIO14, &CGlutPlayDialog::OnBnClickedRadio14) ON_BN_CLICKED(IDC_RADIO15, &CGlutPlayDialog::OnBnClickedRadio15) ON_BN_CLICKED(IDC_RADIO18, &CGlutPlayDialog::OnBnClickedRadio18) ON_BN_CLICKED(IDC_RADIO19, &CGlutPlayDialog::OnBnClickedRadio19) ON_WM_SYSCOMMAND() END_MESSAGE_MAP() // CGlutPlayDialog message handlers BOOL CGlutPlayDialog::OnInitDialog() { m_Font_button.CreatePointFont(100, _T("MS Shell Dlg")); GetDlgItem(IDC_BUTTON1_GLUT_BACK)->SetFont(&m_Font_button); m_Font_text.CreatePointFont(100, _T("MS Shell Dlg")); GetDlgItem(IDC_STATIC1)->SetFont(&m_Font_text); GetDlgItem(IDC_STATIC2)->SetFont(&m_Font_text); GetDlgItem(IDC_STATIC4)->SetFont(&m_Font_text); GetDlgItem(IDC_STATIC5)->SetFont(&m_Font_text); CheckRadioButton(IDC_RADIO18,IDC_RADIO19,IDC_RADIO18); CheckRadioButton(IDC_RADIO1,IDC_RADIO2,IDC_RADIO1); CheckRadioButton(IDC_RADIO12,IDC_RADIO13,IDC_RADIO12); CheckRadioButton(IDC_RADIO14,IDC_RADIO15,IDC_RADIO14); OptionSelect = 1; skeletonFrameIndex = 0; openni::Status rc = openni::STATUS_OK; rc = sampleViewer.Init(0, NULL); if (rc != openni::STATUS_OK) { sampleViewer.~SampleViewer(); CDialogEx::OnCancel(); //CErrorDialog dlg; //dlg.DoModal(); exit(1); } CRect rect; GetDlgItem(opengl_win)->GetWindowRect(rect); ScreenToClient(rect); openGLControl.Create(rect, this); return TRUE; } void CGlutPlayDialog::OnBnClickedButton1() { // TODO: Add your control notification handler code here sampleViewer.~SampleViewer(); CDialogEx::OnCancel(); CPlayDialog dlg; dlg.DoModal(); } void CGlutPlayDialog::OnBnClickedRadio1() { // TODO: Add your control notification handler code here g_drawRecordingFrameId = true; } void CGlutPlayDialog::OnBnClickedRadio2() { // TODO: Add your control notification handler code here g_drawRecordingFrameId = false; } void CGlutPlayDialog::OnBnClickedRadio12() { // TODO: Add your control notification handler code here g_drawRecordingBackground = true; } void CGlutPlayDialog::OnBnClickedRadio13() { // TODO: Add your control notification handler code here g_drawRecordingBackground = false; } void CGlutPlayDialog::OnBnClickedRadio14() { // TODO: Add your control notification handler code here g_drawRecordingDepth = true; } void CGlutPlayDialog::OnBnClickedRadio15() { // TODO: Add your control notification handler code here g_drawRecordingDepth = false; } void CGlutPlayDialog::OnBnClickedRadio18() { // TODO: Add your control notification handler code here g_drawStudentSkeleton = true; } void CGlutPlayDialog::OnBnClickedRadio19() { // TODO: Add your control notification handler code here g_drawStudentSkeleton = false; } void CGlutPlayDialog::OnSysCommand(UINT nID, LPARAM lParam) { // TODO: Add your message handler code here and/or call default if (nID == SC_CLOSE) { // add code so message pops up extern_nID = nID; extern_lParam = lParam; CExitDialog Dlg; Dlg.DoModal(); } }
#include "Wall.h" /*//////////////////////////////////////////////////// PlaneArrayクラス 実装部 Plane構造体を平面壁の個数分確保し,平面壁全体の オペレーションを行うクラス.このクラスを介して Plane構造体に含まれている情報にアクセスする. ////////////////////////////////////////////////////*/ PlaneArray::PlaneArray():PI(3.14159265358979323846264338328){ plane = 0; planeNum = 0; } PlaneArray::~PlaneArray(){ delete [] plane; } void PlaneArray::SetPlaneNum(int PlaneNum){ planeNum = PlaneNum; if(plane) delete [] plane; plane = new Plane[PlaneNum]; for(int i=0; i<planeNum; i++){ (plane+i)->ID = i; } } void PlaneArray::AddPlaneNum(int AddPlaneNum){ if(plane){ Plane* plane_tmp = new Plane[planeNum]; for(int i=0; i<planeNum; i++){ plane_tmp[i] = plane[i]; } delete [] plane; plane = new Plane[planeNum+AddPlaneNum]; for(int i=0; i<planeNum; i++){ plane[i] = plane_tmp[i]; } delete [] plane_tmp; planeNum += AddPlaneNum; } } void PlaneArray::SetArea(int PlaneID, double XLength, double YLength, const double* XVector, const double* YVector){ (plane+PlaneID)->XLength = XLength; (plane+PlaneID)->YLength = YLength; (plane+PlaneID)->XVector[0] = XVector[0]; (plane+PlaneID)->XVector[1] = XVector[1]; (plane+PlaneID)->XVector[2] = XVector[2]; (plane+PlaneID)->YVector[0] = YVector[0]; (plane+PlaneID)->YVector[1] = YVector[1]; (plane+PlaneID)->YVector[2] = YVector[2]; //頂点座標を計算 (plane+PlaneID)->Vertex0[0] = (plane+PlaneID)->CenterPos[0]-XLength*0.5*XVector[0]-YLength*0.5*YVector[0]; (plane+PlaneID)->Vertex0[1] = (plane+PlaneID)->CenterPos[1]-XLength*0.5*XVector[1]-YLength*0.5*YVector[1]; (plane+PlaneID)->Vertex0[2] = (plane+PlaneID)->CenterPos[2]-XLength*0.5*XVector[2]-YLength*0.5*YVector[2]; (plane+PlaneID)->Vertex1[0] = (plane+PlaneID)->CenterPos[0]-XLength*0.5*XVector[0]+YLength*0.5*YVector[0]; (plane+PlaneID)->Vertex1[1] = (plane+PlaneID)->CenterPos[1]-XLength*0.5*XVector[1]+YLength*0.5*YVector[1]; (plane+PlaneID)->Vertex1[2] = (plane+PlaneID)->CenterPos[2]-XLength*0.5*XVector[2]+YLength*0.5*YVector[2]; (plane+PlaneID)->Vertex2[0] = (plane+PlaneID)->CenterPos[0]+XLength*0.5*XVector[0]+YLength*0.5*YVector[0]; (plane+PlaneID)->Vertex2[1] = (plane+PlaneID)->CenterPos[1]+XLength*0.5*XVector[1]+YLength*0.5*YVector[1]; (plane+PlaneID)->Vertex2[2] = (plane+PlaneID)->CenterPos[2]+XLength*0.5*XVector[2]+YLength*0.5*YVector[2]; (plane+PlaneID)->Vertex3[0] = (plane+PlaneID)->CenterPos[0]+XLength*0.5*XVector[0]-YLength*0.5*YVector[0]; (plane+PlaneID)->Vertex3[1] = (plane+PlaneID)->CenterPos[1]+XLength*0.5*XVector[1]-YLength*0.5*YVector[1]; (plane+PlaneID)->Vertex3[2] = (plane+PlaneID)->CenterPos[2]+XLength*0.5*XVector[2]-YLength*0.5*YVector[2]; if(XLength != 0 && YLength != 0) (plane+PlaneID)->hasArea = true; } void PlaneArray::SetMechParamAll(double Young, double Poisson){ for(int i=0; i<planeNum; i++){ (plane+i)->E = Young; (plane+i)->nu = Poisson; (plane+i)->G = Young / (2.0*(1.0+Poisson)); } } void PlaneArray::SetMechParam(int PlaneID, double Young, double Poisson){ (plane+PlaneID)->E = Young; (plane+PlaneID)->nu = Poisson; (plane+PlaneID)->G = Young / (2.0*(1.0+Poisson)); } void PlaneArray::SetFrictionParamAll(double Dynamic){ for(int i=0; i<planeNum; i++){ (plane+i)->dFriction = Dynamic; } } void PlaneArray::SetFrictionParam(int PlaneID, double Dynamic){ (plane+PlaneID)->dFriction = Dynamic; } void PlaneArray::SetDisplayVertex(int PlaneID, const double* Vertex0, const double* Vertex1, const double* Vertex2, const double* Vertex3){ for(int i=0; i<3; i++){ (plane+PlaneID)->Vertex0[i] = Vertex0[i]; (plane+PlaneID)->Vertex1[i] = Vertex1[i]; (plane+PlaneID)->Vertex2[i] = Vertex2[i]; (plane+PlaneID)->Vertex3[i] = Vertex3[i]; } } void PlaneArray::PosUpdate(double TimeStep){ for(int i=0; i<planeNum; i++){ double deltaPos[3]; deltaPos[0] = (plane+i)->CenterVelo[0] * TimeStep; deltaPos[1] = (plane+i)->CenterVelo[1] * TimeStep; deltaPos[2] = (plane+i)->CenterVelo[2] * TimeStep; (plane+i)->CenterPos[0] += deltaPos[0]; (plane+i)->CenterPos[1] += deltaPos[1]; (plane+i)->CenterPos[2] += deltaPos[2]; (plane+i)->Vertex0[0] += deltaPos[0]; (plane+i)->Vertex0[1] += deltaPos[1]; (plane+i)->Vertex0[2] += deltaPos[2]; (plane+i)->Vertex1[0] += deltaPos[0]; (plane+i)->Vertex1[1] += deltaPos[1]; (plane+i)->Vertex1[2] += deltaPos[2]; (plane+i)->Vertex2[0] += deltaPos[0]; (plane+i)->Vertex2[1] += deltaPos[1]; (plane+i)->Vertex2[2] += deltaPos[2]; (plane+i)->Vertex3[0] += deltaPos[0]; (plane+i)->Vertex3[1] += deltaPos[1]; (plane+i)->Vertex3[2] += deltaPos[2]; } } void PlaneArray::GapSimulator(int OPCID, int DEVID, int axis, double OPCDia, double DEVDia, double CirVelo, double DevGap, double TotalTime, double TimeStep, int Counter){ double OPCRadius = OPCDia/2; //感光体半径 double DEVRadius = DEVDia/2; //現像器半径 double DevAngVelo = CirVelo/DEVRadius; //角速度 double iniAngle = PI/2-DevAngVelo*TotalTime/2; //初期角度 double x = DEVRadius*cos(iniAngle+DevAngVelo*TimeStep*Counter); //ギャップ算出用座標 double gap = OPCRadius-pow(pow(OPCRadius,2.0)-pow(x,2.0),0.5)+DEVRadius-pow(pow(DEVRadius,2.0)-pow(x,2.0),0.5)+DevGap; //可変ギャップ //以下,平面の座標値の更新.ただし,暗黙の了解として座標に対して感光体が上,現像器が下と考えている. (plane+OPCID)->CenterPos[axis] = gap+(plane+DEVID)->CenterPos[axis]; (plane+OPCID)->Vertex0[axis] = gap+(plane+DEVID)->Vertex0[axis]; (plane+OPCID)->Vertex1[axis] = gap+(plane+DEVID)->Vertex1[axis]; (plane+OPCID)->Vertex2[axis] = gap+(plane+DEVID)->Vertex2[axis]; (plane+OPCID)->Vertex3[axis] = gap+(plane+DEVID)->Vertex3[axis]; } void PlaneArray::Save(ofstream& Fileout){ Fileout.write((char*)&planeNum, sizeof(int)); for(int i=0; i<planeNum; i++){ Fileout.write((char*)(plane+i), sizeof(Plane)); } } void PlaneArray::Load(ifstream& Filein){ Filein.read((char*)&planeNum, sizeof(int)); if(plane){ delete [] plane; } plane = new Plane[planeNum]; for(int i=0; i<planeNum; i++){ Filein.read((char*)(plane+i), sizeof(Plane)); } } /*//////////////////////////////////////////////////// CylinderArrayクラス 実装部 Cylinder構造体を円筒の個数分確保し,円筒全体の オペレーションを行うクラス.このクラスを介して Cylinder構造体に含まれている情報にアクセスする. ////////////////////////////////////////////////////*/ CylinderArray::CylinderArray():PI(3.14159265358979323846264338328){ cylinder = 0; cylinderNum = 0; } CylinderArray::~CylinderArray(){ delete [] cylinder; } void CylinderArray::SetCylinderNum(int CylinderNum){ cylinderNum = CylinderNum; if(cylinder) delete [] cylinder; cylinder = new Cylinder[cylinderNum]; for(int i=0; i<cylinderNum; i++){ (cylinder+i)->ID = i; } } void CylinderArray::AddCylinderNum(int AddCylinderNum){ if(cylinder){ Cylinder* cylinder_tmp = new Cylinder[cylinderNum]; for(int i=0; i<cylinderNum; i++){ cylinder_tmp[i] = cylinder[i]; } delete [] cylinder; cylinder = new Cylinder[cylinderNum+AddCylinderNum]; for(int i=0; i<cylinderNum; i++){ cylinder[i] = cylinder_tmp[i]; } delete [] cylinder_tmp; cylinderNum += AddCylinderNum; } } void CylinderArray::SetMechParamAll(double Young, double Poisson){ for(int i=0; i<cylinderNum; i++){ (cylinder+i)->E = Young; (cylinder+i)->nu = Poisson; (cylinder+i)->G = Young / (2.0*(1.0+Poisson)); } } void CylinderArray::SetMechParam(int CylinderID, double Young, double Poisson){ (cylinder+CylinderID)->E = Young; (cylinder+CylinderID)->nu = Poisson; (cylinder+CylinderID)->G = Young / (2.0*(1.0+Poisson)); } void CylinderArray::SetFrictionParamAll(double Dynamic){ for(int i=0; i<cylinderNum; i++){ (cylinder+i)->dFriction = Dynamic; } } void CylinderArray::SetFrictionParam(int CylinderID, double Dynamic){ (cylinder+CylinderID)->dFriction = Dynamic; } void CylinderArray::PosUpdate(double TimeStep){ for(int i=0; i<cylinderNum; i++){ double deltaPos[2]; deltaPos[0] = (cylinder+i)->CenterVelo[0] * TimeStep; deltaPos[1] = (cylinder+i)->CenterVelo[1] * TimeStep; (cylinder+i)->CenterPos[0] += deltaPos[0]; (cylinder+i)->CenterPos[1] += deltaPos[1]; } } void CylinderArray::Save(ofstream& Fileout){ Fileout.write((char*)&cylinderNum, sizeof(int)); for(int i=0; i<cylinderNum; i++){ Fileout.write((char*)(cylinder+i), sizeof(Cylinder)); } } void CylinderArray::Load(ifstream& Filein){ Filein.read((char*)&cylinderNum, sizeof(int)); if(cylinder){ delete [] cylinder; } cylinder = new Cylinder[cylinderNum]; for(int i=0; i<cylinderNum; i++){ Filein.read((char*)(cylinder+i), sizeof(Cylinder)); } }
#include "surf.h" #include "extra.h" using namespace std; namespace { // We're only implenting swept surfaces where the profile curve is // flat on the xy-plane. This is a check function. static bool checkFlat(const Curve &profile) { for (unsigned i=0; i<profile.size(); i++) { if (profile[i].V[2] != 0.0 || profile[i].T[2] != 0.0 || profile[i].N[2] != 0.0) { return false; } } return true; } } void addFacesToSurface(Surface& surface, unsigned i, unsigned step, unsigned steps, unsigned profileSize) { // do not create additional triangles once we're at the bottom of the curve if ( i + 1 != profileSize) { unsigned vIndex = step*profileSize + i; // make sure next loops back to zero if you're on the last segment unsigned nextVIndex = (vIndex + profileSize) % (steps * profileSize); Tup3u face1(vIndex, vIndex + 1, nextVIndex); Tup3u face2(vIndex + 1, nextVIndex + 1, nextVIndex); surface.VF.push_back(face1); surface.VF.push_back(face2); } } void sweepProfile(const Curve &profile, unsigned profileSize, unsigned step, unsigned steps, Surface &surface, Matrix4f transform) { Matrix3f transformInvT = transform.getSubmatrix3x3(0, 0).inverse().transposed(); for (unsigned i = 0; i < profileSize; ++i) { CurvePoint profilePoint = profile[i]; Vector3f profileB = profilePoint.B; Vector3f vertexT = (transform * Vector4f(profilePoint.V, 1)).xyz(); // now the inverse transpose bit actually matters for drawing normals Vector3f normalT = (transformInvT * profilePoint.N).xyz().normalized(); surface.VV.push_back(vertexT); surface.VN.push_back(normalT); addFacesToSurface(surface, i, step, steps, profileSize); } } Surface makeSurfRev(const Curve &profile, unsigned steps) { Surface surface; if (!checkFlat(profile)) { cerr << "surfRev profile curve must be flat on xy plane." << endl; exit(0); } // idea: copy profile, transformed over and over by increment of rotation matrix. // faces: curve point 0, same curve point 1, adjacent curve point 0. // and: curve point 1, adjacent curve point 1, adjacent curve point 0. // If I try making my own surfaces, always put profile on left of y-axis (make all x-coords -) // RotateY(radians) * CurvePoint.V, do for each point in profile, radians = 2pi/steps // first iteration: establish the vectors and normals unsigned profileSize = (unsigned)profile.size(); for (unsigned step = 0; step < steps; step++) { float rotation = 2 * M_PI * step / steps; Matrix4f MRotY = Matrix4f::rotateY(rotation); sweepProfile(profile, profileSize, step, steps, surface, MRotY); } return surface; } Surface makeGenCyl(const Curve &profile, const Curve &sweep ) { Surface surface; if (!checkFlat(profile)) { cerr << "genCyl profile curve must be flat on xy plane." << endl; exit(0); } unsigned sweepSize = (unsigned)sweep.size(); unsigned profileSize = (unsigned)profile.size(); for (unsigned step = 0; step < sweepSize; ++step) { CurvePoint point = sweep[step]; // column-wise specification of the transformation Matrix4f transform(Vector4f(point.N, 0), Vector4f(point.B, 0), Vector4f(point.T, 0), Vector4f(point.V, 1), true); sweepProfile(profile, profileSize, step, sweepSize, surface, transform); } return surface; } void drawSurface(const Surface &surface, bool shaded) { // Save current state of OpenGL glPushAttrib(GL_ALL_ATTRIB_BITS); if (shaded) { // This will use the current material color and light // positions. Just set these in drawScene(); glEnable(GL_LIGHTING); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // This tells openGL to *not* draw backwards-facing triangles. // This is more efficient, and in addition it will help you // make sure that your triangles are drawn in the right order. glEnable(GL_CULL_FACE); glCullFace(GL_BACK); } else { glDisable(GL_LIGHTING); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor4f(0.4f,0.4f,0.4f,1.f); glLineWidth(1); } glBegin(GL_TRIANGLES); for (unsigned i=0; i<surface.VF.size(); i++) { glNormal(surface.VN[surface.VF[i][0]]); glVertex(surface.VV[surface.VF[i][0]]); glNormal(surface.VN[surface.VF[i][1]]); glVertex(surface.VV[surface.VF[i][1]]); glNormal(surface.VN[surface.VF[i][2]]); glVertex(surface.VV[surface.VF[i][2]]); } glEnd(); glPopAttrib(); } void drawNormals(const Surface &surface, float len) { // Save current state of OpenGL glPushAttrib(GL_ALL_ATTRIB_BITS); glDisable(GL_LIGHTING); glColor4f(0,1,1,1); glLineWidth(1); glBegin(GL_LINES); for (unsigned i=0; i<surface.VV.size(); i++) { glVertex(surface.VV[i]); glVertex(surface.VV[i] + surface.VN[i] * len); } glEnd(); glPopAttrib(); } void outputObjFile(ostream &out, const Surface &surface) { for (unsigned i=0; i<surface.VV.size(); i++) out << "v " << surface.VV[i][0] << " " << surface.VV[i][1] << " " << surface.VV[i][2] << endl; for (unsigned i=0; i<surface.VN.size(); i++) out << "vn " << surface.VN[i][0] << " " << surface.VN[i][1] << " " << surface.VN[i][2] << endl; out << "vt 0 0 0" << endl; for (unsigned i=0; i<surface.VF.size(); i++) { out << "f "; for (unsigned j=0; j<3; j++) { unsigned a = surface.VF[i][j]+1; out << a << "/" << "1" << "/" << a << " "; } out << endl; } }
/* share_ptr虽然已经很好用了,但是有一点share_ptr智能指针还是有内存泄露的情况, * 当两个对象相互使用一个shared_ptr成员变量指向对方,会造成循环引用,使引用计数失效,从而导致内存泄漏。 */ /* 四种智能指针 auto_ptr(已废弃)、unique_ptr、shared_ptr、weak_ptr */ #include <iostream> #include <string> using namespace std; class shape { public: virtual ~shape() {} }; class shape_wrapper { public: shape_wrapper(shape *ptr = nullptr) : ptr_(ptr) {} ~shape_wrapper() { delete ptr_; } shape *get() const { return ptr_; } private: shape *ptr_{}; }; /* 下面的设计方法,就是c++的auto_ptr和unique_ptr的设计方式,auto_ptr在c++17已经废除掉 */ template<typename T> class smart_ptr { public: explicit smart_ptr(T *ptr = nullptr) : ptr_(ptr) {} /* 注释掉下面后,就变成了unique_ptr的基础基础行为 */ // smart_ptr(smart_ptr& other) //auto_ptr // { // ptr_ = other.release(); // } // // /* 赋值的时候,通过产生一个临时对象,来进行swap,因为赋值函数是需要保留原有的对象的 */ // smart_ptr& operator=(smart_ptr& rhs) //auto_ptr // { // smart_ptr(rhs).swap(*this); // return *this; // } smart_ptr(smart_ptr &&other) { //unique_ptr ptr_ = other.release(); } /* 这里的模板函数是为了解决拥有子类的智能指针到拥有父类的智能指针的隐式类型转换,模板类型的拷贝构造还是第一次见到,需要学习 */ template<typename U> smart_ptr(smart_ptr<U> &&other) { //unique_ptr ptr_ = other.release(); } smart_ptr &operator=(smart_ptr rhs) { //unique_ptr rhs.swap(*this); return *this; } /* 转移指针的所有权,因为拷贝构造就是用一个现存的去生成一个新的 */ T *release() { T *ptr = ptr_; ptr_ = nullptr; return ptr; } void swap(smart_ptr &rhs) { using std::swap; swap(ptr_, rhs.ptr_); } ~smart_ptr() { delete ptr_; } T &operator*() { return *ptr_; } T *operator->() { return ptr_; } /* 下面这段有点忘了 */ explicit operator bool() const { return ptr_; } T *get() const { return ptr_; } private: T *ptr_; }; /********************************************************************/ /* 共享计数,用实现shared_ptr,非线程安全的简化版本 */ class shared_count { public: shared_count() : count_(1) {} void add_count() { ++count_; } long reduce_count() { return --count_; } long get_count() const { return count_; } private: long count_; }; /* shared_ptr */ template<typename T> class shared_smart_ptr { public: /* 模板的各个实例间并不天然就有 friend 关系,因而不能互访私有成员 ptr_ 和 shared_count_,方便的是下面模板拷贝构造和模板移动构造 */ template<typename U> friend class shared_smart_ptr; //模板类型,自己是自己的友元也还是第一次见过,需要学习 explicit shared_smart_ptr(T *ptr = nullptr) : ptr_(ptr) { if (ptr) { shared_count_ = new shared_count(); } } ~shared_smart_ptr() { if (ptr_ && !shared_count_->reduce_count()) { delete ptr_; delete shared_count_; } } shared_smart_ptr(const shared_smart_ptr &other) { ptr_ = other.ptr_; if (ptr_) { other.shared_count_->add_count(); shared_count_ = other.shared_count_; } } /* 这里的模板函数是为了解决拥有子类的智能指针到拥有父类的智能指针的隐式类型转换 */ template<typename U> shared_smart_ptr(const shared_smart_ptr<U> &other) { //此处是模板函数,才需要把参数写成这个样子的 ptr_ = other.ptr_; if (ptr_) { other.shared_count_->add_count(); shared_count_ = other.shared_count_; } } /* 移动语义的共享智能指针,是不会导致共享计数的增加,因为是把另一个移动过来了,只是转接了所有权而已 */ template<typename U> shared_smart_ptr(shared_smart_ptr<U> &&other) { ptr_ = other.ptr_; if (ptr_) { shared_count_ = other.shared_count_; other.ptr_ = nullptr; } } /* 这个构造函数为了下面的dynamic_pointer_cast等转换函数准备的 */ /* 创建了一个拥有指向other内部指针指向的存储区的指针指针对象,并把该存储区的计数加1 */ template<typename U> shared_smart_ptr(const shared_smart_ptr<U> &other, T *ptr) { ptr_ = ptr; if (ptr_) { other.shared_count_->add_count(); shared_count_ = other.shared_count_; } } shared_smart_ptr &operator=(shared_smart_ptr rhs) { rhs.swap(*this); return *this; } void swap(shared_smart_ptr &rhs) { using std::swap; swap(ptr_, rhs.ptr_); swap(shared_count_, rhs.shared_count_); } explicit operator bool() const { return ptr_; } long use_count() const { return ptr_ ? shared_count_->get_count() : 0; } T *get() const noexcept { return ptr_; } private: T *ptr_; shared_count *shared_count_; }; template<typename T> void swap(shared_smart_ptr<T> &lhs, shared_smart_ptr<T> &rhs) noexcept { lhs.swap(rhs); } template<typename T, typename U> shared_smart_ptr<T> static_pointer_cast(const shared_smart_ptr<U> &other) noexcept { T *ptr = static_cast<T *>(other.get()); return smart_ptr<T>(other, ptr); } template<typename T, typename U> shared_smart_ptr<T> reinterpret_pointer_cast(const shared_smart_ptr<U> &other) noexcept { T *ptr = reinterpret_cast<T *>(other.get()); return smart_ptr<T>(other, ptr); } template<typename T, typename U> shared_smart_ptr<T> const_pointer_cast(const shared_smart_ptr<U> &other) noexcept { T *ptr = const_cast<T *>(other.get()); return smart_ptr<T>(other, ptr); } template<typename T, typename U> shared_smart_ptr<T> dynamic_pointer_cast(const shared_smart_ptr<U> &other) noexcept { T *ptr = dynamic_cast<T *>(other.get()); //取出U类型的指针转换成T类型的指针 return shared_smart_ptr<T>(other, ptr); } class circle : public shape { public: ~circle() { puts("~circle()"); } }; int main() { shared_smart_ptr<circle> ptr1(new circle()); printf("use count of ptr1 is %ld\n", ptr1.use_count()); shared_smart_ptr<shape> ptr2; printf("use count of ptr2 was %ld\n", ptr2.use_count()); ptr2 = ptr1; printf("use count of ptr2 is now %ld\n", ptr2.use_count()); shared_smart_ptr<circle> ptr3 = dynamic_pointer_cast<circle>(ptr2); /* 下面的函数的调用等同于上面的,上面的调用,使用到了模板函数的参数类型推导机制,所以就不用指定ptr2的类型 */ //shared_smart_ptr<circle> ptr3 = dynamic_pointer_cast<circle, shape>(ptr2); printf("use count of ptr3 is %ld\n", ptr3.use_count()); if (ptr1) { puts("ptr1 is not empty"); } }
if there are any vertics in graph whose removal splits the graph into some components,then such vertices are known as articulation vertices. Directed Graph: ( also known as diagraphdigraph) if the edges in graph have directions,then it is known as directed graph if in directed graph ,if there is age connecting to same vertex ,then it is known as self loop. the no.of edges that are coming in to a vertex ,is known as indegree of a vertex No.of edges that are going out of a vertex is called out degree of a vertex. A directed graph which does not contain swlf loop and parallel eges is known as simple digraph. In a directed graph ,if you are starting from any vertex, and if we can reach to another vertices,then it is known as strongly connectrd digraph. If two vertices are connected by edge ,then these verttices are called as adjacent vertices. In undirected graph,internally all edges are parallel. Path means set of all edges betwwn a pair of vertices. If there is a path which is starting and ending at the same vertex, that means that graph contains cycle. Directed Acyclic Graph: a directed graph which does not contains any cycle is known as directed acyclic graph. Representation Of Graph: 1.Adjacency Matrix 2.Adjacency List 3.Compact List Every tree is a graph. but every graph is not tree. Graph with no cycle is tree. bsf in graph is similar to levelorder traversal of tree. dfs is similar to preorderj graph can have multiple bsf.