text stringlengths 54 60.6k |
|---|
<commit_before>f1d99282-2e4e-11e5-bc21-28cfe91dbc4b<commit_msg>f1dfe878-2e4e-11e5-aa9f-28cfe91dbc4b<commit_after>f1dfe878-2e4e-11e5-aa9f-28cfe91dbc4b<|endoftext|> |
<commit_before>#include <iostream>
#include "lps.hpp"
int main()
{
std::cout << "OHAI\n";
}
<commit_msg>main: run LPS from mmap-ed file<commit_after>#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <string>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include "lps.hpp"
int main(int argc, char **argv)
{
assert(argc == 2);
int fd = open(argv[1], O_RDONLY);
assert(fd);
struct stat fd_stat;
assert(fstat(static_cast<int>(fd), &fd_stat) == 0);
assert(S_ISREG(fd_stat.st_mode));
void* s = mmap(0, fd_stat.st_size, PROT_READ, MAP_SHARED, fd, 0);
assert(s != MAP_FAILED);
assert(close(fd) == 0);
auto result = lps(static_cast<const char*>(s), fd_stat.st_size);
std::string result_substr {result.first, result.second};
std::cout << result_substr << std::endl;
assert(munmap(s, fd_stat.st_size) == 0);
return 0;
}
<|endoftext|> |
<commit_before>50229f4c-5216-11e5-b847-6c40088e03e4<commit_msg>502ab6f4-5216-11e5-be2d-6c40088e03e4<commit_after>502ab6f4-5216-11e5-be2d-6c40088e03e4<|endoftext|> |
<commit_before>4f3915a8-2e4f-11e5-9194-28cfe91dbc4b<commit_msg>4f3fafe3-2e4f-11e5-9564-28cfe91dbc4b<commit_after>4f3fafe3-2e4f-11e5-9564-28cfe91dbc4b<|endoftext|> |
<commit_before>6ba89d74-2fa5-11e5-9324-00012e3d3f12<commit_msg>6baa4b24-2fa5-11e5-8b6b-00012e3d3f12<commit_after>6baa4b24-2fa5-11e5-8b6b-00012e3d3f12<|endoftext|> |
<commit_before>e9d6cdc8-585a-11e5-b38f-6c40088e03e4<commit_msg>e9ddb098-585a-11e5-a1fd-6c40088e03e4<commit_after>e9ddb098-585a-11e5-a1fd-6c40088e03e4<|endoftext|> |
<commit_before>a501e46e-2747-11e6-a586-e0f84713e7b8<commit_msg>The previous fix has been fixed<commit_after>a5162f78-2747-11e6-8a94-e0f84713e7b8<|endoftext|> |
<commit_before>20709ade-2e4f-11e5-8f08-28cfe91dbc4b<commit_msg>207a6eeb-2e4f-11e5-9c05-28cfe91dbc4b<commit_after>207a6eeb-2e4f-11e5-9c05-28cfe91dbc4b<|endoftext|> |
<commit_before>83000dc1-2d15-11e5-af21-0401358ea401<commit_msg>83000dc2-2d15-11e5-af21-0401358ea401<commit_after>83000dc2-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include <signal.h>
#include "znc.h"
#include "md5.h"
static struct option g_LongOpts[] =
{
{ "help", 0, NULL, 0 },
{ "makepass", 0, NULL, 0 },
#ifdef HAVE_LIBSSL
{ "makepem", 0, NULL, 0 },
{ "encrypt-pem", 0, NULL, 0 },
#endif /* HAVE_LIBSSL */
{ NULL }
};
void GenerateHelp( const char *appname )
{
CUtils::PrintMessage("USAGE: " + string(appname) + " [options] [znc.conf]");
CUtils::PrintMessage("Options are:");
CUtils::PrintMessage("\t--help");
CUtils::PrintMessage("\t--makepass Generates a password for use in config");
#ifdef HAVE_LIBSSL
CUtils::PrintMessage("\t--makepem Generates a pemfile for use with SSL");
CUtils::PrintMessage("\t--encrypt-pem Encrypts the pemfile");
#endif /* HAVE_LIBSSL */
}
void die(int sig) {
signal( SIGSEGV, SIG_DFL );
signal( SIGABRT, SIG_DFL );
signal( SIGPIPE, SIG_DFL );
#ifdef _DEBUG
CUtils::PrintMessage("Exiting on SIG [" + CUtils::ToString(sig) + "]");
if ( ( sig == SIGABRT ) || ( sig == SIGSEGV ) )
abort();
#endif /* _DEBUG */
delete CZNC::New();
exit(sig);
}
int main(int argc, char** argv) {
string sConfig;
#ifdef HAVE_LIBSSL
// initialize ssl, allow client to have compression enabled if desired
InitSSL( CT_ZLIB );
#endif /* HAVE_LIBSSL */
int iArg, iOptIndex = -1;
#ifdef HAVE_LIBSSL
bool bMakePem = false;
bool bEncPem = false;
#endif /* HAVE_LIBSSL */
bool bMakePass = false;
while( ( iArg = getopt_long( argc, argv, "h", g_LongOpts, &iOptIndex ) != -1 ) ) {
switch( iArg ) {
case 1:
{ // long options
if ( iOptIndex >= 0 ) {
string sOption = Lower( g_LongOpts[iOptIndex].name );
if ( sOption == "makepass" )
bMakePass = true;
#ifdef HAVE_LIBSSL
else if ( sOption == "makepem" )
bMakePem = true;
else if ( sOption == "encrypt-pem" )
bEncPem = true;
#endif /* HAVE_LIBSSL */
else if ( sOption == "help" ) {
GenerateHelp( argv[0] );
return( 0 );
}
} else {
GenerateHelp( argv[0] );
return( 1 );
}
break;
}
case 'h':
GenerateHelp( argv[0] );
return( 0 );
default :
{
GenerateHelp( argv[0] );
return( 1 );
}
}
}
if ( optind < argc )
sConfig = argv[optind];
#ifdef HAVE_LIBSSL
if (bMakePem) {
CZNC* pZNC = CZNC::New();
pZNC->InitDirs("");
string sPemFile = pZNC->GetPemLocation();
CUtils::PrintAction("Writing Pem file [" + sPemFile + "]");
if (CFile::Exists(sPemFile)) {
CUtils::PrintStatus(false, "File already exists");
delete pZNC;
return 1;
}
FILE *f = fopen( sPemFile.c_str(), "w" );
if (!f) {
CUtils::PrintStatus(false, "Unable to open");
delete pZNC;
return 1 ;
}
CUtils::GenerateCert( f, bEncPem );
fclose(f);
CUtils::PrintStatus(true);
delete pZNC;
return 0;
}
#endif /* HAVE_LIBSSL */
if ( bMakePass ) {
char* pass = CUtils::GetPass("Enter Password");
char* pass1 = (char*) malloc(strlen(pass) +1);
strcpy(pass1, pass); // Make a copy of this since it is stored in a static buffer and will be overwritten when we fill pass2 below
memset((char*) pass, 0, strlen(pass)); // null out our pass so it doesn't sit in memory
char* pass2 = CUtils::GetPass("Confirm Password");
int iLen = strlen(pass1);
if (strcmp(pass1, pass2) == 0) {
CUtils::PrintMessage("Use this in the <User> section of your config:");
CUtils::PrintMessage("Pass = " + string((const char*) CMD5(pass1, iLen)) + " -");
} else {
CUtils::PrintError("The supplied passwords do not match");
}
memset((char*) pass1, 0, iLen); // null out our pass so it doesn't sit in memory
memset((char*) pass2, 0, strlen(pass2)); // null out our pass so it doesn't sit in memory
free(pass1);
return 0;
}
CZNC* pZNC = CZNC::New();
pZNC->InitDirs(((argc) ? argv[0] : ""));
if (!pZNC->ParseConfig(sConfig)) {
CUtils::PrintError("Unrecoverable config error.");
delete pZNC;
return 1;
}
if (!pZNC->GetListenPort()) {
CUtils::PrintError("You must supply a ListenPort in your config.");
delete pZNC;
return 1;
}
if (!pZNC->OnBoot()) {
CUtils::PrintError("Exiting due to module boot errors.");
delete pZNC;
return 1;
}
#ifndef _DEBUG
CUtils::PrintAction("Forking into the background");
int iPid = fork();
if (iPid == -1) {
CUtils::PrintStatus(false, strerror(errno));
delete pZNC;
exit(1);
}
if (iPid > 0) {
CUtils::PrintStatus(true, "[pid: " + CUtils::ToString(iPid) + "]");
pZNC->WritePidFile(iPid);
CUtils::PrintMessage("ZNC - by prozac@gmail.com");
exit(0);
}
// Redirect std in/out/err to /dev/null
close(0); open("/dev/null", O_RDONLY);
close(1); open("/dev/null", O_WRONLY);
close(2); open("/dev/null", O_WRONLY);
#endif
struct sigaction sa;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &sa, (struct sigaction *)NULL);
sa.sa_handler = die;
sigaction(SIGINT, &sa, (struct sigaction *)NULL);
sigaction(SIGILL, &sa, (struct sigaction *)NULL);
sigaction(SIGQUIT, &sa, (struct sigaction *)NULL);
sigaction(SIGBUS, &sa, (struct sigaction *)NULL);
sigaction(SIGSEGV, &sa, (struct sigaction *)NULL);
sigaction(SIGTERM, &sa, (struct sigaction *)NULL);
int iRet = 0;
try {
iRet = pZNC->Loop();
} catch (CException e) {
// EX_Shutdown is thrown to exit
switch (e.GetType()) {
case CException::EX_Shutdown:
iRet = 0;
default:
iRet = 1;
}
}
delete pZNC;
return iRet;
}
<commit_msg>Changed method of obtaining pass to CUtils::GetHashPass()<commit_after>#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include <signal.h>
#include "znc.h"
#include "md5.h"
static struct option g_LongOpts[] =
{
{ "help", 0, NULL, 0 },
{ "makepass", 0, NULL, 0 },
#ifdef HAVE_LIBSSL
{ "makepem", 0, NULL, 0 },
{ "encrypt-pem", 0, NULL, 0 },
#endif /* HAVE_LIBSSL */
{ NULL }
};
void GenerateHelp( const char *appname )
{
CUtils::PrintMessage("USAGE: " + string(appname) + " [options] [znc.conf]");
CUtils::PrintMessage("Options are:");
CUtils::PrintMessage("\t--help");
CUtils::PrintMessage("\t--makepass Generates a password for use in config");
#ifdef HAVE_LIBSSL
CUtils::PrintMessage("\t--makepem Generates a pemfile for use with SSL");
CUtils::PrintMessage("\t--encrypt-pem Encrypts the pemfile");
#endif /* HAVE_LIBSSL */
}
void die(int sig) {
signal( SIGSEGV, SIG_DFL );
signal( SIGABRT, SIG_DFL );
signal( SIGPIPE, SIG_DFL );
#ifdef _DEBUG
CUtils::PrintMessage("Exiting on SIG [" + CUtils::ToString(sig) + "]");
if ( ( sig == SIGABRT ) || ( sig == SIGSEGV ) )
abort();
#endif /* _DEBUG */
delete CZNC::New();
exit(sig);
}
int main(int argc, char** argv) {
string sConfig;
#ifdef HAVE_LIBSSL
// initialize ssl, allow client to have compression enabled if desired
InitSSL( CT_ZLIB );
#endif /* HAVE_LIBSSL */
int iArg, iOptIndex = -1;
#ifdef HAVE_LIBSSL
bool bMakePem = false;
bool bEncPem = false;
#endif /* HAVE_LIBSSL */
bool bMakePass = false;
while( ( iArg = getopt_long( argc, argv, "h", g_LongOpts, &iOptIndex ) != -1 ) ) {
switch( iArg ) {
case 1:
{ // long options
if ( iOptIndex >= 0 ) {
string sOption = Lower( g_LongOpts[iOptIndex].name );
if ( sOption == "makepass" )
bMakePass = true;
#ifdef HAVE_LIBSSL
else if ( sOption == "makepem" )
bMakePem = true;
else if ( sOption == "encrypt-pem" )
bEncPem = true;
#endif /* HAVE_LIBSSL */
else if ( sOption == "help" ) {
GenerateHelp( argv[0] );
return( 0 );
}
} else {
GenerateHelp( argv[0] );
return( 1 );
}
break;
}
case 'h':
GenerateHelp( argv[0] );
return( 0 );
default :
{
GenerateHelp( argv[0] );
return( 1 );
}
}
}
if ( optind < argc )
sConfig = argv[optind];
#ifdef HAVE_LIBSSL
if (bMakePem) {
CZNC* pZNC = CZNC::New();
pZNC->InitDirs("");
string sPemFile = pZNC->GetPemLocation();
CUtils::PrintAction("Writing Pem file [" + sPemFile + "]");
if (CFile::Exists(sPemFile)) {
CUtils::PrintStatus(false, "File already exists");
delete pZNC;
return 1;
}
FILE *f = fopen( sPemFile.c_str(), "w" );
if (!f) {
CUtils::PrintStatus(false, "Unable to open");
delete pZNC;
return 1 ;
}
CUtils::GenerateCert( f, bEncPem );
fclose(f);
CUtils::PrintStatus(true);
delete pZNC;
return 0;
}
#endif /* HAVE_LIBSSL */
if ( bMakePass ) {
string sHash = CUtils::GetHashPass();
CUtils::PrintMessage("Use this in the <User> section of your config:");
CUtils::PrintMessage("Pass = " + sHash + " -");
return 0;
}
CZNC* pZNC = CZNC::New();
pZNC->InitDirs(((argc) ? argv[0] : ""));
if (!pZNC->ParseConfig(sConfig)) {
CUtils::PrintError("Unrecoverable config error.");
delete pZNC;
return 1;
}
if (!pZNC->GetListenPort()) {
CUtils::PrintError("You must supply a ListenPort in your config.");
delete pZNC;
return 1;
}
if (!pZNC->OnBoot()) {
CUtils::PrintError("Exiting due to module boot errors.");
delete pZNC;
return 1;
}
#ifndef _DEBUG
CUtils::PrintAction("Forking into the background");
int iPid = fork();
if (iPid == -1) {
CUtils::PrintStatus(false, strerror(errno));
delete pZNC;
exit(1);
}
if (iPid > 0) {
CUtils::PrintStatus(true, "[pid: " + CUtils::ToString(iPid) + "]");
pZNC->WritePidFile(iPid);
CUtils::PrintMessage("ZNC - by prozac@gmail.com");
exit(0);
}
// Redirect std in/out/err to /dev/null
close(0); open("/dev/null", O_RDONLY);
close(1); open("/dev/null", O_WRONLY);
close(2); open("/dev/null", O_WRONLY);
#endif
struct sigaction sa;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &sa, (struct sigaction *)NULL);
sa.sa_handler = die;
sigaction(SIGINT, &sa, (struct sigaction *)NULL);
sigaction(SIGILL, &sa, (struct sigaction *)NULL);
sigaction(SIGQUIT, &sa, (struct sigaction *)NULL);
sigaction(SIGBUS, &sa, (struct sigaction *)NULL);
sigaction(SIGSEGV, &sa, (struct sigaction *)NULL);
sigaction(SIGTERM, &sa, (struct sigaction *)NULL);
int iRet = 0;
try {
iRet = pZNC->Loop();
} catch (CException e) {
// EX_Shutdown is thrown to exit
switch (e.GetType()) {
case CException::EX_Shutdown:
iRet = 0;
default:
iRet = 1;
}
}
delete pZNC;
return iRet;
}
<|endoftext|> |
<commit_before>e77de7ae-2e4e-11e5-97b8-28cfe91dbc4b<commit_msg>e7860fb0-2e4e-11e5-a02b-28cfe91dbc4b<commit_after>e7860fb0-2e4e-11e5-a02b-28cfe91dbc4b<|endoftext|> |
<commit_before>788c3c12-5216-11e5-88bf-6c40088e03e4<commit_msg>7892c970-5216-11e5-b8a6-6c40088e03e4<commit_after>7892c970-5216-11e5-b8a6-6c40088e03e4<|endoftext|> |
<commit_before>468a0b28-2e3a-11e5-ab1b-c03896053bdd<commit_msg>46988cc0-2e3a-11e5-a6e6-c03896053bdd<commit_after>46988cc0-2e3a-11e5-a6e6-c03896053bdd<|endoftext|> |
<commit_before>6c120da4-2fa5-11e5-ae2f-00012e3d3f12<commit_msg>6c13bb54-2fa5-11e5-9c55-00012e3d3f12<commit_after>6c13bb54-2fa5-11e5-9c55-00012e3d3f12<|endoftext|> |
<commit_before>acc02480-327f-11e5-ac81-9cf387a8033e<commit_msg>acc62b51-327f-11e5-8fae-9cf387a8033e<commit_after>acc62b51-327f-11e5-8fae-9cf387a8033e<|endoftext|> |
<commit_before>4b3ef4a2-2e3a-11e5-8f08-c03896053bdd<commit_msg>4b52ce6c-2e3a-11e5-bc60-c03896053bdd<commit_after>4b52ce6c-2e3a-11e5-bc60-c03896053bdd<|endoftext|> |
<commit_before>95f368ab-327f-11e5-af95-9cf387a8033e<commit_msg>95fa4fbd-327f-11e5-996d-9cf387a8033e<commit_after>95fa4fbd-327f-11e5-996d-9cf387a8033e<|endoftext|> |
<commit_before>5e08c46c-5216-11e5-8c4b-6c40088e03e4<commit_msg>5e1007c2-5216-11e5-87c9-6c40088e03e4<commit_after>5e1007c2-5216-11e5-87c9-6c40088e03e4<|endoftext|> |
<commit_before>#include "config.h"
#include <fstream>
#include <iostream>
#include "lexer.hpp"
#include "parser.hpp"
#include "ast.hpp"
#include "c_gen.hpp"
int main(int argc, char** argv)
{
std::cout << "Rune v" << VERSION_MAJOR << "." << VERSION_MINOR << "." << VERSION_PATCH << "\n";
if (argc < 2) {
std::cout << "You must specify a file to compile.\n";
return 0;
}
std::cout << "Reading file..." << std::endl;
// Read the file into a string
std::ifstream f(argv[1], std::ios::in | std::ios::binary);
std::string contents;
if (f) {
f.seekg(0, std::ios::end);
contents.resize(f.tellg());
f.seekg(0, std::ios::beg);
f.read(&contents[0], contents.size());
f.close();
}
std::cout << "Lexing..." << std::endl;
auto tokens = lex_string(contents);
for (auto& t: tokens) {
std::cout << "[L" << t.line + 1 << ", C" << t.column << ", " << t.type << "]:\t" << " " << t.text << std::endl;
}
AST ast;
//try {
std::cout << "Parsing..." << std::endl;
ast = parse_tokens(argv[1], tokens);
ast.print();
//}
//catch (ParseError e) {
// throw e;
//}
// Write C output
if (argc > 2) {
std::ofstream f_out(argv[2], std::ios::out | std::ios::binary);
if (f_out)
gen_c_code(ast, f_out);
}
return 0;
}
<commit_msg>Clean Up: Renable some exception handling<commit_after>#include "config.h"
#include <fstream>
#include <iostream>
#include "lexer.hpp"
#include "parser.hpp"
#include "ast.hpp"
#include "c_gen.hpp"
int main(int argc, char** argv)
{
std::cout << "Rune v" << VERSION_MAJOR << "." << VERSION_MINOR << "." << VERSION_PATCH << "\n";
if (argc < 2) {
std::cout << "You must specify a file to compile.\n";
return 0;
}
std::cout << "Reading file..." << std::endl;
// Read the file into a string
std::ifstream f(argv[1], std::ios::in | std::ios::binary);
std::string contents;
if (f) {
f.seekg(0, std::ios::end);
contents.resize(f.tellg());
f.seekg(0, std::ios::beg);
f.read(&contents[0], contents.size());
f.close();
}
std::cout << "Lexing..." << std::endl;
auto tokens = lex_string(contents);
for (auto& t: tokens) {
std::cout << "[L" << t.line + 1 << ", C" << t.column << ", " << t.type << "]:\t" << " " << t.text << std::endl;
}
AST ast;
try {
std::cout << "Parsing..." << std::endl;
ast = parse_tokens(argv[1], tokens);
ast.print();
}
catch (ParseError e) {
throw e;
}
// Write C output
if (argc > 2) {
std::ofstream f_out(argv[2], std::ios::out | std::ios::binary);
if (f_out)
gen_c_code(ast, f_out);
}
return 0;
}
<|endoftext|> |
<commit_before>8c3d208e-2d14-11e5-af21-0401358ea401<commit_msg>8c3d208f-2d14-11e5-af21-0401358ea401<commit_after>8c3d208f-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>81705e21-2d3d-11e5-9be6-c82a142b6f9b<commit_msg>81fde080-2d3d-11e5-9561-c82a142b6f9b<commit_after>81fde080-2d3d-11e5-9561-c82a142b6f9b<|endoftext|> |
<commit_before>5dee1eba-2d3d-11e5-a1f1-c82a142b6f9b<commit_msg>5e5f492b-2d3d-11e5-9e28-c82a142b6f9b<commit_after>5e5f492b-2d3d-11e5-9e28-c82a142b6f9b<|endoftext|> |
<commit_before>5d2865cb-2d16-11e5-af21-0401358ea401<commit_msg>5d2865cc-2d16-11e5-af21-0401358ea401<commit_after>5d2865cc-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>f3690eac-585a-11e5-be6a-6c40088e03e4<commit_msg>f36fbb80-585a-11e5-9362-6c40088e03e4<commit_after>f36fbb80-585a-11e5-9362-6c40088e03e4<|endoftext|> |
<commit_before>#include "server.hpp"
//Added for the json-example:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include<fstream>
using namespace std;
using namespace SimpleWeb;
//Added for the json-example:
using namespace boost::property_tree;
int main() {
//HTTP-server at port 8080 using 4 threads
Server<HTTP> httpserver(8080, 4);
//Add resources using regular expression for path, a method-string, and an anonymous function
//POST-example for the path /string, responds the posted string
httpserver.resources["^/string/?$"]["POST"]=[](ostream& response, const Request& request, const smatch& path_match) {
//Retrieve string from istream (*request.content)
stringstream ss;
*request.content >> ss.rdbuf();
string content=ss.str();
response << "HTTP/1.1 200 OK\r\nContent-Length: " << content.length() << "\r\n\r\n" << content;
};
//POST-example for the path /json, responds firstName+" "+lastName from the posted json
//Responds with an appropriate error message if the posted json is not valid, or if firstName or lastName is missing
//Example posted json:
//{
// "firstName": "John",
// "lastName": "Smith",
// "age": 25
//}
httpserver.resources["^/json/?$"]["POST"]=[](ostream& response, const Request& request, const smatch& path_match) {
try {
ptree pt;
read_json(*request.content, pt);
string name=pt.get<string>("firstName")+" "+pt.get<string>("lastName");
response << "HTTP/1.1 200 OK\r\nContent-Length: " << name.length() << "\r\n\r\n" << name;
}
catch(exception& e) {
response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << strlen(e.what()) << "\r\n\r\n" << e.what();
}
};
//GET-example for the path /info
//Responds with request-information
httpserver.resources["^/info/?$"]["GET"]=[](ostream& response, const Request& request, const smatch& path_match) {
stringstream content_stream;
content_stream << "<h1>Request:</h1>";
content_stream << request.method << " " << request.path << " HTTP/" << request.http_version << "<br>";
for(auto& header: request.header) {
content_stream << header.first << ": " << header.second << "<br>";
}
//find length of content_stream (length received using content_stream.tellp())
content_stream.seekp(0, ios::end);
response << "HTTP/1.1 200 OK\r\nContent-Length: " << content_stream.tellp() << "\r\n\r\n" << content_stream.rdbuf();
};
//GET-example for the path /match/[number], responds with the matched string in path (number)
//For instance a request GET /match/123 will receive: 123
httpserver.resources["^/match/([0-9]+)/?$"]["GET"]=[](ostream& response, const Request& request, const smatch& path_match) {
string number=path_match[1];
response << "HTTP/1.1 200 OK\r\nContent-Length: " << number.length() << "\r\n\r\n" << number;
};
//Default GET-example. If no other matches, this anonymous function will be called.
//Will respond with content in the web/-directory, and its subdirectories.
//Default file: index.html
//Can for instance be used to retrieve a HTML 5 client that uses REST-resources on this server
httpserver.default_resource["^/?(.*)$"]["GET"]=[](ostream& response, const Request& request, const smatch& path_match) {
string filename="web/";
string path=path_match[1];
//Remove all but the last '.' (so we can't leave the web-directory)
size_t last_pos=path.rfind(".");
size_t current_pos=0;
size_t pos;
while((pos=path.find('.', current_pos))!=string::npos && pos!=last_pos) {
cout << pos << endl;
current_pos=pos;
path.erase(pos, 1);
last_pos--;
}
filename+=path;
ifstream ifs;
//HTTP file-or-directory check:
if(filename.find('.')!=string::npos) {
ifs.open(filename, ifstream::in);
}
else {
if(filename[filename.length()-1]!='/')
filename+='/';
filename+="index.html";
ifs.open(filename, ifstream::in);
}
if(ifs) {
ifs.seekg(0, ios::end);
size_t length=ifs.tellg();
ifs.seekg(0, ios::beg);
response << "HTTP/1.1 200 OK\r\nContent-Length: " << length << "\r\n\r\n" << ifs.rdbuf();
ifs.close();
}
else {
string content="Could not open file "+filename;
response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << content.length() << "\r\n\r\n" << content;
}
};
//Start HTTP-server
httpserver.start();
return 0;
}
<commit_msg>fixed typos<commit_after>#include "server.hpp"
//Added for the json-example:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include<fstream>
using namespace std;
using namespace SimpleWeb;
//Added for the json-example:
using namespace boost::property_tree;
int main() {
//HTTP-server at port 8080 using 4 threads
Server<HTTP> httpserver(8080, 4);
//Add resources using regular expression for path, a method-string, and an anonymous function
//POST-example for the path /string, responds the posted string
httpserver.resources["^/string/?$"]["POST"]=[](ostream& response, const Request& request, const smatch& path_match) {
//Retrieve string from istream (*request.content)
stringstream ss;
*request.content >> ss.rdbuf();
string content=ss.str();
response << "HTTP/1.1 200 OK\r\nContent-Length: " << content.length() << "\r\n\r\n" << content;
};
//POST-example for the path /json, responds firstName+" "+lastName from the posted json
//Responds with an appropriate error message if the posted json is not valid, or if firstName or lastName is missing
//Example posted json:
//{
// "firstName": "John",
// "lastName": "Smith",
// "age": 25
//}
httpserver.resources["^/json/?$"]["POST"]=[](ostream& response, const Request& request, const smatch& path_match) {
try {
ptree pt;
read_json(*request.content, pt);
string name=pt.get<string>("firstName")+" "+pt.get<string>("lastName");
response << "HTTP/1.1 200 OK\r\nContent-Length: " << name.length() << "\r\n\r\n" << name;
}
catch(exception& e) {
response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << strlen(e.what()) << "\r\n\r\n" << e.what();
}
};
//GET-example for the path /info
//Responds with request-information
httpserver.resources["^/info/?$"]["GET"]=[](ostream& response, const Request& request, const smatch& path_match) {
stringstream content_stream;
content_stream << "<h1>Request:</h1>";
content_stream << request.method << " " << request.path << " HTTP/" << request.http_version << "<br>";
for(auto& header: request.header) {
content_stream << header.first << ": " << header.second << "<br>";
}
//find length of content_stream (length received using content_stream.tellp())
content_stream.seekp(0, ios::end);
response << "HTTP/1.1 200 OK\r\nContent-Length: " << content_stream.tellp() << "\r\n\r\n" << content_stream.rdbuf();
};
//GET-example for the path /match/[number], responds with the matched string in path (number)
//For instance a request GET /match/123 will receive: 123
httpserver.resources["^/match/([0-9]+)/?$"]["GET"]=[](ostream& response, const Request& request, const smatch& path_match) {
string number=path_match[1];
response << "HTTP/1.1 200 OK\r\nContent-Length: " << number.length() << "\r\n\r\n" << number;
};
//Default GET-example. If no other matches, this anonymous function will be called.
//Will respond with content in the web/-directory, and its subdirectories.
//Default file: index.html
//Can for instance be used to retrieve an HTML 5 client that uses REST-resources on this server
httpserver.default_resource["^/?(.*)$"]["GET"]=[](ostream& response, const Request& request, const smatch& path_match) {
string filename="web/";
string path=path_match[1];
//Remove all but the last '.' (so we can't leave the web-directory)
size_t last_pos=path.rfind(".");
size_t current_pos=0;
size_t pos;
while((pos=path.find('.', current_pos))!=string::npos && pos!=last_pos) {
cout << pos << endl;
current_pos=pos;
path.erase(pos, 1);
last_pos--;
}
filename+=path;
ifstream ifs;
//HTTP file-or-directory check:
if(filename.find('.')!=string::npos) {
ifs.open(filename, ifstream::in);
}
else {
if(filename[filename.length()-1]!='/')
filename+='/';
filename+="index.html";
ifs.open(filename, ifstream::in);
}
if(ifs) {
ifs.seekg(0, ios::end);
size_t length=ifs.tellg();
ifs.seekg(0, ios::beg);
response << "HTTP/1.1 200 OK\r\nContent-Length: " << length << "\r\n\r\n" << ifs.rdbuf();
ifs.close();
}
else {
string content="Could not open file "+filename;
response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << content.length() << "\r\n\r\n" << content;
}
};
//Start HTTP-server
httpserver.start();
return 0;
}
<|endoftext|> |
<commit_before>ccfe2d87-2747-11e6-9c88-e0f84713e7b8<commit_msg>Stuff changed<commit_after>cdf0c87d-2747-11e6-b467-e0f84713e7b8<|endoftext|> |
<commit_before>64aac252-2fa5-11e5-a583-00012e3d3f12<commit_msg>64acbe24-2fa5-11e5-84e0-00012e3d3f12<commit_after>64acbe24-2fa5-11e5-84e0-00012e3d3f12<|endoftext|> |
<commit_before>dff020b3-313a-11e5-b594-3c15c2e10482<commit_msg>dff622fa-313a-11e5-b916-3c15c2e10482<commit_after>dff622fa-313a-11e5-b916-3c15c2e10482<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <boost/lexical_cast.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <sstream>
#include <string>
using namespace std;
void testVector();
void testLexicalCast();
void testFunction();
void testBind();
int main()
{
cout << "Hello, world!" << endl;
//testLexicalCast();
//testFunction();
testBind();
return 0;
}
void testVector()
{
std::vector<int> numbers;
numbers.push_back(1);
numbers.push_back(2);
for (int i = 0; i < (int)numbers.size(); ++i)
cout << i << endl;
}
void testLexicalCast()
{
// 以下会抛出异常
//cout << boost::lexical_cast<int>(" 123 ") << endl;
//cout << boost::lexical_cast<int>("123 ") << endl;
//cout << boost::lexical_cast<int>("12 3") << endl;
//cout << boost::lexical_cast<int>("1 2 3") << endl;
// 空字符串会抛出异常
//cout << boost::lexical_cast<int>("") << endl;
// 不支持十六进制
//cout << boost::lexical_cast<int>("0x0362") << endl;
// 十六进制字符串转成整数 0x前缀可有可无
stringstream ss;
ss << hex << "0x0362f"; // 13871
int i;
ss >> i;
cout << i << endl;
// 十六进制字符串转成整数 C++11 中的 std::stoi <string>
cout << std::stoi("0x0362f", 0, 16) << endl;
cout << std::stoi("0362f", 0, 16) << endl;
//cout << std::stoi("", 0, 16) << endl; // 抛出异常
// 字符串转换为bool 只支持 0 和 1,不支持true或false或其他整数值
//cout << boost::lexical_cast<bool>("true") << endl;
//cout << boost::lexical_cast<bool>("false") << endl;
//cout << boost::lexical_cast<bool>("True") << endl;
//cout << boost::lexical_cast<bool>("-1") << endl;
//cout << boost::lexical_cast<bool>("2") << endl;
cout << boost::lexical_cast<bool>("1") << endl;
cout << boost::lexical_cast<bool>("0") << endl;
// test
}
void func(int i)
{
cout << i << endl;
}
class Test1
{
public:
void func()
{
cout << "Test1::func()" << endl;
}
void func2(int i)
{
cout << "Test1::func()" << i << endl;
}
};
void testFunction()
{
boost::function<void (int)> f1 = &func;
f1(12);
Test1 t1;
boost::function<void (Test1*)> f2 = &Test1::func;
f2(&t1);
boost::function<void (Test1*, int)> f3 = &Test1::func2;
f3(&t1, 100);
}
void testBind()
{
Test1 t1;
auto f1 = boost::bind(&Test1::func2, &t1, _1);
f1(100);
}
<commit_msg>Test c++11 lambda<commit_after>#include <iostream>
#include <vector>
#include <boost/lexical_cast.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <sstream>
#include <string>
#include <algorithm>
using namespace std;
void testVector();
void testLexicalCast();
void testFunction();
void testBind();
void testLambda();
int main()
{
cout << "Hello, world!" << endl;
//testLexicalCast();
//testFunction();
//testBind();
testLambda();
return 0;
}
void testVector()
{
std::vector<int> numbers;
numbers.push_back(1);
numbers.push_back(2);
for (int i = 0; i < (int)numbers.size(); ++i)
cout << i << endl;
}
void testLexicalCast()
{
// 以下会抛出异常
//cout << boost::lexical_cast<int>(" 123 ") << endl;
//cout << boost::lexical_cast<int>("123 ") << endl;
//cout << boost::lexical_cast<int>("12 3") << endl;
//cout << boost::lexical_cast<int>("1 2 3") << endl;
// 空字符串会抛出异常
//cout << boost::lexical_cast<int>("") << endl;
// 不支持十六进制
//cout << boost::lexical_cast<int>("0x0362") << endl;
// 十六进制字符串转成整数 0x前缀可有可无
stringstream ss;
ss << hex << "0x0362f"; // 13871
int i;
ss >> i;
cout << i << endl;
// 十六进制字符串转成整数 C++11 中的 std::stoi <string>
cout << std::stoi("0x0362f", 0, 16) << endl;
cout << std::stoi("0362f", 0, 16) << endl;
//cout << std::stoi("", 0, 16) << endl; // 抛出异常
// 字符串转换为bool 只支持 0 和 1,不支持true或false或其他整数值
//cout << boost::lexical_cast<bool>("true") << endl;
//cout << boost::lexical_cast<bool>("false") << endl;
//cout << boost::lexical_cast<bool>("True") << endl;
//cout << boost::lexical_cast<bool>("-1") << endl;
//cout << boost::lexical_cast<bool>("2") << endl;
cout << boost::lexical_cast<bool>("1") << endl;
cout << boost::lexical_cast<bool>("0") << endl;
// test
}
void func(int i)
{
cout << i << endl;
}
class Test1
{
public:
void func()
{
cout << "Test1::func()" << endl;
}
void func2(int i)
{
cout << "Test1::func()" << i << endl;
}
};
void testFunction()
{
boost::function<void (int)> f1 = &func;
f1(12);
Test1 t1;
boost::function<void (Test1*)> f2 = &Test1::func;
f2(&t1);
boost::function<void (Test1*, int)> f3 = &Test1::func2;
f3(&t1, 100);
}
void testBind()
{
// auto c++11
Test1 t1;
auto f1 = boost::bind(&Test1::func2, &t1, _1);
f1(100);
}
void testLambda()
{
// c++11 Lambda表达式
vector<int> vec;
for (int i = 0; i < 5; ++i)
vec.push_back(i);
int a = 1;
int b = 2;
// []内的参数指的是Lambda表达式可以得到的外部变量
// 如果在[]中传入=的话,表示可以取得所有的外部变量,如a、b
// ()内的参数是每次调用函数时传入的参数
// ->后加上的是Lambda表达式返回值的类型
for_each(vec.begin(), vec.end(), [b](int& x){ cout << x + b << endl; });
for_each(vec.begin(), vec.end(), [=](int& x){ cout << a + b << endl; });
for_each(vec.begin(), vec.end(), [=](int& x)->int{ cout << a + b << endl; return x; });
}
<|endoftext|> |
<commit_before>// STL
#include <iostream>
#include <memory>
#include <string>
#include <functional>
// PDTK
#include <cxxutils/hashing.h>
// incanto
#include "code_printer/cpp.h"
int main(int argc, char *argv[])
{
(void)argc;
(void)argv;
std::unique_ptr<CodePrinterBase> printer;
std::string filename = "/tmp/demo-file.h";
printer = std::make_unique<CppCodePrinter>();
if(printer != nullptr)
{
printer->local_functions.push_back({"local_example", {{"posix::fd_t", "fd"}, {"long", "demo"}, {"std::string", "lol"}}});
printer->remote_functions.push_back({"remote_example", {{"std::string", "lulz"}, {"std::vector<int>", "arr"}}});
printer->local_functions.push_back({"local_example2", {{"std::string", "lulz"}, {"std::vector<int>", "arr"}}});
printer->remote_functions.push_back({"remote_example2", {{"long", "demo"}, {"posix::fd_t", "fd"}, {"std::string", "lol"}}});
try
{
printer->file_open(filename);
printer->print_local();
printer->print_remote();
printer->file_close();
std::cout << "success!" << std::endl;
}
catch(std::system_error e) { std::cout << "error: " << e.what() << std::endl; }
catch(...) { std::cout << "unexpected error!" << std::endl; }
}
return 0;
}
<commit_msg>no idea ;)<commit_after>// STL
#include <iostream>
#include <memory>
#include <string>
#include <functional>
// PDTK
#include <cxxutils/hashing.h>
// incanto
#include "code_printer/cpp.h"
int main(int argc, char *argv[])
{
(void)argc;
(void)argv;
std::unique_ptr<CodePrinterBase> printer;
std::string filename = "/tmp/demo-file.h";
printer = std::make_unique<CppCodePrinter>();
if(printer != nullptr)
{
throw(std::system_error((int)std::errc::invalid_argument, std::generic_category(), "Pointers and references are not allowed with the exception of string literals."));
throw(std::system_error((int)std::errc::invalid_argument, std::generic_category(), "Only \"fixed width integer types\", STL containers thereof, strings and posix::fd_t types are allowed."));
printer->local_functions .push_back({"local_example" , {{"posix::fd_t", "fd"}, {"long", "demo"}, {"std::string", "lol"}}});
printer->remote_functions.push_back({"remote_example" , {{"std::string", "lulz"}, {"std::vector<int>", "arr"}}});
printer->local_functions .push_back({"local_example2" , {{"std::string", "lulz"}, {"std::vector<int>", "arr"}}});
printer->remote_functions.push_back({"remote_example2", {{"long", "demo"}, {"posix::fd_t", "fd"}, {"std::string", "lol"}}});
try
{
printer->file_open(filename);
printer->print_local();
printer->print_remote();
printer->file_close();
std::cout << "success!" << std::endl;
}
catch(std::system_error e) { std::cout << "error: " << e.what() << std::endl; }
catch(...) { std::cout << "unexpected error!" << std::endl; }
}
return 0;
}
<|endoftext|> |
<commit_before>36b75040-5216-11e5-a79b-6c40088e03e4<commit_msg>36bdf5f8-5216-11e5-b994-6c40088e03e4<commit_after>36bdf5f8-5216-11e5-b994-6c40088e03e4<|endoftext|> |
<commit_before>de338c6e-313a-11e5-b7fc-3c15c2e10482<commit_msg>de395005-313a-11e5-b00d-3c15c2e10482<commit_after>de395005-313a-11e5-b00d-3c15c2e10482<|endoftext|> |
<commit_before>b9062442-2e4f-11e5-8d5d-28cfe91dbc4b<commit_msg>b90cf833-2e4f-11e5-85c9-28cfe91dbc4b<commit_after>b90cf833-2e4f-11e5-85c9-28cfe91dbc4b<|endoftext|> |
<commit_before>ae466617-2e4f-11e5-bfaf-28cfe91dbc4b<commit_msg>ae4d6b0c-2e4f-11e5-ad30-28cfe91dbc4b<commit_after>ae4d6b0c-2e4f-11e5-ad30-28cfe91dbc4b<|endoftext|> |
<commit_before>b2782fb3-2e4f-11e5-a8fb-28cfe91dbc4b<commit_msg>b27f100f-2e4f-11e5-8e16-28cfe91dbc4b<commit_after>b27f100f-2e4f-11e5-8e16-28cfe91dbc4b<|endoftext|> |
<commit_before>033fe4ae-2e4f-11e5-9e66-28cfe91dbc4b<commit_msg>03488dc0-2e4f-11e5-8933-28cfe91dbc4b<commit_after>03488dc0-2e4f-11e5-8933-28cfe91dbc4b<|endoftext|> |
<commit_before>777e5a20-2d53-11e5-baeb-247703a38240<commit_msg>777ed874-2d53-11e5-baeb-247703a38240<commit_after>777ed874-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>4a77ed85-ad5b-11e7-8be3-ac87a332f658<commit_msg>add file<commit_after>4ae2c763-ad5b-11e7-a205-ac87a332f658<|endoftext|> |
<commit_before>ce8c4a0f-ad5b-11e7-9d84-ac87a332f658<commit_msg>Nooooooooooooooooooooooooooooooooooooo<commit_after>cf191359-ad5b-11e7-9965-ac87a332f658<|endoftext|> |
<commit_before>c61c4d07-327f-11e5-86b0-9cf387a8033e<commit_msg>c6228acf-327f-11e5-82b8-9cf387a8033e<commit_after>c6228acf-327f-11e5-82b8-9cf387a8033e<|endoftext|> |
<commit_before>ba441fcf-4b02-11e5-9570-28cfe9171a43<commit_msg>Finished?<commit_after>ba4e942e-4b02-11e5-9e58-28cfe9171a43<|endoftext|> |
<commit_before>cad1fce3-2e4e-11e5-b053-28cfe91dbc4b<commit_msg>cad93017-2e4e-11e5-93ff-28cfe91dbc4b<commit_after>cad93017-2e4e-11e5-93ff-28cfe91dbc4b<|endoftext|> |
<commit_before>04da34c5-2e4f-11e5-851e-28cfe91dbc4b<commit_msg>04e10902-2e4f-11e5-900b-28cfe91dbc4b<commit_after>04e10902-2e4f-11e5-900b-28cfe91dbc4b<|endoftext|> |
<commit_before>e8f840ae-327f-11e5-bef2-9cf387a8033e<commit_msg>e8fe1fe3-327f-11e5-9808-9cf387a8033e<commit_after>e8fe1fe3-327f-11e5-9808-9cf387a8033e<|endoftext|> |
<commit_before>809e919a-2d15-11e5-af21-0401358ea401<commit_msg>809e919b-2d15-11e5-af21-0401358ea401<commit_after>809e919b-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>8b3325ac-2d14-11e5-af21-0401358ea401<commit_msg>8b3325ad-2d14-11e5-af21-0401358ea401<commit_after>8b3325ad-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>/*
* main.cpp
*/
#include <iostream>
#include <iomanip>
#include <memory>
#include <chrono>
#include <cstddef>
#include <new>
#include <cassert>
#include <type_traits>
#include <sstream>
#include <functional>
#include <cstring>
#include <cstdlib>
#include <sys/mman.h>
#ifdef USE_BACKWARD_CPP
#include "backward-cpp/backward.hpp"
#endif
#include "stats.hpp"
#include "version.hpp"
#include "args.hxx"
#include "benches.hpp"
#include "timer-info.hpp"
#include "context.hpp"
#include "util.hpp"
#include "timers.hpp"
using namespace std;
using namespace std::chrono;
using namespace Stats;
template <typename T>
static inline bool is_pow2(T x) {
static_assert(std::is_unsigned<T>::value, "must use unsigned integral types");
return x && !(x & (x - 1));
}
const int MAX_ALIGN = 4096;
const size_t TWO_MB = 2 * 1024 * 1024;
const int STORAGE_SIZE = TWO_MB; // * 4 because we overalign the pointer in order to guarantee minimal alignemnt
//unsigned char unaligned_storage[STORAGE_SIZE];
void *storage_ptr = 0;
volatile int zero = 0;
bool storage_init = false;
/*
* Returns a pointer that is minimally aligned to base_alignment. That is, it is
* aligned to base_alignment, but *not* aligned to 2 * base_alignment.
*/
void *aligned_ptr(size_t base_alignment, size_t required_size) {
assert(required_size <= STORAGE_SIZE);
assert(is_pow2(base_alignment));
assert(base_alignment < TWO_MB);
if (!storage_ptr) {
assert(posix_memalign(&storage_ptr, TWO_MB, STORAGE_SIZE + TWO_MB) == 0);
madvise(storage_ptr, STORAGE_SIZE + TWO_MB, MADV_HUGEPAGE);
storage_ptr = ((char *)storage_ptr + TWO_MB);
// it is critical that we memset the memory region to touch each page, otherwise all or some pages
// can be mapped to the zero page, leading to unexpected results for read-only tests (i.e., "too good to be true"
// results for benchmarks that read large amounts of memory, because internally these are all mapped
// to the same page
std::memset(storage_ptr, 1, STORAGE_SIZE);
std::memset(storage_ptr, 0, STORAGE_SIZE);
}
void *p = storage_ptr;
size_t space = STORAGE_SIZE;
/* std::align isn't available in GCC and clang until fairly
* recently. This just gives us a bit more portability for older
* compilers. Code from https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57350#c11 */
void *r;
{
std::uintptr_t pn = reinterpret_cast< std::uintptr_t >( p );
std::uintptr_t aligned = ( pn + base_alignment - 1 ) & - base_alignment;
std::size_t padding = aligned - pn;
if ( space < required_size + padding )
r = nullptr;
space -= padding;
r = reinterpret_cast< void * >( aligned );
}
assert(r);
assert((((uintptr_t)r) & (base_alignment - 1)) == 0);
return r;
}
/**
* Returns a pointer that is first *minimally* aligned to the given base alignment (per
* aligned_ptr()) and then is offset by the about given in misalignment.
*/
void *misaligned_ptr(size_t base_alignment, size_t required_size, ssize_t misalignment) {
char *p = static_cast<char *>(aligned_ptr(base_alignment, required_size));
return p + misalignment;
}
template <size_t ITERS, typename CLOCK>
DescriptiveStats CalcClockRes() {
std::array<nanoseconds::rep, ITERS> results;
for (int r = 0; r < 3; r++) {
for (size_t i = 0; i < ITERS; i++) {
auto t0 = CLOCK::nanos();
auto t1 = CLOCK::nanos();
results[i] = t1 - t0;
}
}
return get_stats(results.begin(), results.end());
}
volatile int64_t sink;
template <size_t ITERS, typename CLOCK>
DescriptiveStats CalcClockCost() {
std::array<double, ITERS> results;
using timer = DefaultClockTimer;
for (int r = 0; r < 3; r++) {
for (size_t i = 0; i < ITERS; i++) {
int64_t sum = 0;
int64_t before = timer::now();
for (int j = 0; j < 1000; j++) {
sum += CLOCK::nanos();
}
results[i] = (timer::now() - before) / 1000.0;
sink = sum;
}
}
return get_stats(results.begin(), results.end());
}
template <typename TIMER>
GroupList make_benches() {
GroupList groupList;
register_default<TIMER>(groupList);
register_loadstore<TIMER>(groupList);
register_mem<TIMER>(groupList);
register_misc<TIMER>(groupList);
register_cpp<TIMER>(groupList);
register_vector<TIMER>(groupList);
register_call<TIMER>(groupList);
return groupList;
}
/*
* This object binds together a particular TIMER implementation (and its corresponding ClockInfo object)
*/
class TimeredList {
static std::vector<TimeredList> all_;
std::unique_ptr<TimerInfo> timer_info_;
GroupList groups_;
public:
TimeredList(std::unique_ptr<TimerInfo>&& timer_info, const GroupList& benches)
: timer_info_(std::move(timer_info)), groups_(benches) {}
TimeredList(const TimeredList &) = delete;
TimeredList(TimeredList &&) = default;
~TimeredList() = default;
TimerInfo& getTimerInfo() {
return *timer_info_;
}
const GroupList& getGroups() const {
return groups_;
}
void runIf(Context &c, const predicate_t& predicate) {
cout << "Running benchmarks groups using timer " << timer_info_->getName() << endl;
for (auto& group : getGroups()) {
group->runIf(c, getTimerInfo(), predicate);
}
}
template <typename TIMER, typename... Args>
static TimeredList create(Args&&... args) {
auto t = new TIMER(std::forward<Args>(args)...);
return TimeredList(std::unique_ptr<TIMER>(t), make_benches<TIMER>());
}
static std::vector<TimeredList>& getAll(Context& c) {
if (all_.empty()) {
all_.push_back(TimeredList::create<DefaultClockTimer>("high_resolution_clock"));
#if USE_LIBPFC
all_.push_back(TimeredList::create<LibpfcTimer>(c));
#endif
}
return all_;
}
};
std::vector<TimeredList> TimeredList::all_;
TimeredList& getForTimer(Context &c) {
std::string timerName = c.getTimerName();
std::vector<TimeredList>& all = TimeredList::getAll(c);
for (auto& i : all) {
if (i.getTimerInfo().getName() == timerName) {
return i;
}
}
throw args::UsageError(string("No timer with name ") + timerName);
}
void listBenches(Context& c) {
std::ostream& out = c.out();
auto benchList = TimeredList::getAll(c).front().getGroups();
out << "Listing " << benchList.size() << " benchmark groups" << endl << endl;
for (auto& group : benchList) {
out << "-------------------------------------\n";
out << "Benchmark group: " << group->getId() << "\n" << group->getDescription() << endl;
out << "-------------------------------------\n";
group->printBenches(out);
out << endl;
}
}
template <typename CLOCK>
void printOneClock(std::ostream& out, const char* name) {
out << setw(48) << name << setw(28) << CalcClockRes<100,CLOCK>().getString4(5,1);
out << setw(30) << CalcClockCost<100,CLOCK>().getString4(5,1) << endl;
}
struct DumbClock {
static int64_t nanos() { return 0; }
};
void printClockOverheads(Context& c) {
std::ostream& out = c.out();
out << "----- Clock Stats --------\n";
out << " Resolution (ns) Runtime (ns)" << endl;
out << " Name min/ med/ avg/ max min/ med/ avg/ max" << endl;
#define PRINT_CLOCK(clock) printOneClock< clock >(out, #clock);
PRINT_CLOCK(StdClockAdapt<system_clock>);
PRINT_CLOCK(StdClockAdapt<steady_clock>);
PRINT_CLOCK(StdClockAdapt<high_resolution_clock>);
PRINT_CLOCK(GettimeAdapter<CLOCK_REALTIME>);
PRINT_CLOCK(GettimeAdapter<CLOCK_REALTIME_COARSE>);
PRINT_CLOCK(GettimeAdapter<CLOCK_MONOTONIC>);
PRINT_CLOCK(GettimeAdapter<CLOCK_MONOTONIC_COARSE>);
PRINT_CLOCK(GettimeAdapter<CLOCK_MONOTONIC_RAW>);
PRINT_CLOCK(GettimeAdapter<CLOCK_PROCESS_CPUTIME_ID>);
PRINT_CLOCK(GettimeAdapter<CLOCK_THREAD_CPUTIME_ID>);
PRINT_CLOCK(GettimeAdapter<CLOCK_BOOTTIME>);
PRINT_CLOCK(DumbClock);
out << endl;
}
/* list the avaiable timers on stdout */
void listTimers(Context& c) {
cout << endl << "Available timers:" << endl << endl;
for (auto& tl : TimeredList::getAll(c)) {
auto& ti = tl.getTimerInfo();
c.out() << ti.getName() << endl << "\t" << ti.getDesciption() << endl << endl;
}
}
/*
* Each timer might have specific arguments it wants to expose to the user, here we add them to the parser.
*/
void addTimerSpecificArgs(args::ArgumentParser& parser) {
#define ADD_TIMER(TIMER) TIMER::addCustomArgs(parser);
ALL_TIMERS_X(ADD_TIMER);
}
/*
* Allow each timer to handle their specific args before starting any benchmark - e.g., for arguments that
* just want to list some configuration then exit (throw SilentSuccess in this case).
*/
void handleTimerSpecificRun(Context& c) {
#define HANDLE_TIMER(TIMER) TIMER::customRunHandler(c);
ALL_TIMERS_X(HANDLE_TIMER);
}
Context::Context(int argc, char **argv, std::ostream *out)
: err_(out), log_(out), out_(out), argc_(argc), argv_(argv) {
try {
addTimerSpecificArgs(parser);
parser.ParseCLI(argc, argv);
} catch (args::Help&) {
log() << parser;
throw SilentSuccess();
} catch (args::ParseError& e) {
err() << "ERROR: " << e.what() << std::endl << parser;
throw SilentFailure();
} catch (args::UsageError & e) {
err() << "ERROR: " << e.what() << std::endl;
throw SilentFailure();
}
}
void Context::run() {
handleTimerSpecificRun(*this);
if (arg_listtimers) {
listTimers(*this);
} else if (arg_listbenches) {
listBenches(*this);
} else if (arg_clockoverhead) {
printClockOverheads(*this);
} else if (arg_internal_dump_timer) {
std::cout << getTimerName();
throw SilentSuccess();
} else {
TimeredList& toRun = getForTimer(*this);
timer_info_ = &toRun.getTimerInfo();
timer_info_->init(*this);
predicate_t pred;
if (arg_test_name) {
pred = [this](const Benchmark& b){ return wildcard_match(b->getPath(), arg_test_name.Get()); };
} else {
pred = [](const Benchmark&){ return true; };
}
toRun.runIf(*this, pred);
}
}
#if USE_BACKWARD_CPP
backward::SignalHandling sh;
#endif
int main(int argc, char **argv) {
cout << "Welcome to uarch-bench (" << GIT_VERSION << ")" << endl;
try {
Context context(argc, argv, &std::cout);
context.run();
} catch (SilentSuccess& e) {
} catch (SilentFailure& e) {
return EXIT_FAILURE;
} catch (const std::exception& e) {
std::cerr << "ERROR: " << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>cache latency WIP<commit_after>/*
* main.cpp
*/
#include <iostream>
#include <iomanip>
#include <memory>
#include <chrono>
#include <cstddef>
#include <new>
#include <cassert>
#include <type_traits>
#include <sstream>
#include <functional>
#include <cstring>
#include <cstdlib>
#include <sys/mman.h>
#ifdef USE_BACKWARD_CPP
#include "backward-cpp/backward.hpp"
#endif
#include "stats.hpp"
#include "version.hpp"
#include "args.hxx"
#include "benches.hpp"
#include "timer-info.hpp"
#include "context.hpp"
#include "util.hpp"
#include "timers.hpp"
using namespace std;
using namespace std::chrono;
using namespace Stats;
template <typename T>
static inline bool is_pow2(T x) {
static_assert(std::is_unsigned<T>::value, "must use unsigned integral types");
return x && !(x & (x - 1));
}
const int MAX_ALIGN = 4096;
const size_t TWO_MB = 2 * 1024 * 1024;
const int STORAGE_SIZE = TWO_MB; // * 4 because we overalign the pointer in order to guarantee minimal alignemnt
//unsigned char unaligned_storage[STORAGE_SIZE];
void *storage_ptr = 0;
volatile int zero = 0;
bool storage_init = false;
/**
* Return a new pointer to a memory region of at least size, aligned to a 2MB boundary and with
* an effort to ensure the pointer is backed by transparent huge pages.
*/
void *new_huge_ptr(size_t size) {
void *ptr;
int result = posix_memalign(&ptr, TWO_MB, size + TWO_MB);
assert(result == 0);
madvise(ptr, size + TWO_MB, MADV_HUGEPAGE);
ptr = ((char *)ptr + TWO_MB);
// it is critical that we memset the memory region to touch each page, otherwise all or some pages
// can be mapped to the zero page, leading to unexpected results for read-only tests (i.e., "too good to be true"
// results for benchmarks that read large amounts of memory, because internally these are all mapped
// to the same page
std::memset(ptr, 1, size);
std::memset(ptr, 0, size);
return ptr;
}
void *align(size_t base_alignment, size_t required_size, void* p, size_t space) {
/* std::align isn't available in GCC and clang until fairly
* recently. This just gives us a bit more portability for older
* compilers. Code from https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57350#c11 */
void *r;
{
std::uintptr_t pn = reinterpret_cast< std::uintptr_t >( p );
std::uintptr_t aligned = ( pn + base_alignment - 1 ) & - base_alignment;
std::size_t padding = aligned - pn;
if ( space < required_size + padding )
r = nullptr;
space -= padding;
r = reinterpret_cast< void * >( aligned );
}
assert(r);
assert((((uintptr_t)r) & (base_alignment - 1)) == 0);
return r;
}
/*
* Returns a pointer that is minimally aligned to base_alignment. That is, it is
* aligned to base_alignment, but *not* aligned to 2 * base_alignment. Each call returns
* the same pointer, so you probably shouldn't write to this memory region.
*/
void *aligned_ptr(size_t base_alignment, size_t required_size) {
assert(required_size <= STORAGE_SIZE);
assert(is_pow2(base_alignment));
assert(base_alignment < TWO_MB);
if (!storage_ptr) {
storage_ptr = new_huge_ptr(STORAGE_SIZE);
}
return align(base_alignment, required_size, storage_ptr, STORAGE_SIZE);
}
/**
* Returns a pointer that is first *minimally* aligned to the given base alignment (per
* aligned_ptr()) and then is offset by the about given in misalignment.
*/
void *misaligned_ptr(size_t base_alignment, size_t required_size, ssize_t misalignment) {
char *p = static_cast<char *>(aligned_ptr(base_alignment, required_size));
return p + misalignment;
}
template <size_t ITERS, typename CLOCK>
DescriptiveStats CalcClockRes() {
std::array<nanoseconds::rep, ITERS> results;
for (int r = 0; r < 3; r++) {
for (size_t i = 0; i < ITERS; i++) {
auto t0 = CLOCK::nanos();
auto t1 = CLOCK::nanos();
results[i] = t1 - t0;
}
}
return get_stats(results.begin(), results.end());
}
volatile int64_t sink;
template <size_t ITERS, typename CLOCK>
DescriptiveStats CalcClockCost() {
std::array<double, ITERS> results;
using timer = DefaultClockTimer;
for (int r = 0; r < 3; r++) {
for (size_t i = 0; i < ITERS; i++) {
int64_t sum = 0;
int64_t before = timer::now();
for (int j = 0; j < 1000; j++) {
sum += CLOCK::nanos();
}
results[i] = (timer::now() - before) / 1000.0;
sink = sum;
}
}
return get_stats(results.begin(), results.end());
}
template <typename TIMER>
GroupList make_benches() {
GroupList groupList;
register_default<TIMER>(groupList);
register_loadstore<TIMER>(groupList);
register_mem<TIMER>(groupList);
register_misc<TIMER>(groupList);
register_cpp<TIMER>(groupList);
register_vector<TIMER>(groupList);
register_call<TIMER>(groupList);
return groupList;
}
/*
* This object binds together a particular TIMER implementation (and its corresponding ClockInfo object)
*/
class TimeredList {
static std::vector<TimeredList> all_;
std::unique_ptr<TimerInfo> timer_info_;
GroupList groups_;
public:
TimeredList(std::unique_ptr<TimerInfo>&& timer_info, const GroupList& benches)
: timer_info_(std::move(timer_info)), groups_(benches) {}
TimeredList(const TimeredList &) = delete;
TimeredList(TimeredList &&) = default;
~TimeredList() = default;
TimerInfo& getTimerInfo() {
return *timer_info_;
}
const GroupList& getGroups() const {
return groups_;
}
void runIf(Context &c, const predicate_t& predicate) {
cout << "Running benchmarks groups using timer " << timer_info_->getName() << endl;
for (auto& group : getGroups()) {
group->runIf(c, getTimerInfo(), predicate);
}
}
template <typename TIMER, typename... Args>
static TimeredList create(Args&&... args) {
auto t = new TIMER(std::forward<Args>(args)...);
return TimeredList(std::unique_ptr<TIMER>(t), make_benches<TIMER>());
}
static std::vector<TimeredList>& getAll(Context& c) {
if (all_.empty()) {
all_.push_back(TimeredList::create<DefaultClockTimer>("high_resolution_clock"));
#if USE_LIBPFC
all_.push_back(TimeredList::create<LibpfcTimer>(c));
#endif
}
return all_;
}
};
std::vector<TimeredList> TimeredList::all_;
TimeredList& getForTimer(Context &c) {
std::string timerName = c.getTimerName();
std::vector<TimeredList>& all = TimeredList::getAll(c);
for (auto& i : all) {
if (i.getTimerInfo().getName() == timerName) {
return i;
}
}
throw args::UsageError(string("No timer with name ") + timerName);
}
void listBenches(Context& c) {
std::ostream& out = c.out();
auto benchList = TimeredList::getAll(c).front().getGroups();
out << "Listing " << benchList.size() << " benchmark groups" << endl << endl;
for (auto& group : benchList) {
out << "-------------------------------------\n";
out << "Benchmark group: " << group->getId() << "\n" << group->getDescription() << endl;
out << "-------------------------------------\n";
group->printBenches(out);
out << endl;
}
}
template <typename CLOCK>
void printOneClock(std::ostream& out, const char* name) {
out << setw(48) << name << setw(28) << CalcClockRes<100,CLOCK>().getString4(5,1);
out << setw(30) << CalcClockCost<100,CLOCK>().getString4(5,1) << endl;
}
struct DumbClock {
static int64_t nanos() { return 0; }
};
void printClockOverheads(Context& c) {
std::ostream& out = c.out();
out << "----- Clock Stats --------\n";
out << " Resolution (ns) Runtime (ns)" << endl;
out << " Name min/ med/ avg/ max min/ med/ avg/ max" << endl;
#define PRINT_CLOCK(clock) printOneClock< clock >(out, #clock);
PRINT_CLOCK(StdClockAdapt<system_clock>);
PRINT_CLOCK(StdClockAdapt<steady_clock>);
PRINT_CLOCK(StdClockAdapt<high_resolution_clock>);
PRINT_CLOCK(GettimeAdapter<CLOCK_REALTIME>);
PRINT_CLOCK(GettimeAdapter<CLOCK_REALTIME_COARSE>);
PRINT_CLOCK(GettimeAdapter<CLOCK_MONOTONIC>);
PRINT_CLOCK(GettimeAdapter<CLOCK_MONOTONIC_COARSE>);
PRINT_CLOCK(GettimeAdapter<CLOCK_MONOTONIC_RAW>);
PRINT_CLOCK(GettimeAdapter<CLOCK_PROCESS_CPUTIME_ID>);
PRINT_CLOCK(GettimeAdapter<CLOCK_THREAD_CPUTIME_ID>);
PRINT_CLOCK(GettimeAdapter<CLOCK_BOOTTIME>);
PRINT_CLOCK(DumbClock);
out << endl;
}
/* list the avaiable timers on stdout */
void listTimers(Context& c) {
cout << endl << "Available timers:" << endl << endl;
for (auto& tl : TimeredList::getAll(c)) {
auto& ti = tl.getTimerInfo();
c.out() << ti.getName() << endl << "\t" << ti.getDesciption() << endl << endl;
}
}
/*
* Each timer might have specific arguments it wants to expose to the user, here we add them to the parser.
*/
void addTimerSpecificArgs(args::ArgumentParser& parser) {
#define ADD_TIMER(TIMER) TIMER::addCustomArgs(parser);
ALL_TIMERS_X(ADD_TIMER);
}
/*
* Allow each timer to handle their specific args before starting any benchmark - e.g., for arguments that
* just want to list some configuration then exit (throw SilentSuccess in this case).
*/
void handleTimerSpecificRun(Context& c) {
#define HANDLE_TIMER(TIMER) TIMER::customRunHandler(c);
ALL_TIMERS_X(HANDLE_TIMER);
}
Context::Context(int argc, char **argv, std::ostream *out)
: err_(out), log_(out), out_(out), argc_(argc), argv_(argv) {
try {
addTimerSpecificArgs(parser);
parser.ParseCLI(argc, argv);
} catch (args::Help&) {
log() << parser;
throw SilentSuccess();
} catch (args::ParseError& e) {
err() << "ERROR: " << e.what() << std::endl << parser;
throw SilentFailure();
} catch (args::UsageError & e) {
err() << "ERROR: " << e.what() << std::endl;
throw SilentFailure();
}
}
void Context::run() {
handleTimerSpecificRun(*this);
if (arg_listtimers) {
listTimers(*this);
} else if (arg_listbenches) {
listBenches(*this);
} else if (arg_clockoverhead) {
printClockOverheads(*this);
} else if (arg_internal_dump_timer) {
std::cout << getTimerName();
throw SilentSuccess();
} else {
TimeredList& toRun = getForTimer(*this);
timer_info_ = &toRun.getTimerInfo();
timer_info_->init(*this);
predicate_t pred;
if (arg_test_name) {
pred = [this](const Benchmark& b){ return wildcard_match(b->getPath(), arg_test_name.Get()); };
} else {
pred = [](const Benchmark&){ return true; };
}
toRun.runIf(*this, pred);
}
}
#if USE_BACKWARD_CPP
backward::SignalHandling sh;
#endif
int main(int argc, char **argv) {
cout << "Welcome to uarch-bench (" << GIT_VERSION << ")" << endl;
try {
Context context(argc, argv, &std::cout);
context.run();
} catch (SilentSuccess& e) {
} catch (SilentFailure& e) {
return EXIT_FAILURE;
} catch (const std::exception& e) {
std::cerr << "ERROR: " << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <stdlib.h> /* srand, rand */
#include <time.h>
#include <limits> /* numeric_limits */
int main()
{
bool playing = true;
std::string playAgain, line;
int playerWins = 0, compWins = 0, compMove, userMove, result;
const std::string moves[] = {"rock", "paper", "scissors"};
// Initialize rng
srand(time(NULL));
std::cout << "Welcome!" << std::endl;
while(playing)
{
std::cout << "Enter 1 to play Rock, 2 to play Paper, and 3 to play Scissors!: ";
std::cin >> userMove;
while(!(std::cin && userMove >= 1 && userMove <= 3))
{
std::cout << "Unknown command! Please try that again..." << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Enter 1 to play Rock, 2 to play Paper, and 3 to play Scissors!: ";
std::cin >> userMove;
}
// Clears input stream if double was input to userMove and decimal values are left in the input stream due to truncation
if(std::cin.peek() != '\n')
{
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
// Create random integer in range [1,3] to simulate the computer selecting a move
compMove = rand() % 3 + 1;
result = userMove - compMove;
if(result == 0)
std::cout << "Tie game!" << std::endl;
else if(result == 1 || result == -2)
{
std::cout << "Congratulations, you won!" << std::endl;
playerWins++;
} else
{
std::cout << "Sorry, you lost!" << std::endl;
compWins++;
}
std::cout << "Your move: " << moves[userMove - 1] << " // Computer's move: " << moves[compMove - 1] << std::endl;
std::cout << "(Player: " << playerWins << " | Computer: " << compWins << ")" << std::endl;
std::cout << "Play again? [y/n]: ";
std::cin >> playAgain;
while(!(std::cin && (playAgain == "y" || playAgain == "n")))
{
std::cout << "Unknown command! Please try that again..." << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Play again? [y/n]: ";
std::cin >> playAgain;
}
if(playAgain != "y")
playing = false;
}
return 0;
}<commit_msg>Removal of unused line variable<commit_after>#include <iostream>
#include <string>
#include <stdlib.h> /* srand, rand */
#include <time.h>
#include <limits> /* numeric_limits */
int main()
{
bool playing = true;
std::string playAgain;
int playerWins = 0, compWins = 0, compMove, userMove, result;
const std::string moves[] = {"rock", "paper", "scissors"};
// Initialize rng
srand(time(NULL));
std::cout << "Welcome!" << std::endl;
while(playing)
{
std::cout << "Enter 1 to play Rock, 2 to play Paper, and 3 to play Scissors!: ";
std::cin >> userMove;
while(!(std::cin && userMove >= 1 && userMove <= 3))
{
std::cout << "Unknown command! Please try that again..." << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Enter 1 to play Rock, 2 to play Paper, and 3 to play Scissors!: ";
std::cin >> userMove;
}
// Clears input stream if double was input to userMove and decimal values are left in the input stream due to truncation
if(std::cin.peek() != '\n')
{
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
// Create random integer in range [1,3] to simulate the computer selecting a move
compMove = rand() % 3 + 1;
result = userMove - compMove;
if(result == 0)
std::cout << "Tie game!" << std::endl;
else if(result == 1 || result == -2)
{
std::cout << "Congratulations, you won!" << std::endl;
playerWins++;
} else
{
std::cout << "Sorry, you lost!" << std::endl;
compWins++;
}
std::cout << "Your move: " << moves[userMove - 1] << " // Computer's move: " << moves[compMove - 1] << std::endl;
std::cout << "(Player: " << playerWins << " | Computer: " << compWins << ")" << std::endl;
std::cout << "Play again? [y/n]: ";
std::cin >> playAgain;
while(!(std::cin && (playAgain == "y" || playAgain == "n")))
{
std::cout << "Unknown command! Please try that again..." << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Play again? [y/n]: ";
std::cin >> playAgain;
}
if(playAgain != "y")
playing = false;
}
return 0;
}<|endoftext|> |
<commit_before>809e923c-2d15-11e5-af21-0401358ea401<commit_msg>809e923d-2d15-11e5-af21-0401358ea401<commit_after>809e923d-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>60c617c0-ad58-11e7-bce9-ac87a332f658<commit_msg>my cat is cute<commit_after>6137d938-ad58-11e7-a062-ac87a332f658<|endoftext|> |
<commit_before>0972ded0-585b-11e5-9051-6c40088e03e4<commit_msg>097c84b0-585b-11e5-a0c9-6c40088e03e4<commit_after>097c84b0-585b-11e5-a0c9-6c40088e03e4<|endoftext|> |
<commit_before>2765f59e-2e4f-11e5-9bb3-28cfe91dbc4b<commit_msg>276cf5a8-2e4f-11e5-92bb-28cfe91dbc4b<commit_after>276cf5a8-2e4f-11e5-92bb-28cfe91dbc4b<|endoftext|> |
<commit_before>bf31a185-2e4f-11e5-bdba-28cfe91dbc4b<commit_msg>bf3835dc-2e4f-11e5-b0d5-28cfe91dbc4b<commit_after>bf3835dc-2e4f-11e5-b0d5-28cfe91dbc4b<|endoftext|> |
<commit_before>60bb477d-2d16-11e5-af21-0401358ea401<commit_msg>60bb477e-2d16-11e5-af21-0401358ea401<commit_after>60bb477e-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>a1da8507-2e4f-11e5-a6b5-28cfe91dbc4b<commit_msg>a1e3afca-2e4f-11e5-af20-28cfe91dbc4b<commit_after>a1e3afca-2e4f-11e5-af20-28cfe91dbc4b<|endoftext|> |
<commit_before>d3f81f26-313a-11e5-b9df-3c15c2e10482<commit_msg>d3fe09e1-313a-11e5-a7eb-3c15c2e10482<commit_after>d3fe09e1-313a-11e5-a7eb-3c15c2e10482<|endoftext|> |
<commit_before>68b83442-2fa5-11e5-87ee-00012e3d3f12<commit_msg>68ba0906-2fa5-11e5-9937-00012e3d3f12<commit_after>68ba0906-2fa5-11e5-9937-00012e3d3f12<|endoftext|> |
<commit_before>d9ba87fa-327f-11e5-93a4-9cf387a8033e<commit_msg>d9c06a26-327f-11e5-92e5-9cf387a8033e<commit_after>d9c06a26-327f-11e5-92e5-9cf387a8033e<|endoftext|> |
<commit_before>e3974680-313a-11e5-9d64-3c15c2e10482<commit_msg>e39d4514-313a-11e5-ac16-3c15c2e10482<commit_after>e39d4514-313a-11e5-ac16-3c15c2e10482<|endoftext|> |
<commit_before>7e7919fc-2d15-11e5-af21-0401358ea401<commit_msg>7e7919fd-2d15-11e5-af21-0401358ea401<commit_after>7e7919fd-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>e66ce6e3-2e4e-11e5-9dec-28cfe91dbc4b<commit_msg>e67493d9-2e4e-11e5-beb6-28cfe91dbc4b<commit_after>e67493d9-2e4e-11e5-beb6-28cfe91dbc4b<|endoftext|> |
<commit_before>e1dbb17a-313a-11e5-aac7-3c15c2e10482<commit_msg>e1e1e0e8-313a-11e5-942a-3c15c2e10482<commit_after>e1e1e0e8-313a-11e5-942a-3c15c2e10482<|endoftext|> |
<commit_before>bd0884f5-327f-11e5-bf5d-9cf387a8033e<commit_msg>bd140599-327f-11e5-ac3e-9cf387a8033e<commit_after>bd140599-327f-11e5-ac3e-9cf387a8033e<|endoftext|> |
<commit_before>#include <iostream>
#include <libdariadb/engines/engine.h>
#include <libdariadb/utils/fs.h>
class QuietLogger : public dariadb::utils::ILogger {
public:
void message(dariadb::utils::LOG_MESSAGE_KIND kind,
const std::string &msg) override {}
};
class Callback : public dariadb::IReadCallback {
public:
Callback() {}
void apply(const dariadb::Meas &measurement) override {
std::cout << " id: " << measurement.id << " timepoint: "
<< dariadb::timeutil::to_string(measurement.time)
<< " value:" << measurement.value << std::endl;
}
void is_end() override {
std::cout << "calback end." << std::endl;
dariadb::IReadCallback::is_end();
}
};
int main(int argc, char **argv) {
const std::string storage_path = "exampledb";
// remove old storage.
if (dariadb::utils::fs::path_exists(storage_path)) {
dariadb::utils::fs::rm(storage_path);
}
// reset standert logger
dariadb::utils::ILogger_ptr log_ptr{ new QuietLogger() };
dariadb::utils::LogManager::start(log_ptr);
// create defaul settings
auto settings = dariadb::storage::Settings::create(storage_path);
settings->save();
auto storage = std::make_unique<dariadb::Engine>(settings);
auto m = dariadb::Meas();
auto start_time = dariadb::timeutil::current_time();
m.time = start_time;
for (size_t i = 0; i < 10; ++i) {
if (i % 2) {
m.id = dariadb::Id(0);
}
else {
m.id = dariadb::Id(1);
}
m.time++;
m.value++;
m.flag = 100 + i % 2;
auto status = storage->append(m);
if (status.writed != 1) {
std::cerr << "Error: " << status.error_message << std::endl;
}
}
//array with writed id`s
dariadb::IdArray all_id{ dariadb::Id(0), dariadb::Id(1) };
// query list of values in interval
dariadb::QueryInterval qi(all_id, dariadb::Flag(), start_time, m.time);
dariadb::MeasList readed_values = storage->readInterval(qi);
std::cout << "Readed: " << readed_values.size() << std::endl;
for (auto measurement : readed_values) {
std::cout << " param: " << measurement.id << " timepoint: "
<< dariadb::timeutil::to_string(measurement.time)
<< " value:" << measurement.value << std::endl;
}
// query timepoint
dariadb::QueryTimePoint qp(all_id, dariadb::Flag(), m.time);
dariadb::Id2Meas timepoint = storage->readTimePoint(qp);
std::cout << "Timepoint: " << std::endl;
for (auto kv : timepoint) {
auto measurement = kv.second;
std::cout << " param: " << kv.first << " timepoint: "
<< dariadb::timeutil::to_string(measurement.time)
<< " value:" << measurement.value << std::endl;
}
// current values
dariadb::Id2Meas cur_values = storage->currentValue(all_id, dariadb::Flag());
std::cout << "Current: " << std::endl;
for (auto kv : timepoint) {
auto measurement = kv.second;
std::cout << " id: " << kv.first << " timepoint: "
<< dariadb::timeutil::to_string(measurement.time)
<< " value:" << measurement.value << std::endl;
}
// apply callback to interval
std::cout << "Callback in interval: " << std::endl;
std::unique_ptr<Callback> callback_ptr{ new Callback() };
storage->foreach(qi, callback_ptr.get());
callback_ptr->wait();
// apply callback to values in timepoint
std::cout << "Callback in timepoint: " << std::endl;
storage->foreach(qp, callback_ptr.get());
callback_ptr->wait();
{ // query statistic for Id==0 in interval
auto stat = storage->stat(dariadb::Id(0), start_time, m.time);
std::cout << "count: " << stat.count << std::endl;
std::cout << "time: [" << dariadb::timeutil::to_string(stat.minTime) << " "
<< dariadb::timeutil::to_string(stat.maxTime) << "]" << std::endl;
std::cout << "val: [" << stat.minValue << " " << stat.maxValue << "]"
<< std::endl;
std::cout << "sum: " << stat.sum << std::endl;
}
}
<commit_msg>callbacks: dont use heap.<commit_after>#include <iostream>
#include <libdariadb/engines/engine.h>
#include <libdariadb/utils/fs.h>
class QuietLogger : public dariadb::utils::ILogger {
public:
void message(dariadb::utils::LOG_MESSAGE_KIND kind,
const std::string &msg) override {}
};
class Callback : public dariadb::IReadCallback {
public:
Callback() {}
void apply(const dariadb::Meas &measurement) override {
std::cout << " id: " << measurement.id << " timepoint: "
<< dariadb::timeutil::to_string(measurement.time)
<< " value:" << measurement.value << std::endl;
}
void is_end() override {
std::cout << "calback end." << std::endl;
dariadb::IReadCallback::is_end();
}
};
int main(int argc, char **argv) {
const std::string storage_path = "exampledb";
// remove old storage.
if (dariadb::utils::fs::path_exists(storage_path)) {
dariadb::utils::fs::rm(storage_path);
}
// reset standert logger
dariadb::utils::ILogger_ptr log_ptr{ new QuietLogger() };
dariadb::utils::LogManager::start(log_ptr);
// create defaul settings
auto settings = dariadb::storage::Settings::create(storage_path);
settings->save();
auto storage = std::make_unique<dariadb::Engine>(settings);
auto m = dariadb::Meas();
auto start_time = dariadb::timeutil::current_time();
m.time = start_time;
for (size_t i = 0; i < 10; ++i) {
if (i % 2) {
m.id = dariadb::Id(0);
}
else {
m.id = dariadb::Id(1);
}
m.time++;
m.value++;
m.flag = 100 + i % 2;
auto status = storage->append(m);
if (status.writed != 1) {
std::cerr << "Error: " << status.error_message << std::endl;
}
}
//array with writed id`s
dariadb::IdArray all_id{ dariadb::Id(0), dariadb::Id(1) };
// query list of values in interval
dariadb::QueryInterval qi(all_id, dariadb::Flag(), start_time, m.time);
dariadb::MeasList readed_values = storage->readInterval(qi);
std::cout << "Readed: " << readed_values.size() << std::endl;
for (auto measurement : readed_values) {
std::cout << " param: " << measurement.id << " timepoint: "
<< dariadb::timeutil::to_string(measurement.time)
<< " value:" << measurement.value << std::endl;
}
// query timepoint
dariadb::QueryTimePoint qp(all_id, dariadb::Flag(), m.time);
dariadb::Id2Meas timepoint = storage->readTimePoint(qp);
std::cout << "Timepoint: " << std::endl;
for (auto kv : timepoint) {
auto measurement = kv.second;
std::cout << " param: " << kv.first << " timepoint: "
<< dariadb::timeutil::to_string(measurement.time)
<< " value:" << measurement.value << std::endl;
}
// current values
dariadb::Id2Meas cur_values = storage->currentValue(all_id, dariadb::Flag());
std::cout << "Current: " << std::endl;
for (auto kv : timepoint) {
auto measurement = kv.second;
std::cout << " id: " << kv.first << " timepoint: "
<< dariadb::timeutil::to_string(measurement.time)
<< " value:" << measurement.value << std::endl;
}
// apply callback to interval
std::cout << "Callback in interval: " << std::endl;
Callback callback;
storage->foreach(qi, &callback);
callback.wait();
// apply callback to values in timepoint
std::cout << "Callback in timepoint: " << std::endl;
storage->foreach(qp, &callback);
callback.wait();
{ // query statistic for Id==0 in interval
auto stat = storage->stat(dariadb::Id(0), start_time, m.time);
std::cout << "count: " << stat.count << std::endl;
std::cout << "time: [" << dariadb::timeutil::to_string(stat.minTime) << " "
<< dariadb::timeutil::to_string(stat.maxTime) << "]" << std::endl;
std::cout << "val: [" << stat.minValue << " " << stat.maxValue << "]"
<< std::endl;
std::cout << "sum: " << stat.sum << std::endl;
}
}
<|endoftext|> |
<commit_before>db6b0821-327f-11e5-88ea-9cf387a8033e<commit_msg>db7257c7-327f-11e5-8f13-9cf387a8033e<commit_after>db7257c7-327f-11e5-8f13-9cf387a8033e<|endoftext|> |
<commit_before>e3d2a8ee-327f-11e5-bfc0-9cf387a8033e<commit_msg>e3d8be07-327f-11e5-a3eb-9cf387a8033e<commit_after>e3d8be07-327f-11e5-a3eb-9cf387a8033e<|endoftext|> |
<commit_before>91d43b06-35ca-11e5-8756-6c40088e03e4<commit_msg>91dada48-35ca-11e5-9909-6c40088e03e4<commit_after>91dada48-35ca-11e5-9909-6c40088e03e4<|endoftext|> |
<commit_before>#include <iostream>
#include "RiptideRecorder/RiptideRecorder.h"
#include "TestDevice.h"
using namespace std;
int main() {
Recorder* rec = Recorder::GetInstance();
TestDevice* dev = new TestDevice("dev");
Relay* rel = new Relay();
rec->AddDevice("relay",rel);
rec->AddDevice(dev);
Macro* mac = rec -> macro();
mac->Record();
mac->Record();
mac->WriteFile("saves/new.csv");
std::cout << "plz work" << std::endl;
return 0;
}
<commit_msg>rewrote test executable to test recording, writing, resettting, reading all for 3000 loops<commit_after>#include <iostream>
#include "RiptideRecorder/RiptideRecorder.h"
#include "TestDevice.h"
using namespace std;
int main() {
Recorder* rec = Recorder::GetInstance();
//One of each device
TestDevice* dev = new TestDevice("dev");
Relay* rel = new Relay();
SpeedController* ctrl = new SpeedController();
Servo* serv = new Servo();
DoubleSolenoid* ds = new DoubleSolenoid();
Solenoid* sol = new Solenoid();
//Add all devices to recorder
rec->AddDevice("Relay",rel);
rec->AddDevice("Speed Controller",ctrl);
rec->AddDevice("Servo",serv);
rec->AddDevice("Double Solenoid",ds);
rec->AddDevice("Solenoid",sol);
rec->AddDevice(dev);
//Creates macro
Macro* mac = rec -> macro();
for (int i = 0; i<3000; i++) {
mac->Record();
}
mac->WriteFile("saves/auto.csv");
mac->Reset();
mac->ReadFile("saves/auto.csv");
while (!mac->IsFinished()) mac->PlayBack();
std::cout << "plz work" << std::endl;
}
<|endoftext|> |
<commit_before>16bc632b-2748-11e6-bf70-e0f84713e7b8<commit_msg>GOD DAMNED IT!<commit_after>16c91b30-2748-11e6-84e2-e0f84713e7b8<|endoftext|> |
<commit_before>de02159e-327f-11e5-8d97-9cf387a8033e<commit_msg>de097e61-327f-11e5-a421-9cf387a8033e<commit_after>de097e61-327f-11e5-a421-9cf387a8033e<|endoftext|> |
<commit_before>f349452e-ad59-11e7-85d8-ac87a332f658<commit_msg>oh my, I hate roselyn<commit_after>f3ad44b5-ad59-11e7-824a-ac87a332f658<|endoftext|> |
<commit_before>48e98dba-ad5b-11e7-86b5-ac87a332f658<commit_msg>GOD DAMNED IT!<commit_after>4977f5ab-ad5b-11e7-b5e8-ac87a332f658<|endoftext|> |
<commit_before>a1d85ac8-35ca-11e5-af78-6c40088e03e4<commit_msg>a1df2f2e-35ca-11e5-a62c-6c40088e03e4<commit_after>a1df2f2e-35ca-11e5-a62c-6c40088e03e4<|endoftext|> |
<commit_before>2a6e5f6c-2f67-11e5-8df4-6c40088e03e4<commit_msg>2a74e62c-2f67-11e5-a07f-6c40088e03e4<commit_after>2a74e62c-2f67-11e5-a07f-6c40088e03e4<|endoftext|> |
<commit_before>/*
The MIT License
Copyright (c) 2010 Bryan Ivory bivory+textureatlas@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS 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 <assert.h>
#include <iostream>
#include <sstream>
#include <string>
#include <list>
#include <vector>
#include "png.hpp"
#include "TexturePacker.h"
#include "tclap/CmdLine.h"
#define VERSION "2010.09.06"
class TextureInfo;
class TextureAtlasInfoVisitor
{
public:
virtual void visit(TextureInfo &im_info,
int x, int y, int width, int height, bool rot90) = 0;
};
class TextureInfo
{
public:
TextureInfo(int index, std::string path)
: idx(index), im_path(path)
{
im = new png::image<png::rgba_pixel>(im_path,
png::convert_color_space<png::rgba_pixel>());
}
void index(size_t i) { idx = i; }
int index() const { return idx; }
std::string path() const { return im_path; }
png::image<png::rgba_pixel>* image() const { return im; }
void writeTo(png::image< png::rgba_pixel > &outimage,
const size_t offset_x, const size_t offset_y,
const size_t out_width, const size_t out_height,
const bool rotate90)
{
for(size_t out_y = offset_y; out_y < (offset_y + out_height); ++out_y)
{
for(size_t out_x = offset_x; out_x < (offset_x + out_width); ++out_x)
{
if (rotate90)
{
size_t rot_y = im->get_height() - (out_x - offset_x) - 1;
size_t rot_x = (out_y - offset_y);
png::rgba_pixel px = (*im)[rot_y][rot_x];
outimage[out_y][out_x] = px;
}
else
{
size_t rot_y = out_y - offset_y;
size_t rot_x = out_x - offset_x;
outimage[out_y][out_x] = (*im)[rot_y][rot_x];
}
}
}
}
private:
int idx;
std::string im_path;
png::image<png::rgba_pixel>* im;
};
class TextureAtlasInfo
{
public:
TextureAtlasInfo(size_t atlas_width, size_t atlas_height, size_t im_count)
: atlas_max_width(atlas_width), atlas_max_height(atlas_height),
atlas_unused_pixels(0), images()
{
atlas = TEXTURE_PACKER::createTexturePacker();
atlas->setTextureCount(im_count);
}
~TextureAtlasInfo(void)
{
delete(atlas);
}
bool addTexture(TextureInfo* im_info)
{
png::image<png::rgba_pixel>* im = im_info->image();
bool fit = atlas->wouldTextureFit(im->get_width(), im->get_height(),
true, false,
atlas_max_width, atlas_max_height);
if (!fit)
{
return false;
}
atlas->addTexture(im->get_width(), im->get_height());
im_info->index(atlas->getTextureCount() - 1);
images.push_back(im_info);
return true;
}
void packTextures(void)
{
int w, h;
atlas_unused_pixels = atlas->packTextures(w, h, true, false);
atlas_max_width = w;
atlas_max_height = h;
}
size_t packedCount(void) { return atlas->getTextureCount(); }
size_t packedUnusedPixels(void) { return atlas_unused_pixels; }
size_t packedWidth(void) { return atlas_max_width; }
size_t packedHeight(void) { return atlas_max_height; }
void visit(TextureAtlasInfoVisitor &taiv)
{
for(std::list<TextureInfo *>::iterator images_iter = images.begin();
images_iter != images.end();
images_iter++)
{
TextureInfo* im_info = *images_iter;
int x, y, width, height;
bool rot90;
rot90 = atlas->getTextureLocation(im_info->index(),
x, y, width, height);
taiv.visit(*im_info, x, y, width, height, rot90);
}
}
private:
size_t atlas_unused_pixels;
size_t atlas_max_width;
size_t atlas_max_height;
TEXTURE_PACKER::TexturePacker* atlas;
std::list<TextureInfo *> images;
};
class TextureAtlasInfoWriteVisitor : public TextureAtlasInfoVisitor
{
public:
TextureAtlasInfoWriteVisitor(std::string path, size_t w, size_t h) :
out_image_path(path), out_image(w, h)
{
}
~TextureAtlasInfoWriteVisitor(void)
{
out_image.write(out_image_path + ".png");
}
void visit(TextureInfo &im_info,
int x, int y, int width, int height, bool rot90)
{
im_info.writeTo(out_image, x, y, width, height, rot90);
}
private:
png::image<png::rgba_pixel> out_image;
std::string out_image_path;
};
class TextureAtlasInfoDebugWriteVisitor : public TextureAtlasInfoVisitor
{
public:
static std::string name() { return "debug"; }
TextureAtlasInfoDebugWriteVisitor(std::string path,
size_t w, size_t h,
size_t num_packed, size_t unused) :
out_image_path(path), out_image_width(w), out_image_height(h)
{
std::cout << "Packed " << num_packed << " images to " << path << ".png"
<< " with " << unused << " unused area "
<< "Width (" << w << ") x Height (" << h << ")"
<< std::endl;
}
~TextureAtlasInfoDebugWriteVisitor(void)
{
std::cout << std::endl;
}
void visit(TextureInfo &im_info,
int x, int y, int width, int height, bool rot90)
{
std::cout << im_info.path() << " => ";
if (rot90) std::cout << "rotated 90 ";
std::cout << "x: " << x << " "
<< "y: " << y << " "
<< "width: " << width << " "
<< "height: " << height << " "
<< std::endl;
}
private:
std::string out_image_path;
size_t out_image_width;
size_t out_image_height;
};
class TextureAtlasInfoCSVWriteVisitor : public TextureAtlasInfoVisitor
{
public:
TextureAtlasInfoCSVWriteVisitor(std::string path, size_t w, size_t h) :
out_image_path(path), out_image_width(w), out_image_height(h)
{
}
~TextureAtlasInfoCSVWriteVisitor(void)
{
}
void visit(TextureInfo &im_info,
int x, int y, int width, int height, bool rot90)
{
}
private:
std::string out_image_path;
size_t out_image_width;
size_t out_image_height;
};
int
main(int argc, char* argv[])
{
std::string out_atlas_name = "";
size_t out_atlas_height = 0;
size_t out_atlas_width = 0;
std::vector<std::string> out_visitors_str;
std::vector<std::string> image_names;
std::list<TextureAtlasInfo *> atlases;
// Read in the command line arguements
try
{
TCLAP::CmdLine cmd("Creates a texture atlas from a list of PNG files.",
' ', VERSION, true);
// Output atlas file name
TCLAP::ValueArg<std::string> out_atlas_name_arg(
"o","out_name",
"Output atlas image's file name.",
false, "out_atlas", "string");
cmd.add(out_atlas_name_arg);
// Output atlas image dimensions
TCLAP::ValueArg<size_t> out_atlas_width_arg(
"x","out_width",
"Maximum output atlas image's width.",
false, 1024, "pixels");
cmd.add(out_atlas_width_arg);
TCLAP::ValueArg<size_t> out_atlas_height_arg(
"y","out_height",
"Maximum output atlas image's height.",
false, 1024, "pixels");
cmd.add(out_atlas_height_arg);
// Input image files
TCLAP::UnlabeledMultiArg<std::string> in_image_names_arg(
"in_names", "List of the image filenames.", true, "PNG file path");
cmd.add(in_image_names_arg);
// Output visitors
TCLAP::SwitchArg quiet_arg("q", "quiet",
"Suppress processing information output.", false);
cmd.add(quiet_arg);
TCLAP::MultiArg<std::string> out_vistors_arg("i", "info_writers",
"Atlas information writers.",
false, "string");
cmd.add(out_vistors_arg);
// Parse the command line options
cmd.parse(argc, argv);
out_atlas_name = out_atlas_name_arg.getValue();
out_atlas_width = out_atlas_width_arg.getValue();
out_atlas_height = out_atlas_height_arg.getValue();
if (!quiet_arg.getValue())
{
out_visitors_str.push_back(TextureAtlasInfoDebugWriteVisitor::name());
}
#if 0
out_visitors_str = out_vistors_arg.getValue();
#endif
image_names = in_image_names_arg.getValue();
}
catch (TCLAP::ArgException &e)
{
std::cerr << "Error: " << e.error() << " for arg " << e.argId() << std::endl;
return 1;
}
// Create the initial texture atlas
atlases.push_back(new TextureAtlasInfo(out_atlas_width, out_atlas_height,
image_names.size()));
// Load the textures
for(size_t idx = 0; idx < image_names.size(); idx++)
{
try
{
// Load the image
TextureInfo* ti = new TextureInfo(idx, image_names[idx]);
if (ti->image()->get_width() > out_atlas_width ||
ti->image()->get_height() > out_atlas_height)
{
std::cerr << "Error: " << ti->path() << " is too big!" << std::endl;
std::cerr << "Image dimensions: " << ti->image()->get_width()
<< " x " << ti->image()->get_height() << std::endl;
std::cerr << "Atlas dimensions: " << out_atlas_width
<< " x " << out_atlas_height << std::endl;
return 1;
}
// Add to the atlas
TextureAtlasInfo* tai = atlases.back();
if (!tai->addTexture(ti))
{
// Create a new atlas
TextureAtlasInfo* tai_next = new TextureAtlasInfo(out_atlas_width,
out_atlas_height,
image_names.size());
tai_next->addTexture(ti);
atlases.push_back(tai_next);
}
}
catch(png::std_error &e)
{
std::cerr << e.what() << std::endl;
return 1;
}
}
// Pack and write out the atlases
int idx = 0;
for(std::list<TextureAtlasInfo *>::iterator atlases_iter = atlases.begin();
atlases_iter != atlases.end();
atlases_iter++, idx++)
{
std::ostringstream oss;
oss << out_atlas_name << "_" << idx;
std::string atlas_name(oss.str());
TextureAtlasInfo* tai = *atlases_iter;
tai->packTextures();
TextureAtlasInfoWriteVisitor tai_writer(atlas_name,
tai->packedWidth(),
tai->packedHeight());
tai->visit(tai_writer);
// Ugly way to do this.
for(std::vector<std::string>::iterator vis_iter = out_visitors_str.begin();
vis_iter != out_visitors_str.end();
vis_iter++)
{
TextureAtlasInfoVisitor* taiv = NULL;
if (vis_iter->compare(TextureAtlasInfoDebugWriteVisitor::name()) == 0)
{
taiv = new TextureAtlasInfoDebugWriteVisitor(atlas_name,
tai->packedWidth(),
tai->packedHeight(),
tai->packedCount(),
tai->packedUnusedPixels());
}
if (taiv != NULL)
{
tai->visit(*taiv);
delete taiv;
}
}
}
return 0;
}
<commit_msg>Start of CSV support<commit_after>/*
The MIT License
Copyright (c) 2010 Bryan Ivory bivory+textureatlas@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS 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 <assert.h>
#include <iostream>
#include <sstream>
#include <string>
#include <list>
#include <vector>
#include "png.hpp"
#include "TexturePacker.h"
#include "tclap/CmdLine.h"
#define VERSION "2010.09.06"
class TextureInfo;
class TextureAtlasInfoVisitor
{
public:
virtual void visit(TextureInfo &im_info,
int x, int y, int width, int height, bool rot90) = 0;
};
class TextureInfo
{
public:
TextureInfo(int index, std::string path)
: idx(index), im_path(path)
{
im = new png::image<png::rgba_pixel>(im_path,
png::convert_color_space<png::rgba_pixel>());
}
void index(size_t i) { idx = i; }
int index() const { return idx; }
std::string path() const { return im_path; }
png::image<png::rgba_pixel>* image() const { return im; }
void writeTo(png::image< png::rgba_pixel > &outimage,
const size_t offset_x, const size_t offset_y,
const size_t out_width, const size_t out_height,
const bool rotate90)
{
for(size_t out_y = offset_y; out_y < (offset_y + out_height); ++out_y)
{
for(size_t out_x = offset_x; out_x < (offset_x + out_width); ++out_x)
{
if (rotate90)
{
size_t rot_y = im->get_height() - (out_x - offset_x) - 1;
size_t rot_x = (out_y - offset_y);
png::rgba_pixel px = (*im)[rot_y][rot_x];
outimage[out_y][out_x] = px;
}
else
{
size_t rot_y = out_y - offset_y;
size_t rot_x = out_x - offset_x;
outimage[out_y][out_x] = (*im)[rot_y][rot_x];
}
}
}
}
private:
int idx;
std::string im_path;
png::image<png::rgba_pixel>* im;
};
class TextureAtlasInfo
{
public:
TextureAtlasInfo(size_t atlas_width, size_t atlas_height, size_t im_count)
: atlas_max_width(atlas_width), atlas_max_height(atlas_height),
atlas_unused_pixels(0), images()
{
atlas = TEXTURE_PACKER::createTexturePacker();
atlas->setTextureCount(im_count);
}
~TextureAtlasInfo(void)
{
delete(atlas);
}
bool addTexture(TextureInfo* im_info)
{
png::image<png::rgba_pixel>* im = im_info->image();
bool fit = atlas->wouldTextureFit(im->get_width(), im->get_height(),
true, false,
atlas_max_width, atlas_max_height);
if (!fit)
{
return false;
}
atlas->addTexture(im->get_width(), im->get_height());
im_info->index(atlas->getTextureCount() - 1);
images.push_back(im_info);
return true;
}
void packTextures(void)
{
int w, h;
atlas_unused_pixels = atlas->packTextures(w, h, true, false);
atlas_max_width = w;
atlas_max_height = h;
}
size_t packedCount(void) { return atlas->getTextureCount(); }
size_t packedUnusedPixels(void) { return atlas_unused_pixels; }
size_t packedWidth(void) { return atlas_max_width; }
size_t packedHeight(void) { return atlas_max_height; }
void visit(TextureAtlasInfoVisitor &taiv)
{
for(std::list<TextureInfo *>::iterator images_iter = images.begin();
images_iter != images.end();
images_iter++)
{
TextureInfo* im_info = *images_iter;
int x, y, width, height;
bool rot90;
rot90 = atlas->getTextureLocation(im_info->index(),
x, y, width, height);
taiv.visit(*im_info, x, y, width, height, rot90);
}
}
private:
size_t atlas_unused_pixels;
size_t atlas_max_width;
size_t atlas_max_height;
TEXTURE_PACKER::TexturePacker* atlas;
std::list<TextureInfo *> images;
};
class TextureAtlasInfoWriteVisitor : public TextureAtlasInfoVisitor
{
public:
TextureAtlasInfoWriteVisitor(std::string path, size_t w, size_t h) :
out_image_path(path), out_image(w, h)
{
}
~TextureAtlasInfoWriteVisitor(void)
{
out_image.write(out_image_path + ".png");
}
void visit(TextureInfo &im_info,
int x, int y, int width, int height, bool rot90)
{
im_info.writeTo(out_image, x, y, width, height, rot90);
}
private:
png::image<png::rgba_pixel> out_image;
std::string out_image_path;
};
class TextureAtlasInfoDebugWriteVisitor : public TextureAtlasInfoVisitor
{
public:
static std::string name() { return "debug"; }
TextureAtlasInfoDebugWriteVisitor(std::string path,
size_t w, size_t h,
size_t num_packed, size_t unused) :
out_image_path(path), out_image_width(w), out_image_height(h)
{
std::cout << "Packed " << num_packed << " images to " << path << ".png"
<< " with " << unused << " unused area "
<< "Width (" << w << ") x Height (" << h << ")"
<< std::endl;
}
~TextureAtlasInfoDebugWriteVisitor(void)
{
std::cout << std::endl;
}
void visit(TextureInfo &im_info,
int x, int y, int width, int height, bool rot90)
{
std::cout << im_info.path() << " => ";
if (rot90) std::cout << "rotated 90 ";
std::cout << "x: " << x << " "
<< "y: " << y << " "
<< "width: " << width << " "
<< "height: " << height << " "
<< std::endl;
}
private:
std::string out_image_path;
size_t out_image_width;
size_t out_image_height;
};
class TextureAtlasInfoCSVWriteVisitor : public TextureAtlasInfoVisitor
{
public:
static std::string name() { return "csv"; }
TextureAtlasInfoCSVWriteVisitor(std::string path,
size_t w, size_t h,
size_t num_packed, size_t unused) :
out_image_path(path), out_image_width(w), out_image_height(h)
{
}
~TextureAtlasInfoCSVWriteVisitor(void)
{
}
void visit(TextureInfo &im_info,
int x, int y, int width, int height, bool rot90)
{
}
private:
std::string out_image_path;
size_t out_image_width;
size_t out_image_height;
};
int
main(int argc, char* argv[])
{
std::string out_atlas_name = "";
size_t out_atlas_height = 0;
size_t out_atlas_width = 0;
std::vector<std::string> out_visitors_str;
std::vector<std::string> image_names;
std::list<TextureAtlasInfo *> atlases;
// Read in the command line arguements
try
{
TCLAP::CmdLine cmd("Creates a texture atlas from a list of PNG files.",
' ', VERSION, true);
// Output atlas file name
TCLAP::ValueArg<std::string> out_atlas_name_arg(
"o","out_name",
"Output atlas image's file name.",
false, "out_atlas", "string");
cmd.add(out_atlas_name_arg);
// Output atlas image dimensions
TCLAP::ValueArg<size_t> out_atlas_width_arg(
"x","out_width",
"Maximum output atlas image's width.",
false, 1024, "pixels");
cmd.add(out_atlas_width_arg);
TCLAP::ValueArg<size_t> out_atlas_height_arg(
"y","out_height",
"Maximum output atlas image's height.",
false, 1024, "pixels");
cmd.add(out_atlas_height_arg);
// Input image files
TCLAP::UnlabeledMultiArg<std::string> in_image_names_arg(
"in_names", "List of the image filenames.", true, "PNG file path");
cmd.add(in_image_names_arg);
// Output visitors
TCLAP::SwitchArg quiet_arg("q", "quiet",
"Suppress processing information output.", false);
cmd.add(quiet_arg);
std::ostringstream info_writers_oss;
info_writers_oss
<< "Atlas information writers: "
<< TextureAtlasInfoCSVWriteVisitor::name();
TCLAP::MultiArg<std::string> out_vistors_arg("i", "info_writers",
info_writers_oss.str(),
false, "string");
cmd.add(out_vistors_arg);
// Parse the command line options
cmd.parse(argc, argv);
out_atlas_name = out_atlas_name_arg.getValue();
out_atlas_width = out_atlas_width_arg.getValue();
out_atlas_height = out_atlas_height_arg.getValue();
if (!quiet_arg.getValue())
{
out_visitors_str.push_back(TextureAtlasInfoDebugWriteVisitor::name());
}
std::vector<std::string> out_visitors_arg_strs = out_vistors_arg.getValue();
std::vector<std::string>::iterator out_visitors_str_iter
= out_visitors_str.end() + 1;
out_visitors_str.insert(out_visitors_str_iter,
out_visitors_arg_strs.begin(),
out_visitors_arg_strs.end());
image_names = in_image_names_arg.getValue();
}
catch (TCLAP::ArgException &e)
{
std::cerr << "Error: " << e.error() << " for arg " << e.argId() << std::endl;
return 1;
}
// Create the initial texture atlas
atlases.push_back(new TextureAtlasInfo(out_atlas_width, out_atlas_height,
image_names.size()));
// Load the textures
for(size_t idx = 0; idx < image_names.size(); idx++)
{
try
{
// Load the image
TextureInfo* ti = new TextureInfo(idx, image_names[idx]);
if (ti->image()->get_width() > out_atlas_width ||
ti->image()->get_height() > out_atlas_height)
{
std::cerr << "Error: " << ti->path() << " is too big!" << std::endl;
std::cerr << "Image dimensions: " << ti->image()->get_width()
<< " x " << ti->image()->get_height() << std::endl;
std::cerr << "Atlas dimensions: " << out_atlas_width
<< " x " << out_atlas_height << std::endl;
return 1;
}
// Add to the atlas
TextureAtlasInfo* tai = atlases.back();
if (!tai->addTexture(ti))
{
// Create a new atlas
TextureAtlasInfo* tai_next = new TextureAtlasInfo(out_atlas_width,
out_atlas_height,
image_names.size());
tai_next->addTexture(ti);
atlases.push_back(tai_next);
}
}
catch(png::std_error &e)
{
std::cerr << e.what() << std::endl;
return 1;
}
}
// Pack and write out the atlases
int idx = 0;
for(std::list<TextureAtlasInfo *>::iterator atlases_iter = atlases.begin();
atlases_iter != atlases.end();
atlases_iter++, idx++)
{
std::ostringstream oss;
oss << out_atlas_name << "_" << idx;
std::string atlas_name(oss.str());
TextureAtlasInfo* tai = *atlases_iter;
tai->packTextures();
TextureAtlasInfoWriteVisitor tai_writer(atlas_name,
tai->packedWidth(),
tai->packedHeight());
tai->visit(tai_writer);
// Ugly way to do this.
for(std::vector<std::string>::iterator vis_iter = out_visitors_str.begin();
vis_iter != out_visitors_str.end();
vis_iter++)
{
TextureAtlasInfoVisitor* taiv = NULL;
if (vis_iter->compare(TextureAtlasInfoDebugWriteVisitor::name()) == 0)
{
taiv = new TextureAtlasInfoDebugWriteVisitor(atlas_name,
tai->packedWidth(),
tai->packedHeight(),
tai->packedCount(),
tai->packedUnusedPixels());
}
else if (vis_iter->compare(TextureAtlasInfoCSVWriteVisitor::name()) == 0)
{
taiv = new TextureAtlasInfoCSVWriteVisitor(atlas_name,
tai->packedWidth(),
tai->packedHeight(),
tai->packedCount(),
tai->packedUnusedPixels());
}
if (taiv != NULL)
{
tai->visit(*taiv);
delete taiv;
}
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include "View.hpp"
#include "ModelStorage.hpp"
#include "Settings.hpp"
#include <QApplication>
#include <QString>
#include "ProjectsView.hpp"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
View widok;
SimpleActionsView *v;
QString filestore = QString::fromUtf8("storage.dat");
ModelStorage storage(filestore);
storage.setSettings(Settings::getInstance());
SimpleActionsModel *m;
v = new SimpleActionsView(QString::fromUtf8("Next Actions"), &widok);
widok.addCategory(v);
m = new SimpleActionsModel(v, v);
storage.addModel(m);
v = new ProjectsView(QString::fromUtf8("Projects"), &widok);
widok.addCategory(v);
m = new SimpleActionsModel(v, v);
storage.addModel(m);
storage.loadAll();
widok.show();
return app.exec();
}
<commit_msg>Keep the storage in a sane place<commit_after>#include "View.hpp"
#include "ModelStorage.hpp"
#include "Settings.hpp"
#include <QApplication>
#include <QString>
#include <QDir>
#include "ProjectsView.hpp"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
View widok;
SimpleActionsView *v;
QString filestore = QDir::homePath()
+ QString::fromUtf8("/.config/GetThingsDone/storage.dat");
ModelStorage storage(filestore);
storage.setSettings(Settings::getInstance());
SimpleActionsModel *m;
v = new SimpleActionsView(QString::fromUtf8("Next Actions"), &widok);
widok.addCategory(v);
m = new SimpleActionsModel(v, v);
storage.addModel(m);
v = new ProjectsView(QString::fromUtf8("Projects"), &widok);
widok.addCategory(v);
m = new SimpleActionsModel(v, v);
storage.addModel(m);
storage.loadAll();
widok.show();
return app.exec();
}
<|endoftext|> |
<commit_before>5d28662c-2d16-11e5-af21-0401358ea401<commit_msg>5d28662d-2d16-11e5-af21-0401358ea401<commit_after>5d28662d-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>c7ce095c-ad59-11e7-99d5-ac87a332f658<commit_msg>Fixed that one bug<commit_after>c8683e8a-ad59-11e7-b024-ac87a332f658<|endoftext|> |
<commit_before>#include <istream>
#include <ostream>
#include <iostream>
#include <vector>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
struct State {
float x, y, radius, r, g, b, a;
State(float x, float y, float radius,
float r, float g, float b, float a):
x(x), y(y), radius(radius),
r(r), g(g), b(b), a(a)
{}
};
State operator+(const State &s1,
const State &s2)
{
return State(s1.x + s2.x,
s1.y + s2.y,
s1.radius + s2.radius,
s1.r + s2.r,
s1.g + s2.g,
s1.b + s2.b,
s1.a + s2.a);
}
State operator-(const State &s1,
const State &s2)
{
return State(s1.x - s2.x,
s1.y - s2.y,
s1.radius - s2.radius,
s1.r - s2.r,
s1.g - s2.g,
s1.b - s2.b,
s1.a - s2.a);
}
State operator*(const State &state, const float factor)
{
return State(state.x * factor,
state.y * factor,
state.radius * factor,
state.r * factor,
state.g * factor,
state.b * factor,
state.a * factor);
}
sf::CircleShape stateToCircle(const State &state)
{
sf::CircleShape circle(state.radius);
circle.setFillColor(sf::Color(state.r, state.g, state.b, state.a));
circle.setPosition(state.x - state.radius / 2.0f, state.y - state.radius / 2.0f);
return circle;
}
std::ostream &operator<<(std::ostream &os, const State &state)
{
os << "("
<< state.x << ", "
<< state.y << ", "
<< state.radius << ", "
<< state.r << ", "
<< state.g << ", "
<< state.b << ", "
<< state.a
<< ")";
return os;
}
struct Transition
{
public:
Transition(const State &initialState,
sf::Int32 transitionTime,
const State &finalState):
currentState(initialState),
timeLeft(transitionTime),
finalState(finalState)
{}
State nextState(const sf::Int32 deltaTime)
{
std::cout << timeLeft << std::endl;
if (deltaTime < timeLeft) {
State deltaState = (finalState - currentState) * ((deltaTime + .0) / timeLeft);
currentState = currentState + deltaState;
} else {
currentState = finalState;
}
timeLeft -= deltaTime;
return currentState;
}
bool isFinished() const
{
return timeLeft <= 0.0f;
}
sf::Int32 getTimeLeft() const
{
return timeLeft;
}
private:
State currentState;
sf::Int32 timeLeft;
const State finalState;
};
int main()
{
sf::RenderWindow App(sf::VideoMode(800, 600, 32), "Hello World - SFML");
sf::SoundBuffer kickBuffer, snareBuffer, hihatBuffer;
if (!kickBuffer.loadFromFile("data/kick.wav")) {
std::cout << "[ERROR] Cannot load data/kick.wav" << std::endl;
return 1;
}
if (!snareBuffer.loadFromFile("data/snare.wav")) {
std::cout << "[ERROR] Cannot load data/snare.wav" << std::endl;
return 1;
}
if (!hihatBuffer.loadFromFile("data/hihat.wav")) {
std::cout << "[ERROR] Cannot load data/hihat.wav" << std::endl;
return 1;
}
sf::Sound kickSound, snareSound , hihatSound;
kickSound.setBuffer(kickBuffer);
snareSound.setBuffer(snareBuffer);
hihatSound.setBuffer(hihatBuffer);
const State normalState(200.0f, 200.0f, 50.0f, 255.0f, 255.0f, 255.0f, 255.0f);
Transition *transition = NULL;
State state(200.0f, 200.0f, 50.0f, 255.0f, 255.0f, 255.0f, 255.0f);
sf::Clock clock;
while (App.isOpen())
{
// std::cout << state << std::endl;
clock.restart();
sf::Event Event;
while (App.pollEvent(Event))
{
if (Event.type == sf::Event::Closed) {
App.close();
} else if (Event.type == sf::Event::JoystickButtonPressed) {
// std::cout << "JoystickButtonEvent: " << Event.joystickButton.button << std::endl;
switch (Event.joystickButton.button) {
case 0:
state.radius = 70.0f;
state.r = 255.0f;
state.g = 0.0f;
state.b = 0.0f;
if (transition != NULL) {
delete transition;
}
transition = new Transition(state, 300, normalState);
kickSound.play();
break;
case 1:
state.radius = 70.0f;
state.r = 0.0f;
state.g = 255.0f;
state.b = 0.0f;
if (transition != NULL) {
delete transition;
}
transition = new Transition(state, 300, normalState);
snareSound.play();
break;
case 2:
hihatSound.play();
break;
default: {}
}
}
}
App.clear(sf::Color(0, 0, 0));
if (transition != NULL) {
state = transition->nextState(clock.getElapsedTime().asMilliseconds());
if (transition->isFinished()) {
delete transition;
transition = NULL;
}
}
App.draw(stateToCircle(state));
App.display();
}
return 0;
}
<commit_msg>Color transition for hihat<commit_after>#include <istream>
#include <ostream>
#include <iostream>
#include <vector>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
struct State {
float x, y, radius, r, g, b, a;
State(float x, float y, float radius,
float r, float g, float b, float a):
x(x), y(y), radius(radius),
r(r), g(g), b(b), a(a)
{}
};
State operator+(const State &s1,
const State &s2)
{
return State(s1.x + s2.x,
s1.y + s2.y,
s1.radius + s2.radius,
s1.r + s2.r,
s1.g + s2.g,
s1.b + s2.b,
s1.a + s2.a);
}
State operator-(const State &s1,
const State &s2)
{
return State(s1.x - s2.x,
s1.y - s2.y,
s1.radius - s2.radius,
s1.r - s2.r,
s1.g - s2.g,
s1.b - s2.b,
s1.a - s2.a);
}
State operator*(const State &state, const float factor)
{
return State(state.x * factor,
state.y * factor,
state.radius * factor,
state.r * factor,
state.g * factor,
state.b * factor,
state.a * factor);
}
sf::CircleShape stateToCircle(const State &state)
{
sf::CircleShape circle(state.radius);
circle.setFillColor(sf::Color(state.r, state.g, state.b, state.a));
circle.setPosition(state.x - state.radius / 2.0f, state.y - state.radius / 2.0f);
return circle;
}
std::ostream &operator<<(std::ostream &os, const State &state)
{
os << "("
<< state.x << ", "
<< state.y << ", "
<< state.radius << ", "
<< state.r << ", "
<< state.g << ", "
<< state.b << ", "
<< state.a
<< ")";
return os;
}
struct Transition
{
public:
Transition(const State &initialState,
sf::Int32 transitionTime,
const State &finalState):
currentState(initialState),
timeLeft(transitionTime),
finalState(finalState)
{}
State nextState(const sf::Int32 deltaTime)
{
std::cout << timeLeft << std::endl;
if (deltaTime < timeLeft) {
State deltaState = (finalState - currentState) * ((deltaTime + .0) / timeLeft);
currentState = currentState + deltaState;
} else {
currentState = finalState;
}
timeLeft -= deltaTime;
return currentState;
}
bool isFinished() const
{
return timeLeft <= 0.0f;
}
sf::Int32 getTimeLeft() const
{
return timeLeft;
}
private:
State currentState;
sf::Int32 timeLeft;
const State finalState;
};
int main()
{
sf::RenderWindow App(sf::VideoMode(800, 600, 32), "Hello World - SFML");
sf::SoundBuffer kickBuffer, snareBuffer, hihatBuffer;
if (!kickBuffer.loadFromFile("data/kick.wav")) {
std::cout << "[ERROR] Cannot load data/kick.wav" << std::endl;
return 1;
}
if (!snareBuffer.loadFromFile("data/snare.wav")) {
std::cout << "[ERROR] Cannot load data/snare.wav" << std::endl;
return 1;
}
if (!hihatBuffer.loadFromFile("data/hihat.wav")) {
std::cout << "[ERROR] Cannot load data/hihat.wav" << std::endl;
return 1;
}
sf::Sound kickSound, snareSound , hihatSound;
kickSound.setBuffer(kickBuffer);
snareSound.setBuffer(snareBuffer);
hihatSound.setBuffer(hihatBuffer);
const State normalState(200.0f, 200.0f, 50.0f, 255.0f, 255.0f, 255.0f, 255.0f);
Transition *transition = NULL;
State state(200.0f, 200.0f, 50.0f, 255.0f, 255.0f, 255.0f, 255.0f);
sf::Clock clock;
while (App.isOpen())
{
// std::cout << state << std::endl;
clock.restart();
sf::Event Event;
while (App.pollEvent(Event))
{
if (Event.type == sf::Event::Closed) {
App.close();
} else if (Event.type == sf::Event::JoystickButtonPressed) {
// std::cout << "JoystickButtonEvent: " << Event.joystickButton.button << std::endl;
switch (Event.joystickButton.button) {
case 0:
state.radius = 70.0f;
state.r = 255.0f;
state.g = 0.0f;
state.b = 0.0f;
if (transition != NULL) {
delete transition;
}
transition = new Transition(state, 300, normalState);
kickSound.play();
break;
case 1:
state.radius = 70.0f;
state.r = 0.0f;
state.g = 255.0f;
state.b = 0.0f;
if (transition != NULL) {
delete transition;
}
transition = new Transition(state, 300, normalState);
snareSound.play();
break;
case 2:
state.radius = 70.0f;
state.r = 0.0f;
state.g = 0.0f;
state.b = 255.0f;
if (transition != NULL) {
delete transition;
}
transition = new Transition(state, 300, normalState);
hihatSound.play();
break;
default: {}
}
}
}
App.clear(sf::Color(0, 0, 0));
if (transition != NULL) {
state = transition->nextState(clock.getElapsedTime().asMilliseconds());
if (transition->isFinished()) {
delete transition;
transition = NULL;
}
}
App.draw(stateToCircle(state));
App.display();
}
return 0;
}
<|endoftext|> |
<commit_before>fbbe6276-585a-11e5-bbeb-6c40088e03e4<commit_msg>fbc56148-585a-11e5-9ff8-6c40088e03e4<commit_after>fbc56148-585a-11e5-9ff8-6c40088e03e4<|endoftext|> |
<commit_before>d72a40d7-2d3c-11e5-8b19-c82a142b6f9b<commit_msg>d77a5985-2d3c-11e5-9480-c82a142b6f9b<commit_after>d77a5985-2d3c-11e5-9480-c82a142b6f9b<|endoftext|> |
<commit_before>fe3f7945-2e4e-11e5-a5fe-28cfe91dbc4b<commit_msg>fe479017-2e4e-11e5-a05e-28cfe91dbc4b<commit_after>fe479017-2e4e-11e5-a05e-28cfe91dbc4b<|endoftext|> |
<commit_before>3e364114-2d3e-11e5-afa5-c82a142b6f9b<commit_msg>3e93aedc-2d3e-11e5-b255-c82a142b6f9b<commit_after>3e93aedc-2d3e-11e5-b255-c82a142b6f9b<|endoftext|> |
<commit_before>6f0ef9f4-2fa5-11e5-804e-00012e3d3f12<commit_msg>6f111cd4-2fa5-11e5-b994-00012e3d3f12<commit_after>6f111cd4-2fa5-11e5-b994-00012e3d3f12<|endoftext|> |
<commit_before>d3a3e973-313a-11e5-9763-3c15c2e10482<commit_msg>d3a9e6a8-313a-11e5-9766-3c15c2e10482<commit_after>d3a9e6a8-313a-11e5-9766-3c15c2e10482<|endoftext|> |
<commit_before>fe45fab3-ad59-11e7-a410-ac87a332f658<commit_msg>Adding stuff<commit_after>fed80b3d-ad59-11e7-aa5f-ac87a332f658<|endoftext|> |
<commit_before>658e92a4-2fa5-11e5-a714-00012e3d3f12<commit_msg>6590dc94-2fa5-11e5-82d6-00012e3d3f12<commit_after>6590dc94-2fa5-11e5-82d6-00012e3d3f12<|endoftext|> |
<commit_before>4340be40-2e4f-11e5-89a4-28cfe91dbc4b<commit_msg>4349b68a-2e4f-11e5-b664-28cfe91dbc4b<commit_after>4349b68a-2e4f-11e5-b664-28cfe91dbc4b<|endoftext|> |
<commit_before>035a442b-2e4f-11e5-9af3-28cfe91dbc4b<commit_msg>0360ed54-2e4f-11e5-8d2d-28cfe91dbc4b<commit_after>0360ed54-2e4f-11e5-8d2d-28cfe91dbc4b<|endoftext|> |
<commit_before>43120bc8-5216-11e5-8c06-6c40088e03e4<commit_msg>431934f0-5216-11e5-b8a3-6c40088e03e4<commit_after>431934f0-5216-11e5-b8a3-6c40088e03e4<|endoftext|> |
<commit_before>ab5de3e8-327f-11e5-b8ea-9cf387a8033e<commit_msg>ab63f057-327f-11e5-bdf0-9cf387a8033e<commit_after>ab63f057-327f-11e5-bdf0-9cf387a8033e<|endoftext|> |
<commit_before>#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <map>
std::map<std::string, std::vector <std::vector <std::string> > > parse_data(std::ifstream){
}
int main(){
std::vector <std::vector <std::string> > data;
std::map<std::string, std::vector <std::vector <std::string> > > map_player_salary;
std::vector <std::vector <std::string> > pitcher_data;
std::map<std::string, std::vector <std::vector <std::string> > > map_pitcher_player;
std::ifstream infile( "2017_MLB_Player_Salary_Info.md" );
std::ifstream infile_batter( "2017_MLB_Batter_Info.md" );
std::ifstream infile_pitcher( "2017_MLB_Pitcher_Info.md" );
int count=0;
while (infile){
std::string s;
if (!getline( infile, s )){
break;
}
std::istringstream ss( s );
std::vector <std::string> record;
while (ss){
std::string s;
if (!getline( ss, s, ',' )){
break;
}
record.push_back( s );
}
data.push_back( record );
std::string full_name= data[count][1];
std::string modified_name="";
int x=0;
while(x<full_name.size()){
if(full_name[x]!='\\'){
modified_name.push_back(full_name[x]);
}else{
modified_name.pop_back();
break;
}
x++;
}
map_player_salary.insert(std::make_pair(modified_name, data));
count++;
}
//test if player salary data works
for(int x=0; x<data.size(); x++){
if((data[x][21])!=""){
std::cout<<"Name: "<< data[x][1]<<" Salary: "<< data[x][21]<<std::endl;
}
}
if(map_player_salary.find("Clayton Kershaw")!=map_player_salary.end()){
std::cout<<"map works!!"<<std::endl;
}
//parse thru player pitcher info and store everything into a map
count=0;
while (infile_pitcher){
std::string s;
if (!getline( infile_pitcher, s )){
break;
}
std::istringstream ss( s );
std::vector <std::string> record;
while (ss){
std::string s;
if (!getline( ss, s, ',' )){
break;
}
record.push_back( s );
}
pitcher_data.push_back( record );
std::string full_name= pitcher_data[count][1];
std::string modified_name="";
int x=0;
while(x<full_name.size()){
if(full_name[x]!='\\'){
modified_name.push_back(full_name[x]);
}else{
modified_name.pop_back();
break;
}
x++;
}
map_pitcher_player.insert(std::make_pair(modified_name, pitcher_data));
count++;
}
//test if pitcher player data works
for(int x=0; x<pitcher_data.size(); x++){
if((pitcher_data[x][1])!="Name"){
std::cout<<"Name: "<< pitcher_data[x][1]<<" ERA: "<< pitcher_data[x][8]<<std::endl;
}
}
if(map_pitcher_player.find("Mike Wright")!=map_pitcher_player.end()){
std::cout<<"map works!!"<<std::endl;
}
return 0;
}
<commit_msg>pass by reference not copy<commit_after>#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <map>
std::map<std::string, std::vector <std::vector <std::string> > >& parse_data(std::ifstream &data){
}
int main(){
std::vector <std::vector <std::string> > data;
std::map<std::string, std::vector <std::vector <std::string> > > map_player_salary;
std::vector <std::vector <std::string> > pitcher_data;
std::map<std::string, std::vector <std::vector <std::string> > > map_pitcher_player;
std::ifstream infile( "2017_MLB_Player_Salary_Info.md" );
std::ifstream infile_batter( "2017_MLB_Batter_Info.md" );
std::ifstream infile_pitcher( "2017_MLB_Pitcher_Info.md" );
int count=0;
while (infile){
std::string s;
if (!getline( infile, s )){
break;
}
std::istringstream ss( s );
std::vector <std::string> record;
while (ss){
std::string s;
if (!getline( ss, s, ',' )){
break;
}
record.push_back( s );
}
data.push_back( record );
std::string full_name= data[count][1];
std::string modified_name="";
int x=0;
while(x<full_name.size()){
if(full_name[x]!='\\'){
modified_name.push_back(full_name[x]);
}else{
modified_name.pop_back();
break;
}
x++;
}
map_player_salary.insert(std::make_pair(modified_name, data));
count++;
}
//test if player salary data works
for(int x=0; x<data.size(); x++){
if((data[x][21])!=""){
std::cout<<"Name: "<< data[x][1]<<" Salary: "<< data[x][21]<<std::endl;
}
}
if(map_player_salary.find("Clayton Kershaw")!=map_player_salary.end()){
std::cout<<"map works!!"<<std::endl;
}
//parse thru player pitcher info and store everything into a map
count=0;
while (infile_pitcher){
std::string s;
if (!getline( infile_pitcher, s )){
break;
}
std::istringstream ss( s );
std::vector <std::string> record;
while (ss){
std::string s;
if (!getline( ss, s, ',' )){
break;
}
record.push_back( s );
}
pitcher_data.push_back( record );
std::string full_name= pitcher_data[count][1];
std::string modified_name="";
int x=0;
while(x<full_name.size()){
if(full_name[x]!='\\'){
modified_name.push_back(full_name[x]);
}else{
modified_name.pop_back();
break;
}
x++;
}
map_pitcher_player.insert(std::make_pair(modified_name, pitcher_data));
count++;
}
//test if pitcher player data works
for(int x=0; x<pitcher_data.size(); x++){
if((pitcher_data[x][1])!="Name"){
std::cout<<"Name: "<< pitcher_data[x][1]<<" ERA: "<< pitcher_data[x][8]<<std::endl;
}
}
if(map_pitcher_player.find("Mike Wright")!=map_pitcher_player.end()){
std::cout<<"map works!!"<<std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>0bc3ea30-2748-11e6-96a4-e0f84713e7b8<commit_msg>testing<commit_after>0bcef01c-2748-11e6-9e0a-e0f84713e7b8<|endoftext|> |
<commit_before>80f3edf3-2e4f-11e5-87ca-28cfe91dbc4b<commit_msg>80fbac35-2e4f-11e5-8517-28cfe91dbc4b<commit_after>80fbac35-2e4f-11e5-8517-28cfe91dbc4b<|endoftext|> |
<commit_before>741aa666-2e4f-11e5-8f40-28cfe91dbc4b<commit_msg>742535c2-2e4f-11e5-ae24-28cfe91dbc4b<commit_after>742535c2-2e4f-11e5-ae24-28cfe91dbc4b<|endoftext|> |
<commit_before>dc969f87-4b02-11e5-9113-28cfe9171a43<commit_msg>roselyn broke it<commit_after>dca42673-4b02-11e5-bd5a-28cfe9171a43<|endoftext|> |
<commit_before>// CS184 Simple OpenGL Example
#include <cstdlib> //for rand
#include <iostream> //to load images
using namespace std;
//#include "CImg.h" //to get rgba data
//using namespace cimg_library;
#include <vector>
#include <iostream>
#include <fstream>
#include <cmath>
#include <string>
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif
#ifdef OSX
#include <GLUT/glut.h>
#include <OpenGL/glu.h>
#else
#include <GL/glut.h>
#include <GL/glu.h>
#endif
#include <time.h>
#include <math.h>
#ifdef _WIN32
static DWORD lastTime;
#else
static struct timeval lastTime;
#endif
#define PI 3.14159265
using namespace std;
//****************************************************
// Some Classes
//****************************************************
/*************** OLD CODE *********************************/
class Viewport {
public:
int w, h; // width and height
};
//****************************************************
// Global Variables
//****************************************************
Viewport viewport;
string input_file_name;
float sub_div_parameter;
// switch from uniform to adaptive mode
bool adaptive = false;
//****************************************************
// keyboard functions
//****************************************************
void special_keyboard(int key, int x, int y){
switch(key){
case GLUT_KEY_RIGHT:
if(glutGetModifiers() == GLUT_ACTIVE_SHIFT) {
printf("object will be translated right\n");
break;
}
printf("object will be rotated right\n");
break;
case GLUT_KEY_LEFT:
if(glutGetModifiers() == GLUT_ACTIVE_SHIFT) {
printf("object will be translated left\n");
break;
}
printf("object will be rotated left\n");
break;
case GLUT_KEY_UP:
if(glutGetModifiers() == GLUT_ACTIVE_SHIFT) {
printf("object will be translated up\n");
break;
}
printf("object will be rotated up\n");
break;
case GLUT_KEY_DOWN:
if(glutGetModifiers() == GLUT_ACTIVE_SHIFT) {
printf("object will be translated down\n");
break;
}
printf("object will be rotated down\n");
break;
}
}
void keyboard(unsigned char key, int x, int y){
switch(key){
case 's':
printf("toggle between flat and smooth shading\n");
break;
case 'w':
printf("toggle between filled and wireframe mode.\n");
break;
case 'c':
printf("do vertex color shading based on the Gaussian Curvature of the surface.\n");
break;
case 43:
// PLUS sign +
printf("zoom in\n");
break;
case 45:
// MINUS sign -
printf("zoom out\n");
break;
}
}
//****************************************************
// reshape viewport if the window is resized
//****************************************************
void myReshape(int w, int h) {
viewport.w = w;
viewport.h = h;
glViewport(0,0,viewport.w,viewport.h);// sets the rectangle that will be the window
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); // loading the identity matrix for the screen
//----------- setting the projection -------------------------
// glOrtho sets left, right, bottom, top, zNear, zFar of the chord system
// glOrtho(-1, 1 + (w-400)/200.0 , -1 -(h-400)/200.0, 1, 1, -1); // resize type = add
// glOrtho(-w/400.0, w/400.0, -h/400.0, h/400.0, 1, -1); // resize type = center
glOrtho(-1, 1, -1, 1, 1, -1); // resize type = stretch
//------------------------------------------------------------
}
//****************************************************
// sets the window up
//****************************************************
void initScene(){
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Clear to black, fully transparent
myReshape(viewport.w,viewport.h);
}
//***************************************************
// function that does the actual drawing
//***************************************************
void myDisplay() {
//----------------------- ----------------------- -----------------------
// This is a quick hack to add a little bit of animation.
static float tip = 0.5f;
const float stp = 0.01f;
const float beg = 0.1f;
const float end = 0.9f;
tip += stp;
if (tip>end) tip = beg;
//----------------------- ----------------------- -----------------------
glClear(GL_COLOR_BUFFER_BIT); // clear the color buffer (sets everything to black)
glMatrixMode(GL_MODELVIEW); // indicate we are specifying camera transformations
glLoadIdentity(); // make sure transformation is "zero'd"
//-----------------------------------------------------------------------
glFlush();
glutSwapBuffers(); // swap buffers (we earlier set double buffer)
}
//****************************************************
// called by glut when there are no messages to handle
//****************************************************
void myFrameMove() {
//nothing here for now
#ifdef _WIN32
Sleep(10); //give ~10ms back to OS (so as not to waste the CPU)
#endif
glutPostRedisplay(); // forces glut to call the display function (myDisplay())
}
//****************************************************
// the usual stuff, nothing exciting here
//****************************************************
int main(int argc, char *argv[]) {
if(argc < 3) {
printf("\nWrong number of command-line arguments. Arguments should be in the format:\n");
printf("main [inputfile.bez] [float subdivision parameter] optional[-a]\n\n");
exit(0);
}
input_file_name = argv[1];
sub_div_parameter = atof(argv[2]);
if(argc == 4 && strcmp(argv[3],"-a")) {
adaptive = true;
}
//This initializes glut
glutInit(&argc, argv);
//This tells glut to use a double-buffered window with red, green, and blue channels
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
// Initalize theviewport size
viewport.w = 1000;//1280
viewport.h = 1000;
//The size and position of the window
glutInitWindowSize(viewport.w, viewport.h);
glutInitWindowPosition(0, 0);
glutCreateWindow("CS184! by Sebastian and Risa");
initScene(); // quick function to set up scene
glutDisplayFunc(myDisplay); // function to run when its time to draw something
glutReshapeFunc(myReshape); // function to run when the window gets resized
glutKeyboardFunc(keyboard);
glutSpecialFunc(special_keyboard);
glutIdleFunc(myFrameMove); // function to run when not handling any other task
glutMainLoop(); // infinite loop that will keep drawing and resizing and whatever else
return 0;
}
<commit_msg>Started file parsing<commit_after>// CS184 Simple OpenGL Example
#include <cstdlib> //for rand
//#include "CImg.h" //to get rgba data
//using namespace cimg_library;
#include <vector>
#include <iostream>
#include <fstream>
#include <cmath>
#include <string>
#include <stdlib.h>
#include <sstream>
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif
#ifdef OSX
#include <GLUT/glut.h>
#include <OpenGL/glu.h>
#else
#include <GL/glut.h>
#include <GL/glu.h>
#endif
#include <time.h>
#include <math.h>
#include "bezier.h"
#ifdef _WIN32
static DWORD lastTime;
#else
static struct timeval lastTime;
#endif
#define PI 3.14159265
using namespace std;
//****************************************************
// Global Variables
//****************************************************
string input_file_name;
float sub_div_parameter;
// switch from uniform to adaptive mode
bool adaptive = false;
//****************************************************
// Some Classes
//****************************************************
class Viewport {
public:
int w, h; // width and height
};
Viewport viewport;
//****************************************************
// Some Functions
//****************************************************
void parseCommandlineArguments(int argc, char *argv[]) {
if(argc < 3) {
printf("\nWrong number of command-line arguments. Arguments should be in the format:\n");
printf("main [inputfile.bez] [float subdivision parameter] optional[-a]\n\n");
exit(0);
}
input_file_name = argv[1];
sub_div_parameter = atof(argv[2]);
if(argc == 4 && strcmp(argv[3],"-a")) {
adaptive = true;
}
}
vector<string> splitAtWhiteSpace(string const &input) {
istringstream buffer(input);
vector<string> ret((istream_iterator<string>(buffer)), istream_iterator<string>());
return ret;
}
void parseInputFile() {
ifstream input_file("models/" + input_file_name);
string line;
if(input_file.is_open()) {
int numPatches = 0;
getline(input_file, line);
numPatches = atoi(line.c_str());
for (int i = 0; i < numPatches; i++){
float point_array[4][4];
for(int c = 0; c < 4; c++) {
getline(input_file, line);
vector<string> coor_list;
coor_list = splitAtWhiteSpace(line);
for(int p = 0; p < 4; p++) {
float x = atof(coor_list[p + 3*c].c_str());
float y = atof(coor_list[p + 3*c].c_str());
float z = atof(coor_list[p + 3*c].c_str());
Point point(x, y, z);
cout << x << " " << y << " " << z << "\n";
}
//float curve[4] = {atof(coor_list[0].c_str()), atof(coor_list[1]), atof(coor_list[2]), atof(coor_list[3])};
//point_array[c] = curve;
}
//blank line
getline(input_file, line);
}
input_file.close();
}
}
//****************************************************
// keyboard functions
//****************************************************
void special_keyboard(int key, int x, int y){
switch(key){
case GLUT_KEY_RIGHT:
if(glutGetModifiers() == GLUT_ACTIVE_SHIFT) {
printf("object will be translated right\n");
break;
}
printf("object will be rotated right\n");
break;
case GLUT_KEY_LEFT:
if(glutGetModifiers() == GLUT_ACTIVE_SHIFT) {
printf("object will be translated left\n");
break;
}
printf("object will be rotated left\n");
break;
case GLUT_KEY_UP:
if(glutGetModifiers() == GLUT_ACTIVE_SHIFT) {
printf("object will be translated up\n");
break;
}
printf("object will be rotated up\n");
break;
case GLUT_KEY_DOWN:
if(glutGetModifiers() == GLUT_ACTIVE_SHIFT) {
printf("object will be translated down\n");
break;
}
printf("object will be rotated down\n");
break;
}
}
void keyboard(unsigned char key, int x, int y){
switch(key){
case 's':
printf("toggle between flat and smooth shading\n");
break;
case 'w':
printf("toggle between filled and wireframe mode.\n");
break;
case 'c':
printf("do vertex color shading based on the Gaussian Curvature of the surface.\n");
break;
case 43:
// PLUS sign +
printf("zoom in\n");
break;
case 45:
// MINUS sign -
printf("zoom out\n");
break;
}
}
//****************************************************
// reshape viewport if the window is resized
//****************************************************
void myReshape(int w, int h) {
viewport.w = w;
viewport.h = h;
glViewport(0,0,viewport.w,viewport.h);// sets the rectangle that will be the window
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); // loading the identity matrix for the screen
//----------- setting the projection -------------------------
// glOrtho sets left, right, bottom, top, zNear, zFar of the chord system
// glOrtho(-1, 1 + (w-400)/200.0 , -1 -(h-400)/200.0, 1, 1, -1); // resize type = add
// glOrtho(-w/400.0, w/400.0, -h/400.0, h/400.0, 1, -1); // resize type = center
glOrtho(-1, 1, -1, 1, 1, -1); // resize type = stretch
//------------------------------------------------------------
}
//****************************************************
// sets the window up
//****************************************************
void initScene(){
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Clear to black, fully transparent
myReshape(viewport.w,viewport.h);
}
//***************************************************
// function that does the actual drawing
//***************************************************
void myDisplay() {
//----------------------- ----------------------- -----------------------
// This is a quick hack to add a little bit of animation.
static float tip = 0.5f;
const float stp = 0.01f;
const float beg = 0.1f;
const float end = 0.9f;
tip += stp;
if (tip>end) tip = beg;
//----------------------- ----------------------- -----------------------
glClear(GL_COLOR_BUFFER_BIT); // clear the color buffer (sets everything to black)
glMatrixMode(GL_MODELVIEW); // indicate we are specifying camera transformations
glLoadIdentity(); // make sure transformation is "zero'd"
//-----------------------------------------------------------------------
glFlush();
glutSwapBuffers(); // swap buffers (we earlier set double buffer)
}
//****************************************************
// called by glut when there are no messages to handle
//****************************************************
void myFrameMove() {
//nothing here for now
#ifdef _WIN32
Sleep(10); //give ~10ms back to OS (so as not to waste the CPU)
#endif
glutPostRedisplay(); // forces glut to call the display function (myDisplay())
}
//****************************************************
// the usual stuff, nothing exciting here
//****************************************************
int main(int argc, char *argv[]) {
parseCommandlineArguments(argc, argv);
parseInputFile();
//This initializes glut
glutInit(&argc, argv);
//This tells glut to use a double-buffered window with red, green, and blue channels
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
// Initalize theviewport size
viewport.w = 1000;//1280
viewport.h = 1000;
//The size and position of the window
glutInitWindowSize(viewport.w, viewport.h);
glutInitWindowPosition(0, 0);
glutCreateWindow("CS184! by Sebastian and Risa");
initScene(); // quick function to set up scene
glutDisplayFunc(myDisplay); // function to run when its time to draw something
glutReshapeFunc(myReshape); // function to run when the window gets resized
glutKeyboardFunc(keyboard);
glutSpecialFunc(special_keyboard);
glutIdleFunc(myFrameMove); // function to run when not handling any other task
glutMainLoop(); // infinite loop that will keep drawing and resizing and whatever else
return 0;
}
<|endoftext|> |
<commit_before>1e77ec00-2748-11e6-a1d4-e0f84713e7b8<commit_msg>I am finally done<commit_after>1e836a6b-2748-11e6-ac9a-e0f84713e7b8<|endoftext|> |
<commit_before>5135df00-ad58-11e7-87f7-ac87a332f658<commit_msg>NO CHANGES<commit_after>51a2670f-ad58-11e7-acdf-ac87a332f658<|endoftext|> |
<commit_before>92d907b6-35ca-11e5-8f3e-6c40088e03e4<commit_msg>92dfee58-35ca-11e5-a497-6c40088e03e4<commit_after>92dfee58-35ca-11e5-a497-6c40088e03e4<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.