text stringlengths 54 60.6k |
|---|
<commit_before>fedfbc5c-585a-11e5-922e-6c40088e03e4<commit_msg>fee7eabe-585a-11e5-89b3-6c40088e03e4<commit_after>fee7eabe-585a-11e5-89b3-6c40088e03e4<|endoftext|> |
<commit_before>9ed625d9-2e4f-11e5-83c4-28cfe91dbc4b<commit_msg>9edf3cf3-2e4f-11e5-a902-28cfe91dbc4b<commit_after>9edf3cf3-2e4f-11e5-a902-28cfe91dbc4b<|endoftext|> |
<commit_before>#include "context.h"
#include "renderer.h"
#include "pmesh.h"
#include "glm/glm.hpp"
#include <unistd.h>
#define width 1024
#define height 768
using namespace std ;
int main(int argc, char** argv)
{
Renderer renderer;
Context context(renderer);
if (!context.init(width, height, "Jeu de voitures trop de ouf !!!", 16))
{
cerr << "Impossible d'initialiser le contexte OpenGL." << endl ;
return 0;
}
PMesh* obj = new PMesh();
obj->loadObject("gun.obj");
Drawable drw;
drw.load(obj->getVertices(), obj->getIndices());
drw.rotate(glm::vec3(1,0,0), 90);
Shader shdr1("shaders/vert.vert", "shaders/couleur3D.frag");
Shader shdr2("shaders/gris.vert", "shaders/couleur3D.frag");
while (context.eventLoop())
{
context.clean();
drw.setShader(&shdr2);
renderer.draw(drw);
drw.setShader(&shdr1);
renderer.draw(drw, GL_LINE);
context.show();
drw.rotate(glm::vec3(0,1,0), 0.01);
}
return 0;
}
<commit_msg>van de hippie sympa<commit_after>#include "context.h"
#include "renderer.h"
#include "pmesh.h"
#include "glm/glm.hpp"
#include <unistd.h>
#define width 1024
#define height 768
using namespace std ;
int main(int argc, char** argv)
{
Renderer renderer;
Context context(renderer);
if (!context.init(width, height, "Jeu de voitures trop de ouf !!!", 0))
{
cerr << "Impossible d'initialiser le contexte OpenGL." << endl ;
return 0;
}
PMesh* obj = new PMesh();
obj->loadObject("van.obj");
Drawable drw;
drw.load(obj->getVertices(), obj->getIndices());
drw.rotate(glm::vec3(1,0,0), 90);
//drw.homothetie(glm::vec3(0.001,0.001,0.001));
Shader shdr1("shaders/vert.vert", "shaders/couleur3D.frag");
Shader shdr2("shaders/gris.vert", "shaders/couleur3D.frag");
while (context.eventLoop())
{
context.clean();
drw.setShader(&shdr2);
renderer.draw(drw);
drw.setShader(&shdr1);
renderer.draw(drw, GL_LINE);
context.show();
drw.rotate(glm::vec3(0,1,0), 0.01);
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <math.h>
#include <SFML/Graphics.hpp>
#include "vector2.h"
#include "triangle.h"
#include "delaunay.h"
typedef Vector2<float> Vec2f;
float RandomFloat(float a, float b) {
float random = ((float) rand()) / (float) RAND_MAX;
float diff = b - a;
float r = random * diff;
return a + r;
}
int main()
{
float numberPoints = roundf(RandomFloat(4, 40));
std::vector<Vec2f> points;
for(int i = 0; i < numberPoints; i++) {
points.push_back(Vec2f(RandomFloat(0, 130), RandomFloat(0, 100)));
}
std::vector<Triangle> tr = Delaunay::triangulate(points);
std::cout << tr.size() << " triangles" << std::endl;
for(auto i = tr.begin(); i != tr.end(); i++) {
std::cout << *i << std::endl;
}
// SFML window
sf::RenderWindow window(sf::VideoMode(800, 600), "Delaunay triangulation");
sf::View scale;
scale.reset(sf::FloatRect(0, 0, 800/6, 600/6));
// Transform each points of each vector as a rectangle
std::vector<sf::RectangleShape*> squares;
for(auto t = begin(tr); t != end(tr); t++) {
sf::RectangleShape *c1 = new sf::RectangleShape(sf::Vector2f(2, 2));
c1->setPosition(t->getP1().getX(), t->getP1().getY());
squares.push_back(c1);
sf::RectangleShape *c2 = new sf::RectangleShape(sf::Vector2f(2, 2));
c2->setPosition(t->getP2().getX(), t->getP2().getY());
squares.push_back(c2);
sf::RectangleShape *c3 = new sf::RectangleShape(sf::Vector2f(2, 2));
c3->setPosition(t->getP3().getX(), t->getP3().getY());
squares.push_back(c3);
}
// Remove the doubles
for(auto i = begin(squares); i != end(squares); i++) {
for(auto j = begin(squares); j != end(squares);) {
if(i != j) {
if((*i)->getPosition().x == (*j)->getPosition().x && (*i)->getPosition().y == (*j)->getPosition().y) {
j = squares.erase(j);
}
else {
j++;
}
}
else {
j++;
}
}
}
// Make the lines
std::vector<std::array<sf::Vertex, 2> > lines;
for(auto t = begin(tr); t != end(tr); t++) {
sf::Vector2f p1(t->getP1().getX() + 1, t->getP1().getY() + 1);
sf::Vector2f p2(t->getP2().getX() + 1, t->getP2().getY() + 1);
sf::Vector2f p3(t->getP3().getX() + 1, t->getP3().getY() + 1);
lines.push_back({sf::Vertex(p1), sf::Vertex(p2)});
lines.push_back({sf::Vertex(p2), sf::Vertex(p3)});
lines.push_back({sf::Vertex(p3), sf::Vertex(p1)});
}
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
// Comment this line for the resolution
window.setView(scale);
window.clear();
// Draw the squares
for(auto s = begin(squares); s != end(squares); s++) {
window.draw(**s);
}
// Draw the lines
for(auto l = begin(lines); l != end(lines); l++) {
window.draw((*l).data(), 2, sf::Lines);
}
window.display();
}
return 0;
}
<commit_msg>Rand fix<commit_after>#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <math.h>
#include <stdlib.h>
#include <SFML/Graphics.hpp>
#include "vector2.h"
#include "triangle.h"
#include "delaunay.h"
typedef Vector2<float> Vec2f;
float RandomFloat(float a, float b) {
float random = ((float) rand()) / (float) RAND_MAX;
float diff = b - a;
float r = random * diff;
return a + r;
}
int main()
{
srand (time(NULL));
float numberPoints = roundf(RandomFloat(4, 40));
std::vector<Vec2f> points;
for(int i = 0; i < numberPoints; i++) {
points.push_back(Vec2f(RandomFloat(0, 130), RandomFloat(0, 100)));
}
std::vector<Triangle> tr = Delaunay::triangulate(points);
std::cout << tr.size() << " triangles" << std::endl;
for(auto i = tr.begin(); i != tr.end(); i++) {
std::cout << *i << std::endl;
}
// SFML window
sf::RenderWindow window(sf::VideoMode(800, 600), "Delaunay triangulation");
sf::View scale;
scale.reset(sf::FloatRect(0, 0, 800/6, 600/6));
// Transform each points of each vector as a rectangle
std::vector<sf::RectangleShape*> squares;
for(auto t = begin(tr); t != end(tr); t++) {
sf::RectangleShape *c1 = new sf::RectangleShape(sf::Vector2f(2, 2));
c1->setPosition(t->getP1().getX(), t->getP1().getY());
squares.push_back(c1);
sf::RectangleShape *c2 = new sf::RectangleShape(sf::Vector2f(2, 2));
c2->setPosition(t->getP2().getX(), t->getP2().getY());
squares.push_back(c2);
sf::RectangleShape *c3 = new sf::RectangleShape(sf::Vector2f(2, 2));
c3->setPosition(t->getP3().getX(), t->getP3().getY());
squares.push_back(c3);
}
// Remove the doubles
for(auto i = begin(squares); i != end(squares); i++) {
for(auto j = begin(squares); j != end(squares);) {
if(i != j) {
if((*i)->getPosition().x == (*j)->getPosition().x && (*i)->getPosition().y == (*j)->getPosition().y) {
j = squares.erase(j);
}
else {
j++;
}
}
else {
j++;
}
}
}
// Make the lines
std::vector<std::array<sf::Vertex, 2> > lines;
for(auto t = begin(tr); t != end(tr); t++) {
sf::Vector2f p1(t->getP1().getX() + 1, t->getP1().getY() + 1);
sf::Vector2f p2(t->getP2().getX() + 1, t->getP2().getY() + 1);
sf::Vector2f p3(t->getP3().getX() + 1, t->getP3().getY() + 1);
lines.push_back({sf::Vertex(p1), sf::Vertex(p2)});
lines.push_back({sf::Vertex(p2), sf::Vertex(p3)});
lines.push_back({sf::Vertex(p3), sf::Vertex(p1)});
}
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
// Comment this line for the resolution
window.setView(scale);
window.clear();
// Draw the squares
for(auto s = begin(squares); s != end(squares); s++) {
window.draw(**s);
}
// Draw the lines
for(auto l = begin(lines); l != end(lines); l++) {
window.draw((*l).data(), 2, sf::Lines);
}
window.display();
}
return 0;
}
<|endoftext|> |
<commit_before>1a2562e1-2e4f-11e5-94b7-28cfe91dbc4b<commit_msg>1a2d3ce1-2e4f-11e5-9fd5-28cfe91dbc4b<commit_after>1a2d3ce1-2e4f-11e5-9fd5-28cfe91dbc4b<|endoftext|> |
<commit_before>dcdf52c5-313a-11e5-a7a4-3c15c2e10482<commit_msg>dce83223-313a-11e5-8ceb-3c15c2e10482<commit_after>dce83223-313a-11e5-8ceb-3c15c2e10482<|endoftext|> |
<commit_before>e3f30d26-2e4e-11e5-9812-28cfe91dbc4b<commit_msg>e3fa51ee-2e4e-11e5-97be-28cfe91dbc4b<commit_after>e3fa51ee-2e4e-11e5-97be-28cfe91dbc4b<|endoftext|> |
<commit_before>396f0cfa-2e4f-11e5-b828-28cfe91dbc4b<commit_msg>39759891-2e4f-11e5-9695-28cfe91dbc4b<commit_after>39759891-2e4f-11e5-9695-28cfe91dbc4b<|endoftext|> |
<commit_before>210c0300-2748-11e6-b60a-e0f84713e7b8<commit_msg>Too poor for Dropbox<commit_after>211722dc-2748-11e6-95bc-e0f84713e7b8<|endoftext|> |
<commit_before>5ba5d39e-2e4f-11e5-8139-28cfe91dbc4b<commit_msg>5bad845e-2e4f-11e5-b0d9-28cfe91dbc4b<commit_after>5bad845e-2e4f-11e5-b0d9-28cfe91dbc4b<|endoftext|> |
<commit_before>c5072461-327f-11e5-8daf-9cf387a8033e<commit_msg>c5107a45-327f-11e5-a717-9cf387a8033e<commit_after>c5107a45-327f-11e5-a717-9cf387a8033e<|endoftext|> |
<commit_before>9101ad6b-2d14-11e5-af21-0401358ea401<commit_msg>9101ad6c-2d14-11e5-af21-0401358ea401<commit_after>9101ad6c-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>6cb41a02-2fa5-11e5-acf1-00012e3d3f12<commit_msg>6cb68b02-2fa5-11e5-8553-00012e3d3f12<commit_after>6cb68b02-2fa5-11e5-8553-00012e3d3f12<|endoftext|> |
<commit_before>68c68de6-2e4f-11e5-89bc-28cfe91dbc4b<commit_msg>68ce2de6-2e4f-11e5-a151-28cfe91dbc4b<commit_after>68ce2de6-2e4f-11e5-a151-28cfe91dbc4b<|endoftext|> |
<commit_before>ba2f5491-2e4f-11e5-ad10-28cfe91dbc4b<commit_msg>ba380530-2e4f-11e5-9006-28cfe91dbc4b<commit_after>ba380530-2e4f-11e5-9006-28cfe91dbc4b<|endoftext|> |
<commit_before>2d238d36-2f67-11e5-b568-6c40088e03e4<commit_msg>2d29f39c-2f67-11e5-9ceb-6c40088e03e4<commit_after>2d29f39c-2f67-11e5-9ceb-6c40088e03e4<|endoftext|> |
<commit_before>3b1d490a-5216-11e5-978f-6c40088e03e4<commit_msg>3b24b6f4-5216-11e5-844c-6c40088e03e4<commit_after>3b24b6f4-5216-11e5-844c-6c40088e03e4<|endoftext|> |
<commit_before>5fbe00d8-5216-11e5-92d3-6c40088e03e4<commit_msg>5fc7de78-5216-11e5-8a73-6c40088e03e4<commit_after>5fc7de78-5216-11e5-8a73-6c40088e03e4<|endoftext|> |
<commit_before>5dee5a66-2e4f-11e5-b2ca-28cfe91dbc4b<commit_msg>5df501eb-2e4f-11e5-8039-28cfe91dbc4b<commit_after>5df501eb-2e4f-11e5-8039-28cfe91dbc4b<|endoftext|> |
<commit_before>68393a9a-5216-11e5-8410-6c40088e03e4<commit_msg>683fbbb6-5216-11e5-af3d-6c40088e03e4<commit_after>683fbbb6-5216-11e5-af3d-6c40088e03e4<|endoftext|> |
<commit_before>83000e99-2d15-11e5-af21-0401358ea401<commit_msg>83000e9a-2d15-11e5-af21-0401358ea401<commit_after>83000e9a-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>8c3d20a5-2d14-11e5-af21-0401358ea401<commit_msg>8c3d20a6-2d14-11e5-af21-0401358ea401<commit_after>8c3d20a6-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>/*
---------------------------------------------------------------------------
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org>
---------------------------------------------------------------------------
*/
/*
Made By: Patrick J. Rye
Purpose: A game I made as an attempt to teach myself c++, just super basic, but going to try to keep improving it as my knowledge increases.
Current Revision: 2.5ß-dev4
Change Log---------------------------------------------------------------------------------------------------------------------------------------------------
Date Revision Changed By Changes
------ --------- ------------ ---------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
-------------------------------------------------------------------------------------------------------------------------------------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MOVED FROM ALPHA TO BETA~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-------------------------------------------------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
2015/02/24 1.0b Patrick Rye -Moved from V5.0-alpha to V1.0-beta
-Fixed level up so it happens when you get to a new level.
-Allowed exit on map.
-Fixed opening text to reflect recent changes in the game.
-Grammar and spelling fixes (yay, made it several revisions without having to do this. :) ).
=============================================================================================================================================================
2015/02/24 1.1b Patrick Rye -Attempted to allow movement on map through arrow keys.
-Could not get this to work and broke everything. Rolling back to previous version.
-Keeping this attempt in the record and will try to implement it again later.
=============================================================================================================================================================
2015/02/25 1.2b Patrick Rye -Grammar and spelling fixes. ((╯°□°)╯︵ ┻━┻)
-Cleaned up code some more.
-Changed some if statements to case switches.
-Added breaks to case switches.
=============================================================================================================================================================
2015/02/26 1.3b Patrick Rye -Moved player movement to the room.h
=============================================================================================================================================================
2015/02/27 2.0b Patrick Rye -Added a save function, for testing purposes.
-Added load function.
-Added function to see if file exists.
=============================================================================================================================================================
2015/02/27 2.1b Patrick Rye -Moved save checker to basic.h
-Renamed casechecker.h to basic.h
-Added more comments explaining parts of the code.
-Changed some names of functions to better reflect what they do.
-Health is now carried between battles.
-Moved healing to be able to happen between battles.
-Added fail check for load function.
=============================================================================================================================================================
2015/03/02 2.2b Patrick Rye -Improved code a bit.
-Added version number tracker.
-Prompt for loading save.
-Prompt for incorrect save version.
-Moved saving and loading functions to its own header.
=============================================================================================================================================================
2015/03/02 2.2.1b Patrick Rye -Quick fix for version not being applied properly.
=============================================================================================================================================================
2015/03/03 2.3b Patrick Rye -Added more comments.
-Changed some wording to better explain stuff.
-Added a debug mode to game, detects if source code exists.
-Grammar & spelling fixes.
=============================================================================================================================================================
2015/03/04 2.4b Patrick Rye -Debug mode can be set by loading a debug save.
-Grammar & spelling fixes.
-Improved map menu.
-Changed save to 'V' rather than 'P'.
=============================================================================================================================================================
2015/03/06 2.5ß Patrick Rye -Changed some debug commands.
-Changed change log date format from MM/DD/YY to YYYY/MM/DD because I like it better.
=============================================================================================================================================================
*/
/*********************************************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <cstdlib>
#include <cmath>
#include <locale>
#include <cstdio>
#include <ctime>
/*********************************************************************************************************/
#include "basic.h" //Functions that are simple and won't need to be changed very often.
#include "battle.h" //Functions that deal with battling, levelling up and making a player.
#include "rooms.h" //Functions that deal with generating a dungeon.
/*********************************************************************************************************/
using namespace std;
Dungeon d; //Define the dungeon class as 'd' so I can use functions in there anywhere later in the code.
/*********************************************************************************************************/
//Make all the global variables that I need.
int intMainLevel; //The level of the dungeon.
int intLevelStart = 1; //The level that the game starts at. Will be 1 unless loading from a save.
bool blDebugMode = false; //If game is in debug mode or not, effects if player has access to debug commands.
const string CurrentVerison = "2.5ß-dev4"; //The current version of this program, stored in a save file later on.
/*********************************************************************************************************/
//These functions have to be up here as functions in save.h use them.
//These values are used to pass values to the save header so that they may be saved.
//Or to set values from a load.
int getmainvalue(int intvalue)
{
if(intvalue == 0 ) {return intMainLevel;}
else if (intvalue == 1) {return intLevelStart;}
else {return 1;}
}
void setmainvalue(int intlocation, int intvalue) {if (intlocation == 0) {intLevelStart = intvalue;}}
void setdebugmode(bool blsetdebugmode) {blDebugMode = blsetdebugmode;}
#include "save.h" //A header to hold functions related to saving and loading.
/*********************************************************************************************************/
int main()
{
PassProgramVerison(CurrentVerison); //Pass current program version into the save header.
cout << string(48, '\n');
char charPlayerDirection;
bool blBattleEnding = false;
char charExitFind;
bool blOldSave = false;
char chrPlayerMade = 'F';
char chrSaveSuccess = 'N'; //N means that save has not been run.
//If game is not already in debug mode, checks if source code exists then put it in debug mode if it does.
if (!(blDebugMode)) {blDebugMode = fileexists("main.cpp"); }
if (blDebugMode) {SetBattleDebugMode(true); SetRoomDebugMode(true);} //Sets debug mode for both rooms.h & battle.h
if (fileexists("save.bif")) //Check if there is a save present.
{
blOldSave = LoadOldSave();
if (blOldSave) {chrPlayerMade = 'T';}
//End of if save exists.
}
else {cout<<string(50, '\n');}
if(!blOldSave) //If it is not an old save show welcome message.
{
cout<<"Welcome to the World of Attacker."<<endl<<"Your objective is to go through 10 randomly generated dungeons."<<endl;
cout<<"You are looking for the stairs down ( > ). While you are represented by † ."<<endl;
cout<<"Every step brings you closer to your goal, but there might be a monster there as well."<<endl;
cout<<"Each level is harder than the last, do you have what it takes to win?"<<endl;
cout<<"Good luck!"<<endl<<endl<<endl<<endl;
while (chrPlayerMade != 'T') {chrPlayerMade = PlayerInitialize();}; //Repeat initialization until player is made.
}
for(intMainLevel = intLevelStart; intMainLevel <= 10; intMainLevel++)
{
//Do level up if new level.
if (intMainLevel > intLevelStart) {LevelUpFunction();}
charExitFind = 'F';
cout<<endl;
if (blOldSave && intMainLevel == intLevelStart) {/*d.playerfind();*/ d.showDungeon();} //If old save and the level of that save, just load old dungeon.
else {Dungeon d;/*Generates dungeon.*/} //If it is not old game OR a different level of old game, make new dungeon.
do
{
cout << string(50, '\n');
d.showDungeon();
cout<<"Level "<<intMainLevel<<" of 10."<<endl;
cout<<"Please enter a direction you would like to go: "<<endl;
cout<<"[N]orth, [E]ast, [S]outh, [W]est "<<endl;
cout<<"E[X]it, [C]heck your health, [H]eal, Sa[V]e "<<endl;
if (blDebugMode) {cout<<"[L]evel up, or [M]onster."<<endl;}
cout<<"> ";
cin>>charPlayerDirection;
charPlayerDirection = CharConvertToUpper(charPlayerDirection);
charExitFind = d.PlayerMovement(charPlayerDirection);
if (charExitFind == 'E') {return 0;} //If we get an error exit program.
if (charExitFind == 'S') {chrSaveSuccess = savefunction();} //Save the game.
switch (chrSaveSuccess)
{
case 'T' :
cout<<endl<<"Save succeeded."<<endl;
system("pause");
chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
break;
case 'F' :
cout<<endl<<"Save failed!"<<endl;
system("pause");
chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
break;
}
if (!(charExitFind=='S') && !(charPlayerDirection == 'C')) //If player did not save or did not check himself, see if player runs into monster.
{
if(rand() % 101 <= 10 || charExitFind == 'M') //Random chance to encounter monster, or debug code to force monster encounter.
{
cout << string(50, '\n');
blBattleEnding = startbattle(intMainLevel); //Starts battle.
if(!blBattleEnding) {return 0;} //Player lost battle.
}
}
}while (charExitFind != 'T'); //Repeat until player finds exit.
//End of FOR levels.
}
cout << string(50, '\n');
cout<<"You win!!";
system("pause");
return 0;
//End of main
}
<commit_msg>Update to V2.5ß <commit_after>/*
---------------------------------------------------------------------------
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org>
---------------------------------------------------------------------------
*/
/*
Made By: Patrick J. Rye
Purpose: A game I made as an attempt to teach myself c++, just super basic, but going to try to keep improving it as my knowledge increases.
Current Revision: 2.5ß
Change Log---------------------------------------------------------------------------------------------------------------------------------------------------
Date Revision Changed By Changes
------ --------- ------------ ---------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
-------------------------------------------------------------------------------------------------------------------------------------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MOVED FROM ALPHA TO BETA~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-------------------------------------------------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
2015/02/24 1.0b Patrick Rye -Moved from V5.0-alpha to V1.0-beta
-Fixed level up so it happens when you get to a new level.
-Allowed exit on map.
-Fixed opening text to reflect recent changes in the game.
-Grammar and spelling fixes (yay, made it several revisions without having to do this. :) ).
=============================================================================================================================================================
2015/02/24 1.1b Patrick Rye -Attempted to allow movement on map through arrow keys.
-Could not get this to work and broke everything. Rolling back to previous version.
-Keeping this attempt in the record and will try to implement it again later.
=============================================================================================================================================================
2015/02/25 1.2b Patrick Rye -Grammar and spelling fixes. ((╯°□°)╯︵ ┻━┻)
-Cleaned up code some more.
-Changed some if statements to case switches.
-Added breaks to case switches.
=============================================================================================================================================================
2015/02/26 1.3b Patrick Rye -Moved player movement to the room.h
=============================================================================================================================================================
2015/02/27 2.0b Patrick Rye -Added a save function, for testing purposes.
-Added load function.
-Added function to see if file exists.
=============================================================================================================================================================
2015/02/27 2.1b Patrick Rye -Moved save checker to basic.h
-Renamed casechecker.h to basic.h
-Added more comments explaining parts of the code.
-Changed some names of functions to better reflect what they do.
-Health is now carried between battles.
-Moved healing to be able to happen between battles.
-Added fail check for load function.
=============================================================================================================================================================
2015/03/02 2.2b Patrick Rye -Improved code a bit.
-Added version number tracker.
-Prompt for loading save.
-Prompt for incorrect save version.
-Moved saving and loading functions to its own header.
=============================================================================================================================================================
2015/03/02 2.2.1b Patrick Rye -Quick fix for version not being applied properly.
=============================================================================================================================================================
2015/03/03 2.3b Patrick Rye -Added more comments.
-Changed some wording to better explain stuff.
-Added a debug mode to game, detects if source code exists.
-Grammar & spelling fixes.
=============================================================================================================================================================
2015/03/04 2.4b Patrick Rye -Debug mode can be set by loading a debug save.
-Grammar & spelling fixes.
-Improved map menu.
-Changed save to 'V' rather than 'P'.
=============================================================================================================================================================
2015/03/06 2.5ß Patrick Rye -Changed some debug commands.
-Changed change log date format from MM/DD/YY to YYYY/MM/DD because I like it better.
-Added better opening message.
-Replaced all system("pause") with getchar();
=============================================================================================================================================================
*/
/*********************************************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <cstdlib>
#include <cmath>
#include <locale>
#include <cstdio>
#include <ctime>
/*********************************************************************************************************/
#include "basic.h" //Functions that are simple and won't need to be changed very often.
#include "battle.h" //Functions that deal with battling, levelling up and making a player.
#include "rooms.h" //Functions that deal with generating a dungeon.
/*********************************************************************************************************/
using namespace std;
Dungeon d; //Define the dungeon class as 'd' so I can use functions in there anywhere later in the code.
/*********************************************************************************************************/
//Make all the global variables that I need.
int intMainLevel; //The level of the dungeon.
int intLevelStart = 1; //The level that the game starts at. Will be 1 unless loading from a save.
bool blDebugMode = false; //If game is in debug mode or not, effects if player has access to debug commands.
const string CurrentVerison = "2.5ß"; //The current version of this program, stored in a save file later on.
/*********************************************************************************************************/
const string OpeningMessage[16] = {" \n",
",--. ,--. ,--. \n",
"| | | | ,---. | | ,---. ,---. ,--,--,--. ,---. \n",
"| |.'.| || .-. :| || .--'| .-. || || .-. : \n",
"| ,'. |\\ --.| |\\ `--.' '-' '| | | |\\ --. \n",
"'--' '--' `----'`--' `---' `---' `--`--`--' `----' \n",
" ,--. \n",
",-' '-. ,---. \n",
"'-. .-'| .-. | \n",
" | | ' '-' ' \n",
" `--' `---' \n",
" ,---. ,--. ,--. ,--. \n",
" / O \\ ,-' '-.,-' '-. ,--,--. ,---.| |,-. ,---. ,--.--. \n",
"| .-. |'-. .-''-. .-'' ,-. || .--'| /| .-. :| .--' \n",
"| | | | | | | | \\ '-' |\\ `--.| \\ \\\\ --.| | \n",
"`--' `--' `--' `--' `--`--' `---'`--'`--'`----'`--' \n"};
/*********************************************************************************************************/
//These functions have to be up here as functions in save.h use them.
//These values are used to pass values to the save header so that they may be saved.
//Or to set values from a load.
int getmainvalue(int intvalue)
{
if(intvalue == 0 ) {return intMainLevel;}
else if (intvalue == 1) {return intLevelStart;}
else {return 1;}
}
void setmainvalue(int intlocation, int intvalue) {if (intlocation == 0) {intLevelStart = intvalue;}}
void setdebugmode(bool blsetdebugmode) {blDebugMode = blsetdebugmode;}
#include "save.h" //A header to hold functions related to saving and loading.
/*********************************************************************************************************/
int main()
{
PassProgramVerison(CurrentVerison); //Pass current program version into the save header.
cout << string(48, '\n');
char charPlayerDirection;
bool blBattleEnding = false;
char charExitFind;
bool blOldSave = false;
char chrPlayerMade = 'F';
char chrSaveSuccess = 'N'; //N means that save has not been run.
//If game is not already in debug mode, checks if source code exists then put it in debug mode if it does.
if (!(blDebugMode)) {blDebugMode = fileexists("main.cpp"); }
if (blDebugMode) {SetBattleDebugMode(true); SetRoomDebugMode(true);} //Sets debug mode for both rooms.h & battle.h
for (int i = 0; i < 16; i++){cout<<OpeningMessage[i];}
getchar();
cout<<string(50,'\n');
if (fileexists("save.bif")) //Check if there is a save present.
{
blOldSave = LoadOldSave();
if (blOldSave) {chrPlayerMade = 'T';}
//End of if save exists.
}
else {cout<<string(50, '\n');}
if(!blOldSave) //If it is not an old save show welcome message.
{
cout<<endl<<"Your objective is to go through 10 randomly generated dungeons."<<endl;
cout<<"You are looking for the stairs down ( > ). While you are represented by † ."<<endl;
cout<<"Every step brings you closer to your goal, but there might be a monster there as well."<<endl;
cout<<"Each level is harder than the last, do you have what it takes to win?"<<endl;
cout<<"Good luck!"<<endl<<endl<<endl<<endl;
while (chrPlayerMade != 'T') {chrPlayerMade = PlayerInitialize();}; //Repeat initialization until player is made.
}
for(intMainLevel = intLevelStart; intMainLevel <= 10; intMainLevel++)
{
//Do level up if new level.
if (intMainLevel > intLevelStart) {LevelUpFunction();}
charExitFind = 'F';
cout<<endl;
if (blOldSave && intMainLevel == intLevelStart) {/*d.playerfind();*/ d.showDungeon();} //If old save and the level of that save, just load old dungeon.
else {Dungeon d;/*Generates dungeon.*/} //If it is not old game OR a different level of old game, make new dungeon.
do
{
cout << string(50, '\n');
d.showDungeon();
cout<<"Level "<<intMainLevel<<" of 10."<<endl;
cout<<"Please enter a direction you would like to go: "<<endl;
cout<<"[N]orth, [E]ast, [S]outh, [W]est "<<endl;
cout<<"E[X]it, [C]heck your health, [H]eal, Sa[V]e "<<endl;
if (blDebugMode) {cout<<"[L]evel up, or [M]onster."<<endl;}
cout<<"> ";
cin>>charPlayerDirection;
charPlayerDirection = CharConvertToUpper(charPlayerDirection);
charExitFind = d.PlayerMovement(charPlayerDirection);
if (charExitFind == 'E') {return 0;} //If we get an error exit program.
if (charExitFind == 'S') {chrSaveSuccess = savefunction();} //Save the game.
switch (chrSaveSuccess)
{
case 'T' :
cout<<endl<<"Save succeeded."<<endl;
getchar();
chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
break;
case 'F' :
cout<<endl<<"Save failed!"<<endl;
getchar();
chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
break;
}
if (!(charExitFind=='S') && !(charPlayerDirection == 'C')) //If player did not save or did not check himself, see if player runs into monster.
{
if(rand() % 101 <= 10 || charExitFind == 'M') //Random chance to encounter monster, or debug code to force monster encounter.
{
cout << string(50, '\n');
blBattleEnding = startbattle(intMainLevel); //Starts battle.
if(!blBattleEnding) {return 0;} //Player lost battle.
}
}
}while (charExitFind != 'T'); //Repeat until player finds exit.
//End of FOR levels.
}
cout << string(50, '\n');
cout<<"You win!!";
getchar();
return 0;
//End of main
}
<|endoftext|> |
<commit_before>9ecf9cf4-35ca-11e5-b443-6c40088e03e4<commit_msg>9ed62614-35ca-11e5-92eb-6c40088e03e4<commit_after>9ed62614-35ca-11e5-92eb-6c40088e03e4<|endoftext|> |
<commit_before>28b6e651-2d3d-11e5-9202-c82a142b6f9b<commit_msg>29187566-2d3d-11e5-a4ed-c82a142b6f9b<commit_after>29187566-2d3d-11e5-a4ed-c82a142b6f9b<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
void solve( vector<vector<int> >& graph ) {
graph.push_back( vector<int>(0) );
vector<vector<int> > full_graph;
full_graph.reserve( graph.size() );
for( size_t v = 0; v < graph.size(); ++v ) {
auto row = graph.at(v);
vector<int> adj_list;
for_each( row.begin(), row.end(), [&](int n) { if( n != 0 ) { adj_list.push_back(n); } } );
for( int i = 0; i < static_cast<int>(v); ++i ) {
row = graph.at(i);
if( any_of( row.begin(), row.end(), [&](int n) { return (n == static_cast<int>(v+1)); } ) ) {
adj_list.push_back(i+1);
}
}
sort( adj_list.begin(), adj_list.end() );
full_graph.push_back( adj_list );
}
for( auto it : full_graph ) {
for( auto itt : it ) {
cout << itt << " ";
}
cout << endl;
}
}
int main( int argc, char **argv ) {
if( argc < 2 ) {
cerr << "Usage: " << argv[0] << " [FILE]" << endl;
return 0;
}
ifstream ifs( argv[1], ifstream::in );
if(! ifs.good() ) {
cerr << "Unable to open input file: " << argv[1] << endl;
}
string line;
vector< vector<int> > graph;
while( ifs.good() ) {
getline( ifs, line );
string val;
stringstream ss;
vector<int> vertex;
ss << line;
while( getline( ss, val, ',' ) ) {
int v = stoi( val );
if( v == -1 ) {
solve( graph );
graph.clear();
break;
} else {
vertex.push_back( v );
}
}
graph.push_back( vertex );
}
//solve( graph );
return 0;
}
<commit_msg>Algorithm complete except check for root<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
struct Vertex {
bool visited;
int num;
int low;
int parent;
};
void FindArt( int v, const vector<vector<int> >& graph, vector<Vertex>& aux, int& counter ) {
aux.at(v-1).visited = true;
aux.at(v-1).low = aux.at(v-1).num = counter++; // Rule 1
auto& row = graph.at(v-1);
for_each( row.begin(), row.end(), [&](int w) {
if(! aux.at(w-1).visited ) { // forward edge
aux.at(w-1).parent = v;
FindArt( w, graph, aux, counter );
if( aux.at(w-1).low >= aux.at(v-1).num ) {
cout << v << " is an articulation point." << endl;
}
aux.at(v-1).low = min( aux.at(v-1).low, aux.at(w-1).low ); // Rule 3
} else {
if( aux.at(v-1).parent != w ) { // back edge
aux.at(v-1).low = min( aux.at(v-1).low, aux.at(w-1).num ); // Rule 2
}
}
});
}
void solve( vector<vector<int> >& graph ) {
graph.push_back( vector<int>(0) );
vector<vector<int> > full_graph;
full_graph.reserve( graph.size() );
for( size_t v = 0; v < graph.size(); ++v ) {
auto row = graph.at(v);
vector<int> adj_list;
for_each( row.begin(), row.end(), [&](int n) { if( n != 0 ) { adj_list.push_back(n); } } );
for( int i = 0; i < static_cast<int>(v); ++i ) {
row = graph.at(i);
if( any_of( row.begin(), row.end(), [&](int n) { return (n == static_cast<int>(v+1)); } ) ) {
adj_list.push_back(i+1);
}
}
sort( adj_list.begin(), adj_list.end() );
full_graph.push_back( adj_list );
}
vector<Vertex> aux;
for( size_t i = 0; i < full_graph.size(); ++i ) {
Vertex v = { false, -1, -1, -1 };
aux.push_back( v );
}
int counter = 1;
FindArt( 1, full_graph, aux, counter );
}
int main( int argc, char **argv ) {
if( argc < 2 ) {
cerr << "Usage: " << argv[0] << " [FILE]" << endl;
return 0;
}
ifstream ifs( argv[1], ifstream::in );
if(! ifs.good() ) {
cerr << "Unable to open input file: " << argv[1] << endl;
}
string line;
vector< vector<int> > graph;
while( ifs.good() ) {
getline( ifs, line );
string val;
stringstream ss;
vector<int> vertex;
ss << line;
while( getline( ss, val, ',' ) ) {
int v = stoi( val );
if( v == -1 ) {
solve( graph );
graph.clear();
break;
} else {
vertex.push_back( v );
}
}
graph.push_back( vertex );
}
//solve( graph );
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
#include <fstream>
#include <vector>
#include <unistd.h>
#include "gen.hpp"
#include "info.hpp"
//Shark package manager
//Shamelessy stolen from some stack overflow thread
char* getField(char** begin, char** end, const std::string& option)
{
char** itr = std::find(begin, end, option);
if(itr != end && ++itr != end)
{
return *itr;
}
return 0;
}
bool getFlag(char** begin, char** end, const std::string& option)
{
return std::find(begin, end, option) != end;
}
std::string root;
int Install(std::string package);
int Untar(std::string tarball);
std::string Download(std::string package, std::string ver = "");
int main(int argc, char* argv[])
{
//Set the default values
root="/";
if(getFlag(argv, argv+argc, "--root"))
{
root = (std::string)getField(argv, argv+argc, "--root");
if(root[root.size()-1] != '/')
{
root.append("/");
}
std::cout << "Using " << root << " as /\n";
}
if(root == "/")
{
std::cout << "Error: no fake root set (safe mode)\n";
return 1;
}
if(getFlag(argv, argv+argc, "-U"))
{
return Untar(getField(argv, argv+argc, "-U"));
}
if(getFlag(argv, argv+argc, "-UI"))
{
std::string pkg = getField(argv, argv+argc, "-UI");
if(Untar(pkg) != 0)
{
return 1;
}
int slash = pkg.find_last_of("/");
if(slash != std::string::npos)
{
pkg = pkg.substr(slash+1);
}
int dot = pkg.find(".tar");
if(dot != std::string::npos)
{
pkg = pkg.substr(0, dot);
}
return Install(pkg);
}
if(getFlag(argv, argv+argc, "-I"))
{
return Install(getField(argv, argv+argc, "-I"));
}
if(getFlag(argv, argv+argc, "-D"))
{
if(Download(getField(argv, argv+argc, "-D")) == "");
return 1;
}
if(getFlag(argv, argv+argc, "-DU"))
{
std::string pkg = getField(argv, argv+argc, "-DU");
std::string dl = Download(pkg);
if(dl == "")
{
return 1;
}
return Untar(dl);
}
if(getFlag(argv, argv+argc, "-DUI"))
{
std::string pkg = getField(argv, argv+argc, "-DUI");
std::string dl = Download(pkg);
if(dl == "")
{
return 1;
}
if(Untar(dl) != 0)
{
return 1;
}
int dot = dl.find(".tar");
if(dot != std::string::npos)
{
dl = dl.substr(0, dot);
}
return Install(dl);
}
if(getFlag(argv, argv+argc, "--gen-dirs"))
{
GenDirs(root, getField(argv, argv+argc, "--gen-dirs"), "");
}
if(getFlag(argv, argv+argc, "--gen-links"))
{
GenLinks(root, getField(argv, argv+argc, "--gen-links"), getField(argv, argv+argc, "-p"));
}
if(getFlag(argv, argv+argc, "--gen-files"))
{
GenFiles(root, getField(argv, argv+argc, "--gen-files"), "");
}
if(getFlag(argv, argv+argc, "--nuke"))
{
if(root == "/")
{
std::cout << "ARE YOU CRAZY\n" << "THIS COMMAND DELETES EVERYTHING ON THE ROOT\n" << "DON'T DO THIS\n";
return 1;
}
std::stringstream nukecmd;
nukecmd << "rm -rf " << root << "*";
//std::cout << nukecmd.str() << std::endl;
system(nukecmd.str().c_str());
}
return 0;
}
int Install(std::string package)
{
std::cout << "Verifying the package (not really)\n";
std::cout << "Loading the package info\n";
std::stringstream infofile;
infofile << root << "usr/pkg/" << package << "/info";
int res;
std::map<std::string, std::string> info = LoadInfo(infofile.str(), res);
if(res != 0)
return res;
std::string pkgname = info["PKG_NAME"];
std::string ver = info["PKG_VER"];
std::ifstream checkreinstall;
std::stringstream reinstallcheck;
reinstallcheck << root << "usr/pkg/" << pkgname;
checkreinstall.open(reinstallcheck.str().c_str());
if(checkreinstall.is_open())
{
std::map<std::string, std::string> reint = LoadInfo(reinstallcheck.str().c_str(), res);
if(ver == reint["PKG_VER"])
{
std::cout << "Package " << pkgname << " is already installed. Reinstall?(Y/n)";
char c;
std::cin >> c;
if(c == 'N' || c == 'n')
{
std::cout << "Installation aborted\n";
return 1;
}
}
else
std::cout << "Upgrading " << pkgname << " to version " << ver << std::endl;
checkreinstall.close();
}
std::cout << "Loading the file list\n";
std::vector<std::string> filelist;
std::ifstream files;
std::stringstream filesfile;
filesfile << root << "usr/pkg/" << package << "/files";
files.open(filesfile.str().c_str());
if(!files.is_open())
{
std::cout << "Error: no file list found. Malformed packge\n";
return 1;
}
std::string line;
while(files.good())
{
std::getline(files, line);
if(line == "EOF")
break;
filelist.push_back(line);
}
files.close();
std::cout << "Looking for conflicts\n";
for(int i = 0; i < filelist.size(); i++)
{
std::stringstream filename;
filename << root << "usr/pkgdb/" << filelist[i];
std::ifstream f;
f.open(filename.str().c_str());
if(f.is_open())
{
//we are probably conflicting, but make sure
std::string pkg;
getline(f, pkg);
if(pkg != pkgname)
{
std::cout << "Error: package " << pkgname << " conflicts with " << pkg << " on file " << filename.str() << ".\nInstallation aborted\n";
return 1;
}
}
}
std::cout << "Installing package " << package << std::endl;
//TODO:load the info file, add it to the package DB
//make the directories from dirs
std::ifstream dirs;
std::stringstream dirsfile;
dirsfile << root << "usr/pkg/" << package << "/dirs";
dirs.open(dirsfile.str().c_str());
if(dirs.is_open()) //assume that nothing needs to be made if there is no file
{
std::string dir;
while(dirs.good())
{
std::getline(dirs, dir);
if(dir == "EOF")
break;
std::stringstream d;
d << "mkdir --parents " << root << dir << " " << root << "usr/pkgdb/" << dir;
system(d.str().c_str());
}
}
//copy any files that need copying
for(int i=0; i < filelist.size(); i++)
{
std::stringstream f;
f << "cp -fd " << root << "usr/pkg/" << package << "/" << filelist[i] << " " << root << filelist[i];
//std::cout << f.str() << std::endl;
system(f.str().c_str());
//update the package db
std::stringstream dbcmd;
dbcmd << "echo \"" << pkgname << "\" > " << root << "usr/pkgdb/" << filelist[i];
//std::cout << dbcmd.str() << "\n";
system(dbcmd.str().c_str());
}
//install the info file
std::stringstream infocmd;
infocmd << "cp -fd " << root << "usr/pkg/" << package << "/info " << root << "usr/pkg/" << pkgname;
//std::cout << infocmd.str() << std::endl;
system(infocmd.str().c_str());
files.close();
return 0;
}
int Untar(std::string tarball)
{
std::cout << "Extracting tarball\n";
std::stringstream tar;
tar << "tar xf " << tarball << " -C "<< root << "usr/pkg";
if(system(tar.str().c_str()))
{
return 1;
}
return 0;
}
std::string Download(std::string package, std::string ver)
{
std::string version;
if(ver == "")
{
std::cout << "Resolving for latest version\n";
//resolve for latest version
std::stringstream infoget;
infoget << "curl -s -f -o " << package << " http://neos300.com/astro/pkg/info/" << package;
if(system(infoget.str().c_str()) != 0)
{
std::cout << "Package " << package << " not found\n";
return "";
}
int r;
std::map<std::string, std::string> newinfo = LoadInfo(package, r);
version = newinfo["PKG_VER"];
std::stringstream rm;
rm << "rm " << package;
system(rm.str().c_str());
}
else
version = ver;
//get the package
std::cout << "Downloading package\n";
std::stringstream pkgcmd;
pkgcmd << "curl -# -f -o " << package << "-" << version << ".tar.xz http://neos300.com/astro/pkg/" << package << "-" << version << ".tar.xz";
if(system(pkgcmd.str().c_str()) != 0)
{
std::cout << "Unable to find package tarball for package " << package << "\n";
return "";
}
std::cout << "Download successful\n";
std::stringstream ret;
ret << package << "-" << version << ".tar.xz";
return ret.str();
}
<commit_msg>Made -DUI clean up after itself.<commit_after>#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
#include <fstream>
#include <vector>
#include <unistd.h>
#include "gen.hpp"
#include "info.hpp"
//Shark package manager
//Shamelessy stolen from some stack overflow thread
char* getField(char** begin, char** end, const std::string& option)
{
char** itr = std::find(begin, end, option);
if(itr != end && ++itr != end)
{
return *itr;
}
return 0;
}
bool getFlag(char** begin, char** end, const std::string& option)
{
return std::find(begin, end, option) != end;
}
std::string root;
int Install(std::string package);
int Untar(std::string tarball);
std::string Download(std::string package, std::string ver = "");
int main(int argc, char* argv[])
{
//Set the default values
root="/";
if(getFlag(argv, argv+argc, "--root"))
{
root = (std::string)getField(argv, argv+argc, "--root");
if(root[root.size()-1] != '/')
{
root.append("/");
}
std::cout << "Using " << root << " as /\n";
}
if(root == "/")
{
std::cout << "Error: no fake root set (safe mode)\n";
return 1;
}
if(getFlag(argv, argv+argc, "-U"))
{
return Untar(getField(argv, argv+argc, "-U"));
}
if(getFlag(argv, argv+argc, "-UI"))
{
std::string pkg = getField(argv, argv+argc, "-UI");
if(Untar(pkg) != 0)
{
return 1;
}
int slash = pkg.find_last_of("/");
if(slash != std::string::npos)
{
pkg = pkg.substr(slash+1);
}
int dot = pkg.find(".tar");
if(dot != std::string::npos)
{
pkg = pkg.substr(0, dot);
}
return Install(pkg);
}
if(getFlag(argv, argv+argc, "-I"))
{
return Install(getField(argv, argv+argc, "-I"));
}
if(getFlag(argv, argv+argc, "-D"))
{
if(Download(getField(argv, argv+argc, "-D")) == "");
return 1;
}
if(getFlag(argv, argv+argc, "-DU"))
{
std::string pkg = getField(argv, argv+argc, "-DU");
std::string dl = Download(pkg);
if(dl == "")
{
return 1;
}
return Untar(dl);
}
if(getFlag(argv, argv+argc, "-DUI"))
{
std::string pkg = getField(argv, argv+argc, "-DUI");
std::string dl = Download(pkg);
if(dl == "")
{
return 1;
}
if(Untar(dl) != 0)
{
return 1;
}
std::string rm = "rm " + dl;
system(rm.c_str());
int dot = dl.find(".tar");
if(dot != std::string::npos)
{
dl = dl.substr(0, dot);
}
return Install(dl);
}
if(getFlag(argv, argv+argc, "--gen-dirs"))
{
GenDirs(root, getField(argv, argv+argc, "--gen-dirs"), "");
}
if(getFlag(argv, argv+argc, "--gen-links"))
{
GenLinks(root, getField(argv, argv+argc, "--gen-links"), getField(argv, argv+argc, "-p"));
}
if(getFlag(argv, argv+argc, "--gen-files"))
{
GenFiles(root, getField(argv, argv+argc, "--gen-files"), "");
}
if(getFlag(argv, argv+argc, "--nuke"))
{
if(root == "/")
{
std::cout << "ARE YOU CRAZY\n" << "THIS COMMAND DELETES EVERYTHING ON THE ROOT\n" << "DON'T DO THIS\n";
return 1;
}
std::stringstream nukecmd;
nukecmd << "rm -rf " << root << "*";
//std::cout << nukecmd.str() << std::endl;
system(nukecmd.str().c_str());
}
return 0;
}
int Install(std::string package)
{
std::cout << "Verifying the package (not really)\n";
std::cout << "Loading the package info\n";
std::stringstream infofile;
infofile << root << "usr/pkg/" << package << "/info";
int res;
std::map<std::string, std::string> info = LoadInfo(infofile.str(), res);
if(res != 0)
return res;
std::string pkgname = info["PKG_NAME"];
std::string ver = info["PKG_VER"];
std::ifstream checkreinstall;
std::stringstream reinstallcheck;
reinstallcheck << root << "usr/pkg/" << pkgname;
checkreinstall.open(reinstallcheck.str().c_str());
if(checkreinstall.is_open())
{
std::map<std::string, std::string> reint = LoadInfo(reinstallcheck.str().c_str(), res);
if(ver == reint["PKG_VER"])
{
std::cout << "Package " << pkgname << " is already installed. Reinstall?(Y/n)";
char c;
std::cin >> c;
if(c == 'N' || c == 'n')
{
std::cout << "Installation aborted\n";
return 1;
}
}
else
std::cout << "Upgrading " << pkgname << " to version " << ver << std::endl;
checkreinstall.close();
}
std::cout << "Loading the file list\n";
std::vector<std::string> filelist;
std::ifstream files;
std::stringstream filesfile;
filesfile << root << "usr/pkg/" << package << "/files";
files.open(filesfile.str().c_str());
if(!files.is_open())
{
std::cout << "Error: no file list found. Malformed packge\n";
return 1;
}
std::string line;
while(files.good())
{
std::getline(files, line);
if(line == "EOF")
break;
if(line == "")
continue;
filelist.push_back(line);
}
files.close();
std::cout << "Looking for conflicts\n";
for(int i = 0; i < filelist.size(); i++)
{
std::stringstream filename;
filename << root << "usr/pkgdb/" << filelist[i];
std::ifstream f;
f.open(filename.str().c_str());
if(f.is_open())
{
//we are probably conflicting, but make sure
std::string pkg;
getline(f, pkg);
if(pkg != pkgname)
{
std::cout << "Error: package " << pkgname << " conflicts with " << pkg << " on file " << filename.str() << ".\nInstallation aborted\n";
return 1;
}
}
}
std::cout << "Installing package " << package << std::endl;
//TODO:load the info file, add it to the package DB
//make the directories from dirs
std::ifstream dirs;
std::stringstream dirsfile;
dirsfile << root << "usr/pkg/" << package << "/dirs";
dirs.open(dirsfile.str().c_str());
if(dirs.is_open()) //assume that nothing needs to be made if there is no file
{
std::string dir;
while(dirs.good())
{
std::getline(dirs, dir);
if(dir == "EOF")
break;
std::stringstream d;
d << "mkdir --parents " << root << dir << " " << root << "usr/pkgdb/" << dir;
system(d.str().c_str());
}
}
//copy any files that need copying
for(int i=0; i < filelist.size(); i++)
{
std::stringstream f;
f << "cp -fd " << root << "usr/pkg/" << package << "/" << filelist[i] << " " << root << filelist[i];
//std::cout << f.str() << std::endl;
system(f.str().c_str());
//update the package db
std::stringstream dbcmd;
dbcmd << "echo \"" << pkgname << "\" > " << root << "usr/pkgdb/" << filelist[i];
//std::cout << dbcmd.str() << "\n";
system(dbcmd.str().c_str());
}
//install the info file
std::stringstream infocmd;
infocmd << "cp -fd " << root << "usr/pkg/" << package << "/info " << root << "usr/pkg/" << pkgname;
//std::cout << infocmd.str() << std::endl;
system(infocmd.str().c_str());
files.close();
return 0;
}
int Untar(std::string tarball)
{
std::cout << "Extracting tarball\n";
std::stringstream tar;
tar << "tar xf " << tarball << " -C "<< root << "usr/pkg";
if(system(tar.str().c_str()))
{
return 1;
}
return 0;
}
std::string Download(std::string package, std::string ver)
{
std::string version;
if(ver == "")
{
std::cout << "Resolving for latest version\n";
//resolve for latest version
std::stringstream infoget;
infoget << "curl -s -f -o " << package << " http://neos300.com/astro/pkg/info/" << package;
if(system(infoget.str().c_str()) != 0)
{
std::cout << "Package " << package << " not found\n";
return "";
}
int r;
std::map<std::string, std::string> newinfo = LoadInfo(package, r);
version = newinfo["PKG_VER"];
std::stringstream rm;
rm << "rm " << package;
system(rm.str().c_str());
}
else
version = ver;
//get the package
std::cout << "Downloading package\n";
std::stringstream pkgcmd;
pkgcmd << "curl -# -f -o " << package << "-" << version << ".tar.xz http://neos300.com/astro/pkg/" << package << "-" << version << ".tar.xz";
if(system(pkgcmd.str().c_str()) != 0)
{
std::cout << "Unable to find package tarball for package " << package << "\n";
return "";
}
std::cout << "Download successful\n";
std::stringstream ret;
ret << package << "-" << version << ".tar.xz";
return ret.str();
}
<|endoftext|> |
<commit_before>11f8ac4a-585b-11e5-af19-6c40088e03e4<commit_msg>11ffc9f6-585b-11e5-a4dd-6c40088e03e4<commit_after>11ffc9f6-585b-11e5-a4dd-6c40088e03e4<|endoftext|> |
<commit_before>5e589485-2d16-11e5-af21-0401358ea401<commit_msg>5e589486-2d16-11e5-af21-0401358ea401<commit_after>5e589486-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>f20e1d9e-327f-11e5-bd75-9cf387a8033e<commit_msg>f21432cf-327f-11e5-a44b-9cf387a8033e<commit_after>f21432cf-327f-11e5-a44b-9cf387a8033e<|endoftext|> |
<commit_before>bfd6e602-ad5b-11e7-bb7e-ac87a332f658<commit_msg>Really doesn't crash if X, now<commit_after>c0529bd1-ad5b-11e7-b80e-ac87a332f658<|endoftext|> |
<commit_before>d2f81c38-585a-11e5-979e-6c40088e03e4<commit_msg>d2ff2474-585a-11e5-8cfc-6c40088e03e4<commit_after>d2ff2474-585a-11e5-8cfc-6c40088e03e4<|endoftext|> |
<commit_before>74ed93b0-4b02-11e5-a948-28cfe9171a43<commit_msg>Tuesday, turns out it was tuesday<commit_after>74f9e391-4b02-11e5-bb07-28cfe9171a43<|endoftext|> |
<commit_before>28c3772e-2e4f-11e5-bedb-28cfe91dbc4b<commit_msg>28cb55e6-2e4f-11e5-93bb-28cfe91dbc4b<commit_after>28cb55e6-2e4f-11e5-93bb-28cfe91dbc4b<|endoftext|> |
<commit_before>af333959-327f-11e5-b087-9cf387a8033e<commit_msg>af3b1e7d-327f-11e5-a97d-9cf387a8033e<commit_after>af3b1e7d-327f-11e5-a97d-9cf387a8033e<|endoftext|> |
<commit_before>dd723b80-585a-11e5-ba41-6c40088e03e4<commit_msg>dd79a30c-585a-11e5-857e-6c40088e03e4<commit_after>dd79a30c-585a-11e5-857e-6c40088e03e4<|endoftext|> |
<commit_before>#include <string>
#include <iostream>
#include "glm/glm.hpp"
#include "graphics/context.h"
#include "graphics/renderer.h"
#include "objects/object.h"
#define width 1024
#define height 768
using namespace std ;
int main(int argc, char** argv)
{
string filename = "suzanne.obj";
if (argc > 1)
{
filename = string(argv[1]);
}
Renderer renderer;
Context context(renderer);
if (!context.init(width, height, "obj viewer", 4))
{
cerr << "Impossible d'initialiser le contexte OpenGL." << endl;
return 0;
}
Object obj;
obj.load(filename);
obj.rotate(glm::vec3(3.1415 / 2.0, 0, 0)); // 90 degrés
Shader shdr1("shaders/vert.vert", "shaders/couleur3D.frag");
Shader shdr2("shaders/gris.vert", "shaders/couleur3D.frag");
while (context.eventLoop())
{
context.clean();
obj.setShader(&shdr2);
renderer.draw(obj);
obj.setShader(&shdr1);
renderer.draw(obj, GL_LINE);
context.show();
obj.rotate(glm::vec3(0,0.01,0));
}
return 0;
}
<commit_msg>ajouté sleep<commit_after>#include <string>
#include <iostream>
#include <unistd.h>
#include "glm/glm.hpp"
#include "graphics/context.h"
#include "graphics/renderer.h"
#include "objects/object.h"
#define width 1024
#define height 768
using namespace std ;
int main(int argc, char** argv)
{
string filename = "suzanne.obj";
if (argc > 1)
{
filename = string(argv[1]);
}
Renderer renderer;
Context context(renderer);
if (!context.init(width, height, "obj viewer", 4))
{
cerr << "Impossible d'initialiser le contexte OpenGL." << endl;
return 0;
}
Object obj;
obj.load(filename);
obj.rotate(glm::vec3(3.1415 / 2.0, 0, 0)); // 90 degrés
Shader shdr1("shaders/vert.vert", "shaders/couleur3D.frag");
Shader shdr2("shaders/gris.vert", "shaders/couleur3D.frag");
while (context.eventLoop())
{
context.clean();
obj.setShader(&shdr2);
renderer.draw(obj);
obj.setShader(&shdr1);
renderer.draw(obj, GL_LINE);
context.show();
obj.rotate(glm::vec3(0,0.001,0));
usleep(100);
}
return 0;
}
<|endoftext|> |
<commit_before>#include <Bull/Core/Exception/InternalError.hpp>
#include <Bull/Core/FileSystem/File.hpp>
#include <Bull/Render/Context/GlFunctions.hpp>
#include <Bull/Render/Shader/ShaderStage.hpp>
namespace Bull
{
namespace
{
unsigned int shaderType[] = {GL_VERTEX_SHADER, GL_FRAGMENT_SHADER, GL_GEOMETRY_SHADER};
}
ShaderStage::ShaderStage() :
m_id(0),
m_isCompiled(false)
{
/// Nothing
}
ShaderStage::ShaderStage(ShaderStage&& right) noexcept
{
std::swap(m_id, right.m_id);
std::swap(m_type, right.m_type);
std::swap(m_isCompiled, right.m_isCompiled);
}
ShaderStage::~ShaderStage()
{
destroy();
}
ShaderStage& ShaderStage::operator=(ShaderStage&& right) noexcept
{
std::swap(m_id, right.m_id);
std::swap(m_type, right.m_type);
std::swap(m_isCompiled, right.m_isCompiled);
return *this;
}
void ShaderStage::create(ShaderStageType type)
{
if(isValid())
{
destroy();
}
ensureContext();
m_type = type;
m_id = gl::createShader(shaderType[type]);
Expect(isValid(), Throw(InternalError, "ShaderStage::create", "Failed to create ShaderStage"));
}
void ShaderStage::compile(const String& code)
{
const char* source = code.getBuffer();
ensureContext();
gl::shaderSource(m_id, 1, &source, nullptr);
gl::compileShader(m_id);
Expect(isCompiled(), Throw(InternalError, "ShaderStage::compile", "Failed to compile ShaderStage + (" + getErrorMessage() + ")"));
m_isCompiled = true;
}
void ShaderStage::destroy()
{
if(gl::isShader(m_id))
{
ensureContext();
gl::deleteShader(m_id);
}
}
bool ShaderStage::isCompiled() const
{
if(isValid())
{
int error = 0;
ensureContext();
gl::getShaderiv(m_id, GL_COMPILE_STATUS, &error);
return error == GL_TRUE;
}
return false;
}
bool ShaderStage::isValid() const
{
ensureContext();
return gl::isShader(m_id);
}
bool ShaderStage::isLoaded() const
{
return isCompiled();
}
String ShaderStage::getSource() const
{
String code;
int size, capacity;
ensureContext();
gl::getShaderiv(m_id, GL_SHADER_SOURCE_LENGTH, &capacity);
code.create(capacity);
gl::getShaderSource(m_id, code.getSize(), &size, &code[0]);
return code;
}
ShaderStageType ShaderStage::getType() const
{
return m_type;
}
unsigned int ShaderStage::getSystemHandler() const
{
return m_id;
}
String ShaderStage::getErrorMessage() const
{
int capacity;
String message;
ensureContext();
gl::getShaderiv(m_id, GL_INFO_LOG_LENGTH, &capacity);
if(capacity)
{
message.setSize(static_cast<std::size_t>(capacity));
gl::getShaderInfoLog(m_id, capacity, nullptr, &message[0]);
}
return message;
}
}
<commit_msg>[Render/ShaderStage] Remove useless context ensuring<commit_after>#include <Bull/Core/Exception/InternalError.hpp>
#include <Bull/Core/FileSystem/File.hpp>
#include <Bull/Render/Context/GlFunctions.hpp>
#include <Bull/Render/Shader/ShaderStage.hpp>
namespace Bull
{
namespace
{
unsigned int shaderType[] = {GL_VERTEX_SHADER, GL_FRAGMENT_SHADER, GL_GEOMETRY_SHADER};
}
ShaderStage::ShaderStage() :
m_id(0),
m_isCompiled(false)
{
/// Nothing
}
ShaderStage::ShaderStage(ShaderStage&& right) noexcept
{
std::swap(m_id, right.m_id);
std::swap(m_type, right.m_type);
std::swap(m_isCompiled, right.m_isCompiled);
}
ShaderStage::~ShaderStage()
{
destroy();
}
ShaderStage& ShaderStage::operator=(ShaderStage&& right) noexcept
{
std::swap(m_id, right.m_id);
std::swap(m_type, right.m_type);
std::swap(m_isCompiled, right.m_isCompiled);
return *this;
}
void ShaderStage::create(ShaderStageType type)
{
if(isValid())
{
destroy();
}
m_type = type;
m_id = gl::createShader(shaderType[type]);
Expect(isValid(), Throw(InternalError, "ShaderStage::create", "Failed to create ShaderStage"));
}
void ShaderStage::compile(const String& code)
{
const char* source = code.getBuffer();
ensureContext();
gl::shaderSource(m_id, 1, &source, nullptr);
gl::compileShader(m_id);
Expect(isCompiled(), Throw(InternalError, "ShaderStage::compile", "Failed to compile ShaderStage + (" + getErrorMessage() + ")"));
m_isCompiled = true;
}
void ShaderStage::destroy()
{
ensureContext();
if(gl::isShader(m_id))
{
gl::deleteShader(m_id);
}
}
bool ShaderStage::isCompiled() const
{
if(isValid())
{
int error = 0;
gl::getShaderiv(m_id, GL_COMPILE_STATUS, &error);
return error == GL_TRUE;
}
return false;
}
bool ShaderStage::isValid() const
{
ensureContext();
return gl::isShader(m_id);
}
bool ShaderStage::isLoaded() const
{
return isCompiled();
}
String ShaderStage::getSource() const
{
String code;
int size, capacity;
ensureContext();
gl::getShaderiv(m_id, GL_SHADER_SOURCE_LENGTH, &capacity);
code.create(capacity);
gl::getShaderSource(m_id, code.getSize(), &size, &code[0]);
return code;
}
ShaderStageType ShaderStage::getType() const
{
return m_type;
}
unsigned int ShaderStage::getSystemHandler() const
{
return m_id;
}
String ShaderStage::getErrorMessage() const
{
int capacity;
String message;
ensureContext();
gl::getShaderiv(m_id, GL_INFO_LOG_LENGTH, &capacity);
if(capacity)
{
message.setSize(static_cast<std::size_t>(capacity));
gl::getShaderInfoLog(m_id, capacity, nullptr, &message[0]);
}
return message;
}
}
<|endoftext|> |
<commit_before>76fbf53a-2d53-11e5-baeb-247703a38240<commit_msg>76fc72ee-2d53-11e5-baeb-247703a38240<commit_after>76fc72ee-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>276cf5a8-2e4f-11e5-92bb-28cfe91dbc4b<commit_msg>2773ab30-2e4f-11e5-8d05-28cfe91dbc4b<commit_after>2773ab30-2e4f-11e5-8d05-28cfe91dbc4b<|endoftext|> |
<commit_before>1792f182-2e4f-11e5-8d6e-28cfe91dbc4b<commit_msg>1799dab0-2e4f-11e5-817c-28cfe91dbc4b<commit_after>1799dab0-2e4f-11e5-817c-28cfe91dbc4b<|endoftext|> |
<commit_before>/*
* Copyright © 2008, 2009 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <cstdlib>
#include <cstdio>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "ast.h"
#include "glsl_parser_extras.h"
#include "glsl_parser.h"
#include "ir_optimization.h"
#include "ir_print_visitor.h"
#include "program.h"
/* Returned string will have 'ctx' as its talloc owner. */
static char *
load_text_file(void *ctx, const char *file_name, size_t *size)
{
char *text = NULL;
struct stat st;
ssize_t total_read = 0;
int fd = open(file_name, O_RDONLY);
*size = 0;
if (fd < 0) {
return NULL;
}
if (fstat(fd, & st) == 0) {
text = (char *) talloc_size(ctx, st.st_size + 1);
if (text != NULL) {
do {
ssize_t bytes = read(fd, text + total_read,
st.st_size - total_read);
if (bytes < 0) {
free(text);
text = NULL;
break;
}
if (bytes == 0) {
break;
}
total_read += bytes;
} while (total_read < st.st_size);
text[total_read] = '\0';
*size = total_read;
}
}
close(fd);
return text;
}
void
usage_fail(const char *name)
{
printf("%s <filename.frag|filename.vert>\n", name);
exit(EXIT_FAILURE);
}
int dump_ast = 0;
int dump_lir = 0;
int do_link = 0;
const struct option compiler_opts[] = {
{ "dump-ast", 0, &dump_ast, 1 },
{ "dump-lir", 0, &dump_lir, 1 },
{ "link", 0, &do_link, 1 },
{ NULL, 0, NULL, 0 }
};
void
compile_shader(struct glsl_shader *shader)
{
struct _mesa_glsl_parse_state *state;
state = talloc_zero(talloc_parent(shader), struct _mesa_glsl_parse_state);
switch (shader->Type) {
case GL_VERTEX_SHADER: state->target = vertex_shader; break;
case GL_FRAGMENT_SHADER: state->target = fragment_shader; break;
case GL_GEOMETRY_SHADER: state->target = geometry_shader; break;
}
state->scanner = NULL;
state->translation_unit.make_empty();
state->symbols = new(shader) glsl_symbol_table;
state->info_log = talloc_strdup(shader, "");
state->error = false;
state->temp_index = 0;
state->loop_or_switch_nesting = NULL;
state->ARB_texture_rectangle_enable = true;
/* Create a new context for the preprocessor output. Ultimately, this
* should probably be the parser context, but there isn't one yet.
*/
const char *source = shader->Source;
state->error = preprocess(shader, &source, &state->info_log);
if (!state->error) {
_mesa_glsl_lexer_ctor(state, source);
_mesa_glsl_parse(state);
_mesa_glsl_lexer_dtor(state);
}
if (dump_ast) {
foreach_list_const(n, &state->translation_unit) {
ast_node *ast = exec_node_data(ast_node, n, link);
ast->print();
}
printf("\n\n");
}
shader->ir.make_empty();
if (!state->error && !state->translation_unit.is_empty())
_mesa_ast_to_hir(&shader->ir, state);
validate_ir_tree(&shader->ir);
/* Optimization passes */
if (!state->error && !shader->ir.is_empty()) {
bool progress;
do {
progress = false;
progress = do_function_inlining(&shader->ir) || progress;
progress = do_if_simplification(&shader->ir) || progress;
progress = do_copy_propagation(&shader->ir) || progress;
progress = do_dead_code_local(&shader->ir) || progress;
progress = do_dead_code_unlinked(&shader->ir) || progress;
progress = do_constant_variable_unlinked(&shader->ir) || progress;
progress = do_constant_folding(&shader->ir) || progress;
progress = do_vec_index_to_swizzle(&shader->ir) || progress;
progress = do_swizzle_swizzle(&shader->ir) || progress;
} while (progress);
}
validate_ir_tree(&shader->ir);
/* Print out the resulting IR */
if (!state->error && dump_lir) {
_mesa_print_ir(&shader->ir, state);
}
shader->symbols = state->symbols;
shader->CompileStatus = !state->error;
if (shader->InfoLog)
talloc_free(shader->InfoLog);
shader->InfoLog = state->info_log;
talloc_free(state);
return;
}
int
main(int argc, char **argv)
{
int status = EXIT_SUCCESS;
int c;
int idx = 0;
while ((c = getopt_long(argc, argv, "", compiler_opts, &idx)) != -1)
/* empty */ ;
if (argc <= optind)
usage_fail(argv[0]);
struct glsl_program *whole_program;
whole_program = talloc_zero (NULL, struct glsl_program);
assert(whole_program != NULL);
for (/* empty */; argc > optind; optind++) {
whole_program->Shaders = (struct glsl_shader **)
realloc(whole_program->Shaders,
sizeof(struct glsl_shader *) * (whole_program->NumShaders + 1));
assert(whole_program->Shaders != NULL);
struct glsl_shader *shader = talloc_zero(whole_program, glsl_shader);
whole_program->Shaders[whole_program->NumShaders] = shader;
whole_program->NumShaders++;
const unsigned len = strlen(argv[optind]);
if (len < 6)
usage_fail(argv[0]);
const char *const ext = & argv[optind][len - 5];
if (strncmp(".vert", ext, 5) == 0)
shader->Type = GL_VERTEX_SHADER;
else if (strncmp(".geom", ext, 5) == 0)
shader->Type = GL_GEOMETRY_SHADER;
else if (strncmp(".frag", ext, 5) == 0)
shader->Type = GL_FRAGMENT_SHADER;
else
usage_fail(argv[0]);
shader->Source = load_text_file(whole_program,
argv[optind], &shader->SourceLen);
if (shader->Source == NULL) {
printf("File \"%s\" does not exist.\n", argv[optind]);
exit(EXIT_FAILURE);
}
compile_shader(shader);
if (!shader->CompileStatus) {
printf("Info log for %s:\n%s\n", argv[optind], shader->InfoLog);
status = EXIT_FAILURE;
break;
}
}
if ((status == EXIT_SUCCESS) && do_link) {
link_shaders(whole_program);
status = (whole_program->LinkStatus) ? EXIT_SUCCESS : EXIT_FAILURE;
}
talloc_free(whole_program);
return status;
}
<commit_msg>glsl2 main: Switch from realloc to talloc_realloc to construct program source.<commit_after>/*
* Copyright © 2008, 2009 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <cstdlib>
#include <cstdio>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "ast.h"
#include "glsl_parser_extras.h"
#include "glsl_parser.h"
#include "ir_optimization.h"
#include "ir_print_visitor.h"
#include "program.h"
/* Returned string will have 'ctx' as its talloc owner. */
static char *
load_text_file(void *ctx, const char *file_name, size_t *size)
{
char *text = NULL;
struct stat st;
ssize_t total_read = 0;
int fd = open(file_name, O_RDONLY);
*size = 0;
if (fd < 0) {
return NULL;
}
if (fstat(fd, & st) == 0) {
text = (char *) talloc_size(ctx, st.st_size + 1);
if (text != NULL) {
do {
ssize_t bytes = read(fd, text + total_read,
st.st_size - total_read);
if (bytes < 0) {
free(text);
text = NULL;
break;
}
if (bytes == 0) {
break;
}
total_read += bytes;
} while (total_read < st.st_size);
text[total_read] = '\0';
*size = total_read;
}
}
close(fd);
return text;
}
void
usage_fail(const char *name)
{
printf("%s <filename.frag|filename.vert>\n", name);
exit(EXIT_FAILURE);
}
int dump_ast = 0;
int dump_lir = 0;
int do_link = 0;
const struct option compiler_opts[] = {
{ "dump-ast", 0, &dump_ast, 1 },
{ "dump-lir", 0, &dump_lir, 1 },
{ "link", 0, &do_link, 1 },
{ NULL, 0, NULL, 0 }
};
void
compile_shader(struct glsl_shader *shader)
{
struct _mesa_glsl_parse_state *state;
state = talloc_zero(talloc_parent(shader), struct _mesa_glsl_parse_state);
switch (shader->Type) {
case GL_VERTEX_SHADER: state->target = vertex_shader; break;
case GL_FRAGMENT_SHADER: state->target = fragment_shader; break;
case GL_GEOMETRY_SHADER: state->target = geometry_shader; break;
}
state->scanner = NULL;
state->translation_unit.make_empty();
state->symbols = new(shader) glsl_symbol_table;
state->info_log = talloc_strdup(shader, "");
state->error = false;
state->temp_index = 0;
state->loop_or_switch_nesting = NULL;
state->ARB_texture_rectangle_enable = true;
/* Create a new context for the preprocessor output. Ultimately, this
* should probably be the parser context, but there isn't one yet.
*/
const char *source = shader->Source;
state->error = preprocess(shader, &source, &state->info_log);
if (!state->error) {
_mesa_glsl_lexer_ctor(state, source);
_mesa_glsl_parse(state);
_mesa_glsl_lexer_dtor(state);
}
if (dump_ast) {
foreach_list_const(n, &state->translation_unit) {
ast_node *ast = exec_node_data(ast_node, n, link);
ast->print();
}
printf("\n\n");
}
shader->ir.make_empty();
if (!state->error && !state->translation_unit.is_empty())
_mesa_ast_to_hir(&shader->ir, state);
validate_ir_tree(&shader->ir);
/* Optimization passes */
if (!state->error && !shader->ir.is_empty()) {
bool progress;
do {
progress = false;
progress = do_function_inlining(&shader->ir) || progress;
progress = do_if_simplification(&shader->ir) || progress;
progress = do_copy_propagation(&shader->ir) || progress;
progress = do_dead_code_local(&shader->ir) || progress;
progress = do_dead_code_unlinked(&shader->ir) || progress;
progress = do_constant_variable_unlinked(&shader->ir) || progress;
progress = do_constant_folding(&shader->ir) || progress;
progress = do_vec_index_to_swizzle(&shader->ir) || progress;
progress = do_swizzle_swizzle(&shader->ir) || progress;
} while (progress);
}
validate_ir_tree(&shader->ir);
/* Print out the resulting IR */
if (!state->error && dump_lir) {
_mesa_print_ir(&shader->ir, state);
}
shader->symbols = state->symbols;
shader->CompileStatus = !state->error;
if (shader->InfoLog)
talloc_free(shader->InfoLog);
shader->InfoLog = state->info_log;
talloc_free(state);
return;
}
int
main(int argc, char **argv)
{
int status = EXIT_SUCCESS;
int c;
int idx = 0;
while ((c = getopt_long(argc, argv, "", compiler_opts, &idx)) != -1)
/* empty */ ;
if (argc <= optind)
usage_fail(argv[0]);
struct glsl_program *whole_program;
whole_program = talloc_zero (NULL, struct glsl_program);
assert(whole_program != NULL);
for (/* empty */; argc > optind; optind++) {
whole_program->Shaders = (struct glsl_shader **)
talloc_realloc(whole_program, whole_program->Shaders,
struct glsl_shader *, whole_program->NumShaders + 1);
assert(whole_program->Shaders != NULL);
struct glsl_shader *shader = talloc_zero(whole_program, glsl_shader);
whole_program->Shaders[whole_program->NumShaders] = shader;
whole_program->NumShaders++;
const unsigned len = strlen(argv[optind]);
if (len < 6)
usage_fail(argv[0]);
const char *const ext = & argv[optind][len - 5];
if (strncmp(".vert", ext, 5) == 0)
shader->Type = GL_VERTEX_SHADER;
else if (strncmp(".geom", ext, 5) == 0)
shader->Type = GL_GEOMETRY_SHADER;
else if (strncmp(".frag", ext, 5) == 0)
shader->Type = GL_FRAGMENT_SHADER;
else
usage_fail(argv[0]);
shader->Source = load_text_file(whole_program,
argv[optind], &shader->SourceLen);
if (shader->Source == NULL) {
printf("File \"%s\" does not exist.\n", argv[optind]);
exit(EXIT_FAILURE);
}
compile_shader(shader);
if (!shader->CompileStatus) {
printf("Info log for %s:\n%s\n", argv[optind], shader->InfoLog);
status = EXIT_FAILURE;
break;
}
}
if ((status == EXIT_SUCCESS) && do_link) {
link_shaders(whole_program);
status = (whole_program->LinkStatus) ? EXIT_SUCCESS : EXIT_FAILURE;
}
talloc_free(whole_program);
return status;
}
<|endoftext|> |
<commit_before>1ff22f11-2e4f-11e5-a751-28cfe91dbc4b<commit_msg>1ff9b35e-2e4f-11e5-86fd-28cfe91dbc4b<commit_after>1ff9b35e-2e4f-11e5-86fd-28cfe91dbc4b<|endoftext|> |
<commit_before>152e6c6e-2e4f-11e5-bf11-28cfe91dbc4b<commit_msg>1534e97a-2e4f-11e5-b120-28cfe91dbc4b<commit_after>1534e97a-2e4f-11e5-b120-28cfe91dbc4b<|endoftext|> |
<commit_before>da800a63-2e4e-11e5-97b7-28cfe91dbc4b<commit_msg>da882af0-2e4e-11e5-9b42-28cfe91dbc4b<commit_after>da882af0-2e4e-11e5-9b42-28cfe91dbc4b<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include "config.h"
#include <cassert>
#include <iostream>
#include <stdexcept>
#include "sqlite-strategies.hh"
#include "sqlite-eval.hh"
#include "ep.hh"
#include "pathexpand.hh"
static const int CURRENT_SCHEMA_VERSION(2);
sqlite3 *SqliteStrategy::open(void) {
if(!db) {
int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
| SQLITE_OPEN_PRIVATECACHE;
if(sqlite3_open_v2(filename, &db, flags, NULL) != SQLITE_OK) {
throw std::runtime_error("Error initializing sqlite3");
}
if(sqlite3_extended_result_codes(db, 1) != SQLITE_OK) {
throw std::runtime_error("Error enabling extended RCs");
}
initDB();
PreparedStatement uv_get(db, "PRAGMA user_version");
uv_get.fetch();
schema_version = uv_get.column_int(0);
initMetaTables();
initTables();
initStatements();
doFile(postInitFile);
shardCount = statements.size();
assert(shardCount > 0);
if (schema_version == 0) {
execute("PRAGMA user_version=2");
schema_version = CURRENT_SCHEMA_VERSION;
} else if (schema_version == 1) {
std::stringstream ss;
ss << "Schema version 1 is not supported anymore.\n"
<< "Run the script to upgrade the schema to version "
<< CURRENT_SCHEMA_VERSION;
close();
throw std::runtime_error(ss.str().c_str());
}
}
return db;
}
void SqliteStrategy::close(void) {
if(db) {
destroyStatements();
sqlite3_close(db);
db = NULL;
}
}
void SqliteStrategy::destroyStatements() {
while (!statements.empty()) {
Statements *st = statements.back();
delete st;
statements.pop_back();
}
destroyMetaStatements();
}
void SqliteStrategy::destroyMetaStatements(void) {
delete ins_vb_stmt;
delete clear_vb_stmt;
delete sel_vb_stmt;
delete clear_stats_stmt;
delete ins_stat_stmt;
}
void SqliteStrategy::initMetaTables() {
assert(db);
PreparedStatement st(db, "select name from sqlite_master where name='vbucket_states'");
if (schema_version == 0 && st.fetch()) {
execute("alter table vbucket_states add column"
" vb_version integer default 0");
} else {
execute("create table if not exists vbucket_states"
" (vbid integer primary key on conflict replace,"
" vb_version interger,"
" state varchar(16),"
" last_change datetime)");
}
execute("create table if not exists stats_snap"
" (name varchar(16),"
" value varchar(24),"
" last_change datetime)");
}
void SqliteStrategy::initTables(void) {
assert(db);
PreparedStatement st(db, "select name from sqlite_master where name='kv'");
if (schema_version == 0 && st.fetch()) {
execute("alter table kv add column"
" vb_version integer default 0");
} else {
execute("create table if not exists kv"
" (vbucket integer,"
" vb_version integer,"
" k varchar(250), "
" flags integer,"
" exptime integer,"
" cas integer,"
" v text)");
}
}
void SqliteStrategy::initMetaStatements(void) {
const char *ins_query = "insert into vbucket_states"
" (vbid, vb_version, state, last_change) values (?, ?, ?, current_timestamp)";
ins_vb_stmt = new PreparedStatement(db, ins_query);
const char *del_query = "delete from vbucket_states";
clear_vb_stmt = new PreparedStatement(db, del_query);
const char *sel_query = "select vbid, vb_version, state from vbucket_states";
sel_vb_stmt = new PreparedStatement(db, sel_query);
const char *clear_stats_query = "delete from stats_snap";
clear_stats_stmt = new PreparedStatement(db, clear_stats_query);
const char *ins_stat_query = "insert into stats_snap "
"(name, value, last_change) values (?, ?, current_timestamp)";
ins_stat_stmt = new PreparedStatement(db, ins_stat_query);
}
void SqliteStrategy::initStatements(void) {
assert(db);
initMetaStatements();
Statements *st = new Statements(db, "kv");
statements.push_back(st);
}
void SqliteStrategy::destroyTables(void) {
execute("drop table if exists kv");
}
void SqliteStrategy::doFile(const char * const fn) {
if (fn) {
SqliteEvaluator eval(db);
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"Running db script: %s\n", fn);
eval.eval(fn);
}
}
void SqliteStrategy::execute(const char * const query) {
PreparedStatement st(db, query);
st.execute();
}
//
// ----------------------------------------------------------------------
// Multi DB strategy
// ----------------------------------------------------------------------
//
void MultiDBSqliteStrategy::initDB() {
char buf[1024];
PathExpander p(filename);
for (int i = 0; i < numTables; i++) {
std::string shardname(p.expand(shardpattern, i));
snprintf(buf, sizeof(buf), "attach database \"%s\" as kv_%d",
shardname.c_str(), i);
execute(buf);
}
doFile(initFile);
}
void MultiDBSqliteStrategy::initTables() {
char buf[1024];
PathExpander p(filename);
for (int i = 0; i < numTables; i++) {
snprintf(buf, sizeof(buf), "select name from kv_%d.sqlite_master where name='kv'", i);
PreparedStatement st(db, buf);
if (schema_version == 0 && st.fetch()) {
snprintf(buf, sizeof(buf),
"alter table kv_%d.kv add column"
" vb_version integer default 0", i);
execute(buf);
} else {
snprintf(buf, sizeof(buf),
"create table if not exists kv_%d.kv"
" (vbucket integer,"
" vb_version integer,"
" k varchar(250),"
" flags integer,"
" exptime integer,"
" cas integer,"
" v text)", i);
execute(buf);
}
}
}
void MultiDBSqliteStrategy::initStatements() {
initMetaStatements();
char buf[64];
for (int i = 0; i < numTables; i++) {
snprintf(buf, sizeof(buf), "kv_%d.kv", i);
statements.push_back(new Statements(db, std::string(buf)));
}
}
void MultiDBSqliteStrategy::destroyTables() {
char buf[1024];
for (int i = 0; i < numTables; i++) {
snprintf(buf, sizeof(buf), "drop table if exists kv_%d.kv", i);
execute(buf);
}
}
<commit_msg>Support the schema upgrade from version 0 to version 2.<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include "config.h"
#include <cassert>
#include <iostream>
#include <stdexcept>
#include "sqlite-strategies.hh"
#include "sqlite-eval.hh"
#include "ep.hh"
#include "pathexpand.hh"
static const int CURRENT_SCHEMA_VERSION(2);
sqlite3 *SqliteStrategy::open(void) {
if(!db) {
int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
| SQLITE_OPEN_PRIVATECACHE;
if(sqlite3_open_v2(filename, &db, flags, NULL) != SQLITE_OK) {
throw std::runtime_error("Error initializing sqlite3");
}
if(sqlite3_extended_result_codes(db, 1) != SQLITE_OK) {
throw std::runtime_error("Error enabling extended RCs");
}
initDB();
PreparedStatement uv_get(db, "PRAGMA user_version");
uv_get.fetch();
schema_version = uv_get.column_int(0);
initMetaTables();
initTables();
initStatements();
doFile(postInitFile);
shardCount = statements.size();
assert(shardCount > 0);
if (schema_version < CURRENT_SCHEMA_VERSION) {
std::stringstream ss;
ss << "Schema version " << schema_version << " is not supported anymore.\n"
<< "Run the script to upgrade the schema to version "
<< CURRENT_SCHEMA_VERSION;
close();
throw std::runtime_error(ss.str().c_str());
}
}
return db;
}
void SqliteStrategy::close(void) {
if(db) {
destroyStatements();
sqlite3_close(db);
db = NULL;
}
}
void SqliteStrategy::destroyStatements() {
while (!statements.empty()) {
Statements *st = statements.back();
delete st;
statements.pop_back();
}
destroyMetaStatements();
}
void SqliteStrategy::destroyMetaStatements(void) {
delete ins_vb_stmt;
delete clear_vb_stmt;
delete sel_vb_stmt;
delete clear_stats_stmt;
delete ins_stat_stmt;
}
void SqliteStrategy::initMetaTables() {
assert(db);
PreparedStatement st(db, "select name from sqlite_master where name='vbucket_states'");
st.fetch();
const char *name = static_cast<const char *>(st.column_blob(0));
if (schema_version == 0 && name != NULL) {
execute("alter table vbucket_states add column"
" vb_version integer default 0");
} else {
execute("create table if not exists vbucket_states"
" (vbid integer primary key on conflict replace,"
" vb_version interger,"
" state varchar(16),"
" last_change datetime)");
if (schema_version == 0 && name == NULL) {
std::stringstream ss;
ss << "PRAGMA user_version=" << CURRENT_SCHEMA_VERSION;
execute(ss.str().c_str());
schema_version = CURRENT_SCHEMA_VERSION;
}
}
execute("create table if not exists stats_snap"
" (name varchar(16),"
" value varchar(24),"
" last_change datetime)");
}
void SqliteStrategy::initTables(void) {
assert(db);
PreparedStatement st(db, "select name from sqlite_master where name='kv'");
if (schema_version == 0 && st.fetch()) {
execute("alter table kv add column"
" vb_version integer default 0");
} else {
execute("create table if not exists kv"
" (vbucket integer,"
" vb_version integer,"
" k varchar(250), "
" flags integer,"
" exptime integer,"
" cas integer,"
" v text)");
}
}
void SqliteStrategy::initMetaStatements(void) {
const char *ins_query = "insert into vbucket_states"
" (vbid, vb_version, state, last_change) values (?, ?, ?, current_timestamp)";
ins_vb_stmt = new PreparedStatement(db, ins_query);
const char *del_query = "delete from vbucket_states";
clear_vb_stmt = new PreparedStatement(db, del_query);
const char *sel_query = "select vbid, vb_version, state from vbucket_states";
sel_vb_stmt = new PreparedStatement(db, sel_query);
const char *clear_stats_query = "delete from stats_snap";
clear_stats_stmt = new PreparedStatement(db, clear_stats_query);
const char *ins_stat_query = "insert into stats_snap "
"(name, value, last_change) values (?, ?, current_timestamp)";
ins_stat_stmt = new PreparedStatement(db, ins_stat_query);
}
void SqliteStrategy::initStatements(void) {
assert(db);
initMetaStatements();
Statements *st = new Statements(db, "kv");
statements.push_back(st);
}
void SqliteStrategy::destroyTables(void) {
execute("drop table if exists kv");
}
void SqliteStrategy::doFile(const char * const fn) {
if (fn) {
SqliteEvaluator eval(db);
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"Running db script: %s\n", fn);
eval.eval(fn);
}
}
void SqliteStrategy::execute(const char * const query) {
PreparedStatement st(db, query);
st.execute();
}
//
// ----------------------------------------------------------------------
// Multi DB strategy
// ----------------------------------------------------------------------
//
void MultiDBSqliteStrategy::initDB() {
char buf[1024];
PathExpander p(filename);
for (int i = 0; i < numTables; i++) {
std::string shardname(p.expand(shardpattern, i));
snprintf(buf, sizeof(buf), "attach database \"%s\" as kv_%d",
shardname.c_str(), i);
execute(buf);
}
doFile(initFile);
}
void MultiDBSqliteStrategy::initTables() {
char buf[1024];
PathExpander p(filename);
for (int i = 0; i < numTables; i++) {
snprintf(buf, sizeof(buf), "select name from kv_%d.sqlite_master where name='kv'", i);
PreparedStatement st(db, buf);
if (schema_version == 0 && st.fetch()) {
snprintf(buf, sizeof(buf),
"alter table kv_%d.kv add column"
" vb_version integer default 0", i);
execute(buf);
} else {
snprintf(buf, sizeof(buf),
"create table if not exists kv_%d.kv"
" (vbucket integer,"
" vb_version integer,"
" k varchar(250),"
" flags integer,"
" exptime integer,"
" cas integer,"
" v text)", i);
execute(buf);
}
}
}
void MultiDBSqliteStrategy::initStatements() {
initMetaStatements();
char buf[64];
for (int i = 0; i < numTables; i++) {
snprintf(buf, sizeof(buf), "kv_%d.kv", i);
statements.push_back(new Statements(db, std::string(buf)));
}
}
void MultiDBSqliteStrategy::destroyTables() {
char buf[1024];
for (int i = 0; i < numTables; i++) {
snprintf(buf, sizeof(buf), "drop table if exists kv_%d.kv", i);
execute(buf);
}
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <array>
#include <cfloat>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <limits>
#include <list>
#include <map>
#include <sstream>
#include <string>
#include <tgmath.h>
#include <unordered_map>
#include <utility>
#include <vector>
#include <functional>
#define N 2 // number of gaussians in the mixture model
using std::abs;
using std::array;
using std::bernoulli_distribution;
using std::cin;
using std::copy;
using std::cout;
using std::endl;
using std::get;
using std::getline;
using std::ifstream;
using std::istream;
using std::knuth_b;
using std::list;
using std::lower_bound;
using std::lognormal_distribution;
using std::map;
using std::max;
using std::min;
using std::mt19937;
using std::multimap;
using std::normal_distribution;
using std::numeric_limits;
using std::ofstream;
using std::pair;
using std::random_device;
using std::random_shuffle;
using std::reverse_iterator;
using std::round;
using std::setw;
using std::shuffle;
using std::sort;
using std::sqrt;
using std::string;
using std::stringstream;
using std::swap;
using std::tuple;
using std::uniform_real_distribution;
using std::uniform_int_distribution;
using std::unique;
using std::unordered_map;
using std::vector;
const double pi = M_PI;
random_device urandom;
mt19937 urng(urandom());
template<typename T> inline const void kahan_sum(
const T &x,
T &c,
T &sum
){
const T y=x-c;
const T t=sum+y;
c = (t-sum)-y;
sum=t;
}
template<typename T> inline const void mean_variance(
const T &x,
const T &w,
T &sumw,
T &mean,
T &M2
){
const T temp = w+sumw;
const T delta = x-mean;
const T R = delta*w/temp;
mean += R;
M2 += sumw*delta*R;
sumw = temp;
}
template<typename T> inline const T variance(
const T &M2,
const T &sumw,
const size_t &n
){
return M2*n/(sumw*(n-1));
}
template<typename T> inline const T variance(
const T &M2,
const T &sumw
){
return M2/sumw;
}
const vector<array<double,3>> ex_max(
const vector<array<double,2>> &data,
const size_t &n
){
double mean=0;
double sumw=0;
double M2=0;
for (auto it=data.begin(); it!=data.end(); ++it){
mean_variance((*it)[0],(*it)[1],sumw,mean,M2);
}
const double s = sqrt(variance(M2,sumw,data.size()));
vector<array<double,3>> model(n); // weight,mean,sigma
// initialize the model with equal weights,
// random points from the dataset as mean
// and the square root of the over all variance
for (size_t i=0; i!=n; ++i){
model[i]={{1.0/n,data[i][0],s/n}};
}
vector<array<double,5>> temp(n); // sumw,mean,M2,T,TS
double change;
do{
change=0.0;
double TS = 0.0;
for (auto t=temp.begin(); t!=temp.end(); ++t){
(*t)[4]=0.0;
}
for (auto d=data.begin(); d!=data.end(); ++d){
auto t=temp.begin();
auto m=model.begin();
for (;m!=model.end()&&t!=temp.end(); (++m,++t)){
const double s2=(*m)[2]*(*m)[2]+(*d)[1]*(*d)[1];
const double i =
exp(-((*d)[0]-(*m)[1])*((*d)[0]-(*m)[1])/(2.0*s2))/sqrt(2*s2*pi);
TS+=i;
(*t)[4]+=i;
}
}
for (auto t=temp.begin(); t!=temp.end(); ++t){
(*t)[0]=(*t)[1]=(*t)[2]=(*t)[3]=0.0;
}
{
auto t=temp.begin();
auto m=model.begin();
for (;m!=model.end()&&t!=temp.end(); (++m,++t)){
change+=((*m)[0]-(*t)[4]/TS)*((*m)[0]-(*t)[4]/TS);
(*m)[0]=(*t)[4]/TS;
}
}
for (auto d=data.begin(); d!=data.end(); ++d){
double T = 0.0;
auto t=temp.begin();
auto m=model.begin();
for (;m!=model.end()&&t!=temp.end(); (++m,++t)){
const double s2=(*m)[2]*(*m)[2]+(*d)[1]*(*d)[1];
const double i =
exp(-((*d)[0]-(*m)[1])*((*d)[0]-(*m)[1])/(2.0*s2))/sqrt(2*s2*pi);
if (isnan(i)){
cout << (*d)[0] << " "
<< (*m)[1] << " "
<< (*m)[2] << " "
<< (*d)[1] << endl;
cout << "NAAAAN !!! !!! " << endl;
exit(0);
}
T+=i;
(*t)[3]=i;
}
t=temp.begin();
m=model.begin();
if (T<numeric_limits<double>::epsilon()) continue;
for (;m!=model.end()&&t!=temp.end(); (++m,++t)){
if ((*t)[3]<numeric_limits<double>::epsilon()) continue;
const double x = (*d)[0];
const double w = (*t)[3]*(*m)[0]/(T*(*d)[1]*(*d)[1]);
mean_variance(x,w,(*t)[0],(*t)[1],(*t)[2]);
}
}
{
auto t=temp.begin();
auto m=model.begin();
for (;m!=model.end()&&t!=temp.end(); (++m,++t)){
change+=((*m)[0]-(*t)[4]/TS)*((*m)[0]-(*t)[4]/TS);
change+=((*m)[1]-(*t)[1])*((*m)[1]-(*t)[1]);
change+=((*m)[2]-variance((*t)[2],(*t)[0]))
*((*m)[2]-variance((*t)[2],(*t)[0]));
(*m)[0]=(*t)[4]/TS;
(*m)[1]=(*t)[1];
(*m)[2]=variance((*t)[2],(*t)[0]);
}
}
cout << change << endl;
}while(change>1e-24);
return model;
}
int main(int argc, char *argv[]){
lognormal_distribution<double> lognormal;
uniform_int_distribution<size_t> uniform(0,N-1);
vector<array<double,2>> data;
for (size_t i=0; i<256*N; ++i){
const double s = lognormal(urng);
data.push_back({normal_distribution<double>(uniform(urng),s)(urng),s});
// data.push_back({normal_distribution<double>(uniform(urng),0.5)(urng),0.1});
}
// for (auto it=data.begin(); it!=data.end(); ++it){
// cout << setw(16) << (*it)[0] << setw(16) << (*it)[1] << endl;
// }
// cout << " * * * * * * * * * * * * * * * * * * * * * * * * " << endl;
vector<array<double,3>> model = ex_max(data,N);
cout << " * * * * * * * * * * * * * * * * * * * * * * * * " << endl;
cout << setw(16) << "weight" << setw(16) << "mean" << setw(16) << "sigma" << endl;
sort(model.begin(),model.end(),
[](const array<double,3> &a, const array<double,3> &b){return a[1]<b[1];});
for (auto it=model.begin(); it!=model.end(); ++it){
cout << setw(16) << (*it)[0] << setw(16) << (*it)[1] << setw(16) << (*it)[2] << endl;
}
return 0;
}
<commit_msg>Something is wrong the algorithm does not converge for starting values that are close to each other<commit_after>#include <algorithm>
#include <array>
#include <cfloat>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <limits>
#include <list>
#include <map>
#include <sstream>
#include <string>
#include <tgmath.h>
#include <unordered_map>
#include <utility>
#include <vector>
#include <functional>
#define N 2 // number of gaussians in the mixture model
using std::abs;
using std::array;
using std::bernoulli_distribution;
using std::cin;
using std::copy;
using std::cout;
using std::endl;
using std::get;
using std::getline;
using std::ifstream;
using std::istream;
using std::knuth_b;
using std::list;
using std::lower_bound;
using std::lognormal_distribution;
using std::map;
using std::max;
using std::min;
using std::mt19937;
using std::multimap;
using std::normal_distribution;
using std::numeric_limits;
using std::ofstream;
using std::pair;
using std::random_device;
using std::random_shuffle;
using std::reverse_iterator;
using std::round;
using std::setw;
using std::shuffle;
using std::sort;
using std::sqrt;
using std::string;
using std::stringstream;
using std::swap;
using std::tuple;
using std::uniform_real_distribution;
using std::uniform_int_distribution;
using std::unique;
using std::unordered_map;
using std::vector;
const double pi = M_PI;
random_device urandom;
mt19937 urng(urandom());
template<typename T> inline const void kahan_sum(
const T &x,
T &c,
T &sum
){
const T y=x-c;
const T t=sum+y;
c = (t-sum)-y;
sum=t;
}
template<typename T> inline const void mean_variance(
const T &x,
const T &w,
T &sumw,
T &mean,
T &M2
){
const T temp = w+sumw;
const T delta = x-mean;
const T R = delta*w/temp;
mean += R;
M2 += sumw*delta*R;
sumw = temp;
}
template<typename T> inline const T variance(
const T &M2,
const T &sumw,
const size_t &n
){
return M2*n/(sumw*(n-1));
}
template<typename T> inline const T variance(
const T &M2,
const T &sumw
){
return M2/sumw;
}
const vector<array<double,3>> ex_max(
const vector<array<double,2>> &data,
const size_t &n
){
double mean=0;
double sumw=0;
double M2=0;
for (auto it=data.begin(); it!=data.end(); ++it){
mean_variance((*it)[0],(*it)[1],sumw,mean,M2);
}
const double v = variance(M2,sumw,data.size());
vector<array<double,3>> model(n); // weight,mean,sigma
// initialize the model with equal weights,
// random points from the dataset as mean
// and the square root of the over all variance
for (size_t i=0; i!=n; ++i){
model[i]={{1.0/n,data[i][0],v/n}};
}
vector<array<double,5>> temp(n); // sumw,mean,M2,T,TS
double change;
do{
change=0.0;
double TS = 0.0;
// for (auto t=temp.begin(); t!=temp.end(); ++t){
// (*t)[0]=(*t)[1]=(*t)[2]=(*t)[3]=(*t)[4]=0.0;
// }
// for (double i=0; i<1.005; i+=0.01){
// double T = 0.0;
// cout << setw(16) << i ;
// auto t=temp.begin();
// auto m=model.begin();
// for (;m!=model.end()&&t!=temp.end(); (++m,++t)){
// const double m1= i;
// const double v1= 0.01*0.01;
// const double m2= (*m)[1];
// const double v2= (*m)[2];
// const double i = exp(-(m1-m2)*(m1-m2)/(2*(v1+v2)))/sqrt(2*pi*(v1+v2));
// T+=i;
// (*t)[3]=i;
// (*t)[4]+=i;
// }
// t=temp.begin();
// m=model.begin();
// for (;m!=model.end()&&t!=temp.end(); (++m,++t)){
// const double v = 0.01*0.01;
// const double w = (*t)[3]/(T*v);
// cout << setw(16) << round(w);
// }
// cout << endl;
// }
for (auto t=temp.begin(); t!=temp.end(); ++t){
(*t)[0]=(*t)[1]=(*t)[2]=(*t)[3]=(*t)[4]=0.0;
}
cout << "--------------------------------" << endl;
for (auto d=data.begin(); d!=data.end(); ++d){
double T = 0.0;
auto t=temp.begin();
auto m=model.begin();
for (;m!=model.end()&&t!=temp.end(); (++m,++t)){
const double s2=(*m)[2]+(*d)[1]*(*d)[1];
const double m1= (*d)[0];
const double v1= (*d)[1]*(*d)[1];
const double m2= (*m)[1];
const double v2= (*m)[2];
const double i = exp(-(m1-m2)*(m1-m2)/(2*(v1+v2)))/sqrt(2*pi*(v1+v2));
T+=i;
TS+=i;
(*t)[3]=i;
(*t)[4]+=i;
}
t=temp.begin();
m=model.begin();
if (T<numeric_limits<double>::epsilon()) continue;
for (;m!=model.end()&&t!=temp.end(); (++m,++t)){
if ((*t)[3]<numeric_limits<double>::epsilon()) continue;
const double m = (*d)[0];
const double v = (*d)[1]*(*d)[1];
const double w = (*t)[3]/(T*v);
// cout << setw(16) << m << setw(16) << w << endl;
mean_variance(m,w,(*t)[0],(*t)[1],(*t)[2]);
}
}
{
auto t=temp.begin();
auto m=model.begin();
for (;m!=model.end()&&t!=temp.end(); (++m,++t)){
change+=((*m)[0]-(*t)[4]/TS)*((*m)[0]-(*t)[4]/TS);
change+=((*m)[1]-(*t)[1])*((*m)[1]-(*t)[1]);
change+=((*m)[2]-(*t)[2]/(*t)[0])
*((*m)[2]-(*t)[2]/(*t)[0]);
cout << setw(16) << (*m)[1] << setw(16) << (*m)[2] << endl;
(*m)[0]=(*t)[4]/TS;
(*m)[1]=(*t)[1];
(*m)[2]=(*t)[2]/(*t)[0];
}
}
cout << "--------------------------------" << endl;
// cout << change << endl;
}while(change>1e-24);
return model;
}
int main(int argc, char *argv[]){
lognormal_distribution<double> lognormal;
uniform_int_distribution<size_t> uniform(0,N-1);
vector<array<double,2>> data;
for (size_t i=0; i<64*N; ++i){
const double s = lognormal(urng);
// data.push_back({normal_distribution<double>(uniform(urng),s)(urng),s});
data.push_back({normal_distribution<double>(uniform(urng),0.1)(urng),0.1});
}
// for (auto it=data.begin(); it!=data.end(); ++it){
// cout << setw(16) << (*it)[0] << setw(16) << (*it)[1] << endl;
// }
// cout << " * * * * * * * * * * * * * * * * * * * * * * * * " << endl;
vector<array<double,3>> model = ex_max(data,N);
cout << " * * * * * * * * * * * * * * * * * * * * * * * * " << endl;
cout << setw(16) << "weight" << setw(16) << "mean" << setw(16) << "sigma" << endl;
sort(model.begin(),model.end(),
[](const array<double,3> &a, const array<double,3> &b){return a[1]<b[1];});
for (auto it=model.begin(); it!=model.end(); ++it){
cout << setw(16) << (*it)[0] << setw(16) << (*it)[1] << setw(16) << sqrt((*it)[2]) << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#define __NO_STD_VECTOR // Use cl::vector instead of STL version
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#include "openCLUtilities.hpp"
#include <string>
#include <iostream>
#include <utility>
#define MU 0.1f
#define ITERATIONS 10
#define FILENAME "aneurism.raw"
#define SIZE_X 256
#define SIZE_Y 256
#define SIZE_Z 256
using namespace cl;
typedef unsigned char uchar;
float * parseRawFile(char * filename) {
// Parse the specified raw file
int rawDataSize = SIZE_X*SIZE_Y*SIZE_Z;
uchar * rawVoxels = new uchar[rawDataSize];
FILE * file = fopen(filename, "rb");
if(file == NULL) {
printf("File not found: %s\n", filename);
exit(-1);
}
fread(rawVoxels, sizeof(uchar), rawDataSize, file);
// Find min and max
int min = 257;
int max = 0;
for(int i = 0; i < rawDataSize; i++) {
if(rawVoxels[i] > max)
max = rawVoxels[i];
if(rawVoxels[i] < min)
min = rawVoxels[i];
}
std::cout << "Min: " << min << " Max: " << max << std::endl;
// Normalize result
float * voxels = new float[rawDataSize];
for(int i = 0; i < rawDataSize; i++) {
voxels[i] = (float)(rawVoxels[i] - min) / (max - min);
}
delete[] rawVoxels;
return voxels;
}
void writeToRaw(float * voxels, char * filename) {
FILE * file = fopen(filename, "wb");
fwrite(voxels, sizeof(float), SIZE_X*SIZE_Y*SIZE_Z, file);
}
int main(void) {
try {
Context context = createCLContext(CL_DEVICE_TYPE_GPU);
// Get a list of devices
vector<Device> devices = context.getInfo<CL_CONTEXT_DEVICES>();
// Create a command queue and use the first device
CommandQueue queue = CommandQueue(context, devices[0]);
Program program = buildProgramFromSource(context, "kernels.cl");
// Create Kernels
Kernel initKernel = Kernel(program, "GVFInit");
Kernel iterationKernel = Kernel(program, "GVFIteration");
Kernel resultKernel = Kernel(program, "GVFResult");
// Load volume to GPU
std::cout << "Reading RAW file " << FILENAME << std::endl;
float * voxels = parseRawFile(FILENAME);
Image3D volume = Image3D(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, ImageFormat(CL_R, CL_FLOAT), SIZE_X, SIZE_Y, SIZE_Z, 0, 0, voxels);
delete[] voxels;
// Query the size of available memory
unsigned int memorySize = devices[0].getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>();
std::cout << "Available memory on selected device " << memorySize << " bytes "<< std::endl;
ImageFormat storageFormat;
if(memorySize > SIZE_X*SIZE_Y*SIZE_Z*4*4*3) {
storageFormat = ImageFormat(CL_RGBA, CL_FLOAT);
std::cout << "Using 32 bits floats texture storage" << std::endl;
} else if(memorySize > SIZE_X*SIZE_Y*SIZE_Z*2*4*3) {
storageFormat = ImageFormat(CL_RGBA, CL_SNORM_INT16);
std::cout << "Not enough memory on device for 32 bit floats, using 16bit for texture storage instead." << std::endl;
} else {
std::cout << "There is not enough memory on this device to calculate the GVF for this dataset!" << std::endl;
exit(-1);
}
// Run initialization kernel
Image3D initVectorField = Image3D(context, CL_MEM_READ_WRITE, storageFormat, SIZE_X, SIZE_Y, SIZE_Z);
initKernel.setArg(0, volume);
initKernel.setArg(1, initVectorField);
queue.enqueueNDRangeKernel(
initKernel,
NullRange,
NDRange(SIZE_X,SIZE_Y,SIZE_Z),
NullRange
);
// Delete volume from device
//volume.~Image3D();
// copy vector field and create double buffer
Image3D vectorField = Image3D(context, CL_MEM_READ_WRITE, storageFormat, SIZE_X, SIZE_Y, SIZE_Z);
Image3D vectorField2 = Image3D(context, CL_MEM_READ_WRITE, storageFormat, SIZE_X, SIZE_Y, SIZE_Z);
cl::size_t<3> offset;
offset[0] = 0;
offset[1] = 0;
offset[2] = 0;
cl::size_t<3> region;
region[0] = SIZE_X;
region[1] = SIZE_Y;
region[2] = SIZE_Z;
queue.enqueueCopyImage(initVectorField, vectorField, offset, offset, region);
//queue.enqueueCopyImage(initVectorField, vectorField2, offset, offset, region);
queue.finish();
std::cout << "Running iterations... ( " << ITERATIONS << " )" << std::endl;
// Run iterations
iterationKernel.setArg(0, initVectorField);
float mu = MU;
iterationKernel.setArg(3, mu);
for(int i = 0; i < ITERATIONS; i++) {
if(i % 2 == 0) {
iterationKernel.setArg(1, vectorField);
iterationKernel.setArg(2, vectorField2);
} else {
iterationKernel.setArg(1, vectorField2);
iterationKernel.setArg(2, vectorField);
}
queue.enqueueNDRangeKernel(
iterationKernel,
NullRange,
NDRange(SIZE_X,SIZE_Y,SIZE_Z),
NDRange(1,1,1)
);
}
queue.finish();
// Read the result in some way (maybe write to a seperate raw file)
volume = Image3D(context, CL_MEM_WRITE_ONLY, ImageFormat(CL_R,CL_FLOAT), SIZE_X, SIZE_Y, SIZE_Z);
resultKernel.setArg(0, volume);
resultKernel.setArg(1, vectorField);
queue.enqueueNDRangeKernel(
resultKernel,
NullRange,
NDRange(SIZE_X, SIZE_Y, SIZE_Z),
NullRange
);
queue.finish();
voxels = new float[SIZE_X*SIZE_Y*SIZE_Z];
std::cout << "Reading vector field from device..." << std::endl;
queue.enqueueReadImage(volume, CL_TRUE, offset, region, 0, 0, voxels);
std::cout << "Writing vector field to RAW file..." << std::endl;
writeToRaw(voxels, "result.raw");
delete[] voxels;
} catch(Error error) {
std::cout << error.what() << "(" << error.err() << ")" << std::endl;
std::cout << getCLErrorString(error.err()) << std::endl;
}
return 0;
}
<commit_msg>added program input parameters<commit_after>#define __NO_STD_VECTOR // Use cl::vector instead of STL version
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#include "openCLUtilities.hpp"
#include <string>
#include <iostream>
#include <utility>
#include <math.h>
using namespace cl;
typedef unsigned char uchar;
float * parseRawFile(char * filename, int SIZE_X, int SIZE_Y, int SIZE_Z) {
// Parse the specified raw file
int rawDataSize = SIZE_X*SIZE_Y*SIZE_Z;
uchar * rawVoxels = new uchar[rawDataSize];
FILE * file = fopen(filename, "rb");
if(file == NULL) {
printf("File not found: %s\n", filename);
exit(-1);
}
fread(rawVoxels, sizeof(uchar), rawDataSize, file);
// Find min and max
int min = 257;
int max = 0;
for(int i = 0; i < rawDataSize; i++) {
if(rawVoxels[i] > max)
max = rawVoxels[i];
if(rawVoxels[i] < min)
min = rawVoxels[i];
}
std::cout << "Min: " << min << " Max: " << max << std::endl;
// Normalize result
float * voxels = new float[rawDataSize];
for(int i = 0; i < rawDataSize; i++) {
voxels[i] = (float)(rawVoxels[i] - min) / (max - min);
}
delete[] rawVoxels;
return voxels;
}
void writeToRaw(float * voxels, char * filename, int SIZE_X, int SIZE_Y, int SIZE_Z) {
FILE * file = fopen(filename, "wb");
fwrite(voxels, sizeof(float), SIZE_X*SIZE_Y*SIZE_Z, file);
}
int main(int argc, char ** argv) {
char * filename;
int SIZE_X, SIZE_Y, SIZE_Z, ITERATIONS;
float mu;
if(argc > 5) {
filename = argv[1];
SIZE_X = atoi(argv[2]);
SIZE_Y = atoi(argv[3]);
SIZE_Z = atoi(argv[4]);
mu = atof(argv[5]);
if(argc == 7) {
ITERATIONS = atoi(argv[6]);
} else {
ITERATIONS = (int)sqrt(SIZE_X*SIZE_Y*SIZE_Z);
}
} else {
std::cout << "usage: filename of raw file size_x size_y size_z mu [iterations]" << std::endl;
exit(-1);
}
try {
Context context = createCLContext(CL_DEVICE_TYPE_GPU);
// Get a list of devices
vector<Device> devices = context.getInfo<CL_CONTEXT_DEVICES>();
// Create a command queue and use the first device
CommandQueue queue = CommandQueue(context, devices[0]);
Program program = buildProgramFromSource(context, "kernels.cl");
// Create Kernels
Kernel initKernel = Kernel(program, "GVFInit");
Kernel iterationKernel = Kernel(program, "GVFIteration");
Kernel resultKernel = Kernel(program, "GVFResult");
// Load volume to GPU
std::cout << "Reading RAW file " << filename << std::endl;
float * voxels = parseRawFile(filename, SIZE_X, SIZE_Y, SIZE_Z);
Image3D volume = Image3D(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, ImageFormat(CL_R, CL_FLOAT), SIZE_X, SIZE_Y, SIZE_Z, 0, 0, voxels);
delete[] voxels;
// Query the size of available memory
unsigned int memorySize = devices[0].getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>();
std::cout << "Available memory on selected device " << memorySize << " bytes "<< std::endl;
ImageFormat storageFormat;
if(memorySize > SIZE_X*SIZE_Y*SIZE_Z*4*4*3) {
storageFormat = ImageFormat(CL_RGBA, CL_FLOAT);
std::cout << "Using 32 bits floats texture storage" << std::endl;
} else if(memorySize > SIZE_X*SIZE_Y*SIZE_Z*2*4*3) {
storageFormat = ImageFormat(CL_RGBA, CL_SNORM_INT16);
std::cout << "Not enough memory on device for 32 bit floats, using 16bit for texture storage instead." << std::endl;
} else {
std::cout << "There is not enough memory on this device to calculate the GVF for this dataset!" << std::endl;
exit(-1);
}
// Run initialization kernel
Image3D initVectorField = Image3D(context, CL_MEM_READ_WRITE, storageFormat, SIZE_X, SIZE_Y, SIZE_Z);
initKernel.setArg(0, volume);
initKernel.setArg(1, initVectorField);
queue.enqueueNDRangeKernel(
initKernel,
NullRange,
NDRange(SIZE_X,SIZE_Y,SIZE_Z),
NullRange
);
// Delete volume from device
//volume.~Image3D();
// copy vector field and create double buffer
Image3D vectorField = Image3D(context, CL_MEM_READ_WRITE, storageFormat, SIZE_X, SIZE_Y, SIZE_Z);
Image3D vectorField2 = Image3D(context, CL_MEM_READ_WRITE, storageFormat, SIZE_X, SIZE_Y, SIZE_Z);
cl::size_t<3> offset;
offset[0] = 0;
offset[1] = 0;
offset[2] = 0;
cl::size_t<3> region;
region[0] = SIZE_X;
region[1] = SIZE_Y;
region[2] = SIZE_Z;
queue.enqueueCopyImage(initVectorField, vectorField, offset, offset, region);
//queue.enqueueCopyImage(initVectorField, vectorField2, offset, offset, region);
queue.finish();
std::cout << "Running iterations... ( " << ITERATIONS << " )" << std::endl;
// Run iterations
iterationKernel.setArg(0, initVectorField);
iterationKernel.setArg(3, mu);
for(int i = 0; i < ITERATIONS; i++) {
if(i % 2 == 0) {
iterationKernel.setArg(1, vectorField);
iterationKernel.setArg(2, vectorField2);
} else {
iterationKernel.setArg(1, vectorField2);
iterationKernel.setArg(2, vectorField);
}
queue.enqueueNDRangeKernel(
iterationKernel,
NullRange,
NDRange(SIZE_X,SIZE_Y,SIZE_Z),
NDRange(1,1,1)
);
}
queue.finish();
// Read the result in some way (maybe write to a seperate raw file)
volume = Image3D(context, CL_MEM_WRITE_ONLY, ImageFormat(CL_R,CL_FLOAT), SIZE_X, SIZE_Y, SIZE_Z);
resultKernel.setArg(0, volume);
resultKernel.setArg(1, vectorField);
queue.enqueueNDRangeKernel(
resultKernel,
NullRange,
NDRange(SIZE_X, SIZE_Y, SIZE_Z),
NullRange
);
queue.finish();
voxels = new float[SIZE_X*SIZE_Y*SIZE_Z];
std::cout << "Reading vector field from device..." << std::endl;
queue.enqueueReadImage(volume, CL_TRUE, offset, region, 0, 0, voxels);
std::cout << "Writing vector field to RAW file..." << std::endl;
writeToRaw(voxels, "result.raw", SIZE_X, SIZE_Y, SIZE_Z);
delete[] voxels;
} catch(Error error) {
std::cout << error.what() << "(" << error.err() << ")" << std::endl;
std::cout << getCLErrorString(error.err()) << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>
#include <stdio.h>
#include <gtk/gtk.h>
#include <cassert>
#include <iostream>
#include "include/cef_base.h"
#include "include/cef_client.h"
#include "include/cef_app.h"
#include "include/cef_browser.h"
#include "include/cef_client.h"
#include "include/cef_runnable.h"
#include "include/cef_task.h"
#include "include/cef_v8.h"
#include "include/cef_app.h"
struct ChromeWindowClient : public CefClient
, public CefLifeSpanHandler
, public CefDisplayHandler
{
virtual CefRefPtr<CefDisplayHandler> GetDisplayHandler() {
return this;
}
virtual CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() {
return this;
}
// CefLifeSpanHandler
virtual void OnAfterCreated(CefRefPtr<CefBrowser> aBrowser) {
if (browser.get()) {
return;
}
browser = aBrowser;
}
// CefDisplayHandler
virtual bool OnConsoleMessage(
CefRefPtr<CefBrowser> browser,
const CefString& message,
const CefString& source,
int line
) {
printf("OnConsoleMessage %S\n", message.ToWString().c_str());
return false;
}
CefRefPtr<CefBrowser> browser;
IMPLEMENT_REFCOUNTING(ChromeWindowClient);
};
struct ChromeWindowApp : public CefApp
, public CefRenderProcessHandler
, public CefV8Handler
{
IMPLEMENT_REFCOUNTING(ChromeWindowApp);
private:
std::vector<std::string> argv;
public:
ChromeWindowApp(const std::vector<std::string>& argv)
: argv(argv)
{
}
// CefApp
virtual CefRefPtr<CefRenderProcessHandler> GetRenderProcessHandler() {
return this;
}
// CefRenderProcessHandler
virtual void OnContextCreated(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefV8Context> context
) {
if (argv[0] == "--type=zygote") {
return;
}
char* contents;
{
FILE* file = fopen(argv.at(1).c_str(), "rb");
if (!file) {
printf("Unable to read %s\n", argv[1].c_str());
return;
}
fseek(file, 0, SEEK_END);
size_t len = ftell(file);
fseek(file, 0, SEEK_SET);
contents = new char[len + 1];
size_t readLen = fread(contents, 1, len, file);
if (len != readLen) {
printf("Failed to read %s\n", argv[1].c_str());
delete[] contents;
return;
}
contents[len] = 0;
fclose(file);
}
CefString sourceCode(contents);
delete[] contents;
contents = 0;
//
CefRefPtr<CefV8Value> leprechaun = CefV8Value::CreateObject(0);
CefRefPtr<CefV8Value> exit = CefV8Value::CreateFunction("exit", this);
leprechaun->SetValue("exit", exit, V8_PROPERTY_ATTRIBUTE_READONLY);
CefRefPtr<CefV8Value> global = context->GetGlobal();
global->SetValue("leprechaun", leprechaun, V8_PROPERTY_ATTRIBUTE_READONLY);
CefRefPtr<CefV8Value> bootstrapFunction;
CefRefPtr<CefV8Exception> bootstrapException;
bool evalResult = context->Eval(
CefString(
"(function leprechaun_bootstrap$(sourceCode) {"
" var s = document.createElement(\"script\");"
" var t = document.createTextNode(sourceCode + \"\\n//@sourceURL=thingie\");"
" s.appendChild(t);"
" document.body.appendChild(s);"
"})"
), bootstrapFunction, bootstrapException
);
if (!evalResult) {
printf("Eval error: %S\n", bootstrapException->GetMessage().ToWString().c_str());
assert(evalResult);
}
CefV8ValueList args;
args.push_back(CefRefPtr<CefV8Value>(CefV8Value::CreateString(sourceCode)));
CefRefPtr<CefV8Value> callResult = bootstrapFunction->ExecuteFunction(0, args);
}
virtual void OnContextReleased(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefV8Context> context
) {
}
virtual void OnWebKitInitialized() {
}
// CefV8Handler
virtual bool Execute(
const CefString& name,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception
) {
if (name == "exit") {
// FIXME: This breaks if we run chromium in multiprocess mode.
// I can't figure out how to get the IPC right. -- andy 5 September 2012
bool result = CefPostTask(
TID_UI,
NewCefRunnableFunction(&CefQuitMessageLoop)
);
retval = CefV8Value::CreateString(result ? L"OK" : L"NOT OK");
return true;
}
return false;
}
};
void destroy() {
CefQuitMessageLoop();
}
int main(int argc, char** argv) {
gtk_init(&argc, &argv);
if (argc > 1 && std::string(argv[1]) == "--type=zygote") {
// ok
} else if (argc == 2) {
// ok
} else {
printf("Syntax: %s filename.js\n", argv[0]);
return 1;
}
CefRefPtr<CefApp> app(new ChromeWindowApp(std::vector<std::string>(argv, argv + argc)));
CefRefPtr<ChromeWindowClient> client(new ChromeWindowClient);
CefMainArgs args(argc, argv);
CefSettings appSettings;
//appSettings.log_severity = LOGSEVERITY_VERBOSE;
appSettings.multi_threaded_message_loop = false;
appSettings.single_process = true;
CefInitialize(args, appSettings, app);
GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_default_size(GTK_WINDOW(window), 640, 480);
g_signal_connect(G_OBJECT(window), "destroy",
G_CALLBACK(gtk_widget_destroyed), &window);
g_signal_connect(G_OBJECT(window), "destroy",
G_CALLBACK(destroy), NULL);
CefWindowInfo info;
info.SetAsChild(window);
CefBrowserSettings settings;
CefBrowser* browser = CefBrowserHost::CreateBrowserSync(
info, client.get(),
"data:text/html,<!DOCTYPE html><html><head></head><body></body><script>void 0;</script></html>",
settings
);
//printf("CreateBrowser result: 0x08X\n", browser);
//gtk_widget_show_all(GTK_WIDGET(window));
CefRunMessageLoop();
CefShutdown();
return 0;
}
<commit_msg>Cleanup.<commit_after>
#include <stdio.h>
#include <gtk/gtk.h>
#include <cassert>
#include <iostream>
#include "include/cef_base.h"
#include "include/cef_client.h"
#include "include/cef_app.h"
#include "include/cef_browser.h"
#include "include/cef_client.h"
#include "include/cef_runnable.h"
#include "include/cef_task.h"
#include "include/cef_v8.h"
#include "include/cef_app.h"
struct ChromeWindowClient : public CefClient
, public CefLifeSpanHandler
, public CefDisplayHandler
{
virtual CefRefPtr<CefDisplayHandler> GetDisplayHandler() {
return this;
}
virtual CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() {
return this;
}
// CefLifeSpanHandler
virtual void OnAfterCreated(CefRefPtr<CefBrowser> aBrowser) {
if (browser.get()) {
return;
}
browser = aBrowser;
}
// CefDisplayHandler
virtual bool OnConsoleMessage(
CefRefPtr<CefBrowser> browser,
const CefString& message,
const CefString& source,
int line
) {
printf("OnConsoleMessage %S\n", message.ToWString().c_str());
return false;
}
CefRefPtr<CefBrowser> browser;
IMPLEMENT_REFCOUNTING(ChromeWindowClient);
};
std::string readFile(const std::string& fileName) {
FILE* file = fopen(fileName.c_str(), "rb");
if (!file) {
printf("Unable to read %s\n", fileName.c_str());
return std::string();
}
fseek(file, 0, SEEK_END);
const size_t len = ftell(file);
fseek(file, 0, SEEK_SET);
char* const contents = new char[len + 1];
const size_t readLen = fread(contents, 1, len, file);
if (len != readLen) {
printf("Failed to read %s\n", fileName.c_str());
delete[] contents;
return std::string();
}
fclose(file);
contents[len] = 0;
std::string s(contents);
delete[] contents;
return s;
}
struct ChromeWindowApp : public CefApp
, public CefRenderProcessHandler
, public CefV8Handler
{
IMPLEMENT_REFCOUNTING(ChromeWindowApp);
private:
CefRefPtr<CefCommandLine> commandLine;
public:
ChromeWindowApp(CefRefPtr<CefCommandLine>& commandLine)
: commandLine(commandLine)
{
}
// CefApp
virtual CefRefPtr<CefRenderProcessHandler> GetRenderProcessHandler() {
return this;
}
// CefRenderProcessHandler
virtual void OnContextCreated(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefV8Context> context
) {
if (!commandLine->HasArguments()) {
return;
}
CefCommandLine::ArgumentList arguments;
commandLine->GetArguments(arguments);
std::string sourceCode = readFile(arguments.at(0));
if (sourceCode.empty()) {
return;
}
//
CefRefPtr<CefV8Value> leprechaun = CefV8Value::CreateObject(0);
CefRefPtr<CefV8Value> exit = CefV8Value::CreateFunction("exit", this);
leprechaun->SetValue("exit", exit, V8_PROPERTY_ATTRIBUTE_READONLY);
CefRefPtr<CefV8Value> global = context->GetGlobal();
global->SetValue("leprechaun", leprechaun, V8_PROPERTY_ATTRIBUTE_READONLY);
CefRefPtr<CefV8Value> bootstrapFunction;
CefRefPtr<CefV8Exception> bootstrapException;
bool evalResult = context->Eval(
CefString(
"(function leprechaun_bootstrap$(sourceCode) {"
" var s = document.createElement(\"script\");"
" var t = document.createTextNode(sourceCode + \"\\n//@sourceURL=thingie\");"
" s.appendChild(t);"
" document.body.appendChild(s);"
"})"
), bootstrapFunction, bootstrapException
);
if (!evalResult) {
printf("Eval error: %S\n", bootstrapException->GetMessage().ToWString().c_str());
assert(evalResult);
}
CefV8ValueList args;
args.push_back(CefRefPtr<CefV8Value>(CefV8Value::CreateString(sourceCode)));
CefRefPtr<CefV8Value> callResult = bootstrapFunction->ExecuteFunction(0, args);
}
virtual void OnContextReleased(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefV8Context> context
) {
}
virtual void OnWebKitInitialized() {
}
// CefV8Handler
virtual bool Execute(
const CefString& name,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception
) {
if (name == "exit") {
// FIXME: This breaks if we run chromium in multiprocess mode.
// I can't figure out how to get the IPC right. -- andy 5 September 2012
bool result = CefPostTask(
TID_UI,
NewCefRunnableFunction(&CefQuitMessageLoop)
);
retval = CefV8Value::CreateString(result ? L"OK" : L"NOT OK");
return true;
}
return false;
}
};
void destroy() {
CefQuitMessageLoop();
}
int main(int argc, char** argv) {
gtk_init(&argc, &argv);
CefRefPtr<CefCommandLine> commandLine(CefCommandLine::CreateCommandLine());
commandLine->InitFromArgv(argc, argv);
printf("Commandline %S\n", commandLine->GetCommandLineString().ToWString().c_str());
// FIXME: Chromium launches a zygote, even though we're in single-process mode.
// It's not clear to me what this accomplishes, but for now, we just roll with it.
// -- andy 7 September 2012
if (!commandLine->HasSwitch("type") && argc != 2) {
printf("Syntax: %s filename.js\n", argv[0]);
return 1;
}
CefRefPtr<CefApp> app(new ChromeWindowApp(commandLine));
CefRefPtr<ChromeWindowClient> client(new ChromeWindowClient);
CefMainArgs args(argc, argv);
CefSettings appSettings;
//appSettings.log_severity = LOGSEVERITY_VERBOSE;
appSettings.multi_threaded_message_loop = false;
appSettings.single_process = true;
CefInitialize(args, appSettings, app);
GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_default_size(GTK_WINDOW(window), 640, 480);
g_signal_connect(G_OBJECT(window), "destroy",
G_CALLBACK(gtk_widget_destroyed), &window);
g_signal_connect(G_OBJECT(window), "destroy",
G_CALLBACK(destroy), NULL);
CefWindowInfo info;
info.SetAsChild(window);
CefBrowserSettings settings;
CefBrowser* browser = CefBrowserHost::CreateBrowserSync(
info, client.get(),
"data:text/html,<!DOCTYPE html><html><head></head><body></body><script>void 0;</script></html>",
settings
);
gtk_widget_show_all(GTK_WIDGET(window));
CefRunMessageLoop();
CefShutdown();
return 0;
}
<|endoftext|> |
<commit_before>deeb7be3-313a-11e5-9700-3c15c2e10482<commit_msg>def1a12b-313a-11e5-80a9-3c15c2e10482<commit_after>def1a12b-313a-11e5-80a9-3c15c2e10482<|endoftext|> |
<commit_before>d7938ce1-327f-11e5-ac03-9cf387a8033e<commit_msg>d79c5226-327f-11e5-8448-9cf387a8033e<commit_after>d79c5226-327f-11e5-8448-9cf387a8033e<|endoftext|> |
<commit_before>84ff2875-2e4f-11e5-9688-28cfe91dbc4b<commit_msg>8505ac6e-2e4f-11e5-9f25-28cfe91dbc4b<commit_after>8505ac6e-2e4f-11e5-9f25-28cfe91dbc4b<|endoftext|> |
<commit_before>048444a1-ad59-11e7-984d-ac87a332f658<commit_msg>GOD DAMNED IT!<commit_after>059bc70c-ad59-11e7-8680-ac87a332f658<|endoftext|> |
<commit_before>5bf67371-2d16-11e5-af21-0401358ea401<commit_msg>5bf67372-2d16-11e5-af21-0401358ea401<commit_after>5bf67372-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>b0db3866-35ca-11e5-91dc-6c40088e03e4<commit_msg>b0e3fbd8-35ca-11e5-ab18-6c40088e03e4<commit_after>b0e3fbd8-35ca-11e5-ab18-6c40088e03e4<|endoftext|> |
<commit_before>b050db46-35ca-11e5-980f-6c40088e03e4<commit_msg>b05768ee-35ca-11e5-a619-6c40088e03e4<commit_after>b05768ee-35ca-11e5-a619-6c40088e03e4<|endoftext|> |
<commit_before>175f5d9a-2f67-11e5-b640-6c40088e03e4<commit_msg>176843a6-2f67-11e5-8fff-6c40088e03e4<commit_after>176843a6-2f67-11e5-8fff-6c40088e03e4<|endoftext|> |
<commit_before>333ac93a-2f67-11e5-b3ac-6c40088e03e4<commit_msg>33418240-2f67-11e5-9134-6c40088e03e4<commit_after>33418240-2f67-11e5-9134-6c40088e03e4<|endoftext|> |
<commit_before>dc80281e-ad5a-11e7-85b2-ac87a332f658<commit_msg>Stuff changed<commit_after>dd08e6b0-ad5a-11e7-a2bd-ac87a332f658<|endoftext|> |
<commit_before>8602a051-4b02-11e5-ad97-28cfe9171a43<commit_msg>Test..<commit_after>860ec8ab-4b02-11e5-ab71-28cfe9171a43<|endoftext|> |
<commit_before>3f83c70c-2e4f-11e5-aa3c-28cfe91dbc4b<commit_msg>3f8b4f68-2e4f-11e5-bcc5-28cfe91dbc4b<commit_after>3f8b4f68-2e4f-11e5-bcc5-28cfe91dbc4b<|endoftext|> |
<commit_before>3110ad6e-2f67-11e5-b234-6c40088e03e4<commit_msg>31179536-2f67-11e5-bf01-6c40088e03e4<commit_after>31179536-2f67-11e5-bf01-6c40088e03e4<|endoftext|> |
<commit_before>83000de2-2d15-11e5-af21-0401358ea401<commit_msg>83000de3-2d15-11e5-af21-0401358ea401<commit_after>83000de3-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>76ed6da6-2749-11e6-b4f5-e0f84713e7b8<commit_msg>Typical ashok<commit_after>76fec8d1-2749-11e6-a52d-e0f84713e7b8<|endoftext|> |
<commit_before>/* Copyright (C) Teemu Suutari */
#include <stdint.h>
#include <memory>
#include <fstream>
#include <vector>
#include <string>
#include <functional>
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include "common/MemoryBuffer.hpp"
#include "common/SubBuffer.hpp"
#include "Decompressor.hpp"
std::unique_ptr<Buffer> readFile(const std::string &fileName)
{
std::unique_ptr<Buffer> ret=std::make_unique<MemoryBuffer>(0);
std::ifstream file(fileName.c_str(),std::ios::in|std::ios::binary);
bool success=false;
if (file.is_open())
{
file.seekg(0,std::ios::end);
size_t length=size_t(file.tellg());
file.seekg(0,std::ios::beg);
ret->resize(length);
file.read(reinterpret_cast<char*>(ret->data()),length);
success=bool(file);
file.close();
}
if (!success)
{
fprintf(stderr,"Could not read file %s\n",fileName.c_str());
return std::unique_ptr<Buffer>();
}
return ret;
}
bool writeFile(const std::string &fileName,const Buffer &content)
{
bool ret=false;
std::ofstream file(fileName.c_str(),std::ios::out|std::ios::binary|std::ios::trunc);
if (file.is_open())
{
file.write(reinterpret_cast<const char*>(content.data()),content.size());
ret=bool(file);
file.close();
}
if (!ret)
{
fprintf(stderr,"Could not write file %s\n",fileName.c_str());
}
return ret;
}
int main(int argc,char **argv)
{
auto usage=[]()
{
fprintf(stderr,"Usage: ancient identify packed_input_file\n");
fprintf(stderr," - identifies compression used in a file\n");
fprintf(stderr,"Usage: ancient verify packed_inout_file unpacked_comparison_file\n");
fprintf(stderr," - verifies decompression against known good unpacked file\n");
fprintf(stderr,"Usage: ancient decompress packed_input_file output_file\n");
fprintf(stderr," - decompresses single file\n");
fprintf(stderr,"Usage: ancient scan input_dir output_dir\n");
fprintf(stderr," - scans input directory recursively and stores all found\n"
" - known compressed streams to separate files in output directory\n");
};
if (argc<3)
{
usage();
return -1;
}
std::string cmd=argv[1];
if (cmd=="identify")
{
if (argc!=3)
{
usage();
return -1;
}
auto packed{readFile(argv[2])};
std::unique_ptr<Decompressor> decompressor;
try
{
decompressor=Decompressor::create(*packed,true,true);
} catch (const Decompressor::InvalidFormatError&)
{
fprintf(stderr,"Unknown or invalid compression format in file %s\n",argv[2]);
return -1;
}
printf("Compression of %s is %s\n",argv[2],decompressor->getName().c_str());
return 0;
} else if (cmd=="decompress" || cmd=="verify") {
if (argc!=4)
{
usage();
return -1;
}
auto packed{readFile(argv[2])};
std::unique_ptr<Decompressor> decompressor;
try
{
decompressor=Decompressor::create(*packed,true,true);
} catch (const Decompressor::InvalidFormatError&)
{
fprintf(stderr,"Unknown or invalid compression format in file %s\n",argv[2]);
return -1;
} catch (const Decompressor::VerificationError&)
{
fprintf(stderr,"Verify (packed) failed for %s\n",argv[2]);
return -1;
}
std::unique_ptr<Buffer> raw=std::make_unique<MemoryBuffer>((decompressor->getRawSize())?decompressor->getRawSize():Decompressor::getMaxRawSize());
try
{
decompressor->decompress(*raw,true);
} catch (const Decompressor::DecompressionError&)
{
fprintf(stderr,"Decompression failed for %s\n",argv[2]);
return -1;
} catch (const Decompressor::VerificationError&)
{
fprintf(stderr,"Verify (raw) failed for %s\n",argv[2]);
return -1;
}
raw->resize(decompressor->getRawSize());
if (decompressor->getImageOffset() || decompressor->getImageSize())
{
printf("File %s is disk image, decompressed stream offset is %zu, full image size is %zu\n",argv[2],decompressor->getImageOffset(),decompressor->getImageSize());
printf("!!! Please note !!!\n!!! The destination will not be padded !!!\n\n");
}
if (cmd=="decompress")
{
writeFile(argv[3],*raw);
return 0;
} else {
auto verify{readFile(argv[3])};
if (raw->size()!=verify->size())
{
fprintf(stderr,"Verify failed for %s and %s - sizes differ\n",argv[2],argv[3]);
return -1;
}
for (size_t i=0;i<raw->size();i++)
{
if (raw->data()[i]!=verify->data()[i])
{
fprintf(stderr,"Verify failed for %s and %s - contents differ @ %zu\n",argv[2],argv[3],i);
return -1;
}
}
printf("Files match!\n");
return 0;
}
}
else if (cmd=="scan") {
if (argc!=4)
{
usage();
return -1;
}
uint32_t fileIndex=0;
std::function<void(std::string)> processDir=[&](std::string inputDir)
{
std::unique_ptr<DIR,decltype(&::closedir)> dir{::opendir(inputDir.c_str()),::closedir};
if (dir)
{
while (struct dirent *de=::readdir(dir.get()))
{
std::string subName(de->d_name);
if (subName=="." || subName=="..") continue;
std::string name=inputDir+"/"+subName;
struct stat st;
if (stat(name.c_str(),&st)<0) continue;
if (st.st_mode&S_IFDIR)
{
processDir(name);
} else if (st.st_mode&S_IFREG) {
auto packed{readFile(name)};
ConstSubBuffer scanBuffer(*packed,0,packed->size());
for (size_t i=0;i<packed->size();)
{
scanBuffer.adjust(i,packed->size()-i);
// We will detect first, before trying the format for real
if (!Decompressor::detect(scanBuffer))
{
i++;
continue;
}
try
{
auto decompressor{Decompressor::create(scanBuffer,false,true)};
std::unique_ptr<Buffer> raw=std::make_unique<MemoryBuffer>((decompressor->getRawSize())?decompressor->getRawSize():Decompressor::getMaxRawSize());
// for formats that do not encode packed size.
// we will get it from decompressor
if (!decompressor->getPackedSize())
decompressor->decompress(*raw,true);
if (decompressor->getPackedSize())
{
// final checks with the limited buffer and fresh decompressor
ConstSubBuffer finalBuffer(*packed,i,decompressor->getPackedSize());
auto decompressor2{Decompressor::create(finalBuffer,true,true)};
decompressor2->decompress(*raw,true);
std::string outputName=std::string(argv[3])+"/file"+std::to_string(fileIndex++)+".pack";
printf("Found compressed stream at %zu, size %zu in file %s with type '%s', storing it into %s\n",i,decompressor2->getPackedSize(),name.c_str(),decompressor2->getName().c_str(),outputName.c_str());
writeFile(outputName,finalBuffer);
i+=finalBuffer.size();
continue;
}
} catch (const Decompressor::Error&) {
// full steam ahead (with next offset)
}
i++;
}
}
}
} else {
fprintf(stderr,"Could not process directory %s\n",inputDir.c_str());
}
};
processDir(std::string(argv[2]));
return 0;
} else {
fprintf(stderr,"Unknown command\n");
usage();
return -1;
}
}
<commit_msg>typo fix<commit_after>/* Copyright (C) Teemu Suutari */
#include <stdint.h>
#include <memory>
#include <fstream>
#include <vector>
#include <string>
#include <functional>
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include "common/MemoryBuffer.hpp"
#include "common/SubBuffer.hpp"
#include "Decompressor.hpp"
std::unique_ptr<Buffer> readFile(const std::string &fileName)
{
std::unique_ptr<Buffer> ret=std::make_unique<MemoryBuffer>(0);
std::ifstream file(fileName.c_str(),std::ios::in|std::ios::binary);
bool success=false;
if (file.is_open())
{
file.seekg(0,std::ios::end);
size_t length=size_t(file.tellg());
file.seekg(0,std::ios::beg);
ret->resize(length);
file.read(reinterpret_cast<char*>(ret->data()),length);
success=bool(file);
file.close();
}
if (!success)
{
fprintf(stderr,"Could not read file %s\n",fileName.c_str());
return std::unique_ptr<Buffer>();
}
return ret;
}
bool writeFile(const std::string &fileName,const Buffer &content)
{
bool ret=false;
std::ofstream file(fileName.c_str(),std::ios::out|std::ios::binary|std::ios::trunc);
if (file.is_open())
{
file.write(reinterpret_cast<const char*>(content.data()),content.size());
ret=bool(file);
file.close();
}
if (!ret)
{
fprintf(stderr,"Could not write file %s\n",fileName.c_str());
}
return ret;
}
int main(int argc,char **argv)
{
auto usage=[]()
{
fprintf(stderr,"Usage: ancient identify packed_input_file\n");
fprintf(stderr," - identifies compression used in a file\n");
fprintf(stderr,"Usage: ancient verify packed_input_file unpacked_comparison_file\n");
fprintf(stderr," - verifies decompression against known good unpacked file\n");
fprintf(stderr,"Usage: ancient decompress packed_input_file output_file\n");
fprintf(stderr," - decompresses single file\n");
fprintf(stderr,"Usage: ancient scan input_dir output_dir\n");
fprintf(stderr," - scans input directory recursively and stores all found\n"
" - known compressed streams to separate files in output directory\n");
};
if (argc<3)
{
usage();
return -1;
}
std::string cmd=argv[1];
if (cmd=="identify")
{
if (argc!=3)
{
usage();
return -1;
}
auto packed{readFile(argv[2])};
std::unique_ptr<Decompressor> decompressor;
try
{
decompressor=Decompressor::create(*packed,true,true);
} catch (const Decompressor::InvalidFormatError&)
{
fprintf(stderr,"Unknown or invalid compression format in file %s\n",argv[2]);
return -1;
}
printf("Compression of %s is %s\n",argv[2],decompressor->getName().c_str());
return 0;
} else if (cmd=="decompress" || cmd=="verify") {
if (argc!=4)
{
usage();
return -1;
}
auto packed{readFile(argv[2])};
std::unique_ptr<Decompressor> decompressor;
try
{
decompressor=Decompressor::create(*packed,true,true);
} catch (const Decompressor::InvalidFormatError&)
{
fprintf(stderr,"Unknown or invalid compression format in file %s\n",argv[2]);
return -1;
} catch (const Decompressor::VerificationError&)
{
fprintf(stderr,"Verify (packed) failed for %s\n",argv[2]);
return -1;
}
std::unique_ptr<Buffer> raw=std::make_unique<MemoryBuffer>((decompressor->getRawSize())?decompressor->getRawSize():Decompressor::getMaxRawSize());
try
{
decompressor->decompress(*raw,true);
} catch (const Decompressor::DecompressionError&)
{
fprintf(stderr,"Decompression failed for %s\n",argv[2]);
return -1;
} catch (const Decompressor::VerificationError&)
{
fprintf(stderr,"Verify (raw) failed for %s\n",argv[2]);
return -1;
}
raw->resize(decompressor->getRawSize());
if (decompressor->getImageOffset() || decompressor->getImageSize())
{
printf("File %s is disk image, decompressed stream offset is %zu, full image size is %zu\n",argv[2],decompressor->getImageOffset(),decompressor->getImageSize());
printf("!!! Please note !!!\n!!! The destination will not be padded !!!\n\n");
}
if (cmd=="decompress")
{
writeFile(argv[3],*raw);
return 0;
} else {
auto verify{readFile(argv[3])};
if (raw->size()!=verify->size())
{
fprintf(stderr,"Verify failed for %s and %s - sizes differ\n",argv[2],argv[3]);
return -1;
}
for (size_t i=0;i<raw->size();i++)
{
if (raw->data()[i]!=verify->data()[i])
{
fprintf(stderr,"Verify failed for %s and %s - contents differ @ %zu\n",argv[2],argv[3],i);
return -1;
}
}
printf("Files match!\n");
return 0;
}
}
else if (cmd=="scan") {
if (argc!=4)
{
usage();
return -1;
}
uint32_t fileIndex=0;
std::function<void(std::string)> processDir=[&](std::string inputDir)
{
std::unique_ptr<DIR,decltype(&::closedir)> dir{::opendir(inputDir.c_str()),::closedir};
if (dir)
{
while (struct dirent *de=::readdir(dir.get()))
{
std::string subName(de->d_name);
if (subName=="." || subName=="..") continue;
std::string name=inputDir+"/"+subName;
struct stat st;
if (stat(name.c_str(),&st)<0) continue;
if (st.st_mode&S_IFDIR)
{
processDir(name);
} else if (st.st_mode&S_IFREG) {
auto packed{readFile(name)};
ConstSubBuffer scanBuffer(*packed,0,packed->size());
for (size_t i=0;i<packed->size();)
{
scanBuffer.adjust(i,packed->size()-i);
// We will detect first, before trying the format for real
if (!Decompressor::detect(scanBuffer))
{
i++;
continue;
}
try
{
auto decompressor{Decompressor::create(scanBuffer,false,true)};
std::unique_ptr<Buffer> raw=std::make_unique<MemoryBuffer>((decompressor->getRawSize())?decompressor->getRawSize():Decompressor::getMaxRawSize());
// for formats that do not encode packed size.
// we will get it from decompressor
if (!decompressor->getPackedSize())
decompressor->decompress(*raw,true);
if (decompressor->getPackedSize())
{
// final checks with the limited buffer and fresh decompressor
ConstSubBuffer finalBuffer(*packed,i,decompressor->getPackedSize());
auto decompressor2{Decompressor::create(finalBuffer,true,true)};
decompressor2->decompress(*raw,true);
std::string outputName=std::string(argv[3])+"/file"+std::to_string(fileIndex++)+".pack";
printf("Found compressed stream at %zu, size %zu in file %s with type '%s', storing it into %s\n",i,decompressor2->getPackedSize(),name.c_str(),decompressor2->getName().c_str(),outputName.c_str());
writeFile(outputName,finalBuffer);
i+=finalBuffer.size();
continue;
}
} catch (const Decompressor::Error&) {
// full steam ahead (with next offset)
}
i++;
}
}
}
} else {
fprintf(stderr,"Could not process directory %s\n",inputDir.c_str());
}
};
processDir(std::string(argv[2]));
return 0;
} else {
fprintf(stderr,"Unknown command\n");
usage();
return -1;
}
}
<|endoftext|> |
<commit_before>a47226f3-2e4f-11e5-a8f1-28cfe91dbc4b<commit_msg>a47b1bc2-2e4f-11e5-89ed-28cfe91dbc4b<commit_after>a47b1bc2-2e4f-11e5-89ed-28cfe91dbc4b<|endoftext|> |
<commit_before>2501310f-ad5c-11e7-b712-ac87a332f658<commit_msg>compiles now<commit_after>25bdb717-ad5c-11e7-8655-ac87a332f658<|endoftext|> |
<commit_before>69b44786-2fa5-11e5-a6fd-00012e3d3f12<commit_msg>69b64352-2fa5-11e5-a337-00012e3d3f12<commit_after>69b64352-2fa5-11e5-a337-00012e3d3f12<|endoftext|> |
<commit_before>a9fefb4f-2747-11e6-80cd-e0f84713e7b8<commit_msg>NO CHANGES<commit_after>aa11ab11-2747-11e6-8e3b-e0f84713e7b8<|endoftext|> |
<commit_before>#include <QApplication>
#include <QFontDatabase>
#include <QTextCodec>
#include "UI/Config/Config.h"
#include <QDialog>
#include "AppManager.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
#if (QT_VERSION <= QT_VERSION_CHECK(5,0,0))
QTextCodec *codec=QTextCodec::codecForName("UTF-8");
QTextCodec::setCodecForLocale(codec);
QTextCodec::setCodecForCStrings(codec);
QTextCodec::setCodecForTr(codec);
#endif
AppManager appManager;
QDialog diaStart;
diaStart.setGeometry(0,0,ui_res_width,ui_res_height);
diaStart.setStyleSheet("background-image:url(:/images/Screen.png);");
QObject::connect(&appManager,SIGNAL(finishMainHMI()),&diaStart, SLOT(accept()));
diaStart.exec();
appManager.ShowUI();
return a.exec();
}
<commit_msg>ford png<commit_after>#include <QApplication>
#include <QFontDatabase>
#include <QTextCodec>
#include "UI/Config/Config.h"
#include <QDialog>
#include "AppManager.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
#if (QT_VERSION <= QT_VERSION_CHECK(5,0,0))
QTextCodec *codec=QTextCodec::codecForName("UTF-8");
QTextCodec::setCodecForLocale(codec);
QTextCodec::setCodecForCStrings(codec);
QTextCodec::setCodecForTr(codec);
#endif
AppManager appManager;
QDialog diaStart;
diaStart.setGeometry(0,0,ui_res_width,ui_res_height);
diaStart.setStyleSheet("border-image:url(:/images/Screen.png);");
QObject::connect(&appManager,SIGNAL(finishMainHMI()),&diaStart, SLOT(accept()));
diaStart.exec();
appManager.ShowUI();
return a.exec();
}
<|endoftext|> |
<commit_before>// -*- Mode:C++; Coding:us-ascii-unix; fill-column:158 -*-
/*******************************************************************************************************************************************************.H.S.**/
/**
@file mandelbrot_period.cpp
@author Mitch Richling <https://www.mitchr.me>
@brief Produce several images related to the period/cycle structure of the Mandelbrot set.@EOL
@std C++20
@copyright
@parblock
Copyright (c) 1988-2015,2021 Mitchell Jay Richling <https://www.mitchr.me> All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
@endparblock
@filedetails
Produce several images related to the period/cycle structure of the Mandelbrot set:
- mandelbrot_periodCYC.tiff: Period -- i.e. the length of the cycle of the orbit.
- mandelbrot_periodSTB.tiff: Number of iterations required for the cycle to be apparent.
- mandelbrot_periodESC.tiff: For divergent points, the number of iterations required for |z|>2.
- mandelbrot_period.tiff: A composite, colorized image showing period and divergent points using a nice color scheme.
********************************************************************************************************************************************************.H.E.**/
/** @cond exj */
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
#include "ramCanvas.hpp"
typedef mjr::ramCanvas1c16b rc16;
typedef mjr::ramCanvas3c8b rc8;
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
int main(void) {
std::chrono::time_point<std::chrono::system_clock> startTime = std::chrono::system_clock::now();
rc8::colorType aColor;
const rc16::colorChanType NUMITR = 4096;
const int CSIZE = 7680/2;
const double MAXZSQ = 4.0;
rc8 theRamCanvas(CSIZE, CSIZE, -2.1, 0.75, -1.4, 1.4);
rc16 perRamCanvas(CSIZE, CSIZE, -2.1, 0.75, -1.4, 1.4); // Period -- 0 => not a periodic point
rc16 stbRamCanvas(CSIZE, CSIZE, -2.1, 0.75, -1.4, 1.4); // Number of iterations period structure was stable
rc16 escRamCanvas(CSIZE, CSIZE, -2.1, 0.75, 1.4, 1.4); // Iteration count for cases where |z|>2
#pragma omp parallel for schedule(static,1)
for(int y=0;y<perRamCanvas.getNumPixY();y++) {
for(int x=0;x<perRamCanvas.getNumPixX();x++) {
std::complex<double> c(perRamCanvas.int2realX(x), perRamCanvas.int2realY(y));
std::complex<double> z(0.0, 0.0);
std::vector<std::complex<double>> lastZs(NUMITR);
rc16::colorChanType count = 0;
while((std::norm(z)<MAXZSQ) && (count<NUMITR)) {
z=std::pow(z, 2) + c;
lastZs[count] = z;
count++;
}
if (count == NUMITR) { // Hit iteration limit
for(rc16::colorChanType period=1; period<(NUMITR-2); period++) {
if(std::abs(z-lastZs[NUMITR-1-period])<1e-4) {
perRamCanvas.drawPoint(x, y, period);
for(rc16::colorChanType stab=0; stab<(NUMITR-period); stab++) {
if(std::abs(lastZs[NUMITR-1-stab]-lastZs[NUMITR-1-period-stab])>1e-6) {
stbRamCanvas.drawPoint(x, y, NUMITR-stab);
break;
}
}
break;
}
}
} else { // Divergence detected because |z|>2
escRamCanvas.drawPoint(x, y, count);
}
}
std::cout << CSIZE << "/" << y << std::endl;
}
perRamCanvas.writeTIFFfile("mandelbrot_periodCYC.tiff");
stbRamCanvas.writeTIFFfile("mandelbrot_periodSTB.tiff");
escRamCanvas.writeTIFFfile("mandelbrot_periodOUT.tiff");
for(int y=0;y<theRamCanvas.getNumPixY();y++) {
for(int x=0;x<theRamCanvas.getNumPixX();x++) {
if (perRamCanvas.getPxColorNC(x, y).getC0() > 0) {
if (perRamCanvas.getPxColorNC(x, y).getC0() > (rc8::colorType::csFPcircular24::numC-1)) {
theRamCanvas.drawPoint(x, y, 255);
} else {
theRamCanvas.drawPoint(x, y, rc8::colorType::csFPcircular24::c(perRamCanvas.getPxColorNC(x, y).getC0()));
}
} else {
rc8::csFltType c = static_cast<rc8::csFltType>(escRamCanvas.getPxColorNC(x, y).getC0()) / NUMITR;
theRamCanvas.drawPoint(x, y, rc8::colorType::csCCdiag01::c(c*30));
}
}
}
theRamCanvas.writeTIFFfile("mandelbrot_period.tiff");
std::chrono::duration<double> runTime = std::chrono::system_clock::now() - startTime;
std::cout << "Total Runtime " << runTime.count() << " sec" << std::endl;
}
/** @endcond */
<commit_msg>Added period labels<commit_after>// -*- Mode:C++; Coding:us-ascii-unix; fill-column:158 -*-
/*******************************************************************************************************************************************************.H.S.**/
/**
@file mandelbrot_period.cpp
@author Mitch Richling <https://www.mitchr.me>
@brief Produce several images related to the period/cycle structure of the Mandelbrot set.@EOL
@std C++20
@copyright
@parblock
Copyright (c) 1988-2015,2021 Mitchell Jay Richling <https://www.mitchr.me> All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
@endparblock
@filedetails
Produce several images related to the period/cycle structure of the Mandelbrot set:
- mandelbrot_periodCYC.tiff: Period -- i.e. the length of the cycle of the orbit.
- mandelbrot_periodSTB.tiff: Number of iterations required for the cycle to be apparent.
- mandelbrot_periodESC.tiff: For divergent points, the number of iterations required for |z|>2.
- mandelbrot_period.tiff: A composite, colorized image showing period and divergent points using a nice color scheme.
********************************************************************************************************************************************************.H.E.**/
/** @cond exj */
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
#include "ramCanvas.hpp"
typedef mjr::ramCanvas1c16b rc16;
typedef mjr::ramCanvas3c8b rc8;
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
int main(void) {
std::chrono::time_point<std::chrono::system_clock> startTime = std::chrono::system_clock::now();
rc8::colorType aColor;
const rc16::colorChanType NUMITR = 4096;
const int CSIZE = 7680/2;
const double MAXZSQ = 4.0;
rc8 theRamCanvas(CSIZE, CSIZE, -2.1, 0.75, -1.4, 1.4);
rc16 perRamCanvas(CSIZE, CSIZE, -2.1, 0.75, -1.4, 1.4); // Period -- 0 => not a periodic point
rc16 stbRamCanvas(CSIZE, CSIZE, -2.1, 0.75, -1.4, 1.4); // Number of iterations period structure was stable
rc16 escRamCanvas(CSIZE, CSIZE, -2.1, 0.75, 1.4, 1.4); // Iteration count for cases where |z|>2
#pragma omp parallel for schedule(static,1)
for(int y=0;y<perRamCanvas.getNumPixY();y++) {
for(int x=0;x<perRamCanvas.getNumPixX();x++) {
std::complex<double> c(perRamCanvas.int2realX(x), perRamCanvas.int2realY(y));
std::complex<double> z(0.0, 0.0);
std::vector<std::complex<double>> lastZs(NUMITR);
rc16::colorChanType count = 0;
while((std::norm(z)<MAXZSQ) && (count<NUMITR)) {
z=std::pow(z, 2) + c;
lastZs[count] = z;
count++;
}
if (count == NUMITR) { // Hit iteration limit
for(rc16::colorChanType period=1; period<(NUMITR-2); period++) {
if(std::abs(z-lastZs[NUMITR-1-period])<1e-4) {
perRamCanvas.drawPoint(x, y, period);
for(rc16::colorChanType stab=0; stab<(NUMITR-period); stab++) {
if(std::abs(lastZs[NUMITR-1-stab]-lastZs[NUMITR-1-period-stab])>1e-6) {
stbRamCanvas.drawPoint(x, y, NUMITR-stab);
break;
}
}
break;
}
}
} else { // Divergence detected because |z|>2
escRamCanvas.drawPoint(x, y, count);
}
}
std::cout << CSIZE << "/" << y << std::endl;
}
perRamCanvas.writeTIFFfile("mandelbrot_periodCYC.tiff");
stbRamCanvas.writeTIFFfile("mandelbrot_periodSTB.tiff");
escRamCanvas.writeTIFFfile("mandelbrot_periodOUT.tiff");
for(int y=0;y<theRamCanvas.getNumPixY();y++) {
for(int x=0;x<theRamCanvas.getNumPixX();x++) {
if (perRamCanvas.getPxColorNC(x, y).getC0() > 0) {
if (perRamCanvas.getPxColorNC(x, y).getC0() > (rc8::colorType::csCBDark2::maxNumC-1)) {
theRamCanvas.drawPoint(x, y, 255);
} else {
theRamCanvas.drawPoint(x, y, rc8::colorType::csCBDark2::c(perRamCanvas.getPxColorNC(x, y).getC0()));
}
} else {
rc8::csFltType c = static_cast<rc8::csFltType>(escRamCanvas.getPxColorNC(x, y).getC0()) / NUMITR;
theRamCanvas.drawPoint(x, y, rc8::colorType::csCCdiag01::c(c*30));
}
}
}
theRamCanvas.drawString("1", mjr::hershey::font::ROMAN_SL_SANSERIF, -0.15, 0.00, "black", 3, 20);
theRamCanvas.drawString("2", mjr::hershey::font::ROMAN_SL_SANSERIF, -1.00, 0.00, "black", 3, 20);
theRamCanvas.drawString("3", mjr::hershey::font::ROMAN_SL_SANSERIF, -0.12, 0.74, "black", 3, 20);
theRamCanvas.drawString("3", mjr::hershey::font::ROMAN_SL_SANSERIF, -0.12, -0.74, "black", 3, 20);
theRamCanvas.drawString("4", mjr::hershey::font::ROMAN_SL_SANSERIF, -1.31, 0.00, "black", 3, 20);
theRamCanvas.drawString("4", mjr::hershey::font::ROMAN_SL_SANSERIF, 0.28, 0.53, "black", 3, 20);
theRamCanvas.drawString("4", mjr::hershey::font::ROMAN_SL_SANSERIF, 0.28, -0.53, "black", 3, 20);
theRamCanvas.writeTIFFfile("mandelbrot_period.tiff");
std::chrono::duration<double> runTime = std::chrono::system_clock::now() - startTime;
std::cout << "Total Runtime " << runTime.count() << " sec" << std::endl;
}
/** @endcond */
<|endoftext|> |
<commit_before>a68c7f45-2d3e-11e5-95cc-c82a142b6f9b<commit_msg>a6f51402-2d3e-11e5-82b1-c82a142b6f9b<commit_after>a6f51402-2d3e-11e5-82b1-c82a142b6f9b<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////////
// //
// main.cpp - (c) 2003 by The Marrowmoon Group //
// //
//////////////////////////////////////////////////////////////////////////////
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
//////////////////////////////////////////////////////////////////////////////
#include "world.h"
#include "scene.h"
#include "camera.h"
#include "animationcontroller.h"
#include "meshobjects.h"
#include "lights.h"
#include "transformations.h"
int TOGGLE_PAUSE = SDLK_SPACE;
int SCENE1 = SDLK_1;
int SCENE2 = SDLK_2;
int SCENE3 = SDLK_3;
int SCENE4 = SDLK_4;
int SCENE5 = SDLK_5;
int handle_key_down(SDL_keysym* keysym) {
if (keysym->sym == SDLK_ESCAPE) {
SDL_Quit();
exit(0);
}
return keysym->sym;
}
int process_events(void) {
SDL_Event event;
while(SDL_PollEvent(&event)) {
if (event.type == SDL_KEYDOWN)
return handle_key_down(&event.key.keysym);
if (event.type == SDL_QUIT) {
SDL_Quit();
exit(0);
}
}
return 0;
}
Scene* Scene1();
Scene* Scene2();
Scene* Scene3();
Scene* Scene4();
Scene* Scene5();
int main(int argc, char** argv) {
World MyWorld;
AnimationController MyAnimationController;
Scene* MyScene = Scene4();
// MyWorld.AddScene( MyScene );
int key;
while(1)
{
key = process_events();
if( key == TOGGLE_PAUSE ) MyScene->GetAnimationController()->TogglePause();
if( key == SCENE1 ){ delete MyScene; MyScene = Scene1(); }
if( key == SCENE2 ){ delete MyScene; MyScene = Scene2(); }
if( key == SCENE3 ){ delete MyScene; MyScene = Scene3(); }
if( key == SCENE4 ){ delete MyScene; MyScene = Scene4(); }
if( key == SCENE5 ){ delete MyScene; MyScene = Scene5(); }
MyScene->Render();
}
return 0;
}
Scene* Scene1(){
int XX = 50;
int YY = 50;
int ZZ = 50;
Scene *MyScene = new Scene;
Camera *MyCamera = new Camera;
MyScene->SetCamera( MyCamera );
AnimationController* MyAnimationController = MyScene->GetAnimationController();
MyCamera->AddTranslation(1, 2, 10);
Grid *grid = new Grid(500, 500, 100, 100);
grid->AddRotation(90, 1, 0, 0);
grid->SetMaterial(.1, .1, .1);
MyScene->AddWorldObject( grid );
// Sphere *sph2 = new Sphere(2, 10, 10);
// sph2->SetMaterial(1, 1, 1);
// MyScene->AddWorldObject( sph2 );
// sph2->AddTranslation( 10, 4, 0 );
Light* light1 = new PointLight(3, 3, 4);
light1->AddTranslation( 10, 4, 0 );
MyScene->AddWorldObject( light1 );
MeshObject* sph1;
AnimatedRotation *aniRot;
srand(0);
for( int i = 0; i < 30; i++ ){
// sph1 = new Cylinder(.5, .5, .7);
// sph1 = new Cube(.7, .7, .7);
sph1 = new Sphere( .5, 30, 30, GLU_FILL );
sph1->AddTranslation( rand()%XX / 10, rand()%YY / 10, rand()%ZZ / 10 );
sph1->SetMaterial(rand()%3/10.0, rand()%3/10.0, rand()%3/10.0);
aniRot = new AnimatedRotation( rand() % 360, (rand()%10/10.0)-.5, (rand()%10/10.0)-.5, (rand()%10/10.0)-.5, (rand() % 10 / 10.0)+.1 );
sph1->AddTransform( aniRot );
MyAnimationController->AddObject( aniRot );
MyScene->AddWorldObject( sph1 );
}
return MyScene;
}
Scene* Scene2(){
Scene *MyScene = new Scene;
Camera *MyCamera = new Camera;
MyScene->SetCamera( MyCamera );
MyCamera->AddTranslation( 0, 0, 10 );
return MyScene;
}
Scene* Scene3(){
Scene *MyScene = new Scene;
Camera *MyCamera = new Camera;
MyCamera->AddRotation(-20, 1, 0, 0);
MyCamera->AddTranslation(0, 20, 40);
Grid *grid = new Grid(100, 100, 100, 100);
grid->SetMaterial(.1, .1, .1);
MyScene->AddWorldObject( grid );
grid->AddRotation(90, 1, 0, 0);
grid->AddRotation(90, 0, 1, 0);
Sphere* sphere = new Sphere(4, 30, 30);
sphere->AddTranslation(0, 5, 0);
sphere->SetMaterial(.5, .5, .5);
MyScene->AddWorldObject( sphere );
AnimatedRotation *rot1 = new AnimatedRotation(0, 0, 1, 0, 1),
*rot2 = new AnimatedRotation(0, 0, 1, 0, 1);
MyScene->GetAnimationController()->AddObject( rot1 );
MyScene->GetAnimationController()->AddObject( rot2 );
Sphere* sphere2 = new Sphere(.5, 20, 20);
sphere2->SetMaterial(1, 1, 1);
MyScene->AddWorldObject( sphere2 );
sphere2->AddTranslation(0, 4, 7);
sphere2->AddTransform( rot1 );
Light *light1 = new SpotLight(40);
MyScene->AddWorldObject( light1 );
light1->AddTranslation(0, 4, 7);
light1->AddTransform( rot2 );
MyScene->SetCamera( MyCamera );
return MyScene;
}
Scene* Scene4(){
Scene *MyScene = new Scene;
Camera *MyCamera = new Camera;
// MyCamera->AddRotation(-20, 1, 0, 0);
// MyCamera->AddRotation(180, 0, 1, 0);
// MyCamera->AddTranslation(0, 20, -40);
srand(12);
int which;
MeshObject* mob;
AnimatedTranslation *AniTrans;
for( int i = 0; i < 20; i++ ){
//rings
AniTrans = new AnimatedTranslation(0, 0, 0, 0, 0, -300, .0006, i/20.0);
MyScene->GetAnimationController()->AddObject( AniTrans );
Disk *disk = new Disk(5, 5.3, 50, 2);
disk->AddTransform( AniTrans );
MyScene->AddWorldObject( disk );
disk->SetMaterial(.1, i%5/5.0+.2, .1);
}
for( int i = 0; i < 60; i++){
//flying objects
AniTrans = new AnimatedTranslation(0, 0, -300, rand()%50/10.0-2.5, rand()%50/10.0-2.5, 300, .0012, i/60.0);
MyScene->GetAnimationController()->AddObject( AniTrans );
which = rand() % 3;
if( which == 0 )
mob = new Sphere(rand()%4/4.0+.2);
else if( which == 1 )
mob = new Cylinder(.4, .4, rand()%10/10.0+.2);
else
mob = new Cube(rand()%10/10.0+.2, rand()%10/10.0+.2, rand()%10/10.0+.2);
mob->AddRotation(rand()%360, rand()%10/10.0, rand()%10/10.0, rand()%10/10.0);
MyScene->AddWorldObject( mob );
mob->AddTransform( AniTrans );
mob->SetMaterial(rand()%10/10.0+.2, rand()%10/10.0+.2, rand()%10/10.0+.2);
}
Grid *grid = new Grid(500, 500, 100, 100);
grid->AddRotation(90, 1, 0, 0);
grid->AddTranslation(0, -6, 0);
grid->SetMaterial(.1, .1, .1);
MyScene->AddWorldObject( grid );
Light *light1 = new PointLight;
MyScene->AddWorldObject( light1 );
light1->AddTranslation(5, 5, -2);
MyScene->SetCamera( MyCamera );
return MyScene;
}
Scene* Scene5(){
Scene *MyScene = new Scene;
Camera *MyCamera = new Camera;
MyScene->SetCamera( MyCamera );
return MyScene;
}
<commit_msg>Rename AddTransform to AddTransformation<commit_after>//////////////////////////////////////////////////////////////////////////////
// //
// main.cpp - (c) 2003 by The Marrowmoon Group //
// //
//////////////////////////////////////////////////////////////////////////////
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
//////////////////////////////////////////////////////////////////////////////
#include "world.h"
#include "scene.h"
#include "camera.h"
#include "animationcontroller.h"
#include "meshobjects.h"
#include "lights.h"
#include "transformations.h"
int TOGGLE_PAUSE = SDLK_SPACE;
int SCENE1 = SDLK_1;
int SCENE2 = SDLK_2;
int SCENE3 = SDLK_3;
int SCENE4 = SDLK_4;
int SCENE5 = SDLK_5;
int handle_key_down(SDL_keysym* keysym) {
if (keysym->sym == SDLK_ESCAPE) {
SDL_Quit();
exit(0);
}
return keysym->sym;
}
int process_events(void) {
SDL_Event event;
while(SDL_PollEvent(&event)) {
if (event.type == SDL_KEYDOWN)
return handle_key_down(&event.key.keysym);
if (event.type == SDL_QUIT) {
SDL_Quit();
exit(0);
}
}
return 0;
}
Scene* Scene1();
Scene* Scene2();
Scene* Scene3();
Scene* Scene4();
Scene* Scene5();
int main(int argc, char** argv) {
World MyWorld;
AnimationController MyAnimationController;
Scene* MyScene = Scene4();
// MyWorld.AddScene( MyScene );
int key;
while(1)
{
key = process_events();
if( key == TOGGLE_PAUSE ) MyScene->GetAnimationController()->TogglePause();
if( key == SCENE1 ){ delete MyScene; MyScene = Scene1(); }
if( key == SCENE2 ){ delete MyScene; MyScene = Scene2(); }
if( key == SCENE3 ){ delete MyScene; MyScene = Scene3(); }
if( key == SCENE4 ){ delete MyScene; MyScene = Scene4(); }
if( key == SCENE5 ){ delete MyScene; MyScene = Scene5(); }
MyScene->Render();
}
return 0;
}
Scene* Scene1(){
int XX = 50;
int YY = 50;
int ZZ = 50;
Scene *MyScene = new Scene;
Camera *MyCamera = new Camera;
MyScene->SetCamera( MyCamera );
AnimationController* MyAnimationController = MyScene->GetAnimationController();
MyCamera->AddTranslation(1, 2, 10);
Grid *grid = new Grid(500, 500, 100, 100);
grid->AddRotation(90, 1, 0, 0);
grid->SetMaterial(.1, .1, .1);
MyScene->AddWorldObject( grid );
// Sphere *sph2 = new Sphere(2, 10, 10);
// sph2->SetMaterial(1, 1, 1);
// MyScene->AddWorldObject( sph2 );
// sph2->AddTranslation( 10, 4, 0 );
Light* light1 = new PointLight(3, 3, 4);
light1->AddTranslation( 10, 4, 0 );
MyScene->AddWorldObject( light1 );
MeshObject* sph1;
AnimatedRotation *aniRot;
srand(0);
for( int i = 0; i < 30; i++ ){
// sph1 = new Cylinder(.5, .5, .7);
// sph1 = new Cube(.7, .7, .7);
sph1 = new Sphere( .5, 30, 30, GLU_FILL );
sph1->AddTranslation( rand()%XX / 10, rand()%YY / 10, rand()%ZZ / 10 );
sph1->SetMaterial(rand()%3/10.0, rand()%3/10.0, rand()%3/10.0);
aniRot = new AnimatedRotation( rand() % 360, (rand()%10/10.0)-.5, (rand()%10/10.0)-.5, (rand()%10/10.0)-.5, (rand() % 10 / 10.0)+.1 );
sph1->AddTransformation( aniRot );
MyAnimationController->AddObject( aniRot );
MyScene->AddWorldObject( sph1 );
}
return MyScene;
}
Scene* Scene2(){
Scene *MyScene = new Scene;
Camera *MyCamera = new Camera;
MyScene->SetCamera( MyCamera );
MyCamera->AddTranslation( 0, 0, 10 );
return MyScene;
}
Scene* Scene3(){
Scene *MyScene = new Scene;
Camera *MyCamera = new Camera;
MyCamera->AddRotation(-20, 1, 0, 0);
MyCamera->AddTranslation(0, 20, 40);
Grid *grid = new Grid(100, 100, 100, 100);
grid->SetMaterial(.1, .1, .1);
MyScene->AddWorldObject( grid );
grid->AddRotation(90, 1, 0, 0);
grid->AddRotation(90, 0, 1, 0);
Sphere* sphere = new Sphere(4, 30, 30);
sphere->AddTranslation(0, 5, 0);
sphere->SetMaterial(.5, .5, .5);
MyScene->AddWorldObject( sphere );
AnimatedRotation *rot1 = new AnimatedRotation(0, 0, 1, 0, 1),
*rot2 = new AnimatedRotation(0, 0, 1, 0, 1);
MyScene->GetAnimationController()->AddObject( rot1 );
MyScene->GetAnimationController()->AddObject( rot2 );
Sphere* sphere2 = new Sphere(.5, 20, 20);
sphere2->SetMaterial(1, 1, 1);
MyScene->AddWorldObject( sphere2 );
sphere2->AddTranslation(0, 4, 7);
sphere2->AddTransformation( rot1 );
Light *light1 = new SpotLight(40);
MyScene->AddWorldObject( light1 );
light1->AddTranslation(0, 4, 7);
light1->AddTransformation( rot2 );
MyScene->SetCamera( MyCamera );
return MyScene;
}
Scene* Scene4(){
Scene *MyScene = new Scene;
Camera *MyCamera = new Camera;
// MyCamera->AddRotation(-20, 1, 0, 0);
// MyCamera->AddRotation(180, 0, 1, 0);
// MyCamera->AddTranslation(0, 20, -40);
srand(12);
int which;
MeshObject* mob;
AnimatedTranslation *AniTrans;
for( int i = 0; i < 20; i++ ){
//rings
AniTrans = new AnimatedTranslation(0, 0, 0, 0, 0, -300, .0006, i/20.0);
MyScene->GetAnimationController()->AddObject( AniTrans );
Disk *disk = new Disk(5, 5.3, 50, 2);
disk->AddTransformation( AniTrans );
MyScene->AddWorldObject( disk );
disk->SetMaterial(.1, i%5/5.0+.2, .1);
}
for( int i = 0; i < 60; i++){
//flying objects
AniTrans = new AnimatedTranslation(0, 0, -300, rand()%50/10.0-2.5, rand()%50/10.0-2.5, 300, .0012, i/60.0);
MyScene->GetAnimationController()->AddObject( AniTrans );
which = rand() % 3;
if( which == 0 )
mob = new Sphere(rand()%4/4.0+.2);
else if( which == 1 )
mob = new Cylinder(.4, .4, rand()%10/10.0+.2);
else
mob = new Cube(rand()%10/10.0+.2, rand()%10/10.0+.2, rand()%10/10.0+.2);
mob->AddRotation(rand()%360, rand()%10/10.0, rand()%10/10.0, rand()%10/10.0);
MyScene->AddWorldObject( mob );
mob->AddTransformation( AniTrans );
mob->SetMaterial(rand()%10/10.0+.2, rand()%10/10.0+.2, rand()%10/10.0+.2);
}
Grid *grid = new Grid(500, 500, 100, 100);
grid->AddRotation(90, 1, 0, 0);
grid->AddTranslation(0, -6, 0);
grid->SetMaterial(.1, .1, .1);
MyScene->AddWorldObject( grid );
Light *light1 = new PointLight;
MyScene->AddWorldObject( light1 );
light1->AddTranslation(5, 5, -2);
MyScene->SetCamera( MyCamera );
return MyScene;
}
Scene* Scene5(){
Scene *MyScene = new Scene;
Camera *MyCamera = new Camera;
MyScene->SetCamera( MyCamera );
return MyScene;
}
<|endoftext|> |
<commit_before>8c3d2060-2d14-11e5-af21-0401358ea401<commit_msg>8c3d2061-2d14-11e5-af21-0401358ea401<commit_after>8c3d2061-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>#include "CMT.h"
#include "gui.h"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <fstream>
#include <cstdio>
#ifdef __GNUC__
#include <getopt.h>
#else
#include "getopt/getopt.h"
#endif
using cmt::CMT;
using cv::imread;
using cv::namedWindow;
using cv::Scalar;
using cv::VideoCapture;
using cv::waitKey;
using std::cerr;
using std::istream;
using std::ifstream;
using std::stringstream;
using std::ofstream;
using std::cout;
using std::min_element;
using std::max_element;
using std::endl;
using ::atof;
static string WIN_NAME = "CMT";
vector<float> getNextLineAndSplitIntoFloats(istream& str)
{
vector<float> result;
string line;
getline(str,line);
stringstream lineStream(line);
string cell;
while(getline(lineStream,cell,','))
{
result.push_back(atof(cell.c_str()));
}
return result;
}
int display(Mat im, CMT & cmt)
{
//Visualize the output
//It is ok to draw on im itself, as CMT only uses the grayscale image
for(size_t i = 0; i < cmt.points_active.size(); i++)
{
circle(im, cmt.points_active[i], 2, Scalar(255,0,0));
}
Point2f vertices[4];
cmt.bb_rot.points(vertices);
for (int i = 0; i < 4; i++)
{
line(im, vertices[i], vertices[(i+1)%4], Scalar(255,0,0));
}
imshow(WIN_NAME, im);
return waitKey(5);
}
int main(int argc, char **argv)
{
//Create a CMT object
CMT cmt;
//Initialization bounding box
Rect rect;
//Parse args
int challenge_flag = 0;
int loop_flag = 0;
int verbose_flag = 0;
int bbox_flag = 0;
string input_path;
const int detector_cmd = 1000;
const int descriptor_cmd = 1001;
const int bbox_cmd = 1002;
const int no_scale_cmd = 1003;
const int with_rotation_cmd = 1004;
struct option longopts[] =
{
//No-argument options
{"challenge", no_argument, &challenge_flag, 1},
{"loop", no_argument, &loop_flag, 1},
{"verbose", no_argument, &verbose_flag, 1},
{"no-scale", no_argument, 0, no_scale_cmd},
{"with-rotation", no_argument, 0, with_rotation_cmd},
//Argument options
{"bbox", required_argument, 0, bbox_cmd},
{"detector", required_argument, 0, detector_cmd},
{"descriptor", required_argument, 0, descriptor_cmd},
{0, 0, 0, 0}
};
int index = 0;
int c;
while((c = getopt_long(argc, argv, "v", longopts, &index)) != -1)
{
switch (c)
{
case 'v':
verbose_flag = true;
break;
case bbox_cmd:
{
//TODO: The following also accepts strings of the form %f,%f,%f,%fxyz...
string bbox_format = "%f,%f,%f,%f";
float x,y,w,h;
int ret = sscanf(optarg, bbox_format.c_str(), &x, &y, &w, &h);
if (ret != 4)
{
cerr << "bounding box must be given in format " << bbox_format << endl;
return 1;
}
bbox_flag = 1;
rect = Rect(x,y,w,h);
}
break;
case detector_cmd:
cmt.str_detector = optarg;
break;
case descriptor_cmd:
cmt.str_descriptor = optarg;
break;
case no_scale_cmd:
cmt.consensus.estimate_scale = false;
break;
case with_rotation_cmd:
cmt.consensus.estimate_rotation = true;
break;
case '?':
return 1;
}
}
//One argument remains
if (optind == argc - 1)
{
input_path = argv[optind];
}
else if (optind < argc - 1)
{
cerr << "Only one argument is allowed." << endl;
return 1;
}
//Set up logging
FILELog::ReportingLevel() = verbose_flag ? logDEBUG : logINFO;
Output2FILE::Stream() = stdout; //Log to stdout
//Challenge mode
if (challenge_flag)
{
//Read list of images
ifstream im_file("images.txt");
vector<string> files;
string line;
while(getline(im_file, line ))
{
files.push_back(line);
}
//Read region
ifstream region_file("region.txt");
vector<float> coords = getNextLineAndSplitIntoFloats(region_file);
if (coords.size() == 4) {
rect = Rect(coords[0], coords[1], coords[2], coords[3]);
}
else if (coords.size() == 8)
{
//Split into x and y coordinates
vector<float> xcoords;
vector<float> ycoords;
for (size_t i = 0; i < coords.size(); i++)
{
if (i % 2 == 0) xcoords.push_back(coords[i]);
else ycoords.push_back(coords[i]);
}
float xmin = *min_element(xcoords.begin(), xcoords.end());
float xmax = *max_element(xcoords.begin(), xcoords.end());
float ymin = *min_element(ycoords.begin(), ycoords.end());
float ymax = *max_element(ycoords.begin(), ycoords.end());
rect = Rect(xmin, ymin, xmax-xmin, ymax-ymin);
cout << "Found bounding box" << xmin << " " << ymin << " " << xmax-xmin << " " << ymax-ymin << endl;
}
else {
cerr << "Invalid Bounding box format" << endl;
return 0;
}
//Read first image
Mat im0 = imread(files[0]);
Mat im0_gray;
cvtColor(im0, im0_gray, CV_BGR2GRAY);
//Initialize cmt
cmt.initialize(im0_gray, rect);
//Write init region to output file
ofstream output_file("output.txt");
output_file << rect.x << ',' << rect.y << ',' << rect.width << ',' << rect.height << std::endl;
//Process images, write output to file
for (size_t i = 1; i < files.size(); i++)
{
FILE_LOG(logINFO) << "Processing frame " << i << "/" << files.size();
Mat im = imread(files[i]);
Mat im_gray;
cvtColor(im, im_gray, CV_BGR2GRAY);
cmt.processFrame(im_gray);
if (verbose_flag)
{
display(im, cmt);
}
rect = cmt.bb_rot.boundingRect();
output_file << rect.x << ',' << rect.y << ',' << rect.width << ',' << rect.height << std::endl;
}
output_file.close();
return 0;
}
//Normal mode
//Create window
namedWindow(WIN_NAME);
VideoCapture cap;
bool show_preview = true;
//If no input was specified
if (input_path.length() == 0)
{
cap.open(0); //Open default camera device
}
//Else open the video specified by input_path
else
{
cap.open(input_path);
show_preview = false;
}
//If it doesn't work, stop
if(!cap.isOpened())
{
cerr << "Unable to open video capture." << endl;
return -1;
}
//Show preview until key is pressed
while (show_preview)
{
Mat preview;
cap >> preview;
screenLog(preview, "Press a key to start selecting an object.");
imshow(WIN_NAME, preview);
char k = waitKey(10);
if (k != -1) {
show_preview = false;
}
}
//Get initial image
Mat im0;
cap >> im0;
//If no bounding was specified, get it from user
if (!bbox_flag)
{
rect = getRect(im0, WIN_NAME);
}
FILE_LOG(logINFO) << "Using " << rect.x << "," << rect.y << "," << rect.width << "," << rect.height
<< " as initial bounding box.";
//Convert im0 to grayscale
Mat im0_gray;
if (im0.channels() > 1) {
cvtColor(im0, im0_gray, CV_BGR2GRAY);
} else {
im0_gray = im0;
}
//Initialize CMT
cmt.initialize(im0_gray, rect);
int frame = 0;
//Main loop
while (true)
{
frame++;
Mat im;
//If loop flag is set, reuse initial image (for debugging purposes)
if (loop_flag) im0.copyTo(im);
else cap >> im; //Else use next image in stream
if (im.empty()) break; //Exit at end of video stream
Mat im_gray;
if (im.channels() > 1) {
cvtColor(im, im_gray, CV_BGR2GRAY);
} else {
im_gray = im;
}
//Let CMT process the frame
cmt.processFrame(im_gray);
char key = display(im, cmt);
if(key == 'q') break;
//TODO: Provide meaningful output
FILE_LOG(logINFO) << "#" << frame << " active: " << cmt.points_active.size();
}
return 0;
}
<commit_msg>Skip frames at the start of a video file.<commit_after>#include "CMT.h"
#include "gui.h"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <fstream>
#include <cstdio>
#ifdef __GNUC__
#include <getopt.h>
#else
#include "getopt/getopt.h"
#endif
using cmt::CMT;
using cv::imread;
using cv::namedWindow;
using cv::Scalar;
using cv::VideoCapture;
using cv::waitKey;
using std::cerr;
using std::istream;
using std::ifstream;
using std::stringstream;
using std::ofstream;
using std::cout;
using std::min_element;
using std::max_element;
using std::endl;
using ::atof;
static string WIN_NAME = "CMT";
vector<float> getNextLineAndSplitIntoFloats(istream& str)
{
vector<float> result;
string line;
getline(str,line);
stringstream lineStream(line);
string cell;
while(getline(lineStream,cell,','))
{
result.push_back(atof(cell.c_str()));
}
return result;
}
int display(Mat im, CMT & cmt)
{
//Visualize the output
//It is ok to draw on im itself, as CMT only uses the grayscale image
for(size_t i = 0; i < cmt.points_active.size(); i++)
{
circle(im, cmt.points_active[i], 2, Scalar(255,0,0));
}
Point2f vertices[4];
cmt.bb_rot.points(vertices);
for (int i = 0; i < 4; i++)
{
line(im, vertices[i], vertices[(i+1)%4], Scalar(255,0,0));
}
imshow(WIN_NAME, im);
return waitKey(5);
}
int main(int argc, char **argv)
{
//Create a CMT object
CMT cmt;
//Initialization bounding box
Rect rect;
//Parse args
int challenge_flag = 0;
int loop_flag = 0;
int verbose_flag = 0;
int bbox_flag = 0;
int skip_frames = 0;
string input_path;
const int detector_cmd = 1000;
const int descriptor_cmd = 1001;
const int bbox_cmd = 1002;
const int no_scale_cmd = 1003;
const int with_rotation_cmd = 1004;
const int skip_cmd = 1005;
struct option longopts[] =
{
//No-argument options
{"challenge", no_argument, &challenge_flag, 1},
{"loop", no_argument, &loop_flag, 1},
{"verbose", no_argument, &verbose_flag, 1},
{"no-scale", no_argument, 0, no_scale_cmd},
{"with-rotation", no_argument, 0, with_rotation_cmd},
//Argument options
{"bbox", required_argument, 0, bbox_cmd},
{"detector", required_argument, 0, detector_cmd},
{"descriptor", required_argument, 0, descriptor_cmd},
{"skip", required_argument, 0, skip_cmd},
{0, 0, 0, 0}
};
int index = 0;
int c;
while((c = getopt_long(argc, argv, "v", longopts, &index)) != -1)
{
switch (c)
{
case 'v':
verbose_flag = true;
break;
case bbox_cmd:
{
//TODO: The following also accepts strings of the form %f,%f,%f,%fxyz...
string bbox_format = "%f,%f,%f,%f";
float x,y,w,h;
int ret = sscanf(optarg, bbox_format.c_str(), &x, &y, &w, &h);
if (ret != 4)
{
cerr << "bounding box must be given in format " << bbox_format << endl;
return 1;
}
bbox_flag = 1;
rect = Rect(x,y,w,h);
}
break;
case detector_cmd:
cmt.str_detector = optarg;
break;
case descriptor_cmd:
cmt.str_descriptor = optarg;
break;
case skip_cmd:
{
int ret = sscanf(optarg, "%d", &skip_frames);
if (ret != 1)
{
skip_frames = 0;
}
}
break;
case no_scale_cmd:
cmt.consensus.estimate_scale = false;
break;
case with_rotation_cmd:
cmt.consensus.estimate_rotation = true;
break;
case '?':
return 1;
}
}
//One argument remains
if (optind == argc - 1)
{
input_path = argv[optind];
}
else if (optind < argc - 1)
{
cerr << "Only one argument is allowed." << endl;
return 1;
}
//Set up logging
FILELog::ReportingLevel() = verbose_flag ? logDEBUG : logINFO;
Output2FILE::Stream() = stdout; //Log to stdout
//Challenge mode
if (challenge_flag)
{
//Read list of images
ifstream im_file("images.txt");
vector<string> files;
string line;
while(getline(im_file, line ))
{
files.push_back(line);
}
//Read region
ifstream region_file("region.txt");
vector<float> coords = getNextLineAndSplitIntoFloats(region_file);
if (coords.size() == 4) {
rect = Rect(coords[0], coords[1], coords[2], coords[3]);
}
else if (coords.size() == 8)
{
//Split into x and y coordinates
vector<float> xcoords;
vector<float> ycoords;
for (size_t i = 0; i < coords.size(); i++)
{
if (i % 2 == 0) xcoords.push_back(coords[i]);
else ycoords.push_back(coords[i]);
}
float xmin = *min_element(xcoords.begin(), xcoords.end());
float xmax = *max_element(xcoords.begin(), xcoords.end());
float ymin = *min_element(ycoords.begin(), ycoords.end());
float ymax = *max_element(ycoords.begin(), ycoords.end());
rect = Rect(xmin, ymin, xmax-xmin, ymax-ymin);
cout << "Found bounding box" << xmin << " " << ymin << " " << xmax-xmin << " " << ymax-ymin << endl;
}
else {
cerr << "Invalid Bounding box format" << endl;
return 0;
}
//Read first image
Mat im0 = imread(files[0]);
Mat im0_gray;
cvtColor(im0, im0_gray, CV_BGR2GRAY);
//Initialize cmt
cmt.initialize(im0_gray, rect);
//Write init region to output file
ofstream output_file("output.txt");
output_file << rect.x << ',' << rect.y << ',' << rect.width << ',' << rect.height << std::endl;
//Process images, write output to file
for (size_t i = 1; i < files.size(); i++)
{
FILE_LOG(logINFO) << "Processing frame " << i << "/" << files.size();
Mat im = imread(files[i]);
Mat im_gray;
cvtColor(im, im_gray, CV_BGR2GRAY);
cmt.processFrame(im_gray);
if (verbose_flag)
{
display(im, cmt);
}
rect = cmt.bb_rot.boundingRect();
output_file << rect.x << ',' << rect.y << ',' << rect.width << ',' << rect.height << std::endl;
}
output_file.close();
return 0;
}
//Normal mode
//Create window
namedWindow(WIN_NAME);
VideoCapture cap;
bool show_preview = true;
//If no input was specified
if (input_path.length() == 0)
{
cap.open(0); //Open default camera device
}
//Else open the video specified by input_path
else
{
cap.open(input_path);
if (skip_frames > 0)
{
cap.set(CV_CAP_PROP_POS_FRAMES, skip_frames);
}
show_preview = false;
}
//If it doesn't work, stop
if(!cap.isOpened())
{
cerr << "Unable to open video capture." << endl;
return -1;
}
//Show preview until key is pressed
while (show_preview)
{
Mat preview;
cap >> preview;
screenLog(preview, "Press a key to start selecting an object.");
imshow(WIN_NAME, preview);
char k = waitKey(10);
if (k != -1) {
show_preview = false;
}
}
//Get initial image
Mat im0;
cap >> im0;
//If no bounding was specified, get it from user
if (!bbox_flag)
{
rect = getRect(im0, WIN_NAME);
}
FILE_LOG(logINFO) << "Using " << rect.x << "," << rect.y << "," << rect.width << "," << rect.height
<< " as initial bounding box.";
//Convert im0 to grayscale
Mat im0_gray;
if (im0.channels() > 1) {
cvtColor(im0, im0_gray, CV_BGR2GRAY);
} else {
im0_gray = im0;
}
//Initialize CMT
cmt.initialize(im0_gray, rect);
int frame = 0;
//Main loop
while (true)
{
frame++;
Mat im;
//If loop flag is set, reuse initial image (for debugging purposes)
if (loop_flag) im0.copyTo(im);
else cap >> im; //Else use next image in stream
if (im.empty()) break; //Exit at end of video stream
Mat im_gray;
if (im.channels() > 1) {
cvtColor(im, im_gray, CV_BGR2GRAY);
} else {
im_gray = im;
}
//Let CMT process the frame
cmt.processFrame(im_gray);
char key = display(im, cmt);
if(key == 'q') break;
//TODO: Provide meaningful output
FILE_LOG(logINFO) << "#" << frame << " active: " << cmt.points_active.size();
}
return 0;
}
<|endoftext|> |
<commit_before>4d492310-5216-11e5-aa8b-6c40088e03e4<commit_msg>4d508862-5216-11e5-a746-6c40088e03e4<commit_after>4d508862-5216-11e5-a746-6c40088e03e4<|endoftext|> |
<commit_before>/* OpenSceneGraph example, osgshape.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Material>
#include <osg/Texture2D>
#include <osgViewer/Viewer>
#include <osgDB/ReadFile>
#include <osg/Math>
// for the grid data..
#include "../osghangglide/terrain_coords.h"
osg::Geode* createShapes()
{
osg::Geode* geode = new osg::Geode();
// ---------------------------------------
// Set up a StateSet to texture the objects
// ---------------------------------------
osg::StateSet* stateset = new osg::StateSet();
osg::Image* image = osgDB::readImageFile( "Images/lz.rgb" );
if (image)
{
osg::Texture2D* texture = new osg::Texture2D;
texture->setImage(image);
stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
}
geode->setStateSet( stateset );
float radius = 0.8f;
float height = 1.0f;
osg::TessellationHints* hints = new osg::TessellationHints;
hints->setDetailRatio(0.5f);
geode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0.0f,0.0f,0.0f),radius),hints));
geode->addDrawable(new osg::ShapeDrawable(new osg::Box(osg::Vec3(2.0f,0.0f,0.0f),2*radius),hints));
geode->addDrawable(new osg::ShapeDrawable(new osg::Cone(osg::Vec3(4.0f,0.0f,0.0f),radius,height),hints));
geode->addDrawable(new osg::ShapeDrawable(new osg::Cylinder(osg::Vec3(6.0f,0.0f,0.0f),radius,height),hints));
geode->addDrawable(new osg::ShapeDrawable(new osg::Capsule(osg::Vec3(8.0f,0.0f,0.0f),radius,height),hints));
osg::HeightField* grid = new osg::HeightField;
grid->allocate(38,39);
grid->setXInterval(0.28f);
grid->setYInterval(0.28f);
for(unsigned int r=0;r<39;++r)
{
for(unsigned int c=0;c<38;++c)
{
grid->setHeight(c,r,vertex[r+c*39][2]);
}
}
geode->addDrawable(new osg::ShapeDrawable(grid));
osg::ConvexHull* mesh = new osg::ConvexHull;
osg::Vec3Array* vertices = new osg::Vec3Array(4);
(*vertices)[0].set(9.0+0.0f,-1.0f+2.0f,-1.0f+0.0f);
(*vertices)[1].set(9.0+1.0f,-1.0f+0.0f,-1.0f+0.0f);
(*vertices)[2].set(9.0+2.0f,-1.0f+2.0f,-1.0f+0.0f);
(*vertices)[3].set(9.0+1.0f,-1.0f+1.0f,-1.0f+2.0f);
osg::UByteArray* indices = new osg::UByteArray(12);
(*indices)[0]=0;
(*indices)[1]=2;
(*indices)[2]=1;
(*indices)[3]=0;
(*indices)[4]=1;
(*indices)[5]=3;
(*indices)[6]=1;
(*indices)[7]=2;
(*indices)[8]=3;
(*indices)[9]=2;
(*indices)[10]=0;
(*indices)[11]=3;
mesh->setVertices(vertices);
mesh->setIndices(indices);
geode->addDrawable(new osg::ShapeDrawable(mesh));
return geode;
}
int main(int, char **)
{
// construct the viewer.
osgViewer::Viewer viewer;
// add model to viewer.
viewer.setSceneData( createShapes() );
return viewer.run();
}
<commit_msg>Added enabling of lighting, and disabling of mipmapping to help out testing of GLES2 target<commit_after>/* OpenSceneGraph example, osgshape.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Material>
#include <osg/Texture2D>
#include <osgUtil/ShaderGen>
#include <osgViewer/Viewer>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osg/Math>
// for the grid data..
#include "../osghangglide/terrain_coords.h"
osg::Geode* createShapes()
{
osg::Geode* geode = new osg::Geode();
// ---------------------------------------
// Set up a StateSet to texture the objects
// ---------------------------------------
osg::StateSet* stateset = new osg::StateSet();
osg::Image* image = osgDB::readImageFile( "Images/lz.rgb" );
if (image)
{
osg::Texture2D* texture = new osg::Texture2D;
texture->setImage(image);
texture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
stateset->setTextureAttributeAndModes(0,texture, osg::StateAttribute::ON);
}
stateset->setMode(GL_LIGHTING, osg::StateAttribute::ON);
geode->setStateSet( stateset );
float radius = 0.8f;
float height = 1.0f;
osg::TessellationHints* hints = new osg::TessellationHints;
hints->setDetailRatio(0.5f);
geode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0.0f,0.0f,0.0f),radius),hints));
geode->addDrawable(new osg::ShapeDrawable(new osg::Box(osg::Vec3(2.0f,0.0f,0.0f),2*radius),hints));
geode->addDrawable(new osg::ShapeDrawable(new osg::Cone(osg::Vec3(4.0f,0.0f,0.0f),radius,height),hints));
geode->addDrawable(new osg::ShapeDrawable(new osg::Cylinder(osg::Vec3(6.0f,0.0f,0.0f),radius,height),hints));
geode->addDrawable(new osg::ShapeDrawable(new osg::Capsule(osg::Vec3(8.0f,0.0f,0.0f),radius,height),hints));
osg::HeightField* grid = new osg::HeightField;
grid->allocate(38,39);
grid->setXInterval(0.28f);
grid->setYInterval(0.28f);
for(unsigned int r=0;r<39;++r)
{
for(unsigned int c=0;c<38;++c)
{
grid->setHeight(c,r,vertex[r+c*39][2]);
}
}
geode->addDrawable(new osg::ShapeDrawable(grid));
osg::ConvexHull* mesh = new osg::ConvexHull;
osg::Vec3Array* vertices = new osg::Vec3Array(4);
(*vertices)[0].set(9.0+0.0f,-1.0f+2.0f,-1.0f+0.0f);
(*vertices)[1].set(9.0+1.0f,-1.0f+0.0f,-1.0f+0.0f);
(*vertices)[2].set(9.0+2.0f,-1.0f+2.0f,-1.0f+0.0f);
(*vertices)[3].set(9.0+1.0f,-1.0f+1.0f,-1.0f+2.0f);
osg::UByteArray* indices = new osg::UByteArray(12);
(*indices)[0]=0;
(*indices)[1]=2;
(*indices)[2]=1;
(*indices)[3]=0;
(*indices)[4]=1;
(*indices)[5]=3;
(*indices)[6]=1;
(*indices)[7]=2;
(*indices)[8]=3;
(*indices)[9]=2;
(*indices)[10]=0;
(*indices)[11]=3;
mesh->setVertices(vertices);
mesh->setIndices(indices);
geode->addDrawable(new osg::ShapeDrawable(mesh));
return geode;
}
int main(int, char **)
{
// construct the viewer.
osgViewer::Viewer viewer;
// add model to viewer.
viewer.setSceneData( createShapes() );
return viewer.run();
}
<|endoftext|> |
<commit_before>1f84f350-2e3a-11e5-9e86-c03896053bdd<commit_msg>1f91edf6-2e3a-11e5-8dff-c03896053bdd<commit_after>1f91edf6-2e3a-11e5-8dff-c03896053bdd<|endoftext|> |
<commit_before><commit_msg>DependencyGraph: Ensure OriginFeatures get in the correct subgraph<commit_after><|endoftext|> |
<commit_before>8da71d9e-35ca-11e5-9751-6c40088e03e4<commit_msg>8dad6d22-35ca-11e5-8a94-6c40088e03e4<commit_after>8dad6d22-35ca-11e5-8a94-6c40088e03e4<|endoftext|> |
<commit_before>48358a92-5216-11e5-8a14-6c40088e03e4<commit_msg>483f51d2-5216-11e5-9bc3-6c40088e03e4<commit_after>483f51d2-5216-11e5-9bc3-6c40088e03e4<|endoftext|> |
<commit_before>#include <algorithm>
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
#include <regex>
#include <curl/curl.h>
#include <openssl/hmac.h>
#include <openssl/bio.h>
#include <json/json.h>
using std::string;
using std::cout;
using std::endl;
using std::strcpy;
using std::getline;
using std::ifstream;
using std::regex;
using std::regex_replace;
struct attribs {
string key, value;
attribs() {}
attribs(string k, string v) {
key = k;
value = v;
}
bool operator<(const attribs &other) const {
if (key == other.key) {
return value < other.value;
}
return key < other.key;
}
string to_string() { return key + "=" + value; }
};
const char ASCII_TABLE[67] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
string find_and_replace(string &s, const string &to_replace, const string &replace_with) {
return s.replace(s.find(to_replace), to_replace.length(), replace_with);
}
string gen_alphanum(int len) {
string buff;
std::srand(time(0));
for (int i = 0; i < len; i++) {
buff += ASCII_TABLE[std::rand() % 62];
}
return buff;
}
unsigned char *hmac_sha1(unsigned char *key, unsigned char *data, int key_size, int data_size) {
unsigned char *digest = HMAC(EVP_sha1(), key, key_size, data, data_size, NULL, NULL);
return digest;
}
string base64(unsigned char *data, int data_size) {
BIO *b64, *bmem;
char *buff;
b64 = BIO_new(BIO_f_base64()); // BIO to perform b64 encode
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); // No newlines in data
bmem = BIO_new(BIO_s_mem()); // BIO to hold result
BIO_push(b64, bmem); // Chains b64 to bmem
BIO_write(b64, data, data_size + 1);
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
long len = BIO_get_mem_data(bmem, &buff);
string ret = string(buff, len - 1);
while (ret.size() < (unsigned long)len) {
ret += "=";
}
BIO_free_all(b64);
return ret;
}
int twitter_lookup(string &username, string &url, string &outfile) {
attribs app_info[8] = {attribs("screen_name", username),
attribs("oauth_consumer_key", ""),
attribs("oauth_nonce", gen_alphanum(42)),
attribs("oauth_signature_method", "HMAC-SHA1"),
attribs("oauth_timestamp", std::to_string(time(0))),
attribs("oauth_token", ""),
attribs("oauth_version", "1.0"),
attribs("oauth_signature", "")};
string secrets[2], line;
ifstream infile;
infile.open("twitter.conf", std::ios::app);
while (getline(infile, line)) {
if (line.find("ckey") != string::npos) {
find_and_replace(line, "ckey=", "");
app_info[1].value = line;
} else if (line.find("csecret") != string::npos) {
find_and_replace(line, "csecret=", "");
secrets[0] = line;
} else if (line.find("atoken") != string::npos) {
find_and_replace(line, "atoken=", "");
app_info[5].value = line;
} else if (line.find("asecret") != string::npos) {
find_and_replace(line, "asecret=", "");
secrets[1] = line;
} else {
continue;
}
}
attribs encode_info[7];
CURL *curl = curl_easy_init();
char *temp0;
for (int i = 0; i < 7; i++) {
temp0 = curl_easy_escape(curl, app_info[i].key.c_str(), app_info[i].key.size());
encode_info[i] = attribs(string(temp0), "");
curl_free(temp0);
temp0 = curl_easy_escape(curl, app_info[i].value.c_str(), app_info[i].value.size());
encode_info[i].value = string(temp0);
curl_free(temp0);
}
std::sort(encode_info, encode_info + 7);
string out = encode_info[0].to_string();
for (int i = 1; i < 7; i++) {
out += "&" + encode_info[i].to_string();
}
temp0 = curl_easy_escape(curl, url.c_str(), url.size());
char *temp1 = curl_easy_escape(curl, out.c_str(), out.size());
out = "GET&" + string(temp0) + "&" + string(temp1);
curl_free(temp0);
curl_free(temp1);
temp0 = curl_easy_escape(curl, secrets[0].c_str(), secrets[0].size());
temp1 = curl_easy_escape(curl, secrets[1].c_str(), secrets[1].size());
string sign_key = string(temp0) + "&" + string(temp1);
curl_free(temp0);
curl_free(temp1);
unsigned char *sha1hash = hmac_sha1((unsigned char *)sign_key.c_str(),
(unsigned char *)out.c_str(), sign_key.size(), out.size());
app_info[7].value = base64(sha1hash, 20);
temp0 = curl_easy_escape(curl, app_info[7].value.c_str(), app_info[7].value.size());
app_info[7].value = string(temp0);
curl_free(temp0);
string command =
"curl --get \'" + url + "\' --data \'screen_name=" + app_info[0].value +
"\' --header \'Authorization: OAuth oauth_consumer_key=\"" + app_info[1].value +
"\", oauth_nonce=\"" + app_info[2].value + "\", oauth_signature=\"" + app_info[7].value +
"\", oauth_signature_method=\"" + app_info[3].value + "\", oauth_timestamp=\"" +
app_info[4].value + "\", oauth_token=\"" + app_info[5].value + "\", oauth_version=\"" +
app_info[6].value + "\"\' --silent >" + outfile;
std::system(command.c_str());
curl_easy_cleanup(curl);
infile.open(outfile.c_str(), std::ios::app);
getline(infile, line);
if (line.find("Bad Authentication Data") != string::npos) {
return 0;
}
return 1;
}
string parse_json(Json::Value &root, string &key) {
const Json::Value value = root[0][key];
Json::FastWriter convert;
return convert.write(value);
}
std::vector<string> get_follower_locations(Json::Value &root) {
Json::FastWriter convert;
std::vector<string> ret;
const Json::Value array = root["users"];
string buff;
for (unsigned int i = 0; i < array.size(); i++) {
buff = convert.write(array[i]["location"]);
ret.push_back(buff.substr(1, buff.size() - 3));
}
return ret;
}
int main() {
string username;
cout << "Enter Twitter Username: ";
getline(std::cin, username);
string outfile = "lookup.json", url = "https://api.twitter.com/1.1/users/lookup.json";
if (twitter_lookup(username, url, outfile)) {
Json::Value user_root;
ifstream stream;
stream.open(outfile, ifstream::binary);
stream >> user_root;
string query = "location";
string location = parse_json(user_root, query);
location = location.substr(1, location.size() - 3);
query = "time_zone";
string timezone = parse_json(user_root, query);
timezone = timezone.substr(1, timezone.size() - 3);
cout << endl;
if (location == "" || location == "ul") {
cout << "Unknown based on location parameter." << endl;
} else {
cout << "Known location: " + location << endl;
return 0;
}
if (timezone == "" || timezone == "ul") {
cout << "Unknown based on timezone parameter." << endl;
} else {
cout << "Known timezone: " + timezone << endl;
}
stream.close();
outfile = "list.json";
url = "https://api.twitter.com/1.1/friends/list.json";
if (twitter_lookup(username, url, outfile)) {
Json::Value follower_root;
stream.open(outfile, ifstream::binary);
stream >> follower_root;
stream.close();
std::vector<string> buff = get_follower_locations(follower_root);
if (buff.size() != 0) {
cout << "Possible locations based on friends:" << endl;
for (int i = 0; i < (int)buff.size(); i++) {
if (buff.at(i) == "") {
buff.erase(buff.begin() + i);
} else {
regex blacklist("([^\u00C0-\u017F\\w\\d\\s,-.])");
string out = regex_replace(buff.at(i), blacklist, "");
cout << out << endl;
}
}
}
return 0;
}
return 1;
}
}
<commit_msg>Fix duplicate outputs<commit_after>#include <algorithm>
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
#include <regex>
#include <curl/curl.h>
#include <openssl/hmac.h>
#include <openssl/bio.h>
#include <json/json.h>
using std::string;
using std::cout;
using std::endl;
using std::strcpy;
using std::getline;
using std::ifstream;
using std::regex;
using std::regex_replace;
struct attribs {
string key, value;
attribs() {}
attribs(string k, string v) {
key = k;
value = v;
}
bool operator<(const attribs &other) const {
if (key == other.key) {
return value < other.value;
}
return key < other.key;
}
string to_string() { return key + "=" + value; }
};
const char ASCII_TABLE[67] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
string find_and_replace(string &s, const string &to_replace, const string &replace_with) {
return s.replace(s.find(to_replace), to_replace.length(), replace_with);
}
string gen_alphanum(int len) {
string buff;
std::srand(time(0));
for (int i = 0; i < len; i++) {
buff += ASCII_TABLE[std::rand() % 62];
}
return buff;
}
unsigned char *hmac_sha1(unsigned char *key, unsigned char *data, int key_size, int data_size) {
unsigned char *digest = HMAC(EVP_sha1(), key, key_size, data, data_size, NULL, NULL);
return digest;
}
string base64(unsigned char *data, int data_size) {
BIO *b64, *bmem;
char *buff;
b64 = BIO_new(BIO_f_base64()); // BIO to perform b64 encode
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); // No newlines in data
bmem = BIO_new(BIO_s_mem()); // BIO to hold result
BIO_push(b64, bmem); // Chains b64 to bmem
BIO_write(b64, data, data_size + 1);
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
long len = BIO_get_mem_data(bmem, &buff);
string ret = string(buff, len - 1);
while (ret.size() < (unsigned long)len) {
ret += "=";
}
BIO_free_all(b64);
return ret;
}
int twitter_lookup(string &username, string &url, string &outfile) {
attribs app_info[8] = {attribs("screen_name", username),
attribs("oauth_consumer_key", ""),
attribs("oauth_nonce", gen_alphanum(42)),
attribs("oauth_signature_method", "HMAC-SHA1"),
attribs("oauth_timestamp", std::to_string(time(0))),
attribs("oauth_token", ""),
attribs("oauth_version", "1.0"),
attribs("oauth_signature", "")};
string secrets[2], line;
ifstream infile;
infile.open("twitter.conf", std::ios::app);
while (getline(infile, line)) {
if (line.find("ckey") != string::npos) {
find_and_replace(line, "ckey=", "");
app_info[1].value = line;
} else if (line.find("csecret") != string::npos) {
find_and_replace(line, "csecret=", "");
secrets[0] = line;
} else if (line.find("atoken") != string::npos) {
find_and_replace(line, "atoken=", "");
app_info[5].value = line;
} else if (line.find("asecret") != string::npos) {
find_and_replace(line, "asecret=", "");
secrets[1] = line;
} else {
continue;
}
}
attribs encode_info[7];
CURL *curl = curl_easy_init();
char *temp0;
for (int i = 0; i < 7; i++) {
temp0 = curl_easy_escape(curl, app_info[i].key.c_str(), app_info[i].key.size());
encode_info[i] = attribs(string(temp0), "");
curl_free(temp0);
temp0 = curl_easy_escape(curl, app_info[i].value.c_str(), app_info[i].value.size());
encode_info[i].value = string(temp0);
curl_free(temp0);
}
std::sort(encode_info, encode_info + 7);
string out = encode_info[0].to_string();
for (int i = 1; i < 7; i++) {
out += "&" + encode_info[i].to_string();
}
temp0 = curl_easy_escape(curl, url.c_str(), url.size());
char *temp1 = curl_easy_escape(curl, out.c_str(), out.size());
out = "GET&" + string(temp0) + "&" + string(temp1);
curl_free(temp0);
curl_free(temp1);
temp0 = curl_easy_escape(curl, secrets[0].c_str(), secrets[0].size());
temp1 = curl_easy_escape(curl, secrets[1].c_str(), secrets[1].size());
string sign_key = string(temp0) + "&" + string(temp1);
curl_free(temp0);
curl_free(temp1);
unsigned char *sha1hash = hmac_sha1((unsigned char *)sign_key.c_str(),
(unsigned char *)out.c_str(), sign_key.size(), out.size());
app_info[7].value = base64(sha1hash, 20);
temp0 = curl_easy_escape(curl, app_info[7].value.c_str(), app_info[7].value.size());
app_info[7].value = string(temp0);
curl_free(temp0);
//
string command =
"curl --get \'" + url + "\' --data \'screen_name=" + app_info[0].value +
"\' --header \'Authorization: OAuth oauth_consumer_key=\"" + app_info[1].value +
"\", oauth_nonce=\"" + app_info[2].value + "\", oauth_signature=\"" + app_info[7].value +
"\", oauth_signature_method=\"" + app_info[3].value + "\", oauth_timestamp=\"" +
app_info[4].value + "\", oauth_token=\"" + app_info[5].value + "\", oauth_version=\"" +
app_info[6].value + "\"\' --silent >" + outfile;
std::system(command.c_str());
//
curl_easy_cleanup(curl);
infile.open(outfile.c_str(), std::ios::app);
getline(infile, line);
if (line.find("Bad Authentication Data") != string::npos) {
return 0;
}
return 1;
}
string parse_json(Json::Value &root, string &key) {
const Json::Value value = root[0][key];
Json::FastWriter convert;
return convert.write(value);
}
std::vector<string> get_follower_locations(Json::Value &root) {
Json::FastWriter convert;
std::vector<string> ret;
const Json::Value array = root["users"];
string buff;
for (unsigned int i = 0; i < array.size(); i++) {
buff = convert.write(array[i]["location"]);
ret.push_back(buff.substr(1, buff.size() - 3));
}
return ret;
}
int main() {
string username;
cout << "Enter Twitter Username: ";
getline(std::cin, username);
string outfile = "lookup.json", url = "https://api.twitter.com/1.1/users/lookup.json";
if (twitter_lookup(username, url, outfile)) {
Json::Value user_root;
ifstream stream;
stream.open(outfile, ifstream::binary);
stream >> user_root;
string query = "location";
string location = parse_json(user_root, query);
location = location.substr(1, location.size() - 3);
query = "time_zone";
string timezone = parse_json(user_root, query);
timezone = timezone.substr(1, timezone.size() - 3);
cout << endl;
if (location == "" || location == "ul") {
cout << "Unknown based on location parameter." << endl;
} else {
cout << "Known location: " + location << endl;
return 0;
}
if (timezone == "" || timezone == "ul") {
cout << "Unknown based on timezone parameter." << endl;
} else {
cout << "Known timezone: " + timezone << endl;
}
stream.close();
outfile = "list.json";
url = "https://api.twitter.com/1.1/friends/list.json";
if (twitter_lookup(username, url, outfile)) {
Json::Value follower_root;
stream.open(outfile, ifstream::binary);
stream >> follower_root;
stream.close();
std::vector<string> buff = get_follower_locations(follower_root);
std::sort(buff.begin(), buff.end());
buff.resize(std::unique(buff.begin(), buff.end()) - buff.begin());
if (buff.size() != 0) {
cout << "Possible locations based on friends:" << endl;
for (int i = 0; i < (int)buff.size(); i++) {
if (buff.at(i) == "") {
buff.erase(buff.begin() + i);
} else {
regex blacklist("([^\u00C0-\u017F\\w\\s,-.])");
string out = regex_replace(buff.at(i), blacklist, "");
cout << out << endl;
}
}
}
return 0;
}
return 1;
}
}
<|endoftext|> |
<commit_before>#include <chrono>
#include <thread>
#include "cscore.h"
#include "llvm/SmallString.h"
#include "llvm/raw_ostream.h"
int main(int argc, char** argv) {
if (argc < 2) {
llvm::errs() << "Usage: settings camera [prop val] ... -- [prop val]...\n";
llvm::errs() << " Example: settings 1 brightness 30 raw_contrast 10\n";
return 1;
}
int id;
if (llvm::StringRef{argv[1]}.getAsInteger(10, id)) {
llvm::errs() << "Expected number for camera\n";
return 2;
}
cs::UsbCamera camera{"usbcam", id};
// Set prior to connect
int arg = 2;
llvm::StringRef propName;
for (; arg < argc && llvm::StringRef{argv[arg]} != "--"; ++arg) {
if (propName.empty())
propName = argv[arg];
else {
llvm::StringRef propVal{argv[arg]};
int intVal;
if (propVal.getAsInteger(10, intVal))
camera.GetProperty(propName).SetString(propVal);
else
camera.GetProperty(propName).Set(intVal);
propName = llvm::StringRef{};
}
}
if (llvm::StringRef{argv[arg]} == "--") ++arg;
// Wait to connect
while (!camera.IsConnected())
std::this_thread::sleep_for(std::chrono::milliseconds(10));
// Set rest
propName = llvm::StringRef{};
for (; arg < argc; ++arg) {
if (propName.empty())
propName = argv[arg];
else {
llvm::StringRef propVal{argv[arg]};
int intVal;
if (propVal.getAsInteger(10, intVal))
camera.GetProperty(propName).SetString(propVal);
else
camera.GetProperty(propName).Set(intVal);
propName = llvm::StringRef{};
}
}
// Print settings
llvm::SmallString<64> buf;
llvm::outs() << "Properties:\n";
for (const auto& prop : camera.EnumerateProperties()) {
llvm::outs() << " " << prop.GetName();
switch (prop.GetKind()) {
case cs::VideoProperty::kBoolean:
llvm::outs() << " (bool): " << "value=" << prop.Get()
<< " default=" << prop.GetDefault();
break;
case cs::VideoProperty::kInteger:
llvm::outs() << " (int): "
<< "value=" << prop.Get() << " min=" << prop.GetMin()
<< " max=" << prop.GetMax() << " step=" << prop.GetStep()
<< " default=" << prop.GetDefault();
break;
case cs::VideoProperty::kString:
llvm::outs() << " (string): " << prop.GetString(buf);
break;
case cs::VideoProperty::kEnum: {
llvm::outs() << " (enum): " << "value=" << prop.Get();
auto choices = prop.GetChoices();
for (size_t i = 0; i < choices.size(); ++i) {
if (choices[i].empty()) continue;
llvm::outs() << "\n " << i << ": " << choices[i];
}
break;
}
default:
break;
}
llvm::outs() << '\n';
}
}
<commit_msg>Fix settings example if there's no "--" in arg list.<commit_after>#include <chrono>
#include <thread>
#include "cscore.h"
#include "llvm/SmallString.h"
#include "llvm/raw_ostream.h"
int main(int argc, char** argv) {
if (argc < 2) {
llvm::errs() << "Usage: settings camera [prop val] ... -- [prop val]...\n";
llvm::errs() << " Example: settings 1 brightness 30 raw_contrast 10\n";
return 1;
}
int id;
if (llvm::StringRef{argv[1]}.getAsInteger(10, id)) {
llvm::errs() << "Expected number for camera\n";
return 2;
}
cs::UsbCamera camera{"usbcam", id};
// Set prior to connect
int arg = 2;
llvm::StringRef propName;
for (; arg < argc && llvm::StringRef{argv[arg]} != "--"; ++arg) {
if (propName.empty())
propName = argv[arg];
else {
llvm::StringRef propVal{argv[arg]};
int intVal;
if (propVal.getAsInteger(10, intVal))
camera.GetProperty(propName).SetString(propVal);
else
camera.GetProperty(propName).Set(intVal);
propName = llvm::StringRef{};
}
}
if (arg < argc && llvm::StringRef{argv[arg]} == "--") ++arg;
// Wait to connect
while (!camera.IsConnected())
std::this_thread::sleep_for(std::chrono::milliseconds(10));
// Set rest
propName = llvm::StringRef{};
for (; arg < argc; ++arg) {
if (propName.empty())
propName = argv[arg];
else {
llvm::StringRef propVal{argv[arg]};
int intVal;
if (propVal.getAsInteger(10, intVal))
camera.GetProperty(propName).SetString(propVal);
else
camera.GetProperty(propName).Set(intVal);
propName = llvm::StringRef{};
}
}
// Print settings
llvm::SmallString<64> buf;
llvm::outs() << "Properties:\n";
for (const auto& prop : camera.EnumerateProperties()) {
llvm::outs() << " " << prop.GetName();
switch (prop.GetKind()) {
case cs::VideoProperty::kBoolean:
llvm::outs() << " (bool): " << "value=" << prop.Get()
<< " default=" << prop.GetDefault();
break;
case cs::VideoProperty::kInteger:
llvm::outs() << " (int): "
<< "value=" << prop.Get() << " min=" << prop.GetMin()
<< " max=" << prop.GetMax() << " step=" << prop.GetStep()
<< " default=" << prop.GetDefault();
break;
case cs::VideoProperty::kString:
llvm::outs() << " (string): " << prop.GetString(buf);
break;
case cs::VideoProperty::kEnum: {
llvm::outs() << " (enum): " << "value=" << prop.Get();
auto choices = prop.GetChoices();
for (size_t i = 0; i < choices.size(); ++i) {
if (choices[i].empty()) continue;
llvm::outs() << "\n " << i << ": " << choices[i];
}
break;
}
default:
break;
}
llvm::outs() << '\n';
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
//#include <vector>
//#include <fstream>
#include "Land.h"
#include "Map.h"
#include "Zombie.h"
#include "Player.h"
using namespace std;
int main()
{
//game start
cout << " -----------------------------" << endl
<< "| Plants v.s Zombies |" << endl
<< " -----------------------------" << endl;
constexpr int LAND_DEFAULT=8;
constexpr int LAND_MAX=10;
constexpr int LAND_MIN=1;
constexpr int ZOMBIE_DEFAULT=3;
constexpr int ZOMBIE_MAX=10;
constexpr int ZOMBIE_MIN=1;
string input;
//initialize game setting
cout << "Number of lands on the map (" << LAND_MIN << "-" << LAND_MAX << ", default: " << LAND_DEFAULT <<")...>";
int value = LAND_DEFAULT;
getline(cin, input);
if(!input.empty())
{
istringstream stream( input );
stream >> value;
if(value > LAND_MAX) value = LAND_MAX;
if(value < LAND_MIN) value = LAND_MIN;
}
const int LANDS=value;
cout << "Number of zombies on the map (" << ZOMBIE_MIN << "-" << ZOMBIE_MAX << ", default: "<< ZOMBIE_DEFAULT <<")...>";
value=ZOMBIE_DEFAULT;
getline(cin, input);
if(!input.empty())
{
istringstream stream( input );
stream >> value;
if(value > ZOMBIE_MAX) value = ZOMBIE_MAX;
if(value < ZOMBIE_MIN) value = ZOMBIE_MIN;
}
const int ZOMBIES=value;
//game rules
cout << "=============================================================================" << endl
<< "Plants vs. Zombies Rule:" << endl
<< endl
<< "How to win:" << endl
<< " (1) All zombies are dead." << endl
<< " (2) At least one plant is live." << endl
<< " (3) The number of dead bomb plants cannot exceed the number of zombies." << endl
<< endl
<< "How to lose:" << endl
<< " All plants are dead." << endl
<< "=============================================================================" << endl;
system("pause");
system("cls");
//game start
//construct
Player *player = new Player();
Zombie *zombie = new Zombie()[ZOMBIES];
Map *map = new Map(LANDS);
/*vector<Plant*> plant;
ifstream fin=open("plants.txt");
while(!fin.eof())
{
char type;
fin << type;
if(fin.eof()) break;
Plant *tmp = nullptr;
switch(type)
{
case 'C':
{
tmp = new CoinPlant(fin);
}
case 'S':
{
tmp = new HornPlant(fin);
}
case 'B':
{
tmp = new BombPlant(fin);
}
case 'H':
{
tmp = new HealPlant(fin);
}
default:
continue;
}
if(tmp)
{
plant.push_back(tmp);
}
}*/
map->Display(*player, zombie); //cout << *map << endl;
cout << "------------------------------------------------" << endl;
cout << "Zombie information:" << endl;
for(int i=0;i<ZOMBIES;i++)
{
cout << '[' << i << "] " << zombie[i];
}
cout << endl << "================================================" << endl;
/*while(true)
{
for(int i=0;i<plant.size();++i)
{
cout << '[' << i << "] " ;
switch(plant[i]->type())
{
case 'C':
cout << dynamic_cast<CoinPlant *>(plant[i]);
case 'S':
cout << dynamic_cast<HornPlant *>(plant[i]);
case 'B':
cout << dynamic_cast<BombPlant *>(plant[i]);
case 'H':
cout << dynamic_cast<HealPlant *>(plant[i]);
}
cout << endl;
}
cout << endl << *player;
int choice = plant.size();
cout << ": Enter your choice (" << plant.size() << " to give up, default: " << choice << ")...>";
if(choice=plant.size()) break;
int cost=0;
string plantname;
switch(plant[choice].type())
{
case 'C':
CoinPlant *tmp = new CoinPlant(*dynamic_cast<CoinPlant *>(plant[choice]))
land->plant(tmp);
plantname="CoinPlant";
cost=tmp->price();
case 'S':
HornPlant *tmp = new HornPlant(*dynamic_cast<CoinPlant *>(plant[choice]))
land->plant(tmp);
plantname="HornPlant";
cost=tmp->price();
case 'B':
BombPlant *tmp = new BombPlant(*dynamic_cast<CoinPlant *>(plant[choice]));
land->plant(tmp);
plantname="BombPlant";
cost=tmp->price();
case 'H':
HealPlant *tmp = new HealPlant(*dynamic_cast<CoinPlant *>(plant[choice]));
land->plant(tmp);
plantname="HealPlant";
cost=tmp->price();
}
if(player->money() >= cost)
{
cout << "You have planted " << plantname << " at land 7 !";
break;
}
else
{
cout << "Not enough money! Please input again.";
}
}*/
// destruct
//while(!plant.empty())
// delete plant.pop_back();
delete player;
delete map;
delete [] zombie;
return 0;
}
<commit_msg>remove useless header<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
//#include <vector>
//#include <fstream>
#include "Map.h"
#include "Zombie.h"
#include "Player.h"
using namespace std;
int main()
{
//game start
cout << " -----------------------------" << endl
<< "| Plants v.s Zombies |" << endl
<< " -----------------------------" << endl;
constexpr int LAND_DEFAULT=8;
constexpr int LAND_MAX=10;
constexpr int LAND_MIN=1;
constexpr int ZOMBIE_DEFAULT=3;
constexpr int ZOMBIE_MAX=10;
constexpr int ZOMBIE_MIN=1;
string input;
//initialize game setting
cout << "Number of lands on the map (" << LAND_MIN << "-" << LAND_MAX << ", default: " << LAND_DEFAULT <<")...>";
int value = LAND_DEFAULT;
getline(cin, input);
if(!input.empty())
{
istringstream stream( input );
stream >> value;
if(value > LAND_MAX) value = LAND_MAX;
if(value < LAND_MIN) value = LAND_MIN;
}
const int LANDS=value;
cout << "Number of zombies on the map (" << ZOMBIE_MIN << "-" << ZOMBIE_MAX << ", default: "<< ZOMBIE_DEFAULT <<")...>";
value=ZOMBIE_DEFAULT;
getline(cin, input);
if(!input.empty())
{
istringstream stream( input );
stream >> value;
if(value > ZOMBIE_MAX) value = ZOMBIE_MAX;
if(value < ZOMBIE_MIN) value = ZOMBIE_MIN;
}
const int ZOMBIES=value;
//game rules
cout << "=============================================================================" << endl
<< "Plants vs. Zombies Rule:" << endl
<< endl
<< "How to win:" << endl
<< " (1) All zombies are dead." << endl
<< " (2) At least one plant is live." << endl
<< " (3) The number of dead bomb plants cannot exceed the number of zombies." << endl
<< endl
<< "How to lose:" << endl
<< " All plants are dead." << endl
<< "=============================================================================" << endl;
system("pause");
system("cls");
//game start
//construct
Player *player = new Player();
Zombie *zombie = new Zombie()[ZOMBIES];
Map *map = new Map(LANDS);
/*vector<Plant*> plant;
ifstream fin=open("plants.txt");
while(!fin.eof())
{
char type;
fin << type;
if(fin.eof()) break;
Plant *tmp = nullptr;
switch(type)
{
case 'C':
{
tmp = new CoinPlant(fin);
}
case 'S':
{
tmp = new HornPlant(fin);
}
case 'B':
{
tmp = new BombPlant(fin);
}
case 'H':
{
tmp = new HealPlant(fin);
}
default:
continue;
}
if(tmp)
{
plant.push_back(tmp);
}
}*/
map->Display(*player, zombie); //cout << *map << endl;
cout << "------------------------------------------------" << endl;
cout << "Zombie information:" << endl;
for(int i=0;i<ZOMBIES;i++)
{
cout << '[' << i << "] " << zombie[i];
}
cout << endl << "================================================" << endl;
/*while(true)
{
for(int i=0;i<plant.size();++i)
{
cout << '[' << i << "] " ;
switch(plant[i]->type())
{
case 'C':
cout << dynamic_cast<CoinPlant *>(plant[i]);
case 'S':
cout << dynamic_cast<HornPlant *>(plant[i]);
case 'B':
cout << dynamic_cast<BombPlant *>(plant[i]);
case 'H':
cout << dynamic_cast<HealPlant *>(plant[i]);
}
cout << endl;
}
cout << endl << *player;
int choice = plant.size();
cout << ": Enter your choice (" << plant.size() << " to give up, default: " << choice << ")...>";
if(choice=plant.size()) break;
int cost=0;
string plantname;
switch(plant[choice].type())
{
case 'C':
CoinPlant *tmp = new CoinPlant(*dynamic_cast<CoinPlant *>(plant[choice]))
land->plant(tmp);
plantname="CoinPlant";
cost=tmp->price();
case 'S':
HornPlant *tmp = new HornPlant(*dynamic_cast<CoinPlant *>(plant[choice]))
land->plant(tmp);
plantname="HornPlant";
cost=tmp->price();
case 'B':
BombPlant *tmp = new BombPlant(*dynamic_cast<CoinPlant *>(plant[choice]));
land->plant(tmp);
plantname="BombPlant";
cost=tmp->price();
case 'H':
HealPlant *tmp = new HealPlant(*dynamic_cast<CoinPlant *>(plant[choice]));
land->plant(tmp);
plantname="HealPlant";
cost=tmp->price();
}
if(player->money() >= cost)
{
cout << "You have planted " << plantname << " at land 7 !";
break;
}
else
{
cout << "Not enough money! Please input again.";
}
}*/
// destruct
//while(!plant.empty())
// delete plant.pop_back();
delete player;
delete map;
delete [] zombie;
return 0;
}
<|endoftext|> |
<commit_before>#include ".hh"
using namespace std;
using namespace answer;
namespace WebServices
{
CalculatorResponse MyService::calculator(const CalculatorRequest &request)
{
CalculatorResponse response;
switch (request.operation)
{
case 'x':
case '*':
response.result = request.operand1 * request.operand2;
break;
case '-':
response.result = request.operand1 - request.operand2;
break;
case 'd':
case '/':
response.result = request.operand1 / request.operand2;
break;
case '+':
response.result = request.operand1 + request.operand2;
break;
default:
throw WebMethodInvalidInput("Invalid operation requested");
}
return response;
}
}
<commit_msg>Removed incomplete example<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <thread>
#include <string>
#include <boost/variant.hpp>
#include <boost/timer/timer.hpp>
#include "variant.hpp"
#define TEXT "Testing various variant implementations with a longish string ........................................."
//#define BOOST_VARIANT_MINIMIZE_SIZE
namespace test {
template <typename V>
struct Holder
{
typedef V value_type;
std::vector<value_type> data;
template <typename T>
void append_move( T && obj)
{
data.emplace_back(std::move(obj));
}
template <typename T>
void append(T const& obj)
{
data.push_back(obj);
}
};
}
struct print
{
template <typename T>
void operator() (T const& val) const
{
std::cerr << val << ":" << typeid(T).name() << std::endl;
}
};
template <typename V>
struct dummy : boost::static_visitor<>
{
dummy(V & v)
: v_(v) {}
template <typename T>
void operator() (T const& val) const
{
v_ = val;
}
V & v_;
};
template <typename V>
struct dummy2
{
dummy2(V & v)
: v_(v) {}
template <typename T>
void operator() (T const& val) const
{
v_.template set<T>(val);
}
V & v_;
};
void run_boost_test(std::size_t runs)
{
test::Holder<boost::variant<int,double,std::string>> h;
h.data.reserve(runs);
for (std::size_t i=0; i< runs;++i)
{
h.append_move(std::string(TEXT));
h.append_move(123);
h.append_move(3.14159);
}
boost::variant<int,double,std::string> v;
for (auto const& v2 : h.data)
{
dummy<boost::variant<int,double,std::string> > d(v);
boost::apply_visitor(d, v2);
}
}
void run_variant_test(std::size_t runs)
{
test::Holder<util::variant<int,double,std::string> > h;
h.data.reserve(runs);
for (std::size_t i=0; i< runs;++i)
{
h.append_move(std::string(TEXT));
h.append_move(123);
h.append_move(3.14159);
}
util::variant<int,double,std::string> v;
for (auto const& v2 : h.data)
{
dummy2<util::variant<int,double,std::string> > d(v);
util::apply_visitor(v2, d);
}
}
int main (int argc, char** argv)
{
if (argc!=2)
{
std::cerr << "Usage:" << argv[0] << " <num-runs>" << std::endl;
return 1;
}
const std::size_t THREADS = 15;
const std::size_t NUM_RUNS = static_cast<std::size_t>(std::stol(argv[1]));
#ifdef SINGLE_THREADED
{
std::cerr << "custom variant: ";
boost::timer::auto_cpu_timer t;
run_variant_test(NUM_RUNS);
}
{
std::cerr << "boost variant: ";
boost::timer::auto_cpu_timer t;
run_boost_test(NUM_RUNS);
}
{
std::cerr << "custom variant: ";
boost::timer::auto_cpu_timer t;
run_variant_test(NUM_RUNS);
}
{
std::cerr << "boost variant: ";
boost::timer::auto_cpu_timer t;
run_boost_test(NUM_RUNS);
}
#else
{
typedef std::vector<std::unique_ptr<std::thread> > thread_group;
typedef thread_group::value_type value_type;
thread_group tg;
std::cerr << "custom variant: ";
boost::timer::auto_cpu_timer timer;
for (std::size_t i=0;i<THREADS;++i)
{
tg.emplace_back(new std::thread(run_variant_test, NUM_RUNS));
}
std::for_each(tg.begin(), tg.end(), [](value_type & t) {if (t->joinable()) t->join();});
}
{
typedef std::vector<std::unique_ptr<std::thread> > thread_group;
typedef thread_group::value_type value_type;
thread_group tg;
std::cerr << "boost variant: ";
boost::timer::auto_cpu_timer timer;
for (std::size_t i=0;i<THREADS;++i)
{
tg.emplace_back(new std::thread(run_boost_test, NUM_RUNS));
}
std::for_each(tg.begin(), tg.end(), [](value_type & t) {if (t->joinable()) t->join();});
}
{
typedef std::vector<std::unique_ptr<std::thread> > thread_group;
typedef thread_group::value_type value_type;
thread_group tg;
std::cerr << "custom variant: ";
boost::timer::auto_cpu_timer timer;
for (std::size_t i=0;i<THREADS;++i)
{
tg.emplace_back(new std::thread(run_variant_test, NUM_RUNS));
}
std::for_each(tg.begin(), tg.end(), [](value_type & t) {if (t->joinable()) t->join();});
}
{
typedef std::vector<std::unique_ptr<std::thread> > thread_group;
typedef thread_group::value_type value_type;
thread_group tg;
std::cerr << "boost variant: ";
boost::timer::auto_cpu_timer timer;
for (std::size_t i=0;i<THREADS;++i)
{
tg.emplace_back(new std::thread(run_boost_test, NUM_RUNS));
}
std::for_each(tg.begin(), tg.end(), [](value_type & t) {if (t->joinable()) t->join();});
}
#endif
#if 0
std::cerr << util::detail::type_traits<bool, bool, int, double, std::string>::id << std::endl;
std::cerr << util::detail::type_traits<int, bool, int, double, std::string>::id << std::endl;
std::cerr << util::detail::type_traits<double, bool, int, double, std::string>::id << std::endl;
std::cerr << util::detail::type_traits<std::string, bool, int, double, std::string>::id << std::endl;
std::cerr << util::detail::type_traits<long, bool, int, double, std::string>::id << std::endl;
std::cerr << util::detail::type_traits<std::vector<int>, bool, int, double, std::string>::id << std::endl;
typedef util::variant<bool,int, double, std::string> variant_type;
variant_type v(std::string("test"));
util::apply_visitor(v, print());
v = std::string("ABC");
util::apply_visitor(v, print());
std::vector<variant_type> vec;
vec.emplace_back(std::move(v));
for (auto const& e : vec)
{
util::apply_visitor(e, print());
}
v=std::string("test");
util::apply_visitor(v, print());
v=123.345;
util::apply_visitor(v, print());
variant_type v2(std::string("testing a bit more"));
util::apply_visitor(v2, print());
variant_type v3(444);
util::apply_visitor(v3, print());
std::cerr << sizeof(v) << std::endl;
std::cerr << sizeof(v2) << std::endl;
std::cerr << sizeof(v3) << std::endl;
std::cerr << sizeof(boost::variant<bool,int, double, std::string>) << std::endl;
#endif
return EXIT_SUCCESS;
}
<commit_msg>10 threads<commit_after>#include <iostream>
#include <vector>
#include <thread>
#include <string>
#include <boost/variant.hpp>
#include <boost/timer/timer.hpp>
#include "variant.hpp"
#define TEXT "Testing various variant implementations with a longish string ........................................."
//#define BOOST_VARIANT_MINIMIZE_SIZE
namespace test {
template <typename V>
struct Holder
{
typedef V value_type;
std::vector<value_type> data;
template <typename T>
void append_move( T && obj)
{
data.emplace_back(std::move(obj));
}
template <typename T>
void append(T const& obj)
{
data.push_back(obj);
}
};
}
struct print
{
template <typename T>
void operator() (T const& val) const
{
std::cerr << val << ":" << typeid(T).name() << std::endl;
}
};
template <typename V>
struct dummy : boost::static_visitor<>
{
dummy(V & v)
: v_(v) {}
template <typename T>
void operator() (T const& val) const
{
v_ = val;
}
V & v_;
};
template <typename V>
struct dummy2
{
dummy2(V & v)
: v_(v) {}
template <typename T>
void operator() (T const& val) const
{
v_.template set<T>(val);
}
V & v_;
};
void run_boost_test(std::size_t runs)
{
test::Holder<boost::variant<int,double,std::string>> h;
h.data.reserve(runs);
for (std::size_t i=0; i< runs;++i)
{
h.append_move(std::string(TEXT));
h.append_move(123);
h.append_move(3.14159);
}
boost::variant<int,double,std::string> v;
for (auto const& v2 : h.data)
{
dummy<boost::variant<int,double,std::string> > d(v);
boost::apply_visitor(d, v2);
}
}
void run_variant_test(std::size_t runs)
{
test::Holder<util::variant<int,double,std::string> > h;
h.data.reserve(runs);
for (std::size_t i=0; i< runs;++i)
{
h.append_move(std::string(TEXT));
h.append_move(123);
h.append_move(3.14159);
}
util::variant<int,double,std::string> v;
for (auto const& v2 : h.data)
{
dummy2<util::variant<int,double,std::string> > d(v);
util::apply_visitor(v2, d);
}
}
int main (int argc, char** argv)
{
if (argc!=2)
{
std::cerr << "Usage:" << argv[0] << " <num-runs>" << std::endl;
return 1;
}
const std::size_t THREADS = 10;
const std::size_t NUM_RUNS = static_cast<std::size_t>(std::stol(argv[1]));
#ifdef SINGLE_THREADED
{
std::cerr << "custom variant: ";
boost::timer::auto_cpu_timer t;
run_variant_test(NUM_RUNS);
}
{
std::cerr << "boost variant: ";
boost::timer::auto_cpu_timer t;
run_boost_test(NUM_RUNS);
}
{
std::cerr << "custom variant: ";
boost::timer::auto_cpu_timer t;
run_variant_test(NUM_RUNS);
}
{
std::cerr << "boost variant: ";
boost::timer::auto_cpu_timer t;
run_boost_test(NUM_RUNS);
}
#else
{
typedef std::vector<std::unique_ptr<std::thread> > thread_group;
typedef thread_group::value_type value_type;
thread_group tg;
std::cerr << "custom variant: ";
boost::timer::auto_cpu_timer timer;
for (std::size_t i=0;i<THREADS;++i)
{
tg.emplace_back(new std::thread(run_variant_test, NUM_RUNS));
}
std::for_each(tg.begin(), tg.end(), [](value_type & t) {if (t->joinable()) t->join();});
}
{
typedef std::vector<std::unique_ptr<std::thread> > thread_group;
typedef thread_group::value_type value_type;
thread_group tg;
std::cerr << "boost variant: ";
boost::timer::auto_cpu_timer timer;
for (std::size_t i=0;i<THREADS;++i)
{
tg.emplace_back(new std::thread(run_boost_test, NUM_RUNS));
}
std::for_each(tg.begin(), tg.end(), [](value_type & t) {if (t->joinable()) t->join();});
}
{
typedef std::vector<std::unique_ptr<std::thread> > thread_group;
typedef thread_group::value_type value_type;
thread_group tg;
std::cerr << "custom variant: ";
boost::timer::auto_cpu_timer timer;
for (std::size_t i=0;i<THREADS;++i)
{
tg.emplace_back(new std::thread(run_variant_test, NUM_RUNS));
}
std::for_each(tg.begin(), tg.end(), [](value_type & t) {if (t->joinable()) t->join();});
}
{
typedef std::vector<std::unique_ptr<std::thread> > thread_group;
typedef thread_group::value_type value_type;
thread_group tg;
std::cerr << "boost variant: ";
boost::timer::auto_cpu_timer timer;
for (std::size_t i=0;i<THREADS;++i)
{
tg.emplace_back(new std::thread(run_boost_test, NUM_RUNS));
}
std::for_each(tg.begin(), tg.end(), [](value_type & t) {if (t->joinable()) t->join();});
}
#endif
#if 0
std::cerr << util::detail::type_traits<bool, bool, int, double, std::string>::id << std::endl;
std::cerr << util::detail::type_traits<int, bool, int, double, std::string>::id << std::endl;
std::cerr << util::detail::type_traits<double, bool, int, double, std::string>::id << std::endl;
std::cerr << util::detail::type_traits<std::string, bool, int, double, std::string>::id << std::endl;
std::cerr << util::detail::type_traits<long, bool, int, double, std::string>::id << std::endl;
std::cerr << util::detail::type_traits<std::vector<int>, bool, int, double, std::string>::id << std::endl;
typedef util::variant<bool,int, double, std::string> variant_type;
variant_type v(std::string("test"));
util::apply_visitor(v, print());
v = std::string("ABC");
util::apply_visitor(v, print());
std::vector<variant_type> vec;
vec.emplace_back(std::move(v));
for (auto const& e : vec)
{
util::apply_visitor(e, print());
}
v=std::string("test");
util::apply_visitor(v, print());
v=123.345;
util::apply_visitor(v, print());
variant_type v2(std::string("testing a bit more"));
util::apply_visitor(v2, print());
variant_type v3(444);
util::apply_visitor(v3, print());
std::cerr << sizeof(v) << std::endl;
std::cerr << sizeof(v2) << std::endl;
std::cerr << sizeof(v3) << std::endl;
std::cerr << sizeof(boost::variant<bool,int, double, std::string>) << std::endl;
#endif
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>c2054b4c-35ca-11e5-9db9-6c40088e03e4<commit_msg>c20c4d52-35ca-11e5-b48a-6c40088e03e4<commit_after>c20c4d52-35ca-11e5-b48a-6c40088e03e4<|endoftext|> |
<commit_before>d6b15c1e-327f-11e5-86c5-9cf387a8033e<commit_msg>d6b769d9-327f-11e5-90de-9cf387a8033e<commit_after>d6b769d9-327f-11e5-90de-9cf387a8033e<|endoftext|> |
<commit_before>1285bcd9-2d3f-11e5-b0a3-c82a142b6f9b<commit_msg>12ebfce8-2d3f-11e5-bd2a-c82a142b6f9b<commit_after>12ebfce8-2d3f-11e5-bd2a-c82a142b6f9b<|endoftext|> |
<commit_before>b6d49075-327f-11e5-b16e-9cf387a8033e<commit_msg>b6dada63-327f-11e5-a86b-9cf387a8033e<commit_after>b6dada63-327f-11e5-a86b-9cf387a8033e<|endoftext|> |
<commit_before>79208be6-2d53-11e5-baeb-247703a38240<commit_msg>7921157a-2d53-11e5-baeb-247703a38240<commit_after>7921157a-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>9e1ca2c2-ad58-11e7-aea8-ac87a332f658<commit_msg>Typical bobby<commit_after>9e8ff751-ad58-11e7-a76e-ac87a332f658<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <map>
#include <fstream>
#include <string>
#include <iterator>
#include <functional>
#include <algorithm>
#include <deque>
#include <sstream>
std::string trim_begin(const std::string& str) {
auto alpha = std::find_if_not(str.begin(), str.end(), ::isspace);
return str.substr(std::distance(str.begin(), alpha));
}
std::string trim_end(const std::string& str) {
auto alpha = std::find_if_not(str.rbegin(), str.rend(), ::isspace).base();
return str.substr(0, std::distance(str.begin(), alpha));
}
std::string str_to_lower(const std::string& str) {
std::string lowercase;
std::transform(std::begin(str), std::end(str), std::back_inserter(lowercase), ::tolower);
return lowercase;
}
std::vector<std::string> str_split_whitespace(const std::string& str) {
std::vector<std::string> words;
std::istringstream is(str);
std::copy(
std::istream_iterator<std::string>(is),
std::istream_iterator<std::string>(),
std::back_inserter(words));
return words;
}
std::vector<std::string> str_split(const std::string& str, const char *delims) {
size_t found = std::string::npos, prev = 0;
std::vector<std::string> out;
out.reserve(log(str.size()));
found = str.find_first_of(delims);
while (found != std::string::npos) {
if (prev < found) {
auto sub = str.substr(prev, found - prev);
if (!sub.empty())
out.push_back(sub);
}
prev = found + 1;
found = str.find_first_of(delims, prev);
}
auto sub = str.substr(prev, std::string::npos);
if (!sub.empty())
out.push_back(sub);
return out;
}
std::vector<std::string> extract_sentences(const std::string& str) {
return str_split(str, ".?!\"");
}
std::vector<std::string> extract_words(const std::string& str) {
return str_split(str, " .,;\"?!\n\r\"");
}
class sentence_file_reader {
std::ifstream ifs;
std::deque<std::string> sentence_buffer;
static const size_t BUFFER_SIZE = 16 * 1024;
char char_buffer[BUFFER_SIZE];
public:
sentence_file_reader(const char *filename) :
ifs(filename, std::ios::in)
{}
~sentence_file_reader() {
ifs.close();
}
std::string get_next_sentence() {
std::string sn;
if (!sentence_buffer.empty()) {
sn = sentence_buffer.front();
sentence_buffer.pop_front();
}
else {
ifs.getline(char_buffer, BUFFER_SIZE);
auto sentences = extract_sentences(char_buffer);
sentence_buffer = std::deque<std::string>(std::begin(sentences), std::end(sentences));
sn = get_next_sentence();
}
return trim_begin(trim_end(sn));
}
bool has_more() {
return ifs.good() || !sentence_buffer.empty();
}
};
struct word_node {
word_node(const std::string& name) :
normalized_name(str_to_lower(name))
{}
void add_original_name(const std::string& original) {
auto found = std::find(
std::begin(original_names),
std::end(original_names),
original);
if (found == original_names.end()) {
original_names.push_back(original);
}
}
std::vector<std::string> original_names;
std::string normalized_name;
std::map<word_node*, size_t> lefts;
std::map<word_node*, size_t> rights;
bool visited;
};
struct word_graph {
std::map<std::string, word_node*> word_nodes;
word_node *head;
word_node *get_or_create(std::string name) {
auto word = str_to_lower(name);
auto name_exists = word_nodes.equal_range(word);
auto found_node = name_exists.first;
if (name_exists.first == name_exists.second) {
word_node *name_node = new word_node(name);
found_node = word_nodes.insert(name_exists.second, std::make_pair(word, name_node));
}
found_node->second->add_original_name(name);
return found_node->second;
}
void make_link(const std::string& a, const std::string& b) {
word_node *a_node = get_or_create(a);
word_node *b_node = get_or_create(b);
a_node->rights[b_node]++;
b_node->lefts[a_node]++;
}
};
class sentence_printer {
public:
void print(word_node *node, int superthreshold, int depth) {
node_visited.clear();
printSentences(node, node->normalized_name, superthreshold, depth);
}
private:
void printSentences(word_node *node, const std::string& name, int superthreshold, int depth) {
bool wasVisites = node_visited[node];
node_visited[node] = true;
for (auto &w_node_cnt : node->rights) {
if (w_node_cnt.second >= superthreshold && !wasVisites) {
printSentences(w_node_cnt.first, name + " " + w_node_cnt.first->normalized_name, superthreshold, depth + 1);
}
else if (depth > 1) {
std::cout << name + " " + w_node_cnt.first->normalized_name << "\n";
}
}
}
private:
std::map<word_node*, bool> node_visited;
};
int main(int argc, char *argv[]) {
std::ios::ios_base::sync_with_stdio(false);
const char *in_filename = "test.txt";
if (argc > 1) {
in_filename = argv[1];
}
sentence_file_reader cfr(in_filename);
word_graph graph;
std::string str;
while (cfr.has_more()) {
std::string sentence = cfr.get_next_sentence();
std::vector<std::string> words = extract_words(sentence);
if (words.size() > 1) {
graph.make_link(words[0], words[1]);
for (size_t i = 1, j = 2; j < words.size(); ++i, ++j) {
graph.make_link(words[i], words[j]);
}
}
else if (words.size() == 1 && !words[0].empty()) {
graph.get_or_create(words[0]);
}
}
const int threshold = 5;
for (auto &kv : graph.word_nodes) {
bool wordprinted = false;
for (auto &w_node_cnt : kv.second->lefts) {
if (w_node_cnt.second >= threshold) {
if (!wordprinted) {
std::cout << kv.first << "\n- left: ";
wordprinted = true;
}
std::cout << w_node_cnt.first->normalized_name << ":" << w_node_cnt.second << " ";
}
}
if (wordprinted)
std::cout << "\n- right: ";
for (auto &w_node_cnt : kv.second->rights) {
if (w_node_cnt.second >= threshold) {
if (!wordprinted) {
std::cout << kv.first << "\n- right: ";
wordprinted = true;
}
std::cout << w_node_cnt.first->normalized_name << ":" << w_node_cnt.second << " ";
}
}
if (wordprinted)
std::cout << "\n\n";
}
const int superthreshold = 100;
sentence_printer printer;
for (auto &kv : graph.word_nodes) {
printer.print(kv.second, superthreshold, 0);
}
return 0;
}
<commit_msg>Refactor and warnings fixes<commit_after>#include <iostream>
#include <vector>
#include <map>
#include <fstream>
#include <string>
#include <iterator>
#include <functional>
#include <algorithm>
#include <deque>
#include <sstream>
std::string trim_begin(const std::string& str) {
auto alpha = std::find_if_not(str.begin(), str.end(), ::isspace);
return str.substr(std::distance(str.begin(), alpha));
}
std::string trim_end(const std::string& str) {
auto alpha = std::find_if_not(str.rbegin(), str.rend(), ::isspace).base();
return str.substr(0, std::distance(str.begin(), alpha));
}
std::string str_to_lower(const std::string& str) {
std::string lowercase;
std::transform(std::begin(str), std::end(str), std::back_inserter(lowercase), ::tolower);
return lowercase;
}
std::vector<std::string> str_split_whitespace(const std::string& str) {
std::vector<std::string> words;
std::istringstream is(str);
std::copy(
std::istream_iterator<std::string>(is),
std::istream_iterator<std::string>(),
std::back_inserter(words));
return words;
}
std::vector<std::string> str_split(const std::string& str, const char *delims) {
size_t found = std::string::npos, prev = 0;
std::vector<std::string> out;
out.reserve(static_cast<size_t>(log(str.size())));
found = str.find_first_of(delims);
while (found != std::string::npos) {
if (prev < found) {
auto sub = str.substr(prev, found - prev);
if (!sub.empty())
out.push_back(sub);
}
prev = found + 1;
found = str.find_first_of(delims, prev);
}
auto sub = str.substr(prev, std::string::npos);
if (!sub.empty())
out.push_back(sub);
return out;
}
std::vector<std::string> extract_sentences(const std::string& str) {
return str_split(str, ".?!\"");
}
std::vector<std::string> extract_words(const std::string& str) {
return str_split(str, " .,;\"?!\n\r\"");
}
class sentence_file_reader {
std::ifstream ifs;
std::deque<std::string> sentence_buffer;
static const size_t BUFFER_SIZE = 16 * 1024;
char char_buffer[BUFFER_SIZE];
public:
sentence_file_reader(const char *filename) :
ifs(filename, std::ios::in)
{}
~sentence_file_reader() {
ifs.close();
}
std::string get_next_sentence() {
std::string sn;
if (!sentence_buffer.empty()) {
sn = sentence_buffer.front();
sentence_buffer.pop_front();
}
else {
ifs.getline(char_buffer, BUFFER_SIZE);
auto sentences = extract_sentences(char_buffer);
sentence_buffer = std::deque<std::string>(std::begin(sentences), std::end(sentences));
sn = get_next_sentence();
}
return trim_begin(trim_end(sn));
}
bool has_more() {
return ifs.good() || !sentence_buffer.empty();
}
};
struct word_node {
word_node(const std::string& name) :
normalized_name(str_to_lower(name))
{}
void add_original_name(const std::string& original) {
auto found = std::find(
std::begin(original_names),
std::end(original_names),
original);
if (found == original_names.end()) {
original_names.push_back(original);
}
}
std::vector<std::string> original_names;
std::string normalized_name;
std::map<word_node*, size_t> lefts;
std::map<word_node*, size_t> rights;
bool visited;
};
struct word_graph {
std::map<std::string, word_node*> word_nodes;
word_node *head;
word_node *get_or_create(std::string name) {
auto word = str_to_lower(name);
auto name_exists = word_nodes.equal_range(word);
auto found_node = name_exists.first;
if (name_exists.first == name_exists.second) {
word_node *name_node = new word_node(name);
found_node = word_nodes.insert(name_exists.second, std::make_pair(word, name_node));
}
found_node->second->add_original_name(name);
return found_node->second;
}
void make_link(const std::string& a, const std::string& b) {
word_node *a_node = get_or_create(a);
word_node *b_node = get_or_create(b);
a_node->rights[b_node]++;
b_node->lefts[a_node]++;
}
};
struct sentence_print {
public:
void operator ()(word_node *node, const std::string& name, size_t superthreshold, int depth) {
bool wasVisites = node_visited[node];
node_visited[node] = true;
for (auto &w_node_cnt : node->rights) {
if (w_node_cnt.second >= superthreshold && !wasVisites) {
(*this)(w_node_cnt.first, name + " " + w_node_cnt.first->normalized_name, superthreshold, depth + 1);
}
else if (depth > 1) {
std::cout << name + " " + w_node_cnt.first->normalized_name << "\n";
}
}
}
private:
std::map<word_node*, bool> node_visited;
};
int main(int argc, char *argv[]) {
std::ios::ios_base::sync_with_stdio(false);
const char *in_filename = "test.txt";
if (argc > 1) {
in_filename = argv[1];
}
sentence_file_reader cfr(in_filename);
word_graph graph;
std::string str;
while (cfr.has_more()) {
std::string sentence = cfr.get_next_sentence();
std::vector<std::string> words = extract_words(sentence);
if (words.size() > 1) {
graph.make_link(words[0], words[1]);
for (size_t i = 1, j = 2; j < words.size(); ++i, ++j) {
graph.make_link(words[i], words[j]);
}
}
else if (words.size() == 1 && !words[0].empty()) {
graph.get_or_create(words[0]);
}
}
const int threshold = 5;
for (auto &kv : graph.word_nodes) {
bool wordprinted = false;
for (auto &w_node_cnt : kv.second->lefts) {
if (w_node_cnt.second >= threshold) {
if (!wordprinted) {
std::cout << kv.first << "\n- left: ";
wordprinted = true;
}
std::cout << w_node_cnt.first->normalized_name << ":" << w_node_cnt.second << " ";
}
}
if (wordprinted)
std::cout << "\n- right: ";
for (auto &w_node_cnt : kv.second->rights) {
if (w_node_cnt.second >= threshold) {
if (!wordprinted) {
std::cout << kv.first << "\n- right: ";
wordprinted = true;
}
std::cout << w_node_cnt.first->normalized_name << ":" << w_node_cnt.second << " ";
}
}
if (wordprinted)
std::cout << "\n\n";
}
const int superthreshold = 100;
for (auto &kv : graph.word_nodes) {
sentence_print()(kv.second, kv.second->normalized_name, superthreshold, 0);
}
return 0;
}
<|endoftext|> |
<commit_before>#include "types.h"
#include "user.h"
#include "lib.h"
#include "amd64.h"
#include "wq.hh"
struct testwork : public work {
testwork(forframe *b) : barrier_(b) {}
virtual void run() {
barrier_->dec();
delete this;
}
static void* operator new(unsigned long nbytes) {
assert(nbytes == sizeof(testwork));
return xmalloc(sizeof(testwork));
}
static void operator delete(void*p) {
xfree(p, sizeof(testwork));
}
struct forframe *barrier_;
};
static void
test(void)
{
enum { pushes = 100 };
struct forframe wqbarrier(pushes);
for (int i = 0; i < pushes; i++) {
testwork *w = new testwork(&wqbarrier);
wq_push(w);
}
while (!wqbarrier.zero())
nop_pause();
}
int
main(int ac, char **av)
{
initwq();
test();
exitwq();
printf("all done!\n");
return 0;
}
<commit_msg>More wq tests<commit_after>#include "types.h"
#include "user.h"
#include "lib.h"
#include "amd64.h"
#include "wq.hh"
#define NEW_DELETE_OPS(classname) \
static void* operator new(unsigned long nbytes) { \
assert(nbytes == sizeof(classname)); \
return malloc(sizeof(classname)); \
} \
\
static void operator delete(void *p) { \
free(p); \
}
struct testwork : public work {
testwork(forframe *b) : barrier_(b) {}
virtual void run() {
barrier_->dec();
delete this;
}
NEW_DELETE_OPS(testwork);
struct forframe *barrier_;
};
static void
test0(void)
{
enum { pushes = 100 };
struct forframe wqbarrier(pushes);
printf("test0...\n");
for (int i = 0; i < pushes; i++) {
testwork *w = new testwork(&wqbarrier);
wq_push(w);
}
while (!wqbarrier.zero())
nop_pause();
printf("test0 done\n");
}
struct forkwork : public work {
forkwork(forframe *b) : barrier_(b) {}
virtual void run() {
int pid;
pid = fork(0);
if (pid < 0)
die("forkwork::run: fork");
else if (pid == 0)
exit();
wait();
barrier_->dec();
delete this;
}
NEW_DELETE_OPS(forkwork);
struct forframe *barrier_;
};
static void
testfork(void)
{
enum { forks = 100 };
struct forframe wqbarrier(forks);
printf("testfork...\n");
for (int i = 0; i < forks; i++) {
forkwork *w = new forkwork(&wqbarrier);
wq_push(w);
}
while (!wqbarrier.zero())
nop_pause();
printf("testfork done\n");
}
int
main(int ac, char **av)
{
initwq();
test0();
testfork();
exitwq();
return 0;
}
<|endoftext|> |
<commit_before>ff4dc36b-2d3c-11e5-8252-c82a142b6f9b<commit_msg>005b16cf-2d3d-11e5-b38a-c82a142b6f9b<commit_after>005b16cf-2d3d-11e5-b38a-c82a142b6f9b<|endoftext|> |
<commit_before>07f72430-2f67-11e5-9536-6c40088e03e4<commit_msg>07fdcb7a-2f67-11e5-b87d-6c40088e03e4<commit_after>07fdcb7a-2f67-11e5-b87d-6c40088e03e4<|endoftext|> |
<commit_before>3e2c4df8-5216-11e5-bbb7-6c40088e03e4<commit_msg>3e32c0ca-5216-11e5-b9b6-6c40088e03e4<commit_after>3e32c0ca-5216-11e5-b9b6-6c40088e03e4<|endoftext|> |
<commit_before>2140b122-585b-11e5-b0b8-6c40088e03e4<commit_msg>21473d6c-585b-11e5-92ab-6c40088e03e4<commit_after>21473d6c-585b-11e5-92ab-6c40088e03e4<|endoftext|> |
<commit_before>fb4e4af5-2747-11e6-a89a-e0f84713e7b8<commit_msg>Did a thing<commit_after>fb60402e-2747-11e6-b308-e0f84713e7b8<|endoftext|> |
<commit_before>28cc1f48-2f67-11e5-897e-6c40088e03e4<commit_msg>28d34958-2f67-11e5-9f3d-6c40088e03e4<commit_after>28d34958-2f67-11e5-9f3d-6c40088e03e4<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.