Esempio n. 1
0
std::ostream& operator<<(std::ostream& os, const OptionsMap& om) {

  for (size_t idx = 0; idx < om.size(); ++idx)
      for (const auto& it : om)
          if (it.second.idx == idx)
          {
              const Option& o = it.second;
              os << "\noption name " << it.first << " type " << o.type;

              if (o.type == "string" || o.type == "check" || o.type == "combo")
                  os << " default " << o.defaultValue;

              if (o.type == "spin")
                  os << " default " << int(stof(o.defaultValue))
                     << " min "     << o.min
                     << " max "     << o.max;

              break;
          }

  return os;
}
Esempio n. 2
0
void Codebook::readIn(string filePath)
{
    ifstream file;
    file.open (filePath, ios::in);
    string line;
    getline (file,line);
    int numOfEntries = stoi(line);
//    assert(numOfEntries==CODEBOOK_SIZE);
    getline (file,line);
    int numOfFeatures = stoi(line);
    for (int n=0; n < numOfEntries; n++)
    {
        vector<double> exemplar;
        for (int f=0; f < numOfFeatures; f++)
        {
            getline (file,line);
            double val = stof(line);
            exemplar.push_back(val);
        }
        push_back(exemplar);
    }
    file.close();
}
Esempio n. 3
0
Plane* SDLReader::read_plane(string filename)
{
  Plane *plane;
	Util::read_file(filename, [&plane](string line, int i) {
	if(line.size() == 0) 
		return;
    if(i > 1) 
      return;
    
    vector<string> parm = Util::split_on_separators(line," ");
    float a = stof(parm[0]);  
    float b = stof(parm[1]);  
    float c = stof(parm[2]); 
    float d = stof(parm[3]);
    float x0 = stof(parm[4]); 
    float y0 = stof(parm[5]);
    float z0 = stof(parm[6]);

    plane = new Plane(a, b, c, d, x0, y0, z0);
  });
  
  return plane;
}
Esempio n. 4
0
Component *Vector::spawn(std::string sig, std::string args){
	std::vector<std::string> arguments = split(args, ' ');
	arguments.erase(arguments.begin());

	if(sig.compare("ff") == 0){
		return new Vector(stof(arguments[0]), stof(arguments[1]));
	}else if(sig.compare("ffi") == 0){
		return new Vector(stof(arguments[0]), stof(arguments[1]), stoi(arguments[2]));
	}else if(sig.compare("ffs") == 0){
		int type = 0;
		if(arguments[2].compare("velocity") == 0){
			type = COMPONENT_VELOCITY;
		}
		if(arguments[2].compare("acceleration") == 0){
			type = COMPONENT_ACCELERATION;
		}
		if(arguments[2].compare("angularVelocity") == 0){
			type = COMPONENT_ANGULARVELOCITY;
		}
		return new Vector(stof(arguments[0]), stof(arguments[1]), type);
	}
	return new Vector();
}
Esempio n. 5
0
void Save::readShip(Ship* mShip, string& property, string& value)
{
	if (!readObject(mShip, property, value))
	{
		if (!property.compare("health"))
		{
			mShip->setHealth(stoi(value));
		}
		if (!property.compare("numFiredBullets"))
		{
			mShip->setNumFiredBullets(stoi(value));
		}
		if (!property.compare("score"))
		{
			mShip->setScore(stoi(value));
		}
		if (!property.compare("lastHitPlanet"))
		{
			mShip->setLastHitPlanet(stoi(value));
		}
		if (!property.compare("speed"))
		{
			mShip->setSpeed(stof(value));
		}
		if (!property.compare("acceleration"))
		{
			mShip->setAcceleration(stof(value));
		}
		if (!property.compare("jolt"))
		{
			mShip->setJolt(stof(value));
		}
		if (!property.compare("maxSpeed"))
		{
			mShip->setMaxSpeed(stof(value));
		}
		if (!property.compare("timer"))
		{
			mShip->setTimer(stof(value));
		}
		if (!property.compare("mAnimationStill"))
		{
			//Manage the animation
			getMI()->_animationManager->addToSurface(mShip->getAnimationStill(), value.c_str(), IND_ALPHA, IND_32);
			getMI()->_entity2dManager->add(mShip->getAnim2dShip());
			mShip->getAnim2dShip()->setAnimation(mShip->getAnimationStill());
			mShip->loadPropsAnim2d();

			// manage the 2d entity
			mShip->getEntity2d()->setPosition(mShip->getPosX(), mShip->getPosY(), 1);
			// set bounding areas
			mShip->getEntity2d()->setBoundingAreas("../SpaceGame/resources/Spaceship with motor new/spaceship_collisions.xml");
		}
		if (!property.compare("mAnimationShip"))
		{
			getMI()->_animationManager->addToSurface(mShip->getAnimationShip(), value.c_str(), IND_ALPHA, IND_32);
		}
		if (!property.compare("mAnimationLeft"))
		{
			getMI()->_animationManager->addToSurface(mShip->getAnimationLeft(), value.c_str(), IND_ALPHA, IND_32);
		}
		if (!property.compare("mAnimationRight"))
		{
			getMI()->_animationManager->addToSurface(mShip->getAnimationRight(), value.c_str(), IND_ALPHA, IND_32);
		}
		if (!property.compare("mAnimationExplode"))
		{
			getMI()->_animationManager->addToSurface(mShip->getAnimationExplode(), value.c_str(), IND_ALPHA, IND_32);
		}
		if (!property.compare(0, 6, "bullet"))
		{
			// extract the serial number of the bullet
			int id = std::stoi(property.substr(6, property.find_first_of("-") - 6));
			if (mShip->getBullets().size() <= id)
			{
				mShip->getBullets().push_back(new Bullet());
				mShip->getBullets().back()->setMI(getMI());
			}

			// change property so that it contains only the actual property of the bullet
			property = property.substr(property.find_first_of("-") + 1, property.find_first_of("]") - property.find_first_of("-") - 1);
			readBullet(mShip->getBullets().back(), property, value);
		}
	}
}
Esempio n. 6
0
int song_battle(sf::RenderWindow *w, Profile * profile, Stage * stage, Stage * mappedStage) {
	std::string filePath = (*stage).getPath();
	const std::string fileExtension = ".ogg";

	/*
	sf::SoundBuffer buffer;
	buffer.loadFromFile(filepath);

	MusicStream stream;
	stream.load(buffer);
	stream.play();
	*/

	//loading stage
	//load fonts
	sf::Font gameFont;
	if (!gameFont.loadFromFile("arial.ttf")) {
		//error
		std::cout << "Cannot load font\n";
	}

	//load background
	sf::Texture backTexture;
	if (!backTexture.loadFromFile(filePath + ".png")) {
		//error
	}
	backTexture.setSmooth(true);
	backTexture.setRepeated(false);
	sf::Sprite backSprite;
	backSprite.setTexture(backTexture);
	backSprite.setColor(sf::Color(255, 255, 255, 96)); // 1/2 transparent

													   //pause overlay
	sf::RectangleShape pauseOverlay(sf::Vector2f(800, 600));
	pauseOverlay.setFillColor(sf::Color(0, 0, 0, 128));
	/*
	//pause menu
	sf::RectangleShape pauseMenu(sf::Vector2f(400, 400));
	pauseOverlay.setFillColor(sf::Color(0, 0, 0, 128));
	*/
	//resume button
	sf::RectangleShape resumeButton(sf::Vector2f(250, 50));
	resumeButton.setFillColor(sf::Color(0, 0, 0, 160));
	resumeButton.setPosition(275, 250);
	sf::Text resumeText;
	resumeText.setFont(gameFont);
	resumeText.setCharacterSize(20);
	resumeText.setPosition(330, 260);
	resumeText.setString("Resume playing");
	//return button
	sf::RectangleShape returnButton(sf::Vector2f(250, 50));
	returnButton.setFillColor(sf::Color(0, 0, 0, 160));
	returnButton.setPosition(275, 300);
	sf::Text returnText;
	returnText.setFont(gameFont);
	returnText.setCharacterSize(20);
	returnText.setPosition(290, 310);
	returnText.setString("Return to song selection");

	//three pathways for beats to travel/drop through
	sf::Color leftPathColor(102, 1, 46, 128); //anchor/default color
	sf::Color middlePathColor(25, 80, 70, 128); //anchor/default color
	sf::Color rightPathColor(18, 40, 76, 128); //anchor/default color
	sf::ConvexShape leftPath;
	leftPath.setPointCount(4);
	leftPath.setPoint(0, sf::Vector2f(10, 0));
	leftPath.setPoint(1, sf::Vector2f(30, 0));
	leftPath.setPoint(2, sf::Vector2f(100, 600));
	leftPath.setPoint(3, sf::Vector2f(10, 600));
	leftPath.setFillColor(leftPathColor);
	sf::ConvexShape middlePath;
	middlePath.setPointCount(4);
	middlePath.setPoint(0, sf::Vector2f(290, 0));
	middlePath.setPoint(1, sf::Vector2f(310, 0));
	middlePath.setPoint(2, sf::Vector2f(345, 600));
	middlePath.setPoint(3, sf::Vector2f(255, 600));
	middlePath.setFillColor(middlePathColor);
	sf::ConvexShape rightPath;
	rightPath.setPointCount(4);
	rightPath.setPoint(0, sf::Vector2f(570, 0));
	rightPath.setPoint(1, sf::Vector2f(590, 0));
	rightPath.setPoint(2, sf::Vector2f(590, 600));
	rightPath.setPoint(3, sf::Vector2f(500, 600));
	rightPath.setFillColor(rightPathColor);

	//three bottom buttons
	sf::CircleShape leftCircle(30);
	leftCircle.setFillColor(sf::Color(102, 1, 46, 128));
	leftCircle.setOutlineThickness(5);
	leftCircle.setOutlineColor(sf::Color(205, 54, 128));
	sf::CircleShape middleTriangle(30, 3);
	middleTriangle.setFillColor(sf::Color(25, 80, 70, 128));
	middleTriangle.setOutlineThickness(5);
	middleTriangle.setOutlineColor(sf::Color(5, 203, 156));
	sf::CircleShape rightSquare(30, 4);
	rightSquare.setFillColor(sf::Color(18, 40, 76, 128));
	rightSquare.setOutlineThickness(5);
	rightSquare.setOutlineColor(sf::Color(3, 181, 170));

	leftCircle.setPosition(20, 500);
	middleTriangle.setPosition(270, 500);
	rightSquare.setPosition(520, 500);

	//score
	int score = 0; //starting game score

				   //text that appears on the screen telling how accurate the hit was
	sf::Text hitText;
	hitText.setFont(gameFont);
	hitText.setCharacterSize(50);
	//for text that appears on the side of the song battle
	sf::Text sideText;
	sideText.setFont(gameFont);

	//initialize character texture/sprite
	std::deque<sf::Texture> charTextures;
	std::deque<Character> * activeTeam = (*(*profile).getTeam()).getActiveTeam();

	for (int i = 0; i < (*activeTeam).size(); i++) {
		sf::Texture charTexture;
		if (!charTexture.loadFromFile("characters/team_" + (*(*profile).getTeam()).getTeamName() + "/" + (*activeTeam)[i].getImagePath())) {
			std::cout << "ERROR: Cannot load image for character " << (*activeTeam)[i].getInfoPath() << "\n";
		}
		charTextures.push_back(charTexture);
	}
	sf::Sprite charSprite;

	//load beats
	std::deque<Beat> beatList;
	std::ifstream file(filePath + ".txt");
	std::string line;
	const std::string delimiter = "@";
	if (file.is_open()) {
		while (std::getline(file, line)) {
			std::string key = line.substr(0, line.find(delimiter));
			float time = stof(line.substr(line.find(delimiter) + 1, line.length()));
			sf::CircleShape shapeGraphics(30);
			if (key == "Left") {
				//shapeGraphics.setFillColor(sf::Color(102, 1, 46, 128));
				//shapeGraphics.setFillColor(sf::Color(205, 54, 128));
				shapeGraphics.setFillColor(sf::Color(250, 127, 191));
				shapeGraphics.setOutlineThickness(5);
				shapeGraphics.setOutlineColor(sf::Color(250, 127, 191));
				shapeGraphics.setPosition(20, 0);
			}
			else if (key == "Up") {
				shapeGraphics.setPointCount(3);
				//shapeGraphics.setFillColor(sf::Color(25, 80, 70, 128));
				shapeGraphics.setFillColor(sf::Color(4, 240, 186));
				shapeGraphics.setOutlineThickness(5);
				shapeGraphics.setOutlineColor(sf::Color(4, 240, 186));
				shapeGraphics.setPosition(270, 0);
			}
			else if (key == "Right") {
				shapeGraphics.setPointCount(4);
				//shapeGraphics.setFillColor(sf::Color(18, 40, 76, 128));
				shapeGraphics.setFillColor(sf::Color(5, 220, 238));
				shapeGraphics.setOutlineThickness(5);
				shapeGraphics.setOutlineColor(sf::Color(5, 220, 238));
				shapeGraphics.setPosition(520, 0);
			}

			beatList.push_back(Beat(key, time, shapeGraphics));
		}
	}

	Beat beat = beatList.front();
	bool finished = false; //status of empty beatlist

						   //containers for beats drawn on screen
	const float pixelsPerMillisecond = .3; //ideal is .25, but when making the song, I lag a bit after hearing the beat
	const float dropDistance = 500; //how far the beat travels
	const float distanceTolerance = 50; //how far off the beat is from the marker we are willing to accept
	const float scoreMultiplier = 100; //scoring scale
	std::deque<Beat> leftBeats;
	std::deque<Beat> upBeats;
	std::deque<Beat> rightBeats;

	sf::Music music;

	bool movieMode = false;
	std::unordered_map<std::string, bool> movieList;
	movieList["Majisuka Gakuen 5 Theme"] = true;
	movieList["Escape"] = true;
	movieList["Sailor Zombie"] = true;
	if (movieList.find(filePath) != movieList.end()) {
		movieMode = true;
	}

	sfe::Movie movie;
	if (movieMode) {
		if (!movie.openFromFile(filePath + ".mp4")) {
			//error loading
		}
		music.setVolume(0); //mute the music
		movie.setPosition(sf::Vector2f(0, (600 - movie.getSize().y) / 2));
		sf::Vector2f movieSize = movie.getSize();
		float dominantAxis = std::max(movieSize.x, movieSize.y); //we intend to resize the video such that the larger axis is 600 pixels
		float scale = 600 / dominantAxis;
		movie.setScale(sf::Vector2f(scale, scale));
		movie.play();
	}
	else {
		if (!music.openFromFile(filePath + fileExtension)) {
			return -1; // error
		}

		music.play();
	}

	std::deque<Effect> effects;

	sf::Clock clock;
	bool paused = false; //keeps track of the game state, paused or active
	float totalTimeElapsed = 0.0; //keeps track of the time elapsed
								  //used for when player pauses the game, we don't keep track of the time when the game is paused
								  //since our game depends on the current time of the clock since the start
								  //and due to how sf::Clock operates (there's no way to "pause" time, only restart it)
								  //we use this variable to accumulate how long the clock has been running for before it restarts due to pausing/resuming
	music.setPlayingOffset(sf::milliseconds(clock.restart().asMilliseconds())); //sync start time of music with clock

	while ((*w).isOpen()) {
		float elapsed = clock.getElapsedTime().asMilliseconds() + totalTimeElapsed;
		//TODO replace all the "clock.getElapsedTime().asMilliseconds() + totalTimeElapsed" with elapsed
		//check if still working afterwards

		//if we finished the song
		if (((movieMode && movie.getStatus() == 0) || (!movieMode && music.getStatus() == 0)) && !paused) {
			int highScore = 0;
			int contestedScore = (*stage).getHighScore();
			if (score > contestedScore) {
				highScore = score;
			}
			else {
				highScore = contestedScore;
			}

			if (score > 0) { //requirement to pass stage, may change later
				(*stage).setProfile(highScore, (*stage).getTimesPlayed() + 1, (*stage).getUnlocked(), (*stage).getHidden());
				(*mappedStage).setProfile(highScore, (*stage).getTimesPlayed() + 1, (*stage).getUnlocked(), (*stage).getHidden());

				//std::cout << "stage high score: " << (*stage).getHighScore() << "\n";

				//do some after game stats display first before returning (manual click)
				std::ofstream file;
				file.open(filePath + ".dat");
				file << "title:" << (*stage).getTitle() << "\n";
				file << "artist:" << (*stage).getArtist() << "\n";
				file << "album:" << (*stage).getAlbum() << "\n";
				file << "year:" << (*stage).getYear() << "\n";
				file << "highest_score:" << highScore << "\n";
				file << "times_played:" << (*stage).getTimesPlayed() << "\n";
				if ((*stage).getUnlocked()) {
					file << "unlocked:" << "true" << "\n";
				}
				else {
					file << "unlocked:" << "false" << "\n";
				}
				if ((*stage).getHidden()) {
					file << "hidden:" << "true" << "\n";
				}
				else {
					file << "hidden:" << "false";
				}
				file.close();

				//update profile
				//money

				//update character data
				std::deque<Character> * aTeam = (*(*profile).getTeam()).getActiveTeam();
				for (int i = 0; i < (*aTeam).size(); i++) {
					Character * c = &(*aTeam)[i];

					//calculate exp based off of score
					(*c).incExp(score / 2); //TODO, write exp system

											//if exp > maxExp for that level, level character

											//write character data to file
					std::ofstream charFile;
					charFile.open("characters/team_" + (*c).getTeam() + "/" + (*aTeam)[i].getInfoPath());
					if (charFile.is_open()) {
						charFile << "firstName:" << (*c).getFirstName() << "\n";
						charFile << "lastName:" << (*c).getLastName() << "\n";
						charFile << "nickname:" << (*c).getNickname() << "\n";
						std::cout << "nickname: " << (*c).getNickname() << "\n";//debug
						charFile << "team:" << (*c).getTeam() << "\n";
						charFile << "rank:" << (*c).getRank() << "\n";
						charFile << "prefix:" << (*c).getPrefix() << "\n";
						charFile << "suffix:" << (*c).getSuffix() << "\n";
						charFile << "level:" << std::to_string((*c).getLevel()) << "\n";
						charFile << "experience:" << std::to_string((*c).getExp()) << "\n";
						if ((*c).getUnlocked()) {
							charFile << "unlocked:true";
						}
						else {
							charFile << "unlocked:false";
						}
					}
					else {
						std::cout << "ERROR: Cannot open character data for saving. Filepath: " << "characters/team_" + (*c).getTeam() + "/" + (*aTeam)[i].getInfoPath() << "\n";
					}
				}
			}
			else {
				//fail stage
			}

			return score; //return score
		}

		//put ready to go beats in beat queue (to appear on the screen)
		//invariant, beats with an earlier time cannot appear before beats with a later time
		//thus, we can simply use a queue to pop a single beat at a time once its ready to put in the ready vectors
		if (!paused && !finished && beat.getTime() - elapsed < 2000) {
			//if beat time is within 2 seconds of the future, start drawing and dropping it on the screen

			std::string beatKey = beat.getKey();
			if (beatKey == "Left") {
				leftBeats.push_back(beat);
			}
			else if (beatKey == "Up") {
				upBeats.push_back(beat);
			}
			else if (beatKey == "Right") {
				rightBeats.push_back(beat);
			}

			if (beatList.size() == 1) {
				//if popped last one, finished
				finished = true;
			}
			else {
				beatList.pop_front();
				beat = beatList.front();
			}
		}

		sf::Event event;

		while ((*w).pollEvent(event)) {
			if (event.type == sf::Event::KeyPressed) {
				//std::cout << event.key.code << "\n"; //debug
				if (!paused) {
					if (event.key.code == 71) { //Left
						std::string baseValues = "";
						sf::Color oC = leftCircle.getOutlineColor();
						baseValues += std::to_string(oC.r);
						baseValues += ",";
						baseValues += std::to_string(oC.g);
						baseValues += ",";
						baseValues += std::to_string(oC.b);
						effects.push_back(Effect(clock.getElapsedTime().asMilliseconds() + totalTimeElapsed, 350.0, &leftCircle, "outline color", "255,76,165", baseValues));

						bool validHit = false;
						for (int i = 0; i < leftBeats.size(); i++) {
							Beat * it = &leftBeats.at(i);
							sf::CircleShape * graphics = (*it).getGraphicsObject();
							float distanceDiff = std::abs((*it).getPos().y - 500.0);
							if (distanceDiff <= distanceTolerance) {
								validHit = true;
								score += (distanceTolerance - distanceDiff) * scoreMultiplier;

								bool effectInProgress = false;
								for (int i = 0; i < effects.size(); i++) {
									Effect * e = &effects.at(i);
									if ((*e).checkEIP(graphics)) {
										effectInProgress = true;
										std::cout << "Effect in progress already!\n"; //debug
										effects.erase(effects.begin() + i);
									}
								}
								effects.push_back(Effect(clock.getElapsedTime().asMilliseconds() + totalTimeElapsed, 250.0, graphics, "outline color", "255,255,255", baseValues));
								effects.push_back(Effect(clock.getElapsedTime().asMilliseconds() + totalTimeElapsed, 250.0, graphics, "fill color", "255,255,255", baseValues));
								effects.push_back(Effect(clock.getElapsedTime().asMilliseconds() + totalTimeElapsed, 250.0, graphics, "radius size", "40",
									std::to_string((*graphics).getRadius()) + ","
									+ std::to_string((*graphics).getPosition().x) + ","
									+ std::to_string((*graphics).getPosition().y)));

								//check if there are any pre-existing effects on hitText
								//if there are, discard them because we want to discard the previous message and start over
								for (int i = 0; i < effects.size(); i++) {
									Effect * e = &effects.at(i);
									if ((*e).checkEIP(&hitText)) {
										std::cout << "Text Effect in progress already!\n"; //debug
										effects.erase(effects.begin() + i);
										break;
									}
								}
								hitText.setColor(sf::Color(255, 255, 255, 224));
								float distDelta = distanceTolerance - distanceDiff;
								if (distDelta < 10) {
									hitText.setString("Spectacular!");
									hitText.setPosition(180, 50);
								}
								else if (distDelta >= 10 && distDelta < 20) {
									hitText.setString("Amazing!");
									hitText.setPosition(220, 50);
								}
								else if (distDelta >= 20 && distDelta < 30) {
									hitText.setString("Awesome");
									hitText.setPosition(220, 50);
								}
								else if (distDelta >= 30 && distDelta < 40) {
									hitText.setString("Great");
									hitText.setPosition(250, 50);
								}
								else if (distDelta >= 40) {
									hitText.setString("Good");
									hitText.setPosition(255, 50);
								}
								effects.push_back(Effect(clock.getElapsedTime().asMilliseconds() + totalTimeElapsed, 500.0, &hitText, "color transparency permanent", "0", "224"));
							}
						}
						if (!validHit) {
							score -= 1000;
							//check if there are any pre-existing effects on hitText
							//if there are, discard them because we want to discard the previous message and start over
							for (int i = 0; i < effects.size(); i++) {
								Effect * e = &effects.at(i);
								if ((*e).checkEIP(&hitText)) {
									std::cout << "Text Effect in progress already!\n"; //debug
									effects.erase(effects.begin() + i);
									break;
								}
							}
							hitText.setColor(sf::Color(255, 255, 255, 224));
							hitText.setString("Miss");
							hitText.setPosition(255, 50);
							effects.push_back(Effect(clock.getElapsedTime().asMilliseconds() + totalTimeElapsed, 500.0, &hitText, "color transparency permanent", "0", "224"));
						}
					}
					else if (event.key.code == 73) { //Up
						std::string baseValues = "";
						sf::Color oC = middleTriangle.getOutlineColor();
						baseValues += std::to_string(oC.r);
						baseValues += ",";
						baseValues += std::to_string(oC.g);
						baseValues += ",";
						baseValues += std::to_string(oC.b);
						effects.push_back(Effect(clock.getElapsedTime().asMilliseconds() + totalTimeElapsed, 350.0, &middleTriangle, "outline color", "55,253,206", baseValues));

						bool validHit = false;
						for (int i = 0; i < upBeats.size(); i++) {
							Beat * it = &upBeats.at(i);
							sf::CircleShape * graphics = (*it).getGraphicsObject();
							float distanceDiff = std::abs((*it).getPos().y - 500.0);
							if (distanceDiff <= distanceTolerance) {
								validHit = true;
								score += (distanceTolerance - distanceDiff) * scoreMultiplier;

								bool effectInProgress = false;
								for (int i = 0; i < effects.size(); i++) {
									Effect * e = &effects.at(i);
									if ((*e).checkEIP(graphics)) {
										effectInProgress = true;
										std::cout << "Effect in progress already!\n"; //debug
										effects.erase(effects.begin() + i);
									}
								}
								effects.push_back(Effect(clock.getElapsedTime().asMilliseconds() + totalTimeElapsed, 250.0, graphics, "outline color", "255,255,255", baseValues));
								effects.push_back(Effect(clock.getElapsedTime().asMilliseconds() + totalTimeElapsed, 250.0, graphics, "fill color", "255,255,255", baseValues));
								effects.push_back(Effect(clock.getElapsedTime().asMilliseconds() + totalTimeElapsed, 250.0, graphics, "radius size", "40",
									std::to_string((*graphics).getRadius()) + ","
									+ std::to_string((*graphics).getPosition().x) + ","
									+ std::to_string((*graphics).getPosition().y)));

								//check if there are any pre-existing effects on hitText
								//if there are, discard them because we want to discard the previous message and start over
								for (int i = 0; i < effects.size(); i++) {
									Effect * e = &effects.at(i);
									if ((*e).checkEIP(&hitText)) {
										std::cout << "Text Effect in progress already!\n"; //debug
										effects.erase(effects.begin() + i);
										break;
									}
								}
								hitText.setColor(sf::Color(255, 255, 255, 224));
								float distDelta = distanceTolerance - distanceDiff;
								if (distDelta < 10) {
									hitText.setString("Spectacular!");
									hitText.setPosition(180, 50);
								}
								else if (distDelta >= 10 && distDelta < 20) {
									hitText.setString("Amazing!");
									hitText.setPosition(220, 50);
								}
								else if (distDelta >= 20 && distDelta < 30) {
									hitText.setString("Awesome");
									hitText.setPosition(220, 50);
								}
								else if (distDelta >= 30 && distDelta < 40) {
									hitText.setString("Great");
									hitText.setPosition(250, 50);
								}
								else if (distDelta >= 40) {
									hitText.setString("Good");
									hitText.setPosition(255, 50);
								}
								effects.push_back(Effect(clock.getElapsedTime().asMilliseconds() + totalTimeElapsed, 500.0, &hitText, "color transparency permanent", "0", "224"));
							}
						}
						if (!validHit) {
							score -= 1000;
							//check if there are any pre-existing effects on hitText
							//if there are, discard them because we want to discard the previous message and start over
							for (int i = 0; i < effects.size(); i++) {
								Effect * e = &effects.at(i);
								if ((*e).checkEIP(&hitText)) {
									std::cout << "Text Effect in progress already!\n"; //debug
									effects.erase(effects.begin() + i);
									break;
								}
							}
							hitText.setColor(sf::Color(255, 255, 255, 224));
							hitText.setString("Miss");
							hitText.setPosition(255, 50);
							effects.push_back(Effect(clock.getElapsedTime().asMilliseconds() + totalTimeElapsed, 500.0, &hitText, "color transparency permanent", "0", "224"));
						}
					}
					else if (event.key.code == 72) { //Right
						std::string baseValues = "";
						sf::Color oC = rightSquare.getOutlineColor();
						baseValues += std::to_string(oC.r);
						baseValues += ",";
						baseValues += std::to_string(oC.g);
						baseValues += ",";
						baseValues += std::to_string(oC.b);
						effects.push_back(Effect(clock.getElapsedTime().asMilliseconds() + totalTimeElapsed, 350.0, &rightSquare, "outline color", "53,231,220", baseValues));

						bool validHit = false;
						for (int i = 0; i < rightBeats.size(); i++) {
							Beat * it = &rightBeats.at(i);
							sf::CircleShape * graphics = (*it).getGraphicsObject();
							float distanceDiff = std::abs((*it).getPos().y - 500.0);
							if (distanceDiff <= distanceTolerance) {
								validHit = true;
								score += (distanceTolerance - distanceDiff) * scoreMultiplier;

								bool effectInProgress = false;
								for (int i = 0; i < effects.size(); i++) {
									Effect * e = &effects.at(i);
									if ((*e).checkEIP(graphics)) {
										effectInProgress = true;
										std::cout << "Effect in progress already!\n"; //debug
										effects.erase(effects.begin() + i);
									}
								}
								//if (!effectInProgress) { //if graphics doesn't have any pre-existing effects
								effects.push_back(Effect(clock.getElapsedTime().asMilliseconds() + totalTimeElapsed, 250.0, graphics, "outline color", "255,255,255", baseValues));
								effects.push_back(Effect(clock.getElapsedTime().asMilliseconds() + totalTimeElapsed, 250.0, graphics, "fill color", "255,255,255", baseValues));
								effects.push_back(Effect(clock.getElapsedTime().asMilliseconds() + totalTimeElapsed, 250.0, graphics, "radius size", "40",
									std::to_string((*graphics).getRadius()) + ","
									+ std::to_string((*graphics).getPosition().x) + ","
									+ std::to_string((*graphics).getPosition().y)));
								//}

								//check if there are any pre-existing effects on hitText
								//if there are, discard them because we want to discard the previous message and start over
								for (int i = 0; i < effects.size(); i++) {
									Effect * e = &effects.at(i);
									if ((*e).checkEIP(&hitText)) {
										std::cout << "Text Effect in progress already!\n"; //debug
										effects.erase(effects.begin() + i);
										break;
									}
								}
								hitText.setColor(sf::Color(255, 255, 255, 224));
								float distDelta = distanceTolerance - distanceDiff;
								if (distDelta < 10) {
									hitText.setString("Spectacular!");
									hitText.setPosition(180, 50);
								}
								else if (distDelta >= 10 && distDelta < 20) {
									hitText.setString("Amazing!");
									hitText.setPosition(220, 50);
								}
								else if (distDelta >= 20 && distDelta < 30) {
									hitText.setString("Awesome");
									hitText.setPosition(220, 50);
								}
								else if (distDelta >= 30 && distDelta < 40) {
									hitText.setString("Great");
									hitText.setPosition(250, 50);
								}
								else if (distDelta >= 40) {
									hitText.setString("Good");
									hitText.setPosition(255, 50);
								}
								effects.push_back(Effect(clock.getElapsedTime().asMilliseconds() + totalTimeElapsed, 500.0, &hitText, "color transparency permanent", "0", "224"));
							}
						}
						if (!validHit) {
							score -= 1000;
							//check if there are any pre-existing effects on hitText
							//if there are, discard them because we want to discard the previous message and start over
							for (int i = 0; i < effects.size(); i++) {
								Effect * e = &effects.at(i);
								if ((*e).checkEIP(&hitText)) {
									std::cout << "Text Effect in progress already!\n"; //debug
									effects.erase(effects.begin() + i);
									break;
								}
							}
							hitText.setColor(sf::Color(255, 255, 255, 224));
							hitText.setString("Miss");
							hitText.setPosition(255, 50);
							effects.push_back(Effect(clock.getElapsedTime().asMilliseconds() + totalTimeElapsed, 500.0, &hitText, "color transparency permanent", "0", "224"));
						}
					}
				}
				if (event.key.code == 11) { //L - List beats
					for (auto it : beatList) {
						std::cout << it.toString();
					}
				}
				else if (event.key.code == 15 || event.key.code == 36) { //P - Pause/Unpause game, Esc - pauses and unpauses the game
					if (paused) {
						paused = false;
						clock.restart();
						music.play();
						music.setPlayingOffset(sf::milliseconds(clock.getElapsedTime().asMilliseconds() + totalTimeElapsed)); //resume from where we left off
					}
					else {
						paused = true;
						totalTimeElapsed += clock.restart().asMilliseconds();
						music.stop();
					}
				}
				else if (event.key.code == 5) { //F - Finish song
					music.stop();
				}
				else if (event.key.code == 2) { //C - Clear console
					system("cls");
				}
			}
			if (event.type == sf::Event::MouseMoved) {
				sf::Vector2i localPos = sf::Mouse::getPosition((*w));

				if (paused) {
					if (localPos.x >= 275 && localPos.x <= 525
						&& localPos.y >= 250 && localPos.y <= 300) {
						//resume button
						returnButton.setFillColor(sf::Color(0, 0, 0, 160));
						resumeButton.setFillColor(sf::Color(96, 96, 96, 160));
					}
					else if (localPos.x >= 275 && localPos.x <= 525
						&& localPos.y >= 300 && localPos.y <= 350) {
						//return button
						resumeButton.setFillColor(sf::Color(0, 0, 0, 160));
						returnButton.setFillColor(sf::Color(96, 96, 96, 160));
					}
					else {
						resumeButton.setFillColor(sf::Color(0, 0, 0, 160));
						returnButton.setFillColor(sf::Color(0, 0, 0, 160));
					}
				}
			}
			if (event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Left) {
				sf::Vector2i localPos = sf::Mouse::getPosition((*w));

				if (paused) {
					if (localPos.x >= 275 && localPos.x <= 525
						&& localPos.y >= 250 && localPos.y <= 300) {
						//resume button was clicked, unpause
						paused = false;
						clock.restart();
						music.play();
						music.setPlayingOffset(sf::milliseconds(clock.getElapsedTime().asMilliseconds() + totalTimeElapsed)); //resume from where we left off
					}
					else if (localPos.x >= 275 && localPos.x <= 525
						&& localPos.y >= 300 && localPos.y <= 350) {
						//return button was clicked
						return 0;
					}
				}
			}
			if (event.type == sf::Event::Closed) {
				(*w).close();
			}
		}

		if (!paused) {
			//handle effects in queue
			float nowTime = clock.getElapsedTime().asMilliseconds() + totalTimeElapsed;
			for (int i = 0; i < effects.size(); i++) {
				Effect * it = &effects.at(i);
				if ((*it).getTimeDelta(nowTime) <= (*it).getDuration()) {
					(*it).transition(nowTime);
				}
				else {
					(*it).expire(); //marks the effect as done so that removal can clean up
				}
			}
			//remove beats that already passed
			leftBeats.erase(std::remove_if(leftBeats.begin(), leftBeats.end(), [](Beat b) {
				return b.getPos().y > 600;
			}), leftBeats.end());
			upBeats.erase(std::remove_if(upBeats.begin(), upBeats.end(), [](Beat b) {
				return b.getPos().y > 600;
			}), upBeats.end());
			rightBeats.erase(std::remove_if(rightBeats.begin(), rightBeats.end(), [](Beat b) {
				return b.getPos().y > 600;
			}), rightBeats.end());

			//remove effects that expired
			effects.erase(std::remove_if(effects.begin(), effects.end(), [](Effect e) {
				return e.getExpired();
			}), effects.end());
		}


		//drawing stage
		//set default background black
		(*w).clear(sf::Color::Black);
		//draw movie if movie stage
		if (movieMode) {
			movie.update();
			(*w).draw(movie);
		}
		else {
			(*w).draw(backSprite); //background
		}

		//score text
		std::string scoreStr = std::to_string(score);
		sideText.setString(scoreStr); //update score
		int scoreXPos = 775 - 28 * scoreStr.length(); //calculate x position so that score shifts accordingly if increased
		sideText.setPosition(scoreXPos, 10);
		sideText.setCharacterSize(50);
		(*w).draw(sideText);

		for (int i = 0; i < 5; i++) {
			charSprite.setTexture(charTextures[i]);
			if (i == 0) {
				Character * captain = (*(*profile).getTeam()).getCaptain();

				charSprite.setScale(sf::Vector2f(.5, .5));
				charSprite.setPosition(625, 100);

				sideText.setCharacterSize(15);
				//team captain's level
				sideText.setString("Level " + std::to_string((*captain).getLevel()));
				sideText.setPosition(625, 300);
				(*w).draw(sideText);
				//team captain's name
				sideText.setString((*captain).getName());
				sideText.setPosition(625, 320);
				(*w).draw(sideText);
			}
			else {
				charSprite.setScale(sf::Vector2f(.23, .23));
				if (i == 1 || i == 2) {
					charSprite.setPosition(625 + 80 * (i % 2), 100 + 250);
				}
				else {
					charSprite.setPosition(625 + 80 * (i % 2), 100 + 250 + 100);
				}
			}
			(*w).draw(charSprite);
		}

		//pathways
		int colorTime = int(elapsed) % 8000;
		const int colorAdder = 70;
		float colorMultiplier = ((colorTime % 2000) * 1.0) / 2000.0;
		float colorAdderResult = colorAdder;
		if (colorTime < 2000) {
			colorAdderResult *= colorMultiplier;
		}
		else if (colorTime >= 2000 && colorTime < 4000) {
			colorAdderResult *= (1 - colorMultiplier);
		}
		else if (colorTime >= 4000 && colorTime < 6000) {
			colorAdderResult *= -1;
			colorAdderResult *= colorMultiplier;
		}
		else if (colorTime >= 6000) {
			colorAdderResult *= -1;
			colorAdderResult *= (1 - colorMultiplier);
		}
		//std::cout << "time: " << colorTime << ", cm: " << colorMultiplier << ", result: " << colorAdderResult << "\n"; //debug
		leftPath.setFillColor(sf::Color(std::max(leftPathColor.r + colorAdderResult, 0.0f),
			std::max(leftPathColor.g + colorAdderResult / 2, 0.0f),
			std::max(leftPathColor.b + colorAdderResult / 2, 0.0f), leftPathColor.a));
		middlePath.setFillColor(sf::Color(std::max(middlePathColor.r + colorAdderResult, 0.0f),
			std::max(middlePathColor.g + colorAdderResult / 2, 0.0f),
			std::max(middlePathColor.b + colorAdderResult / 2, 0.0f), middlePathColor.a));
		rightPath.setFillColor(sf::Color(std::max(rightPathColor.r + colorAdderResult, 0.0f),
			std::max(rightPathColor.g + colorAdderResult / 2, 0.0f),
			std::max(rightPathColor.b + colorAdderResult / 2, 0.0f), rightPathColor.a));
		(*w).draw(leftPath);
		(*w).draw(middlePath);
		(*w).draw(rightPath);
		//lower 3 buttons
		(*w).draw(leftCircle);
		(*w).draw(middleTriangle);
		(*w).draw(rightSquare);
		//active beats
		for (int i = 0; i < leftBeats.size(); i++) {
			Beat * it = &leftBeats.at(i);
			//cycle through active beats and reposition them
			float expectedTime = (*it).getTime();
			float curTime = clock.getElapsedTime().asMilliseconds() + totalTimeElapsed;
			float result = dropDistance - pixelsPerMillisecond * (expectedTime - curTime);

			sf::CircleShape * graphics = (*it).getGraphicsObject();
			const float beatSize = 30;

			if (!paused) {
				bool effectInProgress = false;
				for (int i = 0; i < effects.size(); i++) {
					Effect * e = &effects.at(i);
					if ((*e).checkEIP(graphics)) {
						effectInProgress = true;
					}
				}
				//make the beat grow as it travels downward
				if (!effectInProgress) {
					(*graphics).setRadius(std::min(result / dropDistance * beatSize, beatSize));
				}
				(*graphics).setPosition((*graphics).getPosition().x, result);
				(*it).setY(result);
			}

			(*w).draw(*graphics);
		}
		for (int i = 0; i < upBeats.size(); i++) {
			Beat * it = &upBeats.at(i);
			//cycle through active beats and reposition them
			float expectedTime = (*it).getTime();
			float curTime = clock.getElapsedTime().asMilliseconds() + totalTimeElapsed;
			float result = dropDistance - pixelsPerMillisecond * (expectedTime - curTime);

			sf::CircleShape * graphics = (*it).getGraphicsObject();
			const float beatSize = 30;

			if (!paused) {
				bool effectInProgress = false;
				for (int i = 0; i < effects.size(); i++) {
					Effect * e = &effects.at(i);
					if ((*e).checkEIP(graphics)) {
						effectInProgress = true;
					}
				}
				//make the beat grow as it travels downward
				if (!effectInProgress) {
					float sizeDelta = beatSize - (result / dropDistance * beatSize); //centers the enlarging beat
					(*graphics).setRadius(std::min(result / dropDistance * beatSize, beatSize));
					(*graphics).setPosition(middleTriangle.getPosition().x + sizeDelta, result);
				}
				else {
					(*graphics).setPosition((*graphics).getPosition().x, result);
				}
				(*it).setY(result);
			}

			(*w).draw(*graphics);
		}
		for (int i = 0; i < rightBeats.size(); i++) {
			Beat * it = &rightBeats.at(i);
			//cycle through active beats and reposition them
			float expectedTime = (*it).getTime();
			float curTime = clock.getElapsedTime().asMilliseconds() + totalTimeElapsed;
			float result = dropDistance - pixelsPerMillisecond * (expectedTime - curTime);

			sf::CircleShape * graphics = (*it).getGraphicsObject();
			const float beatSize = 30;

			if (!paused) {
				bool effectInProgress = false;
				for (int i = 0; i < effects.size(); i++) {
					Effect * e = &effects.at(i);
					if ((*e).checkEIP(graphics)) {
						effectInProgress = true;
					}
				}
				//make the beat grow as it travels downward
				if (!effectInProgress) {
					float sizeDelta = beatSize - (result / dropDistance * beatSize); //centers the enlarging beat
					(*graphics).setRadius(std::min(result / dropDistance * beatSize, beatSize));
					(*graphics).setPosition(rightSquare.getPosition().x + sizeDelta * 2, result);
				}
				else {
					(*graphics).setPosition((*graphics).getPosition().x, result);
				}
				(*it).setY(result);
			}

			(*w).draw(*graphics);
		}
		(*w).draw(hitText);
		if (paused) {
			(*w).draw(pauseOverlay); //darkens the entire screen when paused
			(*w).draw(resumeButton); //resume button
			(*w).draw(resumeText); //resume text
			(*w).draw(returnButton); //return button
			(*w).draw(returnText); //return text
		}

		//end current frame
		(*w).display();
	}

	return 0;
}
Esempio n. 7
0
void cmdHelp(std::string* args, CannonBall* ball)
{
    if (args[0].compare("help") == 0)
    {
        printf("exit                Exits the program\n");
        printf("help                Lists available commands.\n");
        printf("printinfo           Prints velocity and force acting on the cannonball\n");
        printf("setlinvel x y z     Sets velocity of cannonball\n");
        printf("setangvel x y z     Sets angular velocity of ball\n");
        printf("setwind x y z       Sets wind velocity\n");
        printf("setmass m           Sets mass of cannonball\n");
        printf("setradius r         Sets radius of cannonball\n");
        printf("setpos x y z        Sets the position of the cannonball\n");
        printf("reset               Sets position, lin. velocity, ang. velocity and wind to 0.\n");
        printf("launch              Launches the ball\n");

    }
    else if (args[0].compare("printinfo") == 0)
    {
        ball->printInfo();
    }
    else if (args[0].compare("launch") == 0)
    {
        ball->launch = true;
    }
    else if (args[0].compare("setpos") == 0)
    {
        float x, y, z;
        set3f(x, y, z, args);
        ball->pos.x = x;
        ball->pos.y = y;
        ball->pos.z = z;
    }
    else if (args[0].compare("reset") == 0)
    {
        ball->pos = vec3f(10, 0, ball->radius);
        ball->linVel = vec3f(0, 0, 0);
        ball->launch = false;
        wind = vec3f(0, 0, 0);
        ball->angVel = vec3f(0, 0, 0);
    }
    else if (args[0].compare("setlinvel") == 0)
    {
        float x, y, z;
        set3f(x, y, z, args);
        ball->linVel.x = x;
        ball->linVel.y = y;
        ball->linVel.z = z;
        cannon->setDirection(ball->linVel);
    }
    else if (args[0].compare("setangvel") == 0)
    {
        float x, y, z;
        set3f(x, y, z, args);
        ball->angVel.x = x;
        ball->angVel.y = y;
        ball->angVel.z = z;
    }
    else if (args[0].compare("setwind") == 0)
    {
        float x, y, z;
        set3f(x, y, z, args);
        wind.x = x;
        wind.y = y;
        wind.z = z;
    }
    else if (args[0].compare("setmass") == 0)
    {
        float x = 0;
        x = stof(args[1]);
        if (x > EPSILON)
        {
            ball->mass = x;
            ball->gravForce = vec3f(0.0f, 0.0f, ball->mass * -1.0f * GRAVACC);
        }
        else
            printf("Mass too low\n");
    }
    else if (args[0].compare("setradius") == 0)
    {
        float x = 0;
        x = stof(args[1]);
        if (x > EPSILON)
        {
            ball->radius = x;
            ball->area = ball->radius * ball->radius * PI;
        }
        else
            printf("Radius too low\n");
    }
    else if (args[0].compare("clear") == 0)
    {
        SDL_LockMutex(gRenderLock);
        clearBackground();
        SDL_UnlockMutex(gRenderLock);
    }
    else
    {
        printf("Unrecognized command\n");
    }
}
Esempio n. 8
0
	XYZPointReader(string file, string format, vector<double> colorRange, vector<double> intensityRange)
	: stream(file, std::ios::in | std::ios::binary)
	{
		this->format = format;
		pointsRead = 0;
		linesSkipped = 0;
		pointCount = 0;
		colorScale = -1;

		if(intensityRange.size() == 2){
			intensityOffset = (float)intensityRange[0];
			intensityScale = (float)intensityRange[1]-(float)intensityRange[0];
		}else if(intensityRange.size() == 1){
			intensityOffset = 0.0f;
			intensityScale = (float)intensityRange[0];
		}else{
			intensityOffset = 0.0f;
			intensityScale = 1.0f;
		}

		if(colorRange.size() == 2){
			colorOffset = (float)colorRange[0];
			colorScale = (float)colorRange[1];
		}else if(colorRange.size() == 1){
			colorOffset = 0.0f;
			colorScale = (float)colorRange[0];
		}else if(colorRange.size() == 0){
			colorOffset = 0.0f;

			// try to find color range by evaluating the first x points.
			float max = 0;
			int j = 0; 
			string line;
			while(getline(stream, line) && j < 1000){
				trim(line);
				vector<string> tokens = split(line, { '\t', ' ', ',' });

				if(this->format == "" && tokens.size() >= 3){
					string f(tokens.size(), 's');
					f.replace(0, 3, "xyz");

					if(tokens.size() >= 6){
						f.replace(tokens.size() - 3, 3, "rgb");
					}

					this->format = f;
					cout << "using format: '" << this->format << "'" << endl;
				}

				if(tokens.size() < this->format.size()){
					continue;
				}

				int i = 0;
				for(const auto &f : format) {
					string token = tokens[i++];
					if(f == 'r'){
						max = std::max(max, stof(token));
					}else if(f == 'g'){
						max = std::max(max, stof(token));
					}else if(f == 'b'){
						max = std::max(max, stof(token));
					}
				}

				

				j++;
			}

			if(max <= 1.0f){
				colorScale = 1.0f;
			} else if(max <= 255){
				colorScale = 255.0f;
			}else if(max <= pow(2, 16) - 1){
				colorScale =(float)pow(2, 16) - 1;
			}else{
				colorScale = (float)max;
			}

			stream.clear();
			stream.seekg(0, stream.beg);

		}

		// read through once to calculate aabb and number of points
		while(readNextPoint()){
			Point p = getPoint();
			aabb.update(p.position);
			pointCount++;
		}
		stream.clear();
		stream.seekg(0, stream.beg);
	}
Esempio n. 9
0
static char *randramp(CSOUND *csound, SRTBLK *bp, char *p,
                      int lincnt, int pcnt, CORFIL *sco)
  /* NB np's may reference a ramp but ramps must terminate in valid nums */
{
    char    *q;
    char    *psav;
    SRTBLK  *prvbp, *nxtbp;
    MYFLT   pval, qval, rval;
    extern  MYFLT stof(CSOUND *, char *);
    int     pnum, n;

    psav = ++p;
    if (UNLIKELY(*psav != SP && *psav != LF))
      goto error1;
    pnum = 0;
    q = bp->text;
    while (q < p)
      if (*q++ == SP)
        pnum++;
    prvbp = bp;
 backup:
    if (LIKELY((prvbp = prvins(prvbp)) != NULL)) {
      p = prvbp->text;
      n = pnum;
      while (n--)
        while (*p++ != SP)
          ;
      if (UNLIKELY(*p == '~'))
        goto backup;
    }
    else goto error2;
    nxtbp = bp;
 forwrd:
    if (LIKELY((nxtbp = nxtins(nxtbp)) != NULL)) {
      q = nxtbp->text;
      n = pnum;
      while (n--)
        while (*q++ != SP)
          ;
      if (*q == '~')
        goto forwrd;
    }
    else goto error2;
    pval = stof(csound, p);     /* the error msgs generated by stof     */
    qval = stof(csound, q);                         /*   are misleading */
    rval = (MYFLT) (((double) (csound->Rand31(&(csound->randSeed1)) - 1)
                     / 2147483645.0) * ((double) qval - (double) pval)
                    + (double) pval);
    fltout(csound, rval, sco);
    return(psav);

 error1:
    csound->Message(csound,Str("swrite: output, sect%d line%d p%d has illegal"
                   " expramp symbol\n"),
               csound->sectcnt,lincnt,pcnt);
    goto put0;
 error2:
    csound->Message(csound,Str("swrite: output, sect%d line%d p%d expramp has"
                               " illegal forward or backward ref\n"),
               csound->sectcnt,lincnt,pcnt);
 put0:
    corfile_putc(csound, '0', sco);
    return(psav);
}
Esempio n. 10
0
void Session::deposit(){
	float val;
	string num, str_val, name;
	/**
	 * admin users have extra information they must provide
	 */
	if(admin){
		printf("COMMAND: deposit - enter user:\n");
		getline(cin, name);
		if(name.compare("") == 0 || !account->validHolder(name)){
			printf("ERROR: User \"%s\" does not exist. Try again\n", 
				name.c_str());
			return;
		}
		printf("Depositing to \"%s\" - enter account number:\n", name.c_str());
	} else {
		/**
		 * standard users can only deposit into their own accounts
		 */
		name = user;
		printf("COMMAND: deposit - enter account number:\n");
	}
	/**
	 * account number
	 */
	getline(cin, num);
	if(!account->validNumber(num, name)){
		printf("ERROR: Account number \"%s\" is not valid. Try again\n", num.c_str());
		return;
	}
	string available = account->available(num);
	if(available.compare("") != 0){
		printf("%s\n", available.c_str());
		return;
	}

	printf("Depositing to \"%s\" - enter amount:\n", num.c_str());
	/**
	 * amount of deposit
	 */
	getline(cin, str_val);
	if(str_val.find_first_not_of(".0123456789") == string::npos){
		val = stof(str_val);
	} else {
		printf("Error: \"%s\" is not a valid number\n", str_val.c_str());
		return;
	}
	/**
	 * maximum deposit
	 */
	if(account->checkAmount(val, true, name, num, admin)){
		printf("ERROR: Maximum balance exceeded. Try again\n");
		return;
	}
	
	/**
	 * create successful transaction code
	 */
	this->file->createTransaction("04", name, num, val, "  ");
	printf("Deposit of %.2f - complete!\n", val);

	return;
}
Esempio n. 11
0
void GUITable::setTable(const TableOptions &options,
		const TableColumns &columns,
		std::vector<std::string> &content)
{
	clear();

	// Naming conventions:
	// i is always a row index, 0-based
	// j is always a column index, 0-based
	// k is another index, for example an option index

	// Handle a stupid error case... (issue #1187)
	if (columns.empty()) {
		TableColumn text_column;
		text_column.type = "text";
		TableColumns new_columns;
		new_columns.push_back(text_column);
		setTable(options, new_columns, content);
		return;
	}

	// Handle table options
	video::SColor default_color(255, 255, 255, 255);
	s32 opendepth = 0;
	for (size_t k = 0; k < options.size(); ++k) {
		const std::string &name = options[k].name;
		const std::string &value = options[k].value;
		if (name == "color")
			parseColorString(value, m_color, false);
		else if (name == "background")
			parseColorString(value, m_background, false);
		else if (name == "border")
			m_border = is_yes(value);
		else if (name == "highlight")
			parseColorString(value, m_highlight, false);
		else if (name == "highlight_text")
			parseColorString(value, m_highlight_text, false);
		else if (name == "opendepth")
			opendepth = stoi(value);
		else
			errorstream<<"Invalid table option: \""<<name<<"\""
				<<" (value=\""<<value<<"\")"<<std::endl;
	}

	// Get number of columns and rows
	// note: error case columns.size() == 0 was handled above
	s32 colcount = columns.size();
	assert(colcount >= 1);
	// rowcount = ceil(cellcount / colcount) but use integer arithmetic
	s32 rowcount = (content.size() + colcount - 1) / colcount;
	assert(rowcount >= 0);
	// Append empty strings to content if there is an incomplete row
	s32 cellcount = rowcount * colcount;
	while (content.size() < (u32) cellcount)
		content.push_back("");

	// Create temporary rows (for processing columns)
	struct TempRow {
		// Current horizontal position (may different between rows due
		// to indent/tree columns, or text/image columns with width<0)
		s32 x;
		// Tree indentation level
		s32 indent;
		// Next cell: Index into m_strings or m_images
		s32 content_index;
		// Next cell: Width in pixels
		s32 content_width;
		// Vector of completed cells in this row
		std::vector<Cell> cells;
		// Stores colors and how long they last (maximum column index)
		std::vector<std::pair<video::SColor, s32> > colors;

		TempRow(): x(0), indent(0), content_index(0), content_width(0) {}
	};
	TempRow *rows = new TempRow[rowcount];

	// Get em width. Pedantically speaking, the width of "M" is not
	// necessarily the same as the em width, but whatever, close enough.
	s32 em = 6;
	if (m_font)
		em = m_font->getDimension(L"M").Width;

	s32 default_tooltip_index = allocString("");

	std::map<s32, s32> active_image_indices;

	// Process content in column-major order
	for (s32 j = 0; j < colcount; ++j) {
		// Check column type
		ColumnType columntype = COLUMN_TYPE_TEXT;
		if (columns[j].type == "text")
			columntype = COLUMN_TYPE_TEXT;
		else if (columns[j].type == "image")
			columntype = COLUMN_TYPE_IMAGE;
		else if (columns[j].type == "color")
			columntype = COLUMN_TYPE_COLOR;
		else if (columns[j].type == "indent")
			columntype = COLUMN_TYPE_INDENT;
		else if (columns[j].type == "tree")
			columntype = COLUMN_TYPE_TREE;
		else
			errorstream<<"Invalid table column type: \""
				<<columns[j].type<<"\""<<std::endl;

		// Process column options
		s32 padding = myround(0.5 * em);
		s32 tooltip_index = default_tooltip_index;
		s32 align = 0;
		s32 width = 0;
		s32 span = colcount;

		if (columntype == COLUMN_TYPE_INDENT) {
			padding = 0; // default indent padding
		}
		if (columntype == COLUMN_TYPE_INDENT ||
				columntype == COLUMN_TYPE_TREE) {
			width = myround(em * 1.5); // default indent width
		}

		for (size_t k = 0; k < columns[j].options.size(); ++k) {
			const std::string &name = columns[j].options[k].name;
			const std::string &value = columns[j].options[k].value;
			if (name == "padding")
				padding = myround(stof(value) * em);
			else if (name == "tooltip")
				tooltip_index = allocString(value);
			else if (name == "align" && value == "left")
				align = 0;
			else if (name == "align" && value == "center")
				align = 1;
			else if (name == "align" && value == "right")
				align = 2;
			else if (name == "align" && value == "inline")
				align = 3;
			else if (name == "width")
				width = myround(stof(value) * em);
			else if (name == "span" && columntype == COLUMN_TYPE_COLOR)
				span = stoi(value);
			else if (columntype == COLUMN_TYPE_IMAGE &&
					!name.empty() &&
					string_allowed(name, "0123456789")) {
				s32 content_index = allocImage(value);
				active_image_indices.insert(std::make_pair(
							stoi(name),
							content_index));
			}
			else {
				errorstream<<"Invalid table column option: \""<<name<<"\""
					<<" (value=\""<<value<<"\")"<<std::endl;
			}
		}

		// If current column type can use information from "color" columns,
		// find out which of those is currently active
		if (columntype == COLUMN_TYPE_TEXT) {
			for (s32 i = 0; i < rowcount; ++i) {
				TempRow *row = &rows[i];
				while (!row->colors.empty() && row->colors.back().second < j)
					row->colors.pop_back();
			}
		}

		// Make template for new cells
		Cell newcell;
		memset(&newcell, 0, sizeof newcell);
		newcell.content_type = columntype;
		newcell.tooltip_index = tooltip_index;
		newcell.reported_column = j+1;

		if (columntype == COLUMN_TYPE_TEXT) {
			// Find right edge of column
			s32 xmax = 0;
			for (s32 i = 0; i < rowcount; ++i) {
				TempRow *row = &rows[i];
				row->content_index = allocString(content[i * colcount + j]);
				const core::stringw &text = m_strings[row->content_index];
				row->content_width = m_font ?
					m_font->getDimension(text.c_str()).Width : 0;
				row->content_width = MYMAX(row->content_width, width);
				s32 row_xmax = row->x + padding + row->content_width;
				xmax = MYMAX(xmax, row_xmax);
			}
			// Add a new cell (of text type) to each row
			for (s32 i = 0; i < rowcount; ++i) {
				newcell.xmin = rows[i].x + padding;
				alignContent(&newcell, xmax, rows[i].content_width, align);
				newcell.content_index = rows[i].content_index;
				newcell.color_defined = !rows[i].colors.empty();
				if (newcell.color_defined)
					newcell.color = rows[i].colors.back().first;
				rows[i].cells.push_back(newcell);
				rows[i].x = newcell.xmax;
			}
		}
		else if (columntype == COLUMN_TYPE_IMAGE) {
			// Find right edge of column
			s32 xmax = 0;
			for (s32 i = 0; i < rowcount; ++i) {
				TempRow *row = &rows[i];
				row->content_index = -1;

				// Find content_index. Image indices are defined in
				// column options so check active_image_indices.
				s32 image_index = stoi(content[i * colcount + j]);
				std::map<s32, s32>::iterator image_iter =
					active_image_indices.find(image_index);
				if (image_iter != active_image_indices.end())
					row->content_index = image_iter->second;

				// Get texture object (might be NULL)
				video::ITexture *image = NULL;
				if (row->content_index >= 0)
					image = m_images[row->content_index];

				// Get content width and update xmax
				row->content_width = image ? image->getOriginalSize().Width : 0;
				row->content_width = MYMAX(row->content_width, width);
				s32 row_xmax = row->x + padding + row->content_width;
				xmax = MYMAX(xmax, row_xmax);
			}
			// Add a new cell (of image type) to each row
			for (s32 i = 0; i < rowcount; ++i) {
				newcell.xmin = rows[i].x + padding;
				alignContent(&newcell, xmax, rows[i].content_width, align);
				newcell.content_index = rows[i].content_index;
				rows[i].cells.push_back(newcell);
				rows[i].x = newcell.xmax;
			}
			active_image_indices.clear();
		}
		else if (columntype == COLUMN_TYPE_COLOR) {
			for (s32 i = 0; i < rowcount; ++i) {
				video::SColor cellcolor(255, 255, 255, 255);
				if (parseColorString(content[i * colcount + j], cellcolor, true))
					rows[i].colors.push_back(std::make_pair(cellcolor, j+span));
			}
		}
		else if (columntype == COLUMN_TYPE_INDENT ||
				columntype == COLUMN_TYPE_TREE) {
			// For column type "tree", reserve additional space for +/-
			// Also enable special processing for treeview-type tables
			s32 content_width = 0;
			if (columntype == COLUMN_TYPE_TREE) {
				content_width = m_font ? m_font->getDimension(L"+").Width : 0;
				m_has_tree_column = true;
			}
			// Add a new cell (of indent or tree type) to each row
			for (s32 i = 0; i < rowcount; ++i) {
				TempRow *row = &rows[i];

				s32 indentlevel = stoi(content[i * colcount + j]);
				indentlevel = MYMAX(indentlevel, 0);
				if (columntype == COLUMN_TYPE_TREE)
					row->indent = indentlevel;

				newcell.xmin = row->x + padding;
				newcell.xpos = newcell.xmin + indentlevel * width;
				newcell.xmax = newcell.xpos + content_width;
				newcell.content_index = 0;
				newcell.color_defined = !rows[i].colors.empty();
				if (newcell.color_defined)
					newcell.color = rows[i].colors.back().first;
				row->cells.push_back(newcell);
				row->x = newcell.xmax;
			}
		}
	}

	// Copy temporary rows to not so temporary rows
	if (rowcount >= 1) {
		m_rows.resize(rowcount);
		for (s32 i = 0; i < rowcount; ++i) {
			Row *row = &m_rows[i];
			row->cellcount = rows[i].cells.size();
			row->cells = new Cell[row->cellcount];
			memcpy((void*) row->cells, (void*) &rows[i].cells[0],
					row->cellcount * sizeof(Cell));
			row->indent = rows[i].indent;
			row->visible_index = i;
			m_visible_rows.push_back(i);
		}
	}

	if (m_has_tree_column) {
		// Treeview: convert tree to indent cells on leaf rows
		for (s32 i = 0; i < rowcount; ++i) {
			if (i == rowcount-1 || m_rows[i].indent >= m_rows[i+1].indent)
				for (s32 j = 0; j < m_rows[i].cellcount; ++j)
					if (m_rows[i].cells[j].content_type == COLUMN_TYPE_TREE)
						m_rows[i].cells[j].content_type = COLUMN_TYPE_INDENT;
		}

		// Treeview: close rows according to opendepth option
		std::set<s32> opened_trees;
		for (s32 i = 0; i < rowcount; ++i)
			if (m_rows[i].indent < opendepth)
				opened_trees.insert(i);
		setOpenedTrees(opened_trees);
	}

	// Delete temporary information used only during setTable()
	delete[] rows;
	allocationComplete();

	// Clamp scroll bar position
	updateScrollBar();
}
Esempio n. 12
0
string CanIdTranslator::translateValidDataToHex(map<string, CanVariable> &data)
{
	string bin = "0000000000000000000000000000000000000000000000000000000000000000";
	int highestBit = 0;

	for (map<string, CanVariable>::iterator iter = data.begin(); iter != data.end(); iter++)
	{
		if (iter->second.getType() == "uint")
		{
			if (iter->second.getStartBit() + iter->second.getBitLength() > highestBit)
				highestBit = iter->second.getStartBit() + iter->second.getBitLength();

			unsigned int a = stou(iter->second.getValue());

			bin.replace(iter->second.getStartBit(), iter->second.getBitLength(), uint2bin(a, iter->second.getBitLength()));
		}
		else if (iter->second.getType() == "float")
		{
			if (iter->second.getStartBit() + iter->second.getBitLength() > highestBit)
				highestBit = iter->second.getStartBit() + iter->second.getBitLength();

			bin.replace(iter->second.getStartBit(), iter->second.getBitLength(), float2bin(stof(iter->second.getValue()), iter->second.getBitLength()));
		}
		else if (iter->second.getType() == "enum")
		{
			if (iter->second.getStartBit() + iter->second.getBitLength() > highestBit)
				highestBit = iter->second.getStartBit() + iter->second.getBitLength();

			string value = iter->second.getEnumIdValue();

			if (value == "")
			{
				throw new CanMessageException("Got enum that could not be converterd to a value. value = \"" + iter->second.getValue() + "\" enumString is \"" + iter->second.getEnumsString() + "\"\n");
			}
			else
			{
				bin.replace(iter->second.getStartBit(), iter->second.getBitLength(), uint2bin(stou(value), iter->second.getBitLength()));
			}
		}
		else if (iter->second.getType() == "ascii")
		{
			for (int n = 0; n < iter->second.getValue().length(); n++)
			{
				if (iter->second.getStartBit()+n*8 + 8 > highestBit)
					highestBit = iter->second.getStartBit()+n*8 + 8;

				//bin.replace(iter->second.getStartBit()+n*8, 8, uint2bin((unsigned int)iter->second.getValue()[n], 8));
				unsigned int temp = iter->second.getValue()[n];
				if (temp > 0xff)
				{
					temp &= 0xff;
				}
				bin.replace(iter->second.getStartBit()+n*8, 8, uint2bin(temp, 8));
			}
		}
		else if (iter->second.getType() == "hexstring")
		{
			for (int n = 0; n < iter->second.getValue().length(); n++)
			{
				if (iter->second.getStartBit()+n*4 + 4 > highestBit)
					highestBit = iter->second.getStartBit()+n*4 + 4;

				string character;
				character += iter->second.getValue()[n];

				bin.replace(iter->second.getStartBit()+n*4, 4, hex2bin(character));
			}
		}
	}

	try
	{
		while (highestBit%8 != 0)
		{
		    highestBit++;
		}
		bin = bin.substr(0, highestBit);
	}
	catch (std::out_of_range& e)
	{
		cout << "DEBUG: translateValidDataToHex exception: " << e.what() << "\n";
		cout << "DEBUG: A bin=" << bin << " :: highestBit=" << highestBit << endl;
	}

	return bin2hex(bin);
}
Esempio n. 13
0
float Settings::getFloat(const std::string &name) const
{
	return stof(get(name));
}
Esempio n. 14
0
int main()
{
	enum atomType { CarbonAlpha, Carbon, Nitrogen, Oxygen };
	/*enum intensityLevel {low =50 , med = 75, high = 100};
	struct helixStruct{
		int helixNum;
		int startPos;
		int endPos;
	};
	struct strand {
		int strandID;
		int startPos;
		int endPos;
	};
	struct sheetStruct {
		std::vector<strand> strands;
		std::string sheetID;
		int startPos;
		int endPos;
	};
	*/
	struct atom {
		atomType type = Carbon;
		float x = 0.0f;
		float y = 0.0f;
		float z = 0.0f;
	};
	struct residue {
		int atomCount = 0;
		int residueNum = 0;
		atom atoms[4];
		std::string chainID = "";
	};


	//std::vector<secondaryStruct> sheet(1);
	//std::vector<residue> residues;
	//std::vector<sheetStruct> sheet;
	//std::vector<helixStruct> helix;
	//std::vector<residue> ();
	std::ifstream pdbFile;
	std::ofstream skelFile;
	residue tmpResidue;
	pdbFile.open("../PDB Files/5fj6.pdb");
	skelFile.open("../PDB Files/5fj6.skel.pdb");
	if (pdbFile.is_open() && skelFile.is_open())
	{
		int currentRes = 0;
		std::string line;
		bool isHeaderLine = false;
		while (std::getline(pdbFile, line))
		{
			if (IsHeaderLine(line))
			{
				skelFile << line << std::endl;
			}
			else // this is an atom, sheet or helix
			{
				if (IsAtom(line)) {
					int atomResNbr = ToInt(line.substr(23, 4));
					if (tmpResidue.residueNum == 0)
					{
						int resNum = atoi(line.substr(23, 4).c_str());
						tmpResidue.atomCount = 1;
						tmpResidue.residueNum = resNum;
						tmpResidue.chainID = line.substr(21, 1);
						tmpResidue.atoms[tmpResidue.atomCount - 1].type = Nitrogen;
						tmpResidue.atoms[tmpResidue.atomCount - 1].x = stof(line.substr(31, 8));
						tmpResidue.atoms[tmpResidue.atomCount - 1].y = stof(line.substr(39, 8));
						tmpResidue.atoms[tmpResidue.atomCount - 1].z = stof(line.substr(47, 8));
					}
					else {
						if (tmpResidue.residueNum == atomResNbr) { // still same amino acid
							tmpResidue.atomCount++;

							switch (tmpResidue.atomCount) {
							case 1:
								tmpResidue.atoms[tmpResidue.atomCount - 1].type = Nitrogen;
								tmpResidue.atoms[tmpResidue.atomCount - 1].x = stof(line.substr(31, 8));
								tmpResidue.atoms[tmpResidue.atomCount - 1].y = stof(line.substr(39, 8));
								tmpResidue.atoms[tmpResidue.atomCount - 1].z = stof(line.substr(47, 8));
								break;
							case 2:
								tmpResidue.atoms[tmpResidue.atomCount - 1].type = CarbonAlpha;
								tmpResidue.atoms[tmpResidue.atomCount - 1].x = stof(line.substr(31, 8));
								tmpResidue.atoms[tmpResidue.atomCount - 1].y = stof(line.substr(39, 8));
								tmpResidue.atoms[tmpResidue.atomCount - 1].z = stof(line.substr(47, 8));
								break;
							case 3:
								tmpResidue.atoms[tmpResidue.atomCount - 1].type = Carbon;
								tmpResidue.atoms[tmpResidue.atomCount - 1].x = stof(line.substr(31, 8));
								tmpResidue.atoms[tmpResidue.atomCount - 1].y = stof(line.substr(39, 8));
								tmpResidue.atoms[tmpResidue.atomCount - 1].z = stof(line.substr(47, 8));
								break;
							case 4:
								tmpResidue.atoms[tmpResidue.atomCount - 1].type = Oxygen;
								tmpResidue.atoms[tmpResidue.atomCount - 1].x = stof(line.substr(31, 8));
								tmpResidue.atoms[tmpResidue.atomCount - 1].y = stof(line.substr(39, 8));
								tmpResidue.atoms[tmpResidue.atomCount - 1].z = stof(line.substr(47, 8));
								break;

							}

						}
						if (tmpResidue.residueNum != atomResNbr) { // we are on a new residue
							std::string tmpLine;
							float avgX=0.0f;
							float avgY = 0.0f;
							float avgZ = 0.0f;
							for (int i = 0; i < 4; i++) {
								avgX += tmpResidue.atoms[i].x;
								avgY += tmpResidue.atoms[i].y;
								avgZ += tmpResidue.atoms[i].z;
							}
							avgX = avgX / 4;
							avgY = avgY / 4;
							avgZ = avgZ / 4;
							//tmpLine = "ATOM      1  N   VAL A   3      18.481  17.489  41.966  1.00 33.08           N";
							/*std::ostringstream oss;
							oss << oss.width(7) << "ATOM";
							oss << oss.right << oss.width(5) << "1";
							oss << oss.right << oss.width(5) << " CA";
							oss << oss.right << oss.width(1) << " ";
							oss << oss.right << oss.width(3) << "GLY";
							oss << oss.right << oss.width(1) << tmpResidue.chainID;
							oss << oss.right << oss.width(4) << tmpResidue.residueNum;
							oss << oss.right << oss.width(8) << avgX;
							oss << oss.right << oss.width(8) << avgY;
							oss << oss.right << oss.width(8) << avgZ;
							oss << oss.right << oss.width(5) << "     ";
							oss << oss.right << oss.width(6) << "      ";
							oss << oss.right << oss.width(2) << " C";
							oss << oss.right << oss.width(2) << "  ";
							std::string outLine = oss.str();*/
							skelFile << std::setw(6) << setiosflags(std::ios_base::left) << "ATOM";
							skelFile << std::setw(5) << std::resetiosflags(std::ios::left) << "1";
							skelFile << std::setw(1) << std::resetiosflags(std::ios::left) << " ";
							skelFile << std::setw(4) << setiosflags(std::ios_base::left)  << "CA";
							skelFile << std::setw(1) << std::resetiosflags(std::ios::left) << " ";
							skelFile << std::setw(3) << "GLY";
							skelFile << std::setw(1) << " ";
							skelFile << std::setw(1) << tmpResidue.chainID;
							skelFile << std::setw(4) << tmpResidue.residueNum;
							skelFile << std::setw(4) << " ";
							skelFile << std::setw(8) << std::fixed << std::setprecision(3) << avgX;
							skelFile << std::setw(8) << std::fixed << std::setprecision(3) << avgY;
							skelFile << std::setw(8) << std::fixed << std::setprecision(3) << avgZ;
							skelFile << std::setw(6) << " ";
							skelFile << std::setw(6) << " ";
							skelFile << std::setw(10) << " ";
							skelFile << std::setw(2) << "C";
							skelFile << std::endl;;


							tmpResidue.residueNum = atomResNbr;
							tmpResidue.atomCount = 1;
							tmpResidue.chainID = line.substr(21, 1);
							switch (tmpResidue.atomCount) {
							case 1:
								tmpResidue.atoms[tmpResidue.atomCount - 1].type = Nitrogen;
								break;
							case 2:
								tmpResidue.atoms[tmpResidue.atomCount - 1].type = CarbonAlpha;
								break;
							case 3:
								tmpResidue.atoms[tmpResidue.atomCount - 1].type = Carbon;
								break;
							case 4:
								tmpResidue.atoms[tmpResidue.atomCount - 1].type = Oxygen;
								break;
							}
							tmpResidue.atoms[tmpResidue.atomCount - 1].x = stof(line.substr(31, 8));
							tmpResidue.atoms[tmpResidue.atomCount - 1].y = stof(line.substr(39, 8));
							tmpResidue.atoms[tmpResidue.atomCount - 1].z = stof(line.substr(47, 8));
						}

					}
				}

				/*if (IsStructure(line)) {
					if (line.substr(0, 5) == "HELIX") {
						std::vector<helixStruct>::iterator it;
						helixStruct tempStructure;

						tempStructure.helixNum = std::stoi(line.substr(8, 3));
						tempStructure.startPos = std::stoi(line.substr(22, 3));
						tempStructure.endPos = std::stoi(line.substr(34, 3));

						it = helix.begin();
						it = helix.insert(it, tempStructure);
					}
					if (line.substr(0, 5) == "SHEET") {

						if (sheet.size() != 0) {

						}
						else
						{
							sheetStruct tempSheet;
							strand tempstrand;
							std::string steve;

							tempstrand.strandID = stoi(line.substr(8, 3));
							tempstrand.startPos = stoi(line.substr(23, 4));
							tempstrand.endPos = stoi(line.substr(34, 4));

							tempSheet.sheetID = line.substr(12, 3);
							tempSheet.startPos = tempstrand.startPos;
							tempSheet.endPos = tempstrand.endPos;

							std::vector<strand>::iterator sit;
							std::vector<sheetStruct>::iterator it;


							sit = tempSheet.strands.begin();
							sit = tempSheet.strands.insert(sit, tempstrand);
							it = sheet.begin();
							it = sheet.insert(it, tempSheet);
							steve = sheet[0].sheetID;
							int bob = 1;



						}
					}
					skelFile << line << std::endl;
				}
				if (IsAtom(line)) {
					int residueNumber = stoi(line.substr(23, 4));

				}*/

			}
		}
		pdbFile.close();
		skelFile.close();
	}
	else std::cout << "Unable to open file";
    return 0;


}bool IsAtom(std::string line) {
Esempio n. 15
0
 inline static float convert(const std::string& str) {
     return stof(str);
 }
Esempio n. 16
0
void Session::withdraw(){
	float val;
	string num, str_val, name;
	/**
	 * admin users have extra information they must provide
	 */
	if(admin){
		printf("COMMAND: withdraw - enter user:\n");
		getline(cin, name);
		if(name.compare("") == 0 || !account->validHolder(name)){
			printf("ERROR: User \"%s\" does not exist. Try again\n", 
				name.c_str());
			return;
		}
		printf("Withdrawing from \"%s\" - enter account number:\n", name.c_str());
	} else {
		/**
		 * standard users can only withdraw from their own accounts
		 */
		name = user;
		printf("COMMAND: withdraw - enter account number:\n");
	}
	/**
	 * account number
	 */
	getline(cin, num);
	if(!account->validNumber(num, name)){
		printf("ERROR: Account number \"%s\" is not valid. Try again\n", num.c_str());
		return;
	}
	string available = account->available(num);
	if(available.compare("") != 0){
		printf("%s\n", available.c_str());
		return;
	}

	printf("Withdrawing from \"%s\" - enter amount:\n", num.c_str());
	/**
	 * amount of withdraw
	 */
	getline(cin, str_val);
	if(str_val.find_first_not_of(".0123456789") == string::npos){
		val = stof(str_val);
	} else {
		printf("Error: \"%s\" is not a valid number\n", str_val.c_str());
		return;
	}
	if(((int) val) % 5 != 0){
		printf("ERROR: You cannot withdraw an amount not divisible by 5. Try again\n");
		return;
	}
	if(val > 500.00){
		printf("ERROR: amount cannot be withdrawn.\n");
		return;
	}
	/**
	 * maximum withdraw
	 */
	if(account->checkAmount(val, false, name, num, admin)){
		printf("ERROR: Minimum balance exceeded. Try again\n");
		return;
	}
	
	/**
	 * create successful transaction code
	 */
	this->file->createTransaction("01", name, num, val, "  ");
	printf("Withdrawal of %.2f - complete!\n", val);

	return;
}
Esempio n. 17
0
void Session::paybill(){
	float val;
	string num, str_val, name, payee;
	/**
	 * admin users have extra information they must provide
	 */
	if(admin){
		printf("COMMAND: paybill - enter user:\n");
		getline(cin, name);
		if(name.compare("") == 0 || !account->validHolder(name)){
			printf("ERROR: User \"%s\" does not exist. Try again\n", 
				name.c_str());
			return;
		}
		printf("Paying bill for \"%s\" - enter account number:\n", name.c_str());
	} else {
		/**
		 * standard users can only deposit into their own accounts
		 */
		name = user;
		printf("COMMAND: paybill - enter account number:\n");
	}
	/**
	 * account number
	 */
	getline(cin, num);
	if(!account->validNumber(num, name)){
		printf("ERROR: Account number \"%s\" is not valid. Try again\n", num.c_str());
		return;
	}
	string available = account->available(num);
	if(available.compare("") != 0){
		printf("%s\n", available.c_str());
		return;
	}

	printf("Paying bill from \"%s\" - enter payee:\n", num.c_str());

	/**
	 * payee of bill
	 */
	getline(cin, payee);
	for(int i=0; i<sizeof(payeeList)/sizeof(string); i++){
		if(payee.compare(payeeList[i]) == 0){
			break;
		} else if(i == sizeof(payeeList)/sizeof(string) - 1){
			printf("ERROR: Company \"%s\" does not exist. Try again\n", payee.c_str());
			return;
		}
	}

	printf("Paying bill to \"%s\" - enter amount:\n", payee.c_str());
	/**
	 * amount of payment
	 */
	getline(cin, str_val);
	if(str_val.find_first_not_of(".0123456789") == string::npos){
		val = stof(str_val);
	} else {
		printf("Error: \"%s\" is not a valid number\n", str_val.c_str());
		return;
	}
	/**
	 * maximum payment
	 */
	if(val > 2000.00){
		printf("ERROR: Maximum amount of 2000.00 exceeded. Try again\n");
		return;
	}
	if(account->checkAmount(val, false, name, num, admin)){
		printf("ERROR: Maximum amount exceeded. Try again\n");
		return;
	}
	
	/**
	 * create successful transaction code
	 */
	this->file->createTransaction("03", name, num, val, "  ");
	printf("Payment of %.2f - complete!\n", val);
}
Esempio n. 18
0
void Standard::Transfer() {

    string padded_acc_holder_f;
    string padded_acc_holder_t;
    string padded_acc_num_f;
    string padded_acc_num_t;
    string padded_amount;
    string padded_new_balance_f;
    string padded_new_balance_t;
    string acc_holder_t;
    string temp_acc_num_f;
    string temp_acc_num_t;
    string temp_amount;
    stringstream stream;
    float amount;
    float new_balance_f = 0.0;
    float new_balance_t = 0.0;
    int acc_num_f;
    int acc_num_t;

    cout << "\nTransfer transaction selected.\n" << endl;

    cout << "Enter you account number: ";
    cin >> temp_acc_num_f;

    regex re_f("[0-9]{0,5}");
    if (regex_match(temp_acc_num_f, re_f) && temp_acc_num_f.compare("99999") != 0) {
        acc_num_f = stoi(temp_acc_num_f);
    } else {
        cerr << "\n>>> ERROR: The account number entered is invalid.\n" << endl;
        return;
    }

    if (curr_user.GetNum() != acc_num_f) {
        cerr << "\n>>> ERROR: The account number does not match your account.\n" << endl;
        cout << "Current user: "******", Account Number: " << acc_num_f << endl;
        return;
    }

    if (transactions.is_Disabled(curr_user.GetNum())) {
        cerr << "\n>>> ERROR: The account is disabled; you may not send funds.\n" << endl;
        return;
    }

    if (transactions.is_New(curr_user.GetNum())) {
        cerr << "\n>>> ERROR: Newly created accounts may not send funds. Please try again in 24 hours.\n" << endl;
        return;
    }

    cout << "Enter destination account number: ";
    cin >> temp_acc_num_t;

    regex re_t("[0-9]{0,5}");
    if (regex_match(temp_acc_num_t, re_t) && temp_acc_num_t.compare("99999") != 0) {
        acc_num_t = stoi(temp_acc_num_t);
    } else {
        cerr << "\n>>> ERROR: The account number entered is invalid.\n" << endl;
        return;
    }

    if (!transactions.NumExists(acc_num_t)) {
        cerr << "\n >>> ERROR: The destination account number entered is invalid.\n" << endl;
        return;
    }

    if (transactions.is_Disabled(acc_num_t)) {
        cerr << "\n>>> ERROR: Disabled accounts may not receive funds.\n" << endl;
        return;
    }

    cout << "Enter amount to transfer: ";
    cin >> temp_amount;

    if (transactions.is_Amount_Valid(temp_amount)) {
        amount = stof(temp_amount);
    } else {
        cerr << "\n>>> ERROR: The amount entered is invalid.\n" << endl;
        return;
    }

    for (int i = 0; i < users.size(); i++) {
        if (users.at(i).GetNum() == acc_num_t) {
            acc_holder_t = users.at(i).GetName();
        }
    }

    padded_acc_holder_f = curr_user.GetName();
    while (padded_acc_holder_f.length() < 20) {
        padded_acc_holder_f = padded_acc_holder_f + " ";
    }

    padded_acc_holder_t = acc_holder_t;
    while (padded_acc_holder_t.length() < 20) {
        padded_acc_holder_t = padded_acc_holder_t + " ";
    }

    padded_acc_num_f = temp_acc_num_f;
    while (padded_acc_num_f.length() < 5) {
        padded_acc_num_f = "0" + padded_acc_num_f;
    }

    padded_acc_num_t = temp_acc_num_t;
    while (padded_acc_num_t.length() < 5) {
        padded_acc_num_t = "0" + padded_acc_num_t;
    }

    padded_amount = temp_amount;
    while (padded_amount.length() < 8) {
        padded_amount = "0" + padded_amount;
    }

    if ((curr_user.GetBalance() - curr_user.GetDeposited()) < amount) {
        cerr << "\n>>> ERROR: You may not transfer recently deposited funds.\n" << endl;
        return;
    }


    if (curr_user.GetPlan() == 'S') {
        // STUFF HERE
    } else if (curr_user.GetPlan() == 'N') {
        // STUFF HERE
    } else {
        cerr << "\n>>> ERROR: Unable to retrieve transaction payment plan information.\n" << endl;
        return;
    }

    for (int i = 0; i < users.size(); i++) {
        if (users.at(i).GetNum() == acc_num_t) {

            if (amount <= curr_user.GetBalance() && (1000.00 >= amount > 0.0) && (amount + users.at(i).GetBalance()) < 100000.00) {

                /*
                * Done in the Back End
                *
                if (curr_user.GetPlan() == 'S')
                  new_balance_f = curr_user.GetBalance() - amount - 0.05;
                else if (curr_user.GetPlan() == 'N')
                  new_balance_f = curr_user.GetBalance() - amount - 0.10;
                else {
                  cerr << "\n>>> ERROR: Unable to retrieve transaction payment plan information.\n" << endl;
                  return;
                }
                */
                new_balance_f = curr_user.GetBalance() - amount;
                new_balance_t = users.at(i).GetBalance() + amount;
                curr_user.SetBalance(new_balance_f);
                users.at(i).SetBalance(new_balance_t);
                users.at(i).SetDeposited(users.at(i).GetDeposited() + amount);
                break;

            } else {
                cerr << "\n>>> ERROR: The amount entered is invalid.\n" << endl;
                return;
            }
        }
    }

    stream << fixed << setprecision(2) << new_balance_f;
    padded_new_balance_f = stream.str();
    while (padded_new_balance_f.length() < 8) {
        padded_new_balance_f = "0" + padded_new_balance_f;
    }

    cout << "\nFunds have been successfully transfered from account " << padded_acc_num_f << " to account " << padded_acc_num_t << "." << endl;
    cout << "New balance: $" + padded_new_balance_f << endl;

    string transaction_line = "02 " + padded_acc_holder_f + " " + padded_acc_num_f + " " + padded_amount + "   ";
    transaction_file.push_back(transaction_line);
    transaction_line = "02 " + padded_acc_holder_t + " " + padded_acc_num_t + " " + padded_amount + "   ";
    transaction_file.push_back(transaction_line);
    cout << "\nEnter a command.\n" << endl;
}
Esempio n. 19
0
static char *expramp(CSOUND *csound, SRTBLK *bp, char *p,
                     int lincnt, int pcnt, CORFIL *sco)
  /* NB np's may reference a ramp but ramps must terminate in valid nums */
{
    char    *q;
    char    *psav;
    SRTBLK  *prvbp, *nxtbp;
    MYFLT   pval, qval, rval;
    double  p2span;
    extern  MYFLT stof(CSOUND *, char *);
    int     pnum, n;

    psav = ++p;
    if (UNLIKELY(*psav != SP && *psav != LF))
      goto error1;
    pnum = 0;
    q = bp->text;
    while (q < p)
      if (*q++ == SP)
        pnum++;
    prvbp = bp;
 backup:
    if (LIKELY((prvbp = prvins(prvbp)) != NULL)) {
      p = prvbp->text;
      n = pnum;
      while (n--)
        while (*p++ != SP)
          ;
      if (*p == '}' || *p == '{' || *p == '(' || *p == ')')
        goto backup;
    }
    else goto error2;
    nxtbp = bp;
 forwrd:
    if (LIKELY((nxtbp = nxtins(nxtbp)) != NULL)) {
      q = nxtbp->text;
      n = pnum;
      while (n--)
        while (*q++ != SP)
          ;
      if (*q == '}' || *q == '{' || *q == '(' || *q == ')')
        goto forwrd;
    }
    else goto error2;
    pval = stof(csound, p);     /* the error msgs generated by stof     */
    qval = stof(csound, q);                         /*   are misleading */
    p2span = (double)(nxtbp->newp2 - prvbp->newp2);
/*  printf("pval=%f qval=%f span = %f\n", pval, qval, p2span); */
    rval = pval * (MYFLT)pow((double)(qval/pval),
                             (double)(bp->newp2 - prvbp->newp2) / p2span);
/*  printf("rval=%f bp->newp2=%f prvbp->newp2-%f\n",
           rval, bp->newp2, prvbp->newp2); */
    fltout(csound, rval, sco);
    return(psav);

 error1:
    csound->Message(csound,Str("swrite: output, sect%d line%d p%d has illegal"
                   " expramp symbol\n"),
               csound->sectcnt,lincnt,pcnt);
    goto put0;
 error2:
    csound->Message(csound, Str("swrite: output, sect%d line%d p%d expramp "
                                "has illegal forward or backward ref\n"),
                            csound->sectcnt, lincnt, pcnt);
 put0:
    corfile_putc(csound, '0', sco);
    return(psav);
}
Esempio n. 20
0
void Standard::Paybill() {

    string padded_acc_holder;
    string padded_acc_num;
    string padded_amount;
    string padded_new_balance;
    string acc_holder;
    string temp_acc_num;
    string temp_amount;
    string company;
    stringstream stream;
    float amount;
    float new_balance;
    float company_count;
    int acc_num;

    cout << "\nPay bill transaction selected.\n" << endl;

    cout << "Enter your account number: ";
    cin >> temp_acc_num;

    regex re("[0-9]{0,5}");
    if (regex_match(temp_acc_num, re)) {
        acc_num = stoi(temp_acc_num);
    } else {
        cerr << "\n>>> ERROR: The account number entered is invalid.\n" << endl;
        return;
    }

    if (curr_user.GetNum() != acc_num) {
        cerr << "\n>>> ERROR: The account number does not match your account.\n" << endl;
        return;
    }

    if (transactions.is_Disabled(curr_user.GetNum())) {
        cerr << "\n>>> ERROR: The account is disabled; you may not send funds.\n" << endl;
        return;
    }

    if (transactions.is_New(curr_user.GetNum())) {
        cerr << "\n>>> ERROR: Newly created accounts may not send funds. Please try again in 24 hours.\n" << endl;
        return;
    }

    cout << "Enter company: ";
    cin >> company;
    company = transactions.to_Lower(company);

    if (company.compare("EC") != 0 || company.compare("CQ") != 0 || company.compare("TV") != 0) {
        cerr << "\n>>> ERROR: The company name is invalid. Must be one of the following: EC, CQ or TV.\n" << endl;
        return;
    }

    cout << "Enter amount to pay: ";
    cin >> temp_amount;

    if (transactions.is_Amount_Valid(temp_amount)) {
        amount = stof(temp_amount);
    } else {
        cerr << "\n>>> ERROR: The amount entered is invalid.\n" << endl;
        return;
    }

    if ((curr_user.GetBalance() - curr_user.GetDeposited()) < amount) {
        cerr << "\n>>> ERROR: You may not pay bills using recently deposited funds.\n" << endl;
        return;
    }

    if (company.compare("EC") == 0) {
        company_count = curr_user.GetECCount() + amount;
        if (company_count > 2000.00) {
            cerr << "\n>>> ERROR: The limit to pay per company per day is $2000.00.\n" << endl;
            return;
        }
        curr_user.SetECCount(company_count);
    } else if (company.compare("TV") == 0) {
        company_count = curr_user.GetTVCount() + amount;
        if (company_count > 2000.00) {
            cerr << "\n>>> ERROR: The limit to pay per company per day is $2000.00.\n" << endl;
            return;
        }
        curr_user.SetTVCount(company_count);
    } else {
        company_count = curr_user.GetCQCount() + amount;
        if (company_count > 2000.00) {
            cerr << "\n>>> ERROR: The limit to pay per company per day is $2000.00.\n" << endl;
            return;
        }
        curr_user.SetCQCount(company_count);
    }

    if (amount <= curr_user.GetBalance() && amount > 0.0) {

        /*
         * Done in the Back End
         *
         if (curr_user.GetPlan() == 'S')
           new_balance = curr_user.GetBalance() - amount - 0.05;
         else if (curr_user.GetPlan() == 'N')
           new_balance = curr_user.GetBalance() - amount - 0.10;
         else {
           cerr << "\n>>> ERROR: Unable to retrieve transaction payment plan information.\n" << endl;
           return;
         }
         */

        new_balance = curr_user.GetBalance() - amount;
        curr_user.SetBalance(new_balance);
    } else {
        cerr << "\n>>> ERROR: The amount entered is invalid.\n" << endl;
        return;
    }

    padded_acc_holder = curr_user.GetName();
    while (padded_acc_holder.length() < 20) {
        padded_acc_holder = padded_acc_holder + " ";
    }

    padded_acc_num = temp_acc_num;
    while (padded_acc_num.length() < 5) {
        padded_acc_num = "0" + padded_acc_num;
    }

    padded_amount = temp_amount;
    while (padded_amount.length() < 8) {
        padded_amount = "0" + padded_amount;
    }

    stream << fixed << setprecision(2) << new_balance;
    padded_new_balance = stream.str();
    while (padded_new_balance.length() < 8) {
        padded_new_balance = "0" + padded_new_balance;
    }

    cout << "\nYou have successfully paid a bill of " << padded_amount << " from account " << padded_acc_num << " to " << company << "." << endl;
    cout << "New balance: $" + padded_new_balance << endl;

    string transaction_line = "03 " + padded_acc_holder + " " + padded_acc_num + " " + padded_amount + " " + company;
    transaction_file.push_back(transaction_line);
    cout << "\nEnter a command.\n" << endl;
}
Esempio n. 21
0
	bool readNextPoint(){
		double x = 0;
		double y = 0;
		double z = 0;
		float nx = 0;
		float ny = 0;
		float nz = 0;
		unsigned char r = 255;
		unsigned char g = 255;
		unsigned char b = 255;
		// unsigned char a = 255;  // unused variable
		unsigned short intensity = 0;

		string line;
		while(getline(stream, line)){
			trim(line);
			vector<string> tokens = split(line, {'\t', ' ', ','});
			if(tokens.size() != format.size()){
				//throw PotreeException("Not enough tokens for the given format");

				if(linesSkipped == 0){
					cout << "some lines may be skipped because they do not match the given format: '" << format << "'" << endl;
				}

				linesSkipped++;
				continue;
			}

			int i = 0;
			for(const auto &f : format) {
				string token = tokens[i++];
				if(f == 'x'){
					x = stod(token);
				}else if(f == 'y'){
					y = stod(token);
				}else if(f == 'z'){
					z = stod(token);
				}else if(f == 'r'){
					r = (unsigned char)(255.0f * (stof(token) - colorOffset) / colorScale); 
				}else if(f == 'g'){
					g = (unsigned char)(255.0f * (stof(token) - colorOffset) / colorScale); 
				}else if(f == 'b'){
					b = (unsigned char)(255.0f * (stof(token) - colorOffset) / colorScale); 
				}else if(f == 'i'){
					intensity = (unsigned short)( 65535 * (stof(token) - intensityOffset) / intensityScale);
				}else if(f == 's'){
					// skip
				}else if(f == 'X'){
					nx = stof(token);
				}else if(f == 'Y'){
					ny = stof(token);
				}else if(f == 'Z'){
					nz = stof(token);
				}
			}

			point = Point(x,y,z,r,g,b);
			point.normal.x = nx;
			point.normal.y = ny;
			point.normal.z = nz;
			point.intensity = intensity;
			pointsRead++;
			return true;
		}

		return false;
	}
Esempio n. 22
0
void Standard::Deposit() {

    string padded_acc_holder;
    string padded_acc_num;
    string padded_amount;
    string padded_new_balance;
    string acc_holder;
    string temp_acc_num;
    string temp_amount;
    stringstream stream;
    float amount;
    float new_balance = 0.0;
    int acc_num;

    cout << "\nDeposit transaction selected.\n" << endl;

    cout << "Enter account number: ";
    cin >> temp_acc_num;

    regex re("[0-9]{0,5}");
    if (regex_match(temp_acc_num, re) && temp_acc_num.compare("99999") != 0) {
        acc_num = stoi(temp_acc_num);
    } else {
        cerr << "\n>>> ERROR: The account number entered is invalid.\n" << endl;
        return;
    }

    if (curr_user.GetNum() != acc_num) {
        cerr << "\n>>> ERROR: The account number does not match your account.\n" << endl;
        return;
    }

    if (transactions.is_Disabled(curr_user.GetNum())) {
        cerr << "\n>>> ERROR: The account is disabled; you may not send funds.\n" << endl;
        return;
    }

    if (transactions.is_New(curr_user.GetNum())) {
        cerr << "\n>>> ERROR: Newly created accounts may not send funds. Please try again in 24 hours.\n" << endl;
        return;
    }

    cout << "Enter amount to deposit: ";
    cin >> temp_amount;

    if (transactions.is_Amount_Valid(temp_amount)) {
        amount = stof(temp_amount);
    } else {
        cerr << "\n>>> ERROR: The amount entered is invalid.\n" << endl;
        return;
    }

    if (((amount + curr_user.GetBalance()) < 100000.00) && (amount > 0.0)) {

        /*
        * Done in the Back End
        *
        if (curr_user.GetPlan() == 'S')
          new_balance = curr_user.GetBalance() + amount - 0.05;
        else if (curr_user.GetPlan() == 'N')
          new_balance = curr_user.GetBalance() + amount - 0.10;
        else {
          cerr << "\n>>> ERROR: Unable to retrieve transaction payment plan information.\n" << endl;
          return;
        }
        */

        new_balance = curr_user.GetBalance() + amount;
        curr_user.SetBalance(new_balance);
        curr_user.SetDeposited(curr_user.GetDeposited() + amount);

    } else {
        cerr << "\n>>> ERROR: The amount entered is invalid.\n" << endl;
        return;
    }

    padded_acc_holder = curr_user.GetName();
    while (padded_acc_holder.length() < 20) {
        padded_acc_holder = padded_acc_holder + " ";
    }

    padded_acc_num = temp_acc_num;
    while (padded_acc_num.length() < 5) {
        padded_acc_num = "0" + padded_acc_num;
    }

    padded_amount = temp_amount;
    while (padded_amount.length() < 8) {
        padded_amount = "0" + padded_amount;
    }

    stream << fixed << setprecision(2) << new_balance;
    padded_new_balance = stream.str();
    while (padded_new_balance.length() < 8) {
        padded_new_balance = "0" + padded_new_balance;
    }

    cout << "\nFunds have been successfully added to the account " << padded_acc_num << "." << endl;
    cout << "New balance: $" + padded_new_balance << endl;

    string transaction_line = "04 " + padded_acc_holder + " " + padded_acc_num + " " + padded_amount + "   ";
    transaction_file.push_back(transaction_line);
    cout << "\nEnter a command.\n" << endl;

}
Esempio n. 23
0
void MPSReader::readBOUNDS(){

  /*				type            meaning
                  ---------------------------------------------------
                  LO    lower bound        b <= x (< +inf)
                  UP    upper bound        (0 <=) x <= b
                  FX    fixed variable     x = b
                  FR    free variable      -inf < x < +inf
                  MI    lower bound -inf   -inf < x (<= 0)
                  PL    upper bound +inf   (0 <=) x < +inf
                  BV    binary variable    x = 0 or 1
                  LI    integer variable   b <= x (< +inf)
                  UI    integer variable   (0 <=) x <= b
                  SC    semi-cont variable x = 0 or l <= x <= b
                  l is the lower bound on the variable
                  If none set then defaults to 1*/

  //Como se trata de um bloco opcional dos problemas,
  //Apenas tratarei os tipos LO e UP.

  StringTokenizer *lineTokens = new StringTokenizer(line);
  string boundType;
  string boundName;
  string nomeVariavel;
  string boundValue;
  string auxRestName; //sera criada uma nova restricao se a fronteira for valida
  Desigualdade tipoDesigualdade;

  if (lineTokens->nextToken().compare("BOUNDS") == 0){

    line = fileReader->readLine();

    while (line.compare("ENDATA") != 0){

      lineTokens->setLine(line);

      //Ler no minimo 3 tokens
      //Nome variavel / Nome Funcao|Restricao / Valor variavel

      boundType = lineTokens->nextToken();
      boundName = lineTokens->nextToken();
      nomeVariavel = lineTokens->nextToken();
      boundValue = lineTokens->nextToken();

      if (boundType.compare("LO") == 0){
        tipoDesigualdade = MaiorOuIgual;
      }
      else if (boundType.compare("UP") == 0){
        tipoDesigualdade = MenorOuIgual;
      }
      auxRestName = funcao->addRestricao();
      //Configurar nova restricao
      funcao->addVariavelRestricao(auxRestName, nomeVariavel, 1.0);
      funcao->setDesigualdadeRestricao(auxRestName, tipoDesigualdade);
      funcao->setTermoLivreRestricao(auxRestName, stof(boundValue.c_str()));

      line = fileReader->readLine(); //ler nova linha ao final
    }

  }

}
Esempio n. 24
0
void Standard::Withdrawal() {

    string padded_acc_holder;
    string padded_acc_num;
    string padded_amount;
    string padded_new_balance;
    string temp_acc_num;
    string temp_amount;
    stringstream stream;
    float amount;
    float new_balance;
    int acc_num;

    cout << "\nWithdrawal transaction selected.\n" << endl;

    cout << "Enter your account number: ";
    cin >> temp_acc_num;

    regex re("[0-9]{0,5}");
    if (regex_match(temp_acc_num, re)) {
        acc_num = stoi(temp_acc_num);
    } else {
        cerr << "\n>>> ERROR: The account number entered is invalid.\n" << endl;
        return;
    }

    if (curr_user.GetNum() != acc_num) {
        cerr << "\n>>> ERROR: The account number does not match your account.\n" << endl;
        return;
    }

    if (transactions.is_Disabled(curr_user.GetNum())) {
        cerr << "\n>>> ERROR: The account is disabled; you may not withdraw funds.\n" << endl;
        return;
    }

    if (transactions.is_New(curr_user.GetNum())) {
        cerr << "\n>>> ERROR: Newly created accounts may not withdraw funds. Please try again in 24 hours.\n" << endl;
        return;
    }

    cout << "Enter amount to withdraw: ";
    cin >> temp_amount;

    if (transactions.is_Amount_Valid(temp_amount)) {
        amount = stof(temp_amount);
    } else {
        cerr << "\n>>> ERROR: The amount entered is invalid.\n" << endl;
        return;
    }

    if (curr_user.GetPlan() == 'S') {
        if (amount <= 0.05 + curr_user.GetBalance() && (500.00 >= amount > 0.0) && (fmod(amount, 5.0) == 0)) {

            new_balance = curr_user.GetBalance() - amount;
            curr_user.SetBalance(new_balance);

        } else {
            cerr << "\n>>> ERROR: The amount entered is invalid.\n" << endl;
            return;
        }

        if ((curr_user.GetBalance() - 0.05 - curr_user.GetDeposited()) < amount) {
            cerr << "\n>>> ERROR: You may not withdraw recently deposited funds.\n" << endl;
            return;
        }
    } else if (curr_user.GetPlan() == 'N') {
        if (amount <= 0.10 + curr_user.GetBalance() && (500.00 >= amount > 0.0) && (fmod(amount, 5.0) == 0)) {

            new_balance = curr_user.GetBalance() - amount;
            curr_user.SetBalance(new_balance);

        } else {
            cerr << "\n>>> ERROR: The amount entered is invalid.\n" << endl;
            return;
        }

        if ((curr_user.GetBalance() - 0.10 - curr_user.GetDeposited()) < amount) {
            cerr << "\n>>> ERROR: You may not withdraw recently deposited funds.\n" << endl;
            return;
        }
    } else {
        cerr << "\n>>> ERROR: Unable to retrieve transaction payment plan information.\n" << endl;
        return;
    }

    padded_acc_holder = curr_user.GetName();
    while (padded_acc_holder.length() < 20) {
        padded_acc_holder = padded_acc_holder + " ";
    }

    padded_acc_num = temp_acc_num;
    while (padded_acc_num.length() < 5) {
        padded_acc_num = "0" + padded_acc_num;
    }

    padded_amount = temp_amount;
    while (padded_amount.length() < 8) {
        padded_amount = "0" + padded_amount;
    }

    stream << fixed << setprecision(2) << new_balance;
    padded_new_balance = stream.str();
    while (padded_new_balance.length() < 8) {
        padded_new_balance = "0" + padded_new_balance;
    }

    cout << "\nFunds have been successfully withdrawn from your account." << endl;
    cout << "New balance: $" + padded_new_balance << endl;

    string transaction_line = "01 " + padded_acc_holder + " " + padded_acc_num + " " + padded_amount + "   ";
    cout << "Transaction line: " << transaction_line << endl;
    transaction_file.push_back(transaction_line);
    cout << "\nEnter a command.\n" << endl;
}
Esempio n. 25
0
void cis_data::readPhenotypes(string fbed) {
	int n_includedS = 0;
	int n_includedP = 0;
	int n_excludedP = 0;
	int n_negativeStrd = 0;
	vector < int > mappingS;

	//Open BED file
	vrb.title("Reading phenotype data in [" + fbed + "]");
	htsFile *fp = hts_open(fbed.c_str(),"r");
	if (!fp) vrb.error("Cannot open file");
	tbx_t *tbx = tbx_index_load(fbed.c_str());
	if (!tbx) vrb.error("Cannot open index file");
	kstring_t str = {0,0,0};
	if (hts_getline(fp, KS_SEP_LINE, &str) <= 0 || !str.l || str.s[0] != tbx->conf.meta_char ) vrb.error("Cannot read header line!");

	//Process sample names
	vector < string > tokens;
	stb.split(string(str.s), tokens);
	if (tokens.size() < 7) vrb.error("Incorrect number of columns!");
	for (int t = 6 ; t < tokens.size() ; t ++) {
		mappingS.push_back(findSample(tokens[t]));
		if (mappingS.back() >= 0) n_includedS++;
	}

	//Read phenotypes
    unsigned int linecount =0;
    
    //Read phenotypes
    if (regionPhenotype.chr != "NA"){
        hts_itr_t *itr = tbx_itr_querys(tbx, regionPhenotype.get().c_str());
        vrb.bullet("target region [" + regionPhenotype.get() + "]");
        if (!itr) vrb.error("Cannot jump to region!");
        //Read data
        while (tbx_itr_next(fp, tbx, itr, &str) >= 0) {
            linecount ++;
            if (linecount % 100000 == 0) vrb.bullet("Read " + stb.str(linecount) + " lines");
            stb.split(string(str.s), tokens);
            if (tokens.size() < 7) vrb.error("Incorrect number of columns!");
            if ((grp_mode == GRP_NONE && filter_phenotype.check(tokens[3])) || (grp_mode != GRP_NONE && filter_phenotype.check(tokens[4]))) {
                phenotype_id.push_back(tokens[3]);
                phenotype_chr.push_back(tokens[0]);
                phenotype_start.push_back(atoi(tokens[1].c_str()) + 1);
                phenotype_end.push_back(atoi(tokens[2].c_str()));
				if (grp_mode > 0 && full_test) phenotype_grp.push_back("ALL_GENES");
				if (grp_mode > 0 && !full_test) phenotype_grp.push_back(tokens[4]);
                phenotype_neg.push_back(tokens[5] == "-");
                if (phenotype_neg.back()) n_negativeStrd ++;
                phenotype_val.push_back(vector < float > (sample_count, 0.0));
                for (int t = 6 ; t < tokens.size() ; t ++) {
                    if (mappingS[t-6] >= 0) {
                        if (tokens[t] == "NA") phenotype_val.back()[mappingS[t-6]] = bcf_float_missing;
                        else phenotype_val.back()[mappingS[t-6]] = stof(tokens[t]);
                    }
                }
                n_includedP++;
            } else n_excludedP ++;
        }
        tbx_itr_destroy(itr);
    }else{
        while (hts_getline(fp, KS_SEP_LINE, &str) >= 0) {
            linecount ++;
            if (linecount % 100000 == 0) vrb.bullet("Read " + stb.str(linecount) + " lines");
            stb.split(string(str.s), tokens);
            if (str.l && str.s[0] != tbx->conf.meta_char) {
                if (tokens.size() < 7) vrb.error("Incorrect number of columns!");
                if ((grp_mode == GRP_NONE && filter_phenotype.check(tokens[3])) || (grp_mode != GRP_NONE && filter_phenotype.check(tokens[4]))) {
                    phenotype_id.push_back(tokens[3]);
                    phenotype_chr.push_back(tokens[0]);
                    phenotype_start.push_back(atoi(tokens[1].c_str()) + 1);
                    phenotype_end.push_back(atoi(tokens[2].c_str()));
    				if (grp_mode > 0 && full_test) phenotype_grp.push_back("ALL_GENES");
    				if (grp_mode > 0 && !full_test) phenotype_grp.push_back(tokens[4]);
                    phenotype_neg.push_back(tokens[5] == "-");
                    if (phenotype_neg.back()) n_negativeStrd ++;
                    phenotype_val.push_back(vector < float > (sample_count, 0.0));
                    for (int t = 6 ; t < tokens.size() ; t ++) {
                        if (mappingS[t-6] >= 0) {
                            if (tokens[t] == "NA") phenotype_val.back()[mappingS[t-6]] = bcf_float_missing;
                            else phenotype_val.back()[mappingS[t-6]] = stof(tokens[t]);
                        }
                    }
                    n_includedP++;
                } else n_excludedP ++;
            }
        }
    }

	//Finalize & verbose
	tbx_destroy(tbx);
	if (hts_close(fp)) vrb.error("Cannot properly close file");
	phenotype_count = phenotype_id.size();
	vrb.bullet(stb.str(n_includedP) + " phenotypes included");
	if (n_excludedP > 0) vrb.bullet(stb.str(n_excludedP) + " phenotypes excluded by user");
	if (n_negativeStrd > 0 ) vrb.bullet(stb.str(n_negativeStrd) + " phenotypes are on the negative strand");
    if (phenotype_count == 0) vrb.leave("Cannot find phenotypes in target region!");
}
InputProcessing::InputProcessing(int inputType, bool DEBUG_MODE) :
    faceCascade(CascadeClassifier()),
    inputType(inputType),
    DEBUG_MODE(DEBUG_MODE),
    eyeCascadeGlasses(CascadeClassifier()),
    eyeCascade(CascadeClassifier())

{

    printf("loading \n");
    if (!faceCascade.load("cascades\\haarcascade_frontalface_alt.xml")) {
        printf("--(!)File not found faceCascade\n");
        exit(-11);
    }
    if (!eyeCascadeGlasses.load("cascades\\haarcascade_eye_tree_eyeglasses.xml")) {
        printf("--(!)File not found eyeCascadeGlasses\n");
        exit(-12);
    }
    if (!eyeCascade.load("cascades\\haarcascade_eye.xml")) {
        printf("--(!)File not found eyeCascade\n");
        exit(-13);
    }
    if (inputType < 1 || inputType > 4) {
        printf("--(!)Input type %i not specified\n", inputType);
        exit(-15);
    }
    else if (inputType == INPUT_TYPE_CAMERA_INPUT) {
        // set default camera
        cap = VideoCapture(0);
        if (!cap.isOpened()) {
            printf("--(!)Camera 0 not available\n");
        }
    }
    else if (inputType == INPUT_TYPE_GI4E_DB) {
        /*
        load ground truth

        Format for GI4E image_labels.txt:
        xxx_yy.png	x1 y1 x2 y2 x3 y3 x4 y4 x5 y5 x6 y6
        The first point (x1,y1) is the external corner of the left user's eye. The second point is the centre of the left iris.
        The third one is the internal corner of the left eye. The other three points are internal corner, iris centre and
        external corner of the right eye.

        */

        ifstream file("../GI4E/labels/image_labels.txt");
        string line;
        if (file.is_open()) {
            while (getline(file, line)) {
                try {
                    istringstream iss(line);
                    string filename, x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, x6, y6;
                    getline(iss, filename, '\t');
                    getline(iss, x1, '\t');
                    getline(iss, y1, '\t');
                    getline(iss, x2, '\t');
                    getline(iss, y2, '\t');
                    getline(iss, x3, '\t');
                    getline(iss, y3, '\t');
                    getline(iss, x4, '\t');
                    getline(iss, y4, '\t');
                    getline(iss, x5, '\t');
                    getline(iss, y5, '\t');
                    getline(iss, x6, '\t');
                    getline(iss, y6, '\t');
                    vector<Point2f> v;

                    v.push_back(Point2f(stof(x1), stof(y1)));
                    v.push_back(Point2f(stof(x2), stof(y2)));
                    v.push_back(Point2f(stof(x3), stof(y3)));
                    v.push_back(Point2f(stof(x4), stof(y4)));
                    v.push_back(Point2f(stof(x5), stof(y5)));
                    v.push_back(Point2f(stof(x6), stof(y6)));
                    v.shrink_to_fit();
                    labels.push_back(v);
                }
                catch (Exception e) {
                    printf("--(!)Error while parsing /GI4E/labels/image_labels.txt\n");
                }
            }
            labels.shrink_to_fit();
            file.close();
        }
    }

}
Esempio n. 27
0
bool Save::readObject(Object* mObject, string& property, string& value)
{
	if (!property.compare("posX"))
	{
		mObject->setPosX(stof(value));
		return true;
	}
	if (!property.compare("posY"))
	{
		mObject->setPosY(stof(value));
		return true;
	}
	if (!property.compare("scaleX"))
	{
		mObject->setScaleX(stof(value));
		return true;
	}
	if (!property.compare("scaleY"))
	{
		mObject->setScaleY(stof(value));
		return true;
	}
	if (!property.compare("speedX"))
	{
		mObject->setSpeedX(stof(value));
		return true;
	}
	if (!property.compare("speedY"))
	{
		mObject->setSpeedY(stof(value));
		return true;
	}
	if (!property.compare("angularSpeed"))
	{
		mObject->setAngularSpeed(stof(value));
		return true;
	}
	if (!property.compare("angularAcceleration"))
	{
		mObject->setAngularAcceleration(stof(value));
		return true;
	}
	if (!property.compare("maxAngularSpeed"))
	{
		mObject->setMaxAngularSpeed(stof(value));
		return true;
	}
	if (!property.compare("angleZ"))
	{
		mObject->setAngleZ(stof(value));
		return true;
	}
	if (!property.compare("pathSurface"))
	{
		mObject->setPathSurface(value.c_str());
		getMI()->_entity2dManager->add(mObject->getEntity2d());
		mObject->getEntity2d()->setHotSpot(0.5f, 0.5f);
		return true;
	}
	// if none of the IFs executes, the property is not one of an object therefore return false
	return false;
}
Esempio n. 28
0
void union_data::readGenotypesBED(string fbed,string region) {
	string buffer;
	int n_includedG = 0;
	int n_excludedG_user = 0;
	int n_includedS = 0;
	int n_excludedS = 0;
	int n_missingS = 0;
	vector < int > mappingS;
	genotype_id.clear();
	genotype_chr.clear();
	genotype_start.clear();
	genotype_end.clear();
	genotype_val.clear();
	genotype_count=0;
	genotype_id_to_idx.clear();
	//Opening files
	htsFile *fp = hts_open(fbed.c_str(),"r");
	if (!fp) vrb.error("Cannot open file!");
	tbx_t * tbx = tbx_index_load(fbed.c_str());
	if (!tbx) vrb.error("Cannot load index file!");
	kstring_t str = {0,0,0};
	if (hts_getline(fp, KS_SEP_LINE, &str) <= 0 || !str.l || str.s[0] != tbx->conf.meta_char ) vrb.error("Cannot read header line!");

	//Process sample names
	vector < string > tokens;
	stb.split(string(str.s), tokens);
	if (tokens.size() < 7) vrb.error("Incorrect number of columns!");
	for (int i0 = 6 ; i0 < tokens.size() ; i0 ++) {
		string sid = tokens[i0];
		if (filter_sample.check(sid)) {
			mappingS.push_back(findSample(sid));
			if (mappingS.back() >= 0) n_includedS ++;
			else n_missingS ++;
		} else {
			mappingS.push_back(-1);
			n_excludedS ++;
		}
	}
	//vrb.bullet(stb.str(n_includedS) + " samples included");
	//if (n_excludedS > 0) vrb.bullet(stb.str(n_excludedS) + " samples excluded by user");
	//if (n_missingS > 0) vrb.bullet(stb.str(n_missingS) + " samples without phenotype data");
	//if (n_includedS != sample_count) vrb.error("Cannot find genotype for " + stb.str(sample_count - n_includedS) + " samples!");

    unsigned int linecount = 0;

	//Jump to interesting region

	hts_itr_t *itr = tbx_itr_querys(tbx, region.c_str());
	//vrb.bullet("target region [" + regionGenotype.get() + "]");
	//if (!itr) vrb.error("Cannot jump to region!");
	while (tbx_itr_next(fp, tbx, itr, &str) >= 0) {
		linecount ++;
		if (linecount % 100000 == 0) vrb.bullet("Read " + stb.str(linecount) + " lines");
		stb.split(string(str.s), tokens);
		if (tokens.size() < 7) vrb.error("Incorrect number of columns!");
		if (filter_genotype.check(tokens[3])) {
			genotype_id.push_back(tokens[3]);
			genotype_chr.push_back(tokens[0]);
			genotype_start.push_back(atoi(tokens[1].c_str()) + 1);
			genotype_end.push_back(atoi(tokens[2].c_str()));
			genotype_val.push_back(vector < float > (sample_count, 0.0));
			for (int t = 6 ; t < tokens.size() ; t ++) {
				if (mappingS[t-6] >= 0) {
					if (tokens[t] == "NA") genotype_val.back()[mappingS[t-6]] = bcf_float_missing;
					else genotype_val.back()[mappingS[t-6]] = stof(tokens[t]);
				}
			}
			pair < string, int > temp (tokens[3],n_includedG);
			genotype_id_to_idx.insert(temp);
			n_includedG++;
		} else n_excludedG_user ++;
	}
	tbx_itr_destroy(itr);


	//Finalize & verbose
	tbx_destroy(tbx);
	if (hts_close(fp)) vrb.error("Cannot properly close file!");
	genotype_count = n_includedG;
	//vrb.bullet(stb.str(n_includedG) + " variants included");
	//if (n_excludedG_user > 0) vrb.bullet(stb.str(n_excludedG_user) + " variants excluded by user");
    //if (genotype_count == 0) vrb.leave("Cannot find variants in target region!");
}
Esempio n. 29
0
float g_maplistCacheQueryNexuizMapList(entity me, float i)
{
	return stof(substring(me.g_maplistCache, i, 1));
}
Esempio n. 30
0
void TrafficSimulation::import_vehicles(std::string vehicles_file)
{
	// load input file
	std::ifstream infile;
	infile.exceptions(std::ifstream::badbit);
	try {
		infile.open(vehicles_file);

		// read and match lines
		std::string line;

		for (uint_fast32_t line_num = 1; std::getline(infile, line);
			 ++line_num) {
			// split by fields
			std::vector<std::string> fields = nonstd::split(line, ':');

			// 4 fields are required (time, name, from, to)
			if (fields.size() < 4) {
				std::cerr << "E: Line " << line_num << " of input file \""
						  << vehicles_file
						  << "\" is not valid. See documentation "
							 "for correct syntax. Skipping..." << std::endl;
				continue;
			}

#ifndef NDEBUG
			std::cout << "Fields:" << std::endl;
			for (auto &f : fields) {
				std::cout << f << std::endl;
			}
			std::cout << "Matched vehicle on line " << line_num << std::endl
					  << "name: " << fields[1] << std::endl
					  << "from: " << fields[2] << std::endl
					  << "to: " << fields[3] << std::endl
					  << "starttime: " << fields[0] << std::endl;
#endif

			// create vehicle; parse starttime, name, from and to
			try {
				Vehicle veh(*this, fields[2], fields[3], stoull(fields[0]),
							fields[1]);

				// parse optional properties
				for (int i = 4; i < fields.size(); ++i) {
					// split property field by =
					std::vector<std::string> property =
						nonstd::split(fields[i], '=');

					// assign property
					switch (nonstd::hash(property[0].c_str())) {
					case nonstd::hash("traffic_increase_caused"):
						veh.traffic_increase_caused = stof(property[1]);
						break;
					case nonstd::hash("max_speed"):
						veh.max_speed = stoul(property[1]);
						break;
					}
				}

				// add vehicle to simulation
				vehicles.push_back(veh);

				std::cout << "I: Vehicle " << veh.name
						  << " loaded for simulation" << std::endl;
			}
			// vehicle construction errors
			catch (const std::runtime_error &e) {
				std::cerr << "E: " << vehicles_file << ":" << line_num
						  << " Vehicle on line " << line_num
						  << "could'n be loaded for simulation. " << e.what()
						  << std::endl;
			}
		}
	}
	// input file errors
	catch (const std::ifstream::failure &e) {
		std::cerr << "E: Couldn't read file '" << vehicles_file << " "
				  << e.what() << std::endl;
	}
}