text stringlengths 54 60.6k |
|---|
<commit_before>8b3325ad-2d14-11e5-af21-0401358ea401<commit_msg>8b3325ae-2d14-11e5-af21-0401358ea401<commit_after>8b3325ae-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>763e1d30-2d53-11e5-baeb-247703a38240<commit_msg>763e9be8-2d53-11e5-baeb-247703a38240<commit_after>763e9be8-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>ebb84935-2e4e-11e5-aaa5-28cfe91dbc4b<commit_msg>ebc16607-2e4e-11e5-9b5c-28cfe91dbc4b<commit_after>ebc16607-2e4e-11e5-9b5c-28cfe91dbc4b<|endoftext|> |
<commit_before>760dcae0-2d53-11e5-baeb-247703a38240<commit_msg>760e4c90-2d53-11e5-baeb-247703a38240<commit_after>760e4c90-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>7f1369ca-4b02-11e5-93ed-28cfe9171a43<commit_msg>master branch<commit_after>7f21b138-4b02-11e5-86db-28cfe9171a43<|endoftext|> |
<commit_before>c5b4be42-35ca-11e5-a9dc-6c40088e03e4<commit_msg>c5be187a-35ca-11e5-9571-6c40088e03e4<commit_after>c5be187a-35ca-11e5-9571-6c40088e03e4<|endoftext|> |
<commit_before>83000e5b-2d15-11e5-af21-0401358ea401<commit_msg>83000e5c-2d15-11e5-af21-0401358ea401<commit_after>83000e5c-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>#include <iostream>
int main(int argc, char **argv )
{
return 0;
}<commit_msg>print message<commit_after>#include <iostream>
int main(int argc, char **argv )
{
std::cout<<"start httpserver"<<std::endl;
return 0;
}<|endoftext|> |
<commit_before>e063db6b-313a-11e5-8d78-3c15c2e10482<commit_msg>e069e287-313a-11e5-b692-3c15c2e10482<commit_after>e069e287-313a-11e5-b692-3c15c2e10482<|endoftext|> |
<commit_before>371ef8c6-5216-11e5-97dd-6c40088e03e4<commit_msg>3725b6fe-5216-11e5-a202-6c40088e03e4<commit_after>3725b6fe-5216-11e5-a202-6c40088e03e4<|endoftext|> |
<commit_before>#include "playlist.hpp"
#include "chromecast.hpp"
#include "webserver.hpp"
#include "cast_channel.pb.h"
#include <syslog.h>
#include <getopt.h>
#include <fstream>
void usage();
extern char* __progname;
const char* ffmpegpath()
{
if (access("./ffmpeg", F_OK) == 0)
return "./ffmpeg";
return "ffmpeg";
}
int main(int argc, char* argv[])
{
GOOGLE_PROTOBUF_VERIFY_VERSION;
OpenSSL_add_ssl_algorithms();
SSL_load_error_strings();
signal(SIGPIPE, SIG_IGN);
openlog(NULL, LOG_PID | LOG_PERROR, LOG_DAEMON);
std::string ip;
unsigned short port = 8080;
bool subtitles = false;
Playlist playlist;
static struct option longopts[] = {
{ "help", no_argument, NULL, 'h' },
{ "chromecast", required_argument, NULL, 'c' },
{ "port", required_argument, NULL, 'p' },
{ "playlist", required_argument, NULL, 'P' },
{ "subtitles", no_argument, NULL, 'S' },
{ "shuffle", no_argument, NULL, 's' },
{ "repeat", no_argument, NULL, 'r' },
{ "repeat-all", no_argument, NULL, 'R' },
{ NULL, 0, NULL, 0 }
};
int ch;
while ((ch = getopt_long(argc, argv, "hc:p:P:sSrR", longopts, NULL)) != -1) {
switch (ch) {
case 'c':
ip = optarg;
break;
case 'p':
port = strtoul(optarg, NULL, 10);
break;
case 'P':
{
std::ifstream input(optarg);
for (std::string line; getline(input, line);)
playlist.insert(line);
}
break;
case 's':
playlist.setShuffle(true);
break;
case 'S':
subtitles = true;
break;
case 'r':
playlist.setRepeat(true);
break;
case 'R':
playlist.setRepeatAll(true);
break;
default:
case 'h':
usage();
}
}
if (ip.empty())
usage();
ChromeCast chromecast(ip);
chromecast.init();
chromecast.setSubtitleSettings(subtitles);
chromecast.setMediaStatusCallback([&chromecast, &playlist, port](const std::string& playerState,
const std::string& idleReason, const std::string& uuid) -> void {
syslog(LOG_DEBUG, "mediastatus: %s %s %s", playerState.c_str(), idleReason.c_str(), uuid.c_str());
if (playerState == "IDLE") {
if (idleReason == "FINISHED") {
try {
std::lock_guard<std::mutex> lock(playlist.getMutex());
PlaylistItem track = playlist.getNextTrack(uuid);
std::thread foo([&chromecast, port, track]() {
chromecast.load("http://" + chromecast.getSocketName() + ":" + std::to_string(port) + "/stream/" + track.getUUID(),
track.getName(), track.getUUID());
});
foo.detach();
} catch (...) {
// ...
}
}
}
});
Webserver http(port, chromecast, playlist);
while (1) sleep(3600);
return 0;
}
void usage()
{
printf("%s --chromecast <ip> [ --port <number> ] [ --playlist <path> ]\n"
"\t[ --shuffle ] [ --repeat ] [ --repeat-all ]\n"
"\t[ --subtitles ]\n", __progname);
exit(1);
}
<commit_msg>auto play playlist<commit_after>#include "playlist.hpp"
#include "chromecast.hpp"
#include "webserver.hpp"
#include "cast_channel.pb.h"
#include <syslog.h>
#include <getopt.h>
#include <fstream>
void usage();
extern char* __progname;
const char* ffmpegpath()
{
if (access("./ffmpeg", F_OK) == 0)
return "./ffmpeg";
return "ffmpeg";
}
int main(int argc, char* argv[])
{
GOOGLE_PROTOBUF_VERIFY_VERSION;
OpenSSL_add_ssl_algorithms();
SSL_load_error_strings();
signal(SIGPIPE, SIG_IGN);
openlog(NULL, LOG_PID | LOG_PERROR, LOG_DAEMON);
std::string ip;
unsigned short port = 8080;
bool subtitles = false, play = false;
Playlist playlist;
static struct option longopts[] = {
{ "help", no_argument, NULL, 'h' },
{ "chromecast", required_argument, NULL, 'c' },
{ "port", required_argument, NULL, 'p' },
{ "playlist", required_argument, NULL, 'P' },
{ "play", no_argument, NULL, 'y' },
{ "subtitles", no_argument, NULL, 'S' },
{ "shuffle", no_argument, NULL, 's' },
{ "repeat", no_argument, NULL, 'r' },
{ "repeat-all", no_argument, NULL, 'R' },
{ NULL, 0, NULL, 0 }
};
int ch;
while ((ch = getopt_long(argc, argv, "hc:p:P:sSrRy", longopts, NULL)) != -1) {
switch (ch) {
case 'c':
ip = optarg;
break;
case 'p':
port = strtoul(optarg, NULL, 10);
break;
case 'P':
{
std::ifstream input(optarg);
for (std::string line; getline(input, line);)
playlist.insert(line);
}
break;
case 's':
playlist.setShuffle(true);
break;
case 'S':
subtitles = true;
break;
case 'r':
playlist.setRepeat(true);
break;
case 'R':
playlist.setRepeatAll(true);
break;
case 'y':
play = true;
break;
default:
case 'h':
usage();
}
}
if (ip.empty())
usage();
ChromeCast chromecast(ip);
chromecast.init();
chromecast.setSubtitleSettings(subtitles);
chromecast.setMediaStatusCallback([&chromecast, &playlist, port](const std::string& playerState,
const std::string& idleReason, const std::string& uuid) -> void {
syslog(LOG_DEBUG, "mediastatus: %s %s %s", playerState.c_str(), idleReason.c_str(), uuid.c_str());
if (playerState == "IDLE") {
if (idleReason == "FINISHED") {
try {
std::lock_guard<std::mutex> lock(playlist.getMutex());
PlaylistItem track = playlist.getNextTrack(uuid);
std::thread foo([&chromecast, port, track]() {
chromecast.load("http://" + chromecast.getSocketName() + ":" + std::to_string(port) + "/stream/" + track.getUUID(),
track.getName(), track.getUUID());
});
foo.detach();
} catch (...) {
// ...
}
}
}
});
Webserver http(port, chromecast, playlist);
if (play) {
try {
const PlaylistItem& track = playlist.getNextTrack("");
chromecast.load(
"http://" + chromecast.getSocketName() + ":" + std::to_string(port) + "/stream/" + track.getUUID(),
track.getName(), track.getUUID());
} catch (const std::runtime_error& e) {
syslog(LOG_DEBUG, "--play failed: %s", e.what());
}
}
while (1) sleep(3600);
return 0;
}
void usage()
{
printf("%s --chromecast <ip> [ --port <number> ] [ --playlist <path> ]\n"
"\t[ --shuffle ] [ --repeat ] [ --repeat-all ]\n"
"\t[ --subtitles ] [ --play ]\n", __progname);
exit(1);
}
<|endoftext|> |
<commit_before>d50384de-2d3c-11e5-92d6-c82a142b6f9b<commit_msg>d55a2530-2d3c-11e5-b758-c82a142b6f9b<commit_after>d55a2530-2d3c-11e5-b758-c82a142b6f9b<|endoftext|> |
<commit_before>2e372f38-5216-11e5-acda-6c40088e03e4<commit_msg>2e3e09b6-5216-11e5-be34-6c40088e03e4<commit_after>2e3e09b6-5216-11e5-be34-6c40088e03e4<|endoftext|> |
<commit_before>d2d220e1-2e4e-11e5-8ce5-28cfe91dbc4b<commit_msg>d2d94457-2e4e-11e5-939d-28cfe91dbc4b<commit_after>d2d94457-2e4e-11e5-939d-28cfe91dbc4b<|endoftext|> |
<commit_before>5e5893f1-2d16-11e5-af21-0401358ea401<commit_msg>5e5893f2-2d16-11e5-af21-0401358ea401<commit_after>5e5893f2-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>f566fb38-2747-11e6-a0ad-e0f84713e7b8<commit_msg>this is my first commit?<commit_after>f57257d9-2747-11e6-9290-e0f84713e7b8<|endoftext|> |
<commit_before>cf191359-ad5b-11e7-9965-ac87a332f658<commit_msg>Fix that bug where things didn't work but now they should<commit_after>d012629e-ad5b-11e7-9e7f-ac87a332f658<|endoftext|> |
<commit_before>04178907-2e4f-11e5-8627-28cfe91dbc4b<commit_msg>041e56ca-2e4f-11e5-ad87-28cfe91dbc4b<commit_after>041e56ca-2e4f-11e5-ad87-28cfe91dbc4b<|endoftext|> |
<commit_before>3725b6fe-5216-11e5-a202-6c40088e03e4<commit_msg>372c7014-5216-11e5-9b23-6c40088e03e4<commit_after>372c7014-5216-11e5-9b23-6c40088e03e4<|endoftext|> |
<commit_before>#include "display.h"
#include "Timer.h"
#include "T1/T1.h"
#include "T2/T2Poker.h"
#include "T2/T2Display.h"
#include "GameObject.h"
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sstream>
#include "D1/Poker.h"
using namespace std;
void runT1(GameObject game);
void runT2(GameObject game);
void runD1(GameObject game);
bool inHitBox(int cardX, int cardY, int x1, int x2, int y1, int y2);
T2Display T2GameDisplay; //global used in T2
GameObject* game = new GameObject(500,0);
void runT2(GameObject*);
void runT1(GameObject*);
void runD1(GameObject*);
int main (void) {
//initial values
display gameDisplay;
int initialBalance = 300;
int initialCards = 0;
//pointers for variables to be passed to functions
int* playerBalance = &initialBalance;
int* playedCards = &initialCards;
//create a time object to record time playing t2
Timer* t2Timer = new Timer();
gameDisplay.drawBox(50, 28, 19, 6, 0); // Top Left
T1::setText("B11","Texas Hold'em 1");
gameDisplay.drawBox(69, 28, 18, 6, 0); // Top Middle
T1::setText("B21","Texas Hold'em 2");
gameDisplay.drawBox(87, 28, 19, 6, 0); // Top Right
T1::setText("B31","Five Card Draw");
int keynew = 0;
char key;
char key2;
bool onGoing = true;
int cardX, cardY;
stringstream messageString;
while(onGoing){
key = gameDisplay.captureInput();
keynew = key - 48;
// if a mouse event occurred
if (key == -1) {
// record the location of the mouse event
cardX = gameDisplay.getMouseEventX();
cardY = gameDisplay.getMouseEventY();
//Start game
if((cardX >= 50) && (cardX <= 68) && (cardY >= 28) && (cardY <= 34)){
runT1(game);
}else if((cardX >= 87) && (cardX <= 105) && (cardY >= 35) && (cardY <= 40)){
exit(0);
}
}
}
return 0;
}
void runT1(GameObject game){
T1 t1;
t1.runGame(&game);
}
void runT2(GameObject game) {
T2Poker t2;
t2.runGame(&game);
}
void runD1(GameObject game) {
Poker poker;
poker.runGame(&game);
}
bool inHitBox(int cardX, int cardY, int x1, int x2, int y1, int y2){
return (cardX >= x1) && (cardX <= x2) && (cardY >= y1) && (cardY <= y2);
}
<commit_msg>Shit works even mo<commit_after>#include "display.h"
#include "Timer.h"
#include "T1/T1.h"
#include "T2/T2Poker.h"
#include "T2/T2Display.h"
#include "GameObject.h"
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sstream>
#include "D1/Poker.h"
using namespace std;
void initScreen(display gameDisplay);
void runT1(GameObject game);
void runT2(GameObject game);
void runD1(GameObject game);
bool inHitBox(int cardX, int cardY, int x1, int x2, int y1, int y2);
T2Display T2GameDisplay; //global used in T2
GameObject game(500,0);
int main (void) {
//initial values
display gameDisplay;
int keynew = 0;
char key;
char key2;
bool onGoing = true;
int cardX, cardY;
stringstream messageString;
initScreen(gameDisplay);
while(onGoing){
key = gameDisplay.captureInput();
keynew = key - 48;
// if a mouse event occurred
if (key == -1) {
// record the location of the mouse event
cardX = gameDisplay.getMouseEventX();
cardY = gameDisplay.getMouseEventY();
//Start game
if(inHitBox(cardX,cardY,50,69,28,34)){
runT1(game);
}else if(inHitBox(cardX,cardY,69,87,28,34)){
runT2(game);
}else if(inHitBox(cardX,cardY,87,106,28,34)){
runD1(game);
}
else if((cardX >= 87) && (cardX <= 105) && (cardY >= 35) && (cardY <= 40)){
exit(0);
}
}
}
return 0;
}
void runT1(GameObject game){
T1 t1;
t1.runGame(&game);
}
void runT2(GameObject game) {
T2Poker t2;
t2.runGame(&game);
}
void runD1(GameObject game) {
Poker poker;
poker.runGame(&game);
}
bool inHitBox(int cardX, int cardY, int x1, int x2, int y1, int y2){
return (cardX >= x1) && (cardX <= x2) && (cardY >= y1) && (cardY <= y2);
}
void initScreen(display gameDisplay){
gameDisplay.drawBox(50, 28, 19, 6, 0); // Top Left
T1::setText("B11","Texas Hold'em 1");
gameDisplay.drawBox(69, 28, 18, 6, 0); // Top Middle
T1::setText("B21","Texas Hold'em 2");
gameDisplay.drawBox(87, 28, 19, 6, 0); // Top Right
T1::setText("B31","Five Card Draw");
}
<|endoftext|> |
<commit_before>856279a3-2d15-11e5-af21-0401358ea401<commit_msg>856279a4-2d15-11e5-af21-0401358ea401<commit_after>856279a4-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>#include "matrix.hpp"
#include "matrixview.hpp"
#include "alg.hpp"
#include <functional>
#include <cctype>
#include <locale>
#include <chrono>
static inline std::string <rim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
// trim from end
static inline std::string &rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
// trim from both ends
static inline std::string &trim(std::string &s) {
return ltrim(rtrim(s));
}
static inline bool do_file_exist (const std::string& name) {
if (FILE *file = fopen(name.c_str(), "r")) {
fclose(file);
return true;
} else
return false;
}
matrix<int> load_labels (const char *labelfile) {
vector< vector<int> > clusters;
ifstream file(labelfile);
string line;
size_t total_points = 0;
while (getline (file, line)) {
vector<int> indices;
line = trim(line);
stringstream ssin(line);
while (ssin.good()) {
int value;
ssin >> value;
indices.push_back(value);
total_points++;
}
clusters.push_back(indices);
}
matrix<int> labels(total_points, 1);
for (int i=0; i < clusters.size(); ++i)
for (int j=0; j < clusters[i].size(); ++j)
labels(clusters[i][j], 0) = i;
return labels;
}
matrix<float> compute_cluster_centers (matrix<float>& X, matrix<int>& y) {
assert(X.rows() == y.size());
int num_classes = y.max() + 1;
matrix<float> centers(num_classes, X.cols());
size_t m = X.rows();
for (int i=0; i < num_classes; ++i) {
centers.r_(i) = X.r_(y == i).mean(0);
}
return centers;
}
matrix<float>& compute_coefficients (matrix<float>& X, matrix<int>& y, matrix<float>& centers) {
int num_clusters = y.max() + 1;
matrix<float> avg_coeffs(1, num_clusters);
for (int i=0; i < num_clusters; ++i) {
cout << "Computing cluster #" << i << "..." << endl;
matrix<float> thiscluster = X.r_(y == i).detach();
matrix<float> inter_dist = cuda_pairwise_distance (thiscluster, centers);
matrix<size_t> sorted_ix = matrix_argsort(inter_dist, matrix<size_t>::SORT_ROWS);
matrix<size_t> nearest_clusters(1, thiscluster.rows());
for (int j=0; j < sorted_ix.rows(); ++j) {
if (sorted_ix(j,0) != i)
nearest_clusters(0,j) = sorted_ix(j, 0);
else
nearest_clusters(0,j) = sorted_ix(j, 1);
}
// group points having common nearest clusters and compute silhouette coefficients
vector<size_t> unique_nearest_clusters(nearest_clusters.ptr(), nearest_clusters.ptr() + nearest_clusters.size());
std::sort (unique_nearest_clusters.begin(), unique_nearest_clusters.end());
vector<size_t>::iterator it = std::unique (unique_nearest_clusters.begin(), unique_nearest_clusters.end());
unique_nearest_clusters.resize(std::distance(unique_nearest_clusters.begin(), it) );
int count = 0;
matrix<float> intra_dist = cuda_pairwise_distance (thiscluster);
matrix<float> coeffs(1, nearest_clusters.size());
for (size_t k=0; k < unique_nearest_clusters.size(); ++k) {
size_t next_cluster = unique_nearest_clusters[k];
matrix<float> subcluster = X.r_(y == (int)next_cluster).detach();
matrix<unsigned char> bool_ix = nearest_clusters == next_cluster;
matrix<float> vecs = thiscluster.r_(bool_ix).detach();
matrix<float> mean_b = cuda_pairwise_distance(vecs, subcluster).mean(1);
matrix<float> mean_a = intra_dist.r_(bool_ix).mean(1);
assert(mean_a.size() == mean_b.size() && vecs.rows() == mean_a.size());
for (int j=0; j < mean_a.rows(); ++j) {
float coeff = (mean_b(j,0) - mean_a(j,0))/std::max(mean_b(j,0), mean_a(j,0));
coeffs(0, count++) = coeff;
}
}
assert(count == coeffs.size());
avg_coeffs(0, i) = coeffs.mean();
cout << "coefficient #" << i << ": " << avg_coeffs(0,i) << endl;
}
return avg_coeffs;
}
void csil () {
cout << "Loading features..." << endl;
matrix<float> X = matrix<float>::load("../dat/20m_signatures_random.caffe.256", 18389592, 256);
X = X.c_(0, 16).detach();
cout << "...has dimension (" << X.rows() << ", " << X.cols() << ")" << endl;
cout << "Loading labels..." << endl;
matrix<int> y = load_labels("../dat/cluster_20msig_5kcenter_random.lst");
cout << "...has dimension (" << y.rows() << ", " << y.cols() << ")" << endl;
matrix<float> centers;
if (do_file_exist(string("../dat/centers.16"))) {
cout << "Loading centers..." << endl;
centers = matrix<float>::load("../dat/centers.16", 5000, 16);
} else {
cout << "Computing cluster centers..." << endl;
centers = compute_cluster_centers (X, y);
cout << "Saving cluster centers..." << endl;
matrix<float>::dump("../dat/centers.16", centers);
}
cout << "Computing Silhouette coefficients..." << endl;
matrix<float> coeffs = compute_coefficients (X, y, centers);
matrix<float>::dump("../dat/coeffs.bin", coeffs);
cout << "Dumped results to ../dat/coeffs.bin. DONE.";
}
// trim from start
void csil_sanitycheck () {
cout << "Loading features..." << endl;
matrix<float> X = matrix<float>::load("../dat/MNIST.dat", 10000, 5);
cout << "...has dimension (" << X.rows() << ", " << X.cols() << ")" << endl;
cout << "Loading labels..." << endl;
matrix<int> y = matrix<int>::load("../dat/MNIST.label", 10000, 1);
cout << "...has dimension (" << y.rows() << ", " << y.cols() << ")" << endl;
matrix<float> centers;
if (do_file_exist(string("../dat/centers.5"))) {
cout << "Loading centers..." << endl;
centers = matrix<float>::load("../dat/centers.5", 10, 5);
} else {
cout << "Computing cluster centers..." << endl;
centers = compute_cluster_centers (X, y);
cout << "Saving cluster centers..." << endl;
matrix<float>::dump("../dat/centers.16", centers);
}
cout << "Computing Silhouette coefficients..." << endl;
matrix<float> coeffs = compute_coefficients (X, y, centers);
matrix<float>::dump("../dat/coeffs.bin", coeffs);
cout << "Dumped results to ../dat/coeffs.bin. DONE.";
}
void gen_training_data () {
// load filenames
cout << "Loading image list..." << endl;
vector<string> images(18389592);
ifstream file("../dat/20m_signatures_random.lst");
assert(file.is_open());
string line;
while (getline (file, line)) {
images.push_back(trim(line));
}
cout << "..." << images.size() << " images were loaded" << endl;
matrix<float> coeffs = matrix<float>::load("../dat/coeffs.bin", 5000, 1);
matrix<size_t> top_clusters = matrix_argsort(coeffs);
view<size_t> top1k = top_clusters.c_(0,1000);
cout << "Top 1000 clusters with largest Silhouette coefficients chosen" << endl;
cout << "The largest Silhouette coefficient = " << coeffs(top1k(0,0), 0) << endl;
cout << "The smallest Silhouette coefficient = " << coeffs(top1k(matrix<size_t>::END,0), 0) << endl;
cout << "Loading labels..." << endl;
matrix<int> y = load_labels("../dat/cluster_20msig_5kcenter_random.lst");
ofstream train_file("../dat/train.txt", ios::out);
ofstream val_file("../dat/val.txt", ios::out);
for (size_t i=0; i < 1000; i++) {
cout << "Writing cluster " << i << "..." << endl;
view<int> suby = y.r_(y == (int)top1k(i,0));
assert(suby.size() > 1000);
for (size_t j=0; j < 100; ++j)
val_file << images[suby(j,0)] << " " << i << endl;
for (size_t j=100; j < suby.size(); ++j)
train_file << images[suby(j,0)] << " " << i << endl;
}
train_file.close();
val_file.close();
cout << ".DONE." << endl;
}
int main() {
gen_training_data();
return 0;
}
<commit_msg>change END to 999<commit_after>#include "matrix.hpp"
#include "matrixview.hpp"
#include "alg.hpp"
#include <functional>
#include <cctype>
#include <locale>
#include <chrono>
static inline std::string <rim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
// trim from end
static inline std::string &rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
// trim from both ends
static inline std::string &trim(std::string &s) {
return ltrim(rtrim(s));
}
static inline bool do_file_exist (const std::string& name) {
if (FILE *file = fopen(name.c_str(), "r")) {
fclose(file);
return true;
} else
return false;
}
matrix<int> load_labels (const char *labelfile) {
vector< vector<int> > clusters;
ifstream file(labelfile);
string line;
size_t total_points = 0;
while (getline (file, line)) {
vector<int> indices;
line = trim(line);
stringstream ssin(line);
while (ssin.good()) {
int value;
ssin >> value;
indices.push_back(value);
total_points++;
}
clusters.push_back(indices);
}
matrix<int> labels(total_points, 1);
for (int i=0; i < clusters.size(); ++i)
for (int j=0; j < clusters[i].size(); ++j)
labels(clusters[i][j], 0) = i;
return labels;
}
matrix<float> compute_cluster_centers (matrix<float>& X, matrix<int>& y) {
assert(X.rows() == y.size());
int num_classes = y.max() + 1;
matrix<float> centers(num_classes, X.cols());
size_t m = X.rows();
for (int i=0; i < num_classes; ++i) {
centers.r_(i) = X.r_(y == i).mean(0);
}
return centers;
}
matrix<float>& compute_coefficients (matrix<float>& X, matrix<int>& y, matrix<float>& centers) {
int num_clusters = y.max() + 1;
matrix<float> avg_coeffs(1, num_clusters);
for (int i=0; i < num_clusters; ++i) {
cout << "Computing cluster #" << i << "..." << endl;
matrix<float> thiscluster = X.r_(y == i).detach();
matrix<float> inter_dist = cuda_pairwise_distance (thiscluster, centers);
matrix<size_t> sorted_ix = matrix_argsort(inter_dist, matrix<size_t>::SORT_ROWS);
matrix<size_t> nearest_clusters(1, thiscluster.rows());
for (int j=0; j < sorted_ix.rows(); ++j) {
if (sorted_ix(j,0) != i)
nearest_clusters(0,j) = sorted_ix(j, 0);
else
nearest_clusters(0,j) = sorted_ix(j, 1);
}
// group points having common nearest clusters and compute silhouette coefficients
vector<size_t> unique_nearest_clusters(nearest_clusters.ptr(), nearest_clusters.ptr() + nearest_clusters.size());
std::sort (unique_nearest_clusters.begin(), unique_nearest_clusters.end());
vector<size_t>::iterator it = std::unique (unique_nearest_clusters.begin(), unique_nearest_clusters.end());
unique_nearest_clusters.resize(std::distance(unique_nearest_clusters.begin(), it) );
int count = 0;
matrix<float> intra_dist = cuda_pairwise_distance (thiscluster);
matrix<float> coeffs(1, nearest_clusters.size());
for (size_t k=0; k < unique_nearest_clusters.size(); ++k) {
size_t next_cluster = unique_nearest_clusters[k];
matrix<float> subcluster = X.r_(y == (int)next_cluster).detach();
matrix<unsigned char> bool_ix = nearest_clusters == next_cluster;
matrix<float> vecs = thiscluster.r_(bool_ix).detach();
matrix<float> mean_b = cuda_pairwise_distance(vecs, subcluster).mean(1);
matrix<float> mean_a = intra_dist.r_(bool_ix).mean(1);
assert(mean_a.size() == mean_b.size() && vecs.rows() == mean_a.size());
for (int j=0; j < mean_a.rows(); ++j) {
float coeff = (mean_b(j,0) - mean_a(j,0))/std::max(mean_b(j,0), mean_a(j,0));
coeffs(0, count++) = coeff;
}
}
assert(count == coeffs.size());
avg_coeffs(0, i) = coeffs.mean();
cout << "coefficient #" << i << ": " << avg_coeffs(0,i) << endl;
}
return avg_coeffs;
}
void csil () {
cout << "Loading features..." << endl;
matrix<float> X = matrix<float>::load("../dat/20m_signatures_random.caffe.256", 18389592, 256);
X = X.c_(0, 16).detach();
cout << "...has dimension (" << X.rows() << ", " << X.cols() << ")" << endl;
cout << "Loading labels..." << endl;
matrix<int> y = load_labels("../dat/cluster_20msig_5kcenter_random.lst");
cout << "...has dimension (" << y.rows() << ", " << y.cols() << ")" << endl;
matrix<float> centers;
if (do_file_exist(string("../dat/centers.16"))) {
cout << "Loading centers..." << endl;
centers = matrix<float>::load("../dat/centers.16", 5000, 16);
} else {
cout << "Computing cluster centers..." << endl;
centers = compute_cluster_centers (X, y);
cout << "Saving cluster centers..." << endl;
matrix<float>::dump("../dat/centers.16", centers);
}
cout << "Computing Silhouette coefficients..." << endl;
matrix<float> coeffs = compute_coefficients (X, y, centers);
matrix<float>::dump("../dat/coeffs.bin", coeffs);
cout << "Dumped results to ../dat/coeffs.bin. DONE.";
}
// trim from start
void csil_sanitycheck () {
cout << "Loading features..." << endl;
matrix<float> X = matrix<float>::load("../dat/MNIST.dat", 10000, 5);
cout << "...has dimension (" << X.rows() << ", " << X.cols() << ")" << endl;
cout << "Loading labels..." << endl;
matrix<int> y = matrix<int>::load("../dat/MNIST.label", 10000, 1);
cout << "...has dimension (" << y.rows() << ", " << y.cols() << ")" << endl;
matrix<float> centers;
if (do_file_exist(string("../dat/centers.5"))) {
cout << "Loading centers..." << endl;
centers = matrix<float>::load("../dat/centers.5", 10, 5);
} else {
cout << "Computing cluster centers..." << endl;
centers = compute_cluster_centers (X, y);
cout << "Saving cluster centers..." << endl;
matrix<float>::dump("../dat/centers.16", centers);
}
cout << "Computing Silhouette coefficients..." << endl;
matrix<float> coeffs = compute_coefficients (X, y, centers);
matrix<float>::dump("../dat/coeffs.bin", coeffs);
cout << "Dumped results to ../dat/coeffs.bin. DONE.";
}
void gen_training_data () {
// load filenames
cout << "Loading image list..." << endl;
vector<string> images;
ifstream file("../dat/20m_signatures_random.lst");
assert(file.is_open());
string line;
while (getline (file, line)) {
images.push_back(trim(line));
}
cout << "..." << images.size() << " images were loaded" << endl;
matrix<float> coeffs = matrix<float>::load("../dat/coeffs.bin", 5000, 1);
cout << coeffs.size() << " coefficients loaded" << endl;
matrix<size_t> top_clusters = matrix_argsort(coeffs);
view<size_t> top1k = top_clusters.c_(0,1000);
cout << "Top 1000 clusters with largest Silhouette coefficients chosen" << endl;
cout << "The largest Silhouette coefficient = " << coeffs(top1k(0,0), 0) << endl;
cout << "The smallest Silhouette coefficient = " << coeffs(top1k(999,0), 0) << endl;
cout << "Loading labels..." << endl;
matrix<int> y = load_labels("../dat/cluster_20msig_5kcenter_random.lst");
ofstream train_file("../dat/train.txt", ios::out);
ofstream val_file("../dat/val.txt", ios::out);
for (size_t i=0; i < 1000; i++) {
cout << "Writing cluster " << i << "..." << endl;
view<int> suby = y.r_(y == (int)top1k(i,0));
assert(suby.size() > 1000);
for (size_t j=0; j < 100; ++j)
val_file << images[suby(j,0)] << " " << i << endl;
for (size_t j=100; j < suby.size(); ++j)
train_file << images[suby(j,0)] << " " << i << endl;
}
train_file.close();
val_file.close();
cout << ".DONE." << endl;
}
int main() {
gen_training_data();
return 0;
}
<|endoftext|> |
<commit_before>5e589484-2d16-11e5-af21-0401358ea401<commit_msg>5e589485-2d16-11e5-af21-0401358ea401<commit_after>5e589485-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>1e20050a-2d3f-11e5-b028-c82a142b6f9b<commit_msg>1e913819-2d3f-11e5-b26e-c82a142b6f9b<commit_after>1e913819-2d3f-11e5-b26e-c82a142b6f9b<|endoftext|> |
<commit_before>c02b22b8-327f-11e5-a67c-9cf387a8033e<commit_msg>c0310f02-327f-11e5-b269-9cf387a8033e<commit_after>c0310f02-327f-11e5-b269-9cf387a8033e<|endoftext|> |
<commit_before>61d4e551-2e4f-11e5-b84f-28cfe91dbc4b<commit_msg>61dbeb99-2e4f-11e5-9bd1-28cfe91dbc4b<commit_after>61dbeb99-2e4f-11e5-9bd1-28cfe91dbc4b<|endoftext|> |
<commit_before>fca7e999-2e4e-11e5-b8fa-28cfe91dbc4b<commit_msg>fcae21d4-2e4e-11e5-a6ba-28cfe91dbc4b<commit_after>fcae21d4-2e4e-11e5-a6ba-28cfe91dbc4b<|endoftext|> |
<commit_before>819500de-ad58-11e7-8cfc-ac87a332f658<commit_msg>Bug fixes and performance improvements<commit_after>820f0911-ad58-11e7-a532-ac87a332f658<|endoftext|> |
<commit_before>#include <unistd.h>
#include <getopt.h>
#include <openssl/sha.h>
#include "SHA1.h"
#include "MD5ex.h"
#include "SHA256.h"
#include "SHA512ex.h"
#include "MD4ex.h"
using namespace std;
vector<unsigned char> StringToVector(unsigned char * str)
{
vector<unsigned char> ret;
for(unsigned int x = 0; x < strlen((char*)str); x++)
{
ret.push_back(str[x]);
}
return ret;
}
void DigestToRaw(string hash, unsigned char * raw)
{
transform(hash.begin(), hash.end(), hash.begin(), ::tolower);
string alpha("0123456789abcdef");
for(unsigned int x = 0; x < (hash.length() / 2); x++)
{
raw[x] = (unsigned char)((alpha.find(hash.at((x * 2))) << 4));
raw[x] |= (unsigned char)(alpha.find(hash.at((x * 2) + 1)));
}
}
vector<unsigned char> * GenerateRandomData()
{
vector<unsigned char> * ret = new vector<unsigned char>();
int length = rand() % 128;
for(int x = 0; x < length; x++)
{
ret->push_back((rand() % (126 - 32)) + 32);
}
return ret;
}
void TestExtender(Extender * sex)
{
//First generate a signature, with randomly generated data
vector<unsigned char> * vkey = GenerateRandomData();
vector<unsigned char> * vmessage = GenerateRandomData();
vector<unsigned char> * additionalData = GenerateRandomData();
unsigned char * firstSig;
unsigned char * secondSig;
sex->GenerateSignature(*vkey, *vmessage, &firstSig);
if(sex->ValidateSignature(*vkey, *vmessage, firstSig))
{
vector<unsigned char> * newData = sex->GenerateStretchedData(*vmessage, vkey->size(), firstSig, *additionalData, &secondSig);
if(sex->ValidateSignature(*vkey, *newData, secondSig))
{
cout << "\tTest passed." << endl;
delete vkey;
delete vmessage;
delete additionalData;
delete newData;
return;
}
else
{
cout << "\tGenerated data failed to be verified as correctly signed." << endl;
delete vkey;
delete vmessage;
delete additionalData;
delete newData;
return;
}
}
else
{
cout << "\tInitial signature check failed." << endl;
delete vkey;
delete vmessage;
delete additionalData;
return;
}
}
Extender * GetExtenderForHash(string sig)
{
if(sig.length() == 40)
{
return new SHA1ex();
}
else if(sig.length() == 64)
{
return new SHA256ex();
}
else if(sig.length() == 32)
{
return new MD5ex();
}
else if(sig.length() == 128)
{
return new SHA512ex();
}
return NULL;
}
void PrintHelp()
{
cout << "HashPump [-h help] [-t test] [-s signature] [-d data] [-a additional] [-k keylength]" << endl;
cout << " HashPump generates strings to exploit signatures vulnerable to the Hash Length Extension Attack." << endl;
cout << " -h --help Display this message." << endl;
cout << " -t --test Run tests to verify each algorithm is operating properly." << endl;
cout << " -s --signature The signature from known message." << endl;
cout << " -d --data The data from the known message." << endl;
cout << " -a --additional The information you would like to add to the known message." << endl;
cout << " -k --keylength The length in bytes of the key being used to sign the original message with." << endl;
cout << " Version 1.0 with MD5, SHA1, SHA256 and SHA512 support." << endl;
cout << " <Developed by bwall(@bwallHatesTwits)>" << endl;
}
int main(int argc, char ** argv)
{
string sig;
string data;
int keylength = 0;
string datatoadd;
Extender * sex = NULL;
bool run_tests = false;
while(1)
{
int option_index = 0;
static struct option long_options[] = {
{"test", no_argument, 0, 0},
{"signature", required_argument, 0, 0},
{"data", required_argument, 0, 0},
{"additional", required_argument, 0, 0},
{"keylength", required_argument, 0, 0},
{"help", no_argument, 0, 0},
{0, 0, 0, 0}
};
int c = getopt_long(argc, argv, "ts:d:a:k:h", long_options, &option_index);
if (c == -1)
break;
switch(c)
{
case 0:
switch(option_index)
{
case 0:
run_tests = true;
break;
case 1:
sig.assign(optarg);
sex = GetExtenderForHash(sig);
if(sex == NULL)
{
cout << "Unsupported signature size." << endl;
return 0;
}
break;
case 2:
data.assign(optarg);
break;
case 3:
datatoadd.assign(optarg);
break;
case 4:
keylength = atoi(optarg);
break;
case 5:
PrintHelp();
return 0;
}
break;
case 't':
run_tests = true;
break;
case 's':
sig.assign(optarg);
sex = GetExtenderForHash(sig);
if(sex == NULL)
{
cout << "Unsupported hash size." << endl;
return 0;
}
break;
case 'd':
data.assign(optarg);
break;
case 'a':
datatoadd.assign(optarg);
break;
case 'k':
keylength = atoi(optarg);
break;
case 'h':
PrintHelp();
return 0;
}
}
if(run_tests)
{
//Just a simple way to force tests
cout << "Testing SHA1" << endl;
TestExtender(new SHA1ex());
cout << "Testing SHA256" << endl;
TestExtender(new SHA256ex());
cout << "Testing SHA512" << endl;
TestExtender(new SHA512ex());
cout << "Testing MD5" << endl;
TestExtender(new MD5ex());
cout << "Testing MD4" << endl;
TestExtender(new MD4ex());
cout << "Testing concluded" << endl;
return 0;
}
if(sig.size() == 0)
{
cout << "Input Signature: ";
cin >> sig;
sex = GetExtenderForHash(sig);
if(sex == NULL)
{
cout << "Unsupported hash size." << endl;
return 0;
}
}
if(data.size() == 0)
{
cout << "Input Data: ";
cin >> data;
}
if(keylength == 0)
{
cout << "Input Key Length: ";
cin >> keylength;
}
if(datatoadd.size() == 0)
{
cout << "Input Data to Add: ";
cin >> datatoadd;
}
vector<unsigned char> vmessage = StringToVector((unsigned char*)data.c_str());
vector<unsigned char> vtoadd = StringToVector((unsigned char*)datatoadd.c_str());
unsigned char firstSig[128];
DigestToRaw(sig, firstSig);
unsigned char * secondSig;
vector<unsigned char> * secondMessage = sex->GenerateStretchedData(vmessage, keylength, firstSig, vtoadd, &secondSig);
for(unsigned int x = 0; x < sig.size()/2; x++)
{
printf("%02x", secondSig[x]);
}
cout << endl;
for(unsigned int x = 0; x < secondMessage->size(); x++)
{
unsigned char c = secondMessage->at(x);
if(c >= 32 && c <= 126)
{
cout << c;
}
else
{
printf("\\x%02x", c);
}
}
delete secondMessage;
cout << endl;
return 0;
}
<commit_msg>Respect semantic versioning<commit_after>#include <unistd.h>
#include <getopt.h>
#include <openssl/sha.h>
#include "SHA1.h"
#include "MD5ex.h"
#include "SHA256.h"
#include "SHA512ex.h"
#include "MD4ex.h"
using namespace std;
vector<unsigned char> StringToVector(unsigned char * str)
{
vector<unsigned char> ret;
for(unsigned int x = 0; x < strlen((char*)str); x++)
{
ret.push_back(str[x]);
}
return ret;
}
void DigestToRaw(string hash, unsigned char * raw)
{
transform(hash.begin(), hash.end(), hash.begin(), ::tolower);
string alpha("0123456789abcdef");
for(unsigned int x = 0; x < (hash.length() / 2); x++)
{
raw[x] = (unsigned char)((alpha.find(hash.at((x * 2))) << 4));
raw[x] |= (unsigned char)(alpha.find(hash.at((x * 2) + 1)));
}
}
vector<unsigned char> * GenerateRandomData()
{
vector<unsigned char> * ret = new vector<unsigned char>();
int length = rand() % 128;
for(int x = 0; x < length; x++)
{
ret->push_back((rand() % (126 - 32)) + 32);
}
return ret;
}
void TestExtender(Extender * sex)
{
//First generate a signature, with randomly generated data
vector<unsigned char> * vkey = GenerateRandomData();
vector<unsigned char> * vmessage = GenerateRandomData();
vector<unsigned char> * additionalData = GenerateRandomData();
unsigned char * firstSig;
unsigned char * secondSig;
sex->GenerateSignature(*vkey, *vmessage, &firstSig);
if(sex->ValidateSignature(*vkey, *vmessage, firstSig))
{
vector<unsigned char> * newData = sex->GenerateStretchedData(*vmessage, vkey->size(), firstSig, *additionalData, &secondSig);
if(sex->ValidateSignature(*vkey, *newData, secondSig))
{
cout << "\tTest passed." << endl;
delete vkey;
delete vmessage;
delete additionalData;
delete newData;
return;
}
else
{
cout << "\tGenerated data failed to be verified as correctly signed." << endl;
delete vkey;
delete vmessage;
delete additionalData;
delete newData;
return;
}
}
else
{
cout << "\tInitial signature check failed." << endl;
delete vkey;
delete vmessage;
delete additionalData;
return;
}
}
Extender * GetExtenderForHash(string sig)
{
if(sig.length() == 40)
{
return new SHA1ex();
}
else if(sig.length() == 64)
{
return new SHA256ex();
}
else if(sig.length() == 32)
{
return new MD5ex();
}
else if(sig.length() == 128)
{
return new SHA512ex();
}
return NULL;
}
void PrintHelp()
{
cout << "HashPump [-h help] [-t test] [-s signature] [-d data] [-a additional] [-k keylength]" << endl;
cout << " HashPump generates strings to exploit signatures vulnerable to the Hash Length Extension Attack." << endl;
cout << " -h --help Display this message." << endl;
cout << " -t --test Run tests to verify each algorithm is operating properly." << endl;
cout << " -s --signature The signature from known message." << endl;
cout << " -d --data The data from the known message." << endl;
cout << " -a --additional The information you would like to add to the known message." << endl;
cout << " -k --keylength The length in bytes of the key being used to sign the original message with." << endl;
cout << " Version 1.0.0 with MD5, SHA1, SHA256 and SHA512 support." << endl;
cout << " <Developed by bwall(@bwallHatesTwits)>" << endl;
}
int main(int argc, char ** argv)
{
string sig;
string data;
int keylength = 0;
string datatoadd;
Extender * sex = NULL;
bool run_tests = false;
while(1)
{
int option_index = 0;
static struct option long_options[] = {
{"test", no_argument, 0, 0},
{"signature", required_argument, 0, 0},
{"data", required_argument, 0, 0},
{"additional", required_argument, 0, 0},
{"keylength", required_argument, 0, 0},
{"help", no_argument, 0, 0},
{0, 0, 0, 0}
};
int c = getopt_long(argc, argv, "ts:d:a:k:h", long_options, &option_index);
if (c == -1)
break;
switch(c)
{
case 0:
switch(option_index)
{
case 0:
run_tests = true;
break;
case 1:
sig.assign(optarg);
sex = GetExtenderForHash(sig);
if(sex == NULL)
{
cout << "Unsupported signature size." << endl;
return 0;
}
break;
case 2:
data.assign(optarg);
break;
case 3:
datatoadd.assign(optarg);
break;
case 4:
keylength = atoi(optarg);
break;
case 5:
PrintHelp();
return 0;
}
break;
case 't':
run_tests = true;
break;
case 's':
sig.assign(optarg);
sex = GetExtenderForHash(sig);
if(sex == NULL)
{
cout << "Unsupported hash size." << endl;
return 0;
}
break;
case 'd':
data.assign(optarg);
break;
case 'a':
datatoadd.assign(optarg);
break;
case 'k':
keylength = atoi(optarg);
break;
case 'h':
PrintHelp();
return 0;
}
}
if(run_tests)
{
//Just a simple way to force tests
cout << "Testing SHA1" << endl;
TestExtender(new SHA1ex());
cout << "Testing SHA256" << endl;
TestExtender(new SHA256ex());
cout << "Testing SHA512" << endl;
TestExtender(new SHA512ex());
cout << "Testing MD5" << endl;
TestExtender(new MD5ex());
cout << "Testing MD4" << endl;
TestExtender(new MD4ex());
cout << "Testing concluded" << endl;
return 0;
}
if(sig.size() == 0)
{
cout << "Input Signature: ";
cin >> sig;
sex = GetExtenderForHash(sig);
if(sex == NULL)
{
cout << "Unsupported hash size." << endl;
return 0;
}
}
if(data.size() == 0)
{
cout << "Input Data: ";
cin >> data;
}
if(keylength == 0)
{
cout << "Input Key Length: ";
cin >> keylength;
}
if(datatoadd.size() == 0)
{
cout << "Input Data to Add: ";
cin >> datatoadd;
}
vector<unsigned char> vmessage = StringToVector((unsigned char*)data.c_str());
vector<unsigned char> vtoadd = StringToVector((unsigned char*)datatoadd.c_str());
unsigned char firstSig[128];
DigestToRaw(sig, firstSig);
unsigned char * secondSig;
vector<unsigned char> * secondMessage = sex->GenerateStretchedData(vmessage, keylength, firstSig, vtoadd, &secondSig);
for(unsigned int x = 0; x < sig.size()/2; x++)
{
printf("%02x", secondSig[x]);
}
cout << endl;
for(unsigned int x = 0; x < secondMessage->size(); x++)
{
unsigned char c = secondMessage->at(x);
if(c >= 32 && c <= 126)
{
cout << c;
}
else
{
printf("\\x%02x", c);
}
}
delete secondMessage;
cout << endl;
return 0;
}
<|endoftext|> |
<commit_before>5297766e-5216-11e5-9a39-6c40088e03e4<commit_msg>529e153e-5216-11e5-84d0-6c40088e03e4<commit_after>529e153e-5216-11e5-84d0-6c40088e03e4<|endoftext|> |
<commit_before>1b2264a4-2f67-11e5-9d2e-6c40088e03e4<commit_msg>1b2a69ec-2f67-11e5-93bc-6c40088e03e4<commit_after>1b2a69ec-2f67-11e5-93bc-6c40088e03e4<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016, 2017, Yutaka Tsutano
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#include <iostream>
#include <vector>
#include <string>
#include "jitana/util/axml_parser.hpp"
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
void process_xml(std::ostream& os, const std::string& filename)
{
boost::property_tree::ptree pt;
try {
// First, try to read as a binary XML file.
jitana::read_axml(filename, pt);
}
catch (const jitana::axml_parser_magic_mismatched& e) {
// Binary parser has faied: try to read it as a normal XML file.
boost::property_tree::read_xml(filename, pt);
}
boost::property_tree::xml_writer_settings<std::string> settings(' ', 2);
write_xml(os, pt, settings);
}
int main(int argc, char** argv)
{
namespace po = boost::program_options;
// Declare command line argument options.
po::options_description desc("Allowed options");
desc.add_options()("help", "Display available options")(
"input-file,i", po::value<std::string>(), "Input file")(
"output-file,o", po::value<std::string>(), "Output file");
po::positional_options_description p;
p.add("input-file", -1);
try {
// Process the command line arguments.
po::variables_map vmap;
po::store(po::command_line_parser(argc, argv)
.options(desc)
.positional(p)
.run(),
vmap);
po::notify(vmap);
if (vmap.count("help") || !vmap.count("input-file")) {
// Print help and quit.
std::cout << "Usage: axmldec [options] <input_file>\n";
std::cout << desc << "\n";
return 0;
}
if (vmap.count("input-file")) {
// Construct the output stream.
std::ostream* os = &std::cout;
std::ofstream ofs;
if (vmap.count("output-file")) {
ofs.open(vmap["output-file"].as<std::string>());
os = &ofs;
}
// Process the file.
process_xml(*os, vmap["input-file"].as<std::string>());
}
}
catch (std::exception& e) {
std::cerr << "error: " << e.what() << "\n";
return 1;
}
}
<commit_msg>Add comments<commit_after>/*
* Copyright (c) 2016, 2017, Yutaka Tsutano
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "jitana/util/axml_parser.hpp"
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/program_options.hpp>
void process_xml(std::ostream& os, const std::string& filename)
{
// Construct a property tree from the input XML file.
boost::property_tree::ptree pt;
try {
// First, try to read as a binary XML file.
jitana::read_axml(filename, pt);
}
catch (const jitana::axml_parser_magic_mismatched& e) {
// Binary parser has faied: try to read it as a normal XML file.
boost::property_tree::read_xml(filename, pt);
}
// Write the ptree to the output.
boost::property_tree::xml_writer_settings<std::string> settings(' ', 2);
boost::property_tree::write_xml(os, pt, settings);
}
int main(int argc, char** argv)
{
namespace po = boost::program_options;
// Declare command line argument options.
po::options_description desc("Allowed options");
desc.add_options()("help", "Display available options")(
"input-file,i", po::value<std::string>(), "Input file")(
"output-file,o", po::value<std::string>(), "Output file");
po::positional_options_description p;
p.add("input-file", -1);
try {
// Process the command line arguments.
po::variables_map vmap;
po::store(po::command_line_parser(argc, argv)
.options(desc)
.positional(p)
.run(),
vmap);
po::notify(vmap);
if (vmap.count("help") || !vmap.count("input-file")) {
// Print help and quit.
std::cout << "Usage: axmldec [options] <input_file>\n";
std::cout << desc << "\n";
return 0;
}
if (vmap.count("input-file")) {
// Construct the output stream.
std::ostream* os = &std::cout;
std::ofstream ofs;
if (vmap.count("output-file")) {
ofs.open(vmap["output-file"].as<std::string>());
os = &ofs;
}
// Process the file.
process_xml(*os, vmap["input-file"].as<std::string>());
}
}
catch (std::exception& e) {
std::cerr << "error: " << e.what() << "\n";
return 1;
}
}
<|endoftext|> |
<commit_before>88d28307-2e4f-11e5-9efe-28cfe91dbc4b<commit_msg>88d81ad1-2e4f-11e5-b3b0-28cfe91dbc4b<commit_after>88d81ad1-2e4f-11e5-b3b0-28cfe91dbc4b<|endoftext|> |
<commit_before>67a25776-2fa5-11e5-be21-00012e3d3f12<commit_msg>67a47a54-2fa5-11e5-b624-00012e3d3f12<commit_after>67a47a54-2fa5-11e5-b624-00012e3d3f12<|endoftext|> |
<commit_before>25f976e1-2d3e-11e5-bf37-c82a142b6f9b<commit_msg>2653fdc2-2d3e-11e5-872f-c82a142b6f9b<commit_after>2653fdc2-2d3e-11e5-872f-c82a142b6f9b<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <forward_list>
#include <unordered_map>
#include <stack>
using namespace std;
/**
* @brief The Language class
* Base of all supported language
* In order to support certain language into the system, one has to
* provide:
* - the basic names for basic number from 0 to 9
* e.g zero, one, two, three..
*
* - list of unit number for each 3 digits.
* e.g thousand, million, billion, ..
* note: must be started from thousand-equivalent
*
* - replacements dictionary.
* each language has its own rule and there are always exceptions to
* that rule.
* for example: obeying the rule, one would spell 12 as 'twoteen'.
* using exception, 12 then becomes 'twelve'.
*
*/
class Language {
public:
Language(){}
virtual vector<string> base() = 0;
virtual vector<string> units() = 0;
virtual unordered_map<string, string> replacements() = 0;
};
/**
* @brief The Eng class
* Example implementation of English language
*/
class English: public Language {
public:
English() : Language()
{}
vector<string> base() {
return _base;
}
vector<string> units() {
return _units;
}
unordered_map<string, string> replacements() {
return _replacements;
}
const string O = "teen";
const string OO = "ty";
const string OOO = "hundred";
private:
// basic names of numbers
vector<string> _base { "zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine" };
// units of numbers
vector<string> _units { "", "thousand", "million", "billion" };
// also known as convention
unordered_map<string, string> _replacements {
// teens
{"teen","ten"},
{"oneteen","eleven"},
{"twoteen", "twelve"},
{"threeteen", "thirteen"},
{"fiveteen", "fifteen"},
// tens
{"onety", "ten"},
{"twoty", "twenty"},
{"threety", "thirty"},
{"fourty", "forty"},
{"fivety", "fifty"},
{"eightty", "eighty"}
};
};
/**
* @brief The Bahasa class
* Example implementation of Bahasa Indonesia
*/
class Bahasa: public Language {
public:
Bahasa() : Language() {}
vector<string> base() {
return _base;
}
vector<string> units() {
return _units;
}
unordered_map<string, string> replacements() {
return _replacements;
}
const string O = "belas";
const string OO = "puluh";
const string OOO = "ratus";
private:
// basic names of numbers
vector<string> _base { "nol", "satu", "dua", "tiga", "empat",
"lima", "enam", "tujuh", "delapan", "sembilan" };
// units of numbers
vector<string> _units { "", "ribu", "juta", "milyar" };
// also known as convention
unordered_map<string, string> _replacements {
{" belas","sepuluh"},
{"satu belas","sebelas"},
{"satu ratus", "seratus"},
{"satu ribu", "seribu"},
};
};
/**
* @brief The Number class
*
* Base of translatable Number class
*
* Given an integer ranged from 0 - 999, it should be able
* to translate the integer into it textual form.
*
* This is virtual class, thus it has to be subclassed,
* and subclass has to override translate() method
* to support the language that the number will be translated into.
*
*
*/
class Number {
public:
explicit Number() {
this->value = 0;
}
explicit Number(const int integer) {
this->value = integer;
}
virtual string translate() = 0;
virtual Language* lang() = 0;
void setValue(const int value) {
this->value = value;
}
void revise(string &probablyWrong) {
try {
probablyWrong = lang()->replacements().at(probablyWrong);
}
catch (out_of_range) {}
}
protected:
int value;
};
/**
* @brief The EngNumber class
* A Number which translate its value into English word.
*/
class EnglishNumber : public Number {
public:
explicit EnglishNumber() : Number()
{}
explicit EnglishNumber(const int integer) :
Number(integer) {}
string translate() {
if ( value < 100 ) {
return dealWithTens(value);
}
else if ( value < 1000 ) {
return dealWithHundreds(value);
}
else {
return "unknown";
}
}
Language* lang() {
return &language;
}
// utilities
private:
string toBase(const int value) {
return language.base().at(value);
}
string toTeen(const int value) {
int lastDigit = value % 10;
// don't spell zero
string output = "";
if ( lastDigit > 0 ) {
output = toBase(lastDigit);
}
output += language.O;
revise(output);
return output;
}
string toTens(int value) {
int firstDigit, lastDigit;
// first digit
firstDigit = value / 10;
string output = toBase(firstDigit) + language.OO;
revise(output);
// last digit
lastDigit = value % 10;
string lastDigitSpell = "";
if ( lastDigit > 0 ) {
lastDigitSpell = toBase(lastDigit);
}
return output + ( lastDigitSpell == "" ? "" : "-" + lastDigitSpell );
}
string dealWithTens(int num) {
if ( num == 00 ) {
return "";
}
else if ( num < 10 ) {
return toBase(num);
}
else if ( num < 20 ) {
return toTeen(num);
}
else if ( num < 100 ) {
return toTens(num);
}
return "unknown";
}
string dealWithHundreds(int num) {
if ( num == 000 ) {
return "";
}
const int firstDigit = num / 100;
string output = toBase(firstDigit) + " " + language.OOO;
const int theLastTwo = num % 100;
string output2 = dealWithTens(theLastTwo);
return output + ( output2.empty() ? "" : " and " + output2 );
}
private:
English language = English();
};
/**
* @brief The BahasaNumber class
* A Number which translate its value into Bahasa.
*/
class BahasaNumber: public Number {
public:
explicit BahasaNumber() : Number() {}
explicit BahasaNumber(const int integer) :
Number(integer) {}
string translate() {
string output;
if ( value < 100 ) {
output = dealWithTens(value);
}
else if ( value < 1000 ) {
output = dealWithHundreds(value);
} else {
output = "unknown";
}
return output;
}
Language* lang() {
return &bahasa;
}
private:
string toBase(const int value) {
return bahasa.base().at(value);
}
string toTeen(const int value) {
int lastDigit = value % 10;
// don't spell zero
string output = "";
if ( lastDigit > 0 ) {
output = toBase(lastDigit);
}
output += " " + bahasa.O;
revise(output);
return output;
}
string toTens(int value) {
int firstDigit, lastDigit;
// first digit
firstDigit = value / 10;
string output = toBase(firstDigit) + " " + bahasa.OO;
revise(output);
// last digit
lastDigit = value % 10;
string lastDigitSpell = "";
if ( lastDigit > 0 ) {
lastDigitSpell = toBase(lastDigit);
}
output += ( lastDigitSpell == "" ? "" : " " + lastDigitSpell );
revise(output);
return output;
}
string dealWithTens(int num) {
if ( num == 00 ) {
return "";
}
else if ( num < 10 ) {
return toBase(num);
}
else if ( num < 20 ) {
return toTeen(num);
}
else if ( num < 100 ) {
return toTens(num);
}
return "unknown";
}
string dealWithHundreds(int num) {
const int firstDigit = num / 100;
string output = toBase(firstDigit) + " " + bahasa.OOO;
revise(output);
const int theLastTwo = num % 100;
string output2 = dealWithTens(theLastTwo);
output += ( output2.empty() ? "" : " " + output2 );
revise(output);
return output;
}
private:
Bahasa bahasa = Bahasa();
};
/**
* @brief The Speller class
* It splits the number into triples,
* turn each triple into Number object from which the textual form of particular number
* could be retreived,
* then form a complete textual form for each triple with their corresponding units respectively.
*
* usage:
* Create new instance of Speller with number to spell, as in:
* Speller speller("1123");
*
* The instance will be able to process() only if the number is valid
* i.e only contains digit character nothing else.
* the ability can be queried using ready() method.
*/
class Speller {
public:
enum SpellingLanguage {
EN=1, ID
};
public:
/**
* @brief Speller
* @param input
* @param language
* construct the Speller to spell 'input' in the given 'language'
*/
explicit Speller(const string input, const SpellingLanguage language) {
this->input = input;
this->language = language;
isAbleToWork = false;
this->validate();
}
/**
* @brief Speller
* @param input
* convenience constructor using EN by default
*/
explicit Speller(const string input) {
Speller(input, EN);
}
/**
* @brief ready
* @return
* Ask me prior to doing process()
* to make sure the work done on the right thing
*/
bool ready() {
return isAbleToWork;
}
/**
* @brief process
* @return
*
* order the Speller to do its hard work converting
* numbers into their textual form of their language
*
* don't forget to ask ready() before calling this function,
* for best result.
*
*/
string process(){
// make sure ready
if ( !ready() ) return "unable to proceed!";
// the final output
string textualForm;
// group the string by three chars each
vector<string> triples = group();
// setting the language to use
Number* number;
switch (language) {
case EN:
number = new EnglishNumber();
break;
case ID:
number = new BahasaNumber();
break;
default:
number = new EnglishNumber();
}
// shortcut for '0'
if ( input == "0" ) return number->lang()->base().at(0);
// create the stack of unit to use
for (unsigned int i=0; i<triples.size(); ++i) {
unitStack.push( number->lang()->units().at(i) );
}
// translate each triple
for (unsigned int i=0; i<triples.size(); ++i ) {
string triple = triples.at(i);
number->setValue( toNumber(triple) );
string translated = number->translate();
if ( !translated.empty() ) {
textualForm
.append( translated )
.append( unitStack.top().empty() ? "" : " " )
.append( unitStack.top() );
number->revise(textualForm);
textualForm.append( ", " );
}
unitStack.pop();
}
// remove the last ', '
int idx = textualForm.find_last_of(", ");
textualForm.replace(idx-1, 2, "");
// done
return textualForm;
}
/**
* @brief setLanguage
* @param language
* set the language to use
*/
void setLanguage(const SpellingLanguage language) {
this->language = language;
}
// utilities
private:
/**
* @brief validate
* check the input and update ready() status
*/
void validate() {
isAbleToWork = isValid() && input.length() < 13;
}
/**
* @brief isValid
* @return
*
* return true if input contains exactly digit characters only
* return false otherwise
*
*/
bool isValid(){
for (auto it = input.cbegin(); it!=input.cend(); ++it) {
char c = *it;
switch (c) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
break;
default:
return false;
}
}
return true;
}
/**
* @brief toNumber
* @param num
* @return
*
* convert num char to its integer equivalent
*/
int toNumber(const string num) {
if (isValid()) {
try {
return stoi(num);
} catch (out_of_range) {
return -1;
}
}
return -1;
}
/**
* @brief group
* @return
*
* take 3 char, group them and add them into triples
* triples: vector of triple
*/
vector<string> group() {
vector<string> triples;
unsigned int overhead = input.size()%3;
string prefix;
for (auto i=input.cbegin(); i!=input.cbegin()+overhead; ++i) {
prefix.push_back(*i);
}
if (!prefix.empty()) triples.push_back(prefix);
for ( auto x=overhead; x<input.length(); x+=3 ) {
string triple;
triple.push_back(input.at(x));
triple.push_back(input.at(x+1));
triple.push_back(input.at(x+2));
triples.push_back(triple);
}
return triples;
}
private:
/**
* @brief input
* string of digit char that will be translated
*/
string input;
/**
* @brief isAbleToWork
* mark of capability to translate
*/
bool isAbleToWork;
/**
* @brief unitStack
* collection of units of number in the language
*/
stack<string> unitStack;
SpellingLanguage language;
};
// =========================================================================
void printUsage() {
const string programName = program_invocation_short_name;
cout
<< "usage: " << programName << " [n]" << endl
<< "n: positive number from 0 to maximum of 999999999999" << endl
<< "example: " << programName << " 2300" << endl;
}
int main(int argc, char* argv[])
{
// check args
if ( argc == 2 ) {
string input = argv[1];
// bussiness
Speller robot(input, Speller::EN);
if ( robot.ready() ) {
string output = robot.process();
cout << output << endl;
} else {
cout << "invalid input!" << endl;
printUsage();
}
} else {
printUsage();
}
return 0;
}
<commit_msg>added replacement for 18<commit_after>#include <iostream>
#include <vector>
#include <forward_list>
#include <unordered_map>
#include <stack>
using namespace std;
/**
* @brief The Language class
* Base of all supported language
* In order to support certain language into the system, one has to
* provide:
* - the basic names for basic number from 0 to 9
* e.g zero, one, two, three..
*
* - list of unit number for each 3 digits.
* e.g thousand, million, billion, ..
* note: must be started from thousand-equivalent
*
* - replacements dictionary.
* each language has its own rule and there are always exceptions to
* that rule.
* for example: obeying the rule, one would spell 12 as 'twoteen'.
* using exception, 12 then becomes 'twelve'.
*
*/
class Language {
public:
Language(){}
virtual vector<string> base() = 0;
virtual vector<string> units() = 0;
virtual unordered_map<string, string> replacements() = 0;
};
/**
* @brief The Eng class
* Example implementation of English language
*/
class English: public Language {
public:
English() : Language()
{}
vector<string> base() {
return _base;
}
vector<string> units() {
return _units;
}
unordered_map<string, string> replacements() {
return _replacements;
}
const string O = "teen";
const string OO = "ty";
const string OOO = "hundred";
private:
// basic names of numbers
vector<string> _base { "zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine" };
// units of numbers
vector<string> _units { "", "thousand", "million", "billion" };
// also known as convention
unordered_map<string, string> _replacements {
// teens
{"teen","ten"},
{"oneteen","eleven"},
{"twoteen", "twelve"},
{"threeteen", "thirteen"},
{"fiveteen", "fifteen"},
{"eightteen", "eighteen"},
// tens
{"onety", "ten"},
{"twoty", "twenty"},
{"threety", "thirty"},
{"fourty", "forty"},
{"fivety", "fifty"},
{"eightty", "eighty"}
};
};
/**
* @brief The Bahasa class
* Example implementation of Bahasa Indonesia
*/
class Bahasa: public Language {
public:
Bahasa() : Language() {}
vector<string> base() {
return _base;
}
vector<string> units() {
return _units;
}
unordered_map<string, string> replacements() {
return _replacements;
}
const string O = "belas";
const string OO = "puluh";
const string OOO = "ratus";
private:
// basic names of numbers
vector<string> _base { "nol", "satu", "dua", "tiga", "empat",
"lima", "enam", "tujuh", "delapan", "sembilan" };
// units of numbers
vector<string> _units { "", "ribu", "juta", "milyar" };
// also known as convention
unordered_map<string, string> _replacements {
{" belas","sepuluh"},
{"satu belas","sebelas"},
{"satu ratus", "seratus"},
{"satu ribu", "seribu"},
};
};
/**
* @brief The Number class
*
* Base of translatable Number class
*
* Given an integer ranged from 0 - 999, it should be able
* to translate the integer into it textual form.
*
* This is virtual class, thus it has to be subclassed,
* and subclass has to override translate() method
* to support the language that the number will be translated into.
*
*
*/
class Number {
public:
explicit Number() {
this->value = 0;
}
explicit Number(const int integer) {
this->value = integer;
}
virtual string translate() = 0;
virtual Language* lang() = 0;
void setValue(const int value) {
this->value = value;
}
void revise(string &probablyWrong) {
try {
probablyWrong = lang()->replacements().at(probablyWrong);
}
catch (out_of_range) {}
}
protected:
int value;
};
/**
* @brief The EngNumber class
* A Number which translate its value into English word.
*/
class EnglishNumber : public Number {
public:
explicit EnglishNumber() : Number()
{}
explicit EnglishNumber(const int integer) :
Number(integer) {}
string translate() {
if ( value < 100 ) {
return dealWithTens(value);
}
else if ( value < 1000 ) {
return dealWithHundreds(value);
}
else {
return "unknown";
}
}
Language* lang() {
return &language;
}
// utilities
private:
string toBase(const int value) {
return language.base().at(value);
}
string toTeen(const int value) {
int lastDigit = value % 10;
// don't spell zero
string output = "";
if ( lastDigit > 0 ) {
output = toBase(lastDigit);
}
output += language.O;
revise(output);
return output;
}
string toTens(int value) {
int firstDigit, lastDigit;
// first digit
firstDigit = value / 10;
string output = toBase(firstDigit) + language.OO;
revise(output);
// last digit
lastDigit = value % 10;
string lastDigitSpell = "";
if ( lastDigit > 0 ) {
lastDigitSpell = toBase(lastDigit);
}
return output + ( lastDigitSpell == "" ? "" : "-" + lastDigitSpell );
}
string dealWithTens(int num) {
if ( num == 00 ) {
return "";
}
else if ( num < 10 ) {
return toBase(num);
}
else if ( num < 20 ) {
return toTeen(num);
}
else if ( num < 100 ) {
return toTens(num);
}
return "unknown";
}
string dealWithHundreds(int num) {
if ( num == 000 ) {
return "";
}
const int firstDigit = num / 100;
string output = toBase(firstDigit) + " " + language.OOO;
const int theLastTwo = num % 100;
string output2 = dealWithTens(theLastTwo);
return output + ( output2.empty() ? "" : " and " + output2 );
}
private:
English language = English();
};
/**
* @brief The BahasaNumber class
* A Number which translate its value into Bahasa.
*/
class BahasaNumber: public Number {
public:
explicit BahasaNumber() : Number() {}
explicit BahasaNumber(const int integer) :
Number(integer) {}
string translate() {
string output;
if ( value < 100 ) {
output = dealWithTens(value);
}
else if ( value < 1000 ) {
output = dealWithHundreds(value);
} else {
output = "unknown";
}
return output;
}
Language* lang() {
return &bahasa;
}
private:
string toBase(const int value) {
return bahasa.base().at(value);
}
string toTeen(const int value) {
int lastDigit = value % 10;
// don't spell zero
string output = "";
if ( lastDigit > 0 ) {
output = toBase(lastDigit);
}
output += " " + bahasa.O;
revise(output);
return output;
}
string toTens(int value) {
int firstDigit, lastDigit;
// first digit
firstDigit = value / 10;
string output = toBase(firstDigit) + " " + bahasa.OO;
revise(output);
// last digit
lastDigit = value % 10;
string lastDigitSpell = "";
if ( lastDigit > 0 ) {
lastDigitSpell = toBase(lastDigit);
}
output += ( lastDigitSpell == "" ? "" : " " + lastDigitSpell );
revise(output);
return output;
}
string dealWithTens(int num) {
if ( num == 00 ) {
return "";
}
else if ( num < 10 ) {
return toBase(num);
}
else if ( num < 20 ) {
return toTeen(num);
}
else if ( num < 100 ) {
return toTens(num);
}
return "unknown";
}
string dealWithHundreds(int num) {
const int firstDigit = num / 100;
string output = toBase(firstDigit) + " " + bahasa.OOO;
revise(output);
const int theLastTwo = num % 100;
string output2 = dealWithTens(theLastTwo);
output += ( output2.empty() ? "" : " " + output2 );
revise(output);
return output;
}
private:
Bahasa bahasa = Bahasa();
};
/**
* @brief The Speller class
* It splits the number into triples,
* turn each triple into Number object from which the textual form of particular number
* could be retreived,
* then form a complete textual form for each triple with their corresponding units respectively.
*
* usage:
* Create new instance of Speller with number to spell, as in:
* Speller speller("1123");
*
* The instance will be able to process() only if the number is valid
* i.e only contains digit character nothing else.
* the ability can be queried using ready() method.
*/
class Speller {
public:
enum SpellingLanguage {
EN=1, ID
};
public:
/**
* @brief Speller
* @param input
* @param language
* construct the Speller to spell 'input' in the given 'language'
*/
explicit Speller(const string input, const SpellingLanguage language) {
this->input = input;
this->language = language;
isAbleToWork = false;
this->validate();
}
/**
* @brief Speller
* @param input
* convenience constructor using EN by default
*/
explicit Speller(const string input) {
Speller(input, EN);
}
/**
* @brief ready
* @return
* Ask me prior to doing process()
* to make sure the work done on the right thing
*/
bool ready() {
return isAbleToWork;
}
/**
* @brief process
* @return
*
* order the Speller to do its hard work converting
* numbers into their textual form of their language
*
* don't forget to ask ready() before calling this function,
* for best result.
*
*/
string process(){
// make sure ready
if ( !ready() ) return "unable to proceed!";
// the final output
string textualForm;
// group the string by three chars each
vector<string> triples = group();
// setting the language to use
Number* number;
switch (language) {
case EN:
number = new EnglishNumber();
break;
case ID:
number = new BahasaNumber();
break;
default:
number = new EnglishNumber();
}
// shortcut for '0'
if ( input == "0" ) return number->lang()->base().at(0);
// create the stack of unit to use
for (unsigned int i=0; i<triples.size(); ++i) {
unitStack.push( number->lang()->units().at(i) );
}
// translate each triple
for (unsigned int i=0; i<triples.size(); ++i ) {
string triple = triples.at(i);
number->setValue( toNumber(triple) );
string translated = number->translate();
if ( !translated.empty() ) {
textualForm
.append( translated )
.append( unitStack.top().empty() ? "" : " " )
.append( unitStack.top() );
number->revise(textualForm);
textualForm.append( ", " );
}
unitStack.pop();
}
// remove the last ', '
int idx = textualForm.find_last_of(", ");
textualForm.replace(idx-1, 2, "");
// done
return textualForm;
}
/**
* @brief setLanguage
* @param language
* set the language to use
*/
void setLanguage(const SpellingLanguage language) {
this->language = language;
}
// utilities
private:
/**
* @brief validate
* check the input and update ready() status
*/
void validate() {
isAbleToWork = isValid() && input.length() < 13;
}
/**
* @brief isValid
* @return
*
* return true if input contains exactly digit characters only
* return false otherwise
*
*/
bool isValid(){
for (auto it = input.cbegin(); it!=input.cend(); ++it) {
char c = *it;
switch (c) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
break;
default:
return false;
}
}
return true;
}
/**
* @brief toNumber
* @param num
* @return
*
* convert num char to its integer equivalent
*/
int toNumber(const string num) {
if (isValid()) {
try {
return stoi(num);
} catch (out_of_range) {
return -1;
}
}
return -1;
}
/**
* @brief group
* @return
*
* take 3 char, group them and add them into triples
* triples: vector of triple
*/
vector<string> group() {
vector<string> triples;
unsigned int overhead = input.size()%3;
string prefix;
for (auto i=input.cbegin(); i!=input.cbegin()+overhead; ++i) {
prefix.push_back(*i);
}
if (!prefix.empty()) triples.push_back(prefix);
for ( auto x=overhead; x<input.length(); x+=3 ) {
string triple;
triple.push_back(input.at(x));
triple.push_back(input.at(x+1));
triple.push_back(input.at(x+2));
triples.push_back(triple);
}
return triples;
}
private:
/**
* @brief input
* string of digit char that will be translated
*/
string input;
/**
* @brief isAbleToWork
* mark of capability to translate
*/
bool isAbleToWork;
/**
* @brief unitStack
* collection of units of number in the language
*/
stack<string> unitStack;
SpellingLanguage language;
};
// =========================================================================
void printUsage() {
const string programName = program_invocation_short_name;
cout
<< "usage: " << programName << " [n]" << endl
<< "n: positive number from 0 to maximum of 999999999999" << endl
<< "example: " << programName << " 2300" << endl;
}
int main(int argc, char* argv[])
{
// check args
if ( argc == 2 ) {
string input = argv[1];
// bussiness
Speller robot(input, Speller::EN);
if ( robot.ready() ) {
string output = robot.process();
cout << output << endl;
} else {
cout << "invalid input!" << endl;
printUsage();
}
} else {
printUsage();
}
return 0;
}
<|endoftext|> |
<commit_before>92323b4f-2d14-11e5-af21-0401358ea401<commit_msg>92323b50-2d14-11e5-af21-0401358ea401<commit_after>92323b50-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>a3256ce6-327f-11e5-83fe-9cf387a8033e<commit_msg>a32b6f38-327f-11e5-8d21-9cf387a8033e<commit_after>a32b6f38-327f-11e5-8d21-9cf387a8033e<|endoftext|> |
<commit_before>9a1079a3-4b02-11e5-9083-28cfe9171a43<commit_msg>Adding stuff<commit_after>9a1f8dab-4b02-11e5-a30a-28cfe9171a43<|endoftext|> |
<commit_before>5e589412-2d16-11e5-af21-0401358ea401<commit_msg>5e589413-2d16-11e5-af21-0401358ea401<commit_after>5e589413-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>#include "MatrixHe.cpp"
#include <QDebug>
#include<stdio.h>
int main()
{
MatrixHe matriz;
matriz.create(3,3);
matriz.setElementAt(0,0,1);
matriz.setElementAt(0,1,2);
matriz.setElementAt(0,2,5);
matriz.setElementAt(1,0,0);
matriz.setElementAt(1,1,0);
matriz.setElementAt(1,2,3);
matriz.setElementAt(2,0,-1);
matriz.setElementAt(2,1,0);
matriz.setElementAt(2,2,-2);
qDebug() << "matriz.elementAt(0,0)="<< matriz.elementAt(0,0);
qDebug() << matriz.toString();
qDebug() <<"determinat:" << matriz.determinant();
qDebug() <<"transpose" << matriz.transpose()->toString();
matriz.multiplyBy(2);
qDebug() << "multiplyBy(2)\n"<<matriz.toString();
matriz.sub(matriz);
qDebug()<<"matriz.sub(matriz)" << matriz.toString();
}
<commit_msg>Delete main.cpp<commit_after><|endoftext|> |
<commit_before>ec8dc3d1-2d3c-11e5-875a-c82a142b6f9b<commit_msg>ecffe51e-2d3c-11e5-ba7f-c82a142b6f9b<commit_after>ecffe51e-2d3c-11e5-ba7f-c82a142b6f9b<|endoftext|> |
<commit_before>#include "ids.h"
#include <QtCore/QVariant>
#include <QtCore/QUuid>
using namespace qReal;
Id Id::loadFromString(QString const &string)
{
QStringList const path = string.split('/');
Q_ASSERT(path.count() > 0 && path.count() <= 5);
Q_ASSERT(path[0] == "qrm:");
Id result;
switch (path.count()) {
case 5: result.mId = path[4];
// Fall-thru
case 4: result.mElement = path[3];
// Fall-thru
case 3: result.mDiagram = path[2];
// Fall-thru
case 2: result.mEditor = path[1];
// Fall-thru
}
Q_ASSERT(string == result.toString());
Q_ASSERT(string == result.toUrl().toString());
return result;
}
Id Id::createElementId(QString const &editor, QString const &diagram, QString const &element)
{
return Id(editor, diagram, element, QUuid::createUuid().toString());
}
Id Id::rootId()
{
return Id("ROOT_ID", "ROOT_ID", "ROOT_ID", "ROOT_ID");
}
Id::Id(QString const &editor, QString const &diagram, QString const &element, QString const &id)
: mEditor(editor)
, mDiagram(diagram)
, mElement(element)
, mId(id)
{
Q_ASSERT(checkIntegrity());
}
Id::Id(Id const &base, QString const &additional)
: mEditor(base.mEditor)
, mDiagram(base.mDiagram)
, mElement(base.mElement)
, mId(base.mId)
{
unsigned const baseSize = base.idSize();
switch (baseSize) {
case 0:
mEditor = additional;
break;
case 1:
mDiagram = additional;
break;
case 2:
mElement = additional;
break;
case 3:
mId = additional;
break;
default:
Q_ASSERT(!"Can not add a part to Id, it will be too long");
}
Q_ASSERT(checkIntegrity());
}
bool Id::isNull() const
{
return mEditor.isEmpty() && mDiagram.isEmpty()
&& mElement.isEmpty() && mId.isEmpty();
}
QString Id::editor() const
{
return mEditor;
}
QString Id::diagram() const
{
return mDiagram;
}
QString Id::element() const
{
return mElement;
}
QString Id::id() const
{
return mId;
}
Id Id::type() const
{
return Id(mEditor, mDiagram, mElement);
}
Id Id::sameTypeId() const
{
return Id(mEditor, mDiagram, mElement, QUuid::createUuid().toString());
}
unsigned Id::idSize() const
{
if (!mId.isEmpty()) {
return 4;
} if (!mElement.isEmpty()) {
return 3;
} if (!mDiagram.isEmpty()) {
return 2;
} if (!mEditor.isEmpty()) {
return 1;
}
return 0;
}
QUrl Id::toUrl() const
{
return QUrl(toString());
}
QString Id::toString() const
{
QString path = "qrm:/" + mEditor;
if (mDiagram != "") {
path += "/" + mDiagram;
} if (mElement != "") {
path += "/" + mElement;
} if (mId != "") {
path += "/" + mId;
}
return path;
}
bool Id::checkIntegrity() const
{
bool emptyPartsAllowed = true;
if (!mId.isEmpty()) {
emptyPartsAllowed = false;
}
if (!mElement.isEmpty()) {
emptyPartsAllowed = false;
} else if (!emptyPartsAllowed) {
return false;
}
if (!mDiagram.isEmpty()) {
emptyPartsAllowed = false;
} else if (!emptyPartsAllowed) {
return false;
}
if (mEditor.isEmpty() && !emptyPartsAllowed) {
return false;
}
return true;
}
QVariant Id::toVariant() const
{
QVariant result;
result.setValue(*this);
return result;
}
QVariant IdListHelper::toVariant(IdList const &list)
{
QVariant v;
v.setValue(list);
return v;
}
QDataStream& operator<< (QDataStream &out, Id const &id)
{
out << id.toString();
return out;
}
QDataStream& operator>> (QDataStream &in, Id &id)
{
QString idString;
in >> idString;
id = Id::loadFromString(idString);
return in;
}
<commit_msg>check removed since Id is never actually cast to QUrl anywhere is the project and this check is failing, because symbol '{' is cast to code %7 and result is not identical<commit_after>#include "ids.h"
#include <QtCore/QVariant>
#include <QtCore/QUuid>
using namespace qReal;
Id Id::loadFromString(QString const &string)
{
QStringList const path = string.split('/');
Q_ASSERT(path.count() > 0 && path.count() <= 5);
Q_ASSERT(path[0] == "qrm:");
Id result;
switch (path.count()) {
case 5: result.mId = path[4];
// Fall-thru
case 4: result.mElement = path[3];
// Fall-thru
case 3: result.mDiagram = path[2];
// Fall-thru
case 2: result.mEditor = path[1];
// Fall-thru
}
Q_ASSERT(string == result.toString());
return result;
}
Id Id::createElementId(QString const &editor, QString const &diagram, QString const &element)
{
return Id(editor, diagram, element, QUuid::createUuid().toString());
}
Id Id::rootId()
{
return Id("ROOT_ID", "ROOT_ID", "ROOT_ID", "ROOT_ID");
}
Id::Id(QString const &editor, QString const &diagram, QString const &element, QString const &id)
: mEditor(editor)
, mDiagram(diagram)
, mElement(element)
, mId(id)
{
Q_ASSERT(checkIntegrity());
}
Id::Id(Id const &base, QString const &additional)
: mEditor(base.mEditor)
, mDiagram(base.mDiagram)
, mElement(base.mElement)
, mId(base.mId)
{
unsigned const baseSize = base.idSize();
switch (baseSize) {
case 0:
mEditor = additional;
break;
case 1:
mDiagram = additional;
break;
case 2:
mElement = additional;
break;
case 3:
mId = additional;
break;
default:
Q_ASSERT(!"Can not add a part to Id, it will be too long");
}
Q_ASSERT(checkIntegrity());
}
bool Id::isNull() const
{
return mEditor.isEmpty() && mDiagram.isEmpty()
&& mElement.isEmpty() && mId.isEmpty();
}
QString Id::editor() const
{
return mEditor;
}
QString Id::diagram() const
{
return mDiagram;
}
QString Id::element() const
{
return mElement;
}
QString Id::id() const
{
return mId;
}
Id Id::type() const
{
return Id(mEditor, mDiagram, mElement);
}
Id Id::sameTypeId() const
{
return Id(mEditor, mDiagram, mElement, QUuid::createUuid().toString());
}
unsigned Id::idSize() const
{
if (!mId.isEmpty()) {
return 4;
} if (!mElement.isEmpty()) {
return 3;
} if (!mDiagram.isEmpty()) {
return 2;
} if (!mEditor.isEmpty()) {
return 1;
}
return 0;
}
QUrl Id::toUrl() const
{
return QUrl(toString());
}
QString Id::toString() const
{
QString path = "qrm:/" + mEditor;
if (mDiagram != "") {
path += "/" + mDiagram;
} if (mElement != "") {
path += "/" + mElement;
} if (mId != "") {
path += "/" + mId;
}
return path;
}
bool Id::checkIntegrity() const
{
bool emptyPartsAllowed = true;
if (!mId.isEmpty()) {
emptyPartsAllowed = false;
}
if (!mElement.isEmpty()) {
emptyPartsAllowed = false;
} else if (!emptyPartsAllowed) {
return false;
}
if (!mDiagram.isEmpty()) {
emptyPartsAllowed = false;
} else if (!emptyPartsAllowed) {
return false;
}
if (mEditor.isEmpty() && !emptyPartsAllowed) {
return false;
}
return true;
}
QVariant Id::toVariant() const
{
QVariant result;
result.setValue(*this);
return result;
}
QVariant IdListHelper::toVariant(IdList const &list)
{
QVariant v;
v.setValue(list);
return v;
}
QDataStream& operator<< (QDataStream &out, Id const &id)
{
out << id.toString();
return out;
}
QDataStream& operator>> (QDataStream &in, Id &id)
{
QString idString;
in >> idString;
id = Id::loadFromString(idString);
return in;
}
<|endoftext|> |
<commit_before>#pragma once
#include <vector>
using std::vector;
template<typename T>
class FenwickTree {
public:
FenwickTree(int size) {
tree.resize(size);
}
void add(int i, T delta) {
for (; i < (int)tree.size(); i |= i + 1)
tree[i] += delta;
}
T sum(int left, int right) {
return sum(right) - sum(left - 1);
}
private:
vector<T> tree;
T sum(int index) {
T sum = 0;
while (index >= 0) {
sum += tree[index];
index &= index + 1;
index--;
}
return sum;
}
};<commit_msg>Cleaned up Fenwick<commit_after>#pragma once
#include <vector>
template<typename T>
class FenwickTree {
public:
FenwickTree(int size) {
tree.resize(size);
}
void add(int i, T delta) {
for (; i < (int)tree.size(); i |= i + 1)
tree[i] += delta;
}
T sum(int left, int right) {
return sum(right) - sum(left - 1);
}
private:
std::vector<T> tree;
T sum(int index) {
T sum = 0;
while (index >= 0) {
sum += tree[index];
index &= index + 1;
index--;
}
return sum;
}
};<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef QUEUE_HH_
#define QUEUE_HH_
#include "circular_buffer.hh"
#include "future.hh"
#include <queue>
#include <experimental/optional>
namespace seastar {
template <typename T>
class queue {
std::queue<T, circular_buffer<T>> _q;
size_t _max;
std::experimental::optional<promise<>> _not_empty;
std::experimental::optional<promise<>> _not_full;
std::exception_ptr _ex = nullptr;
private:
void notify_not_empty();
void notify_not_full();
public:
explicit queue(size_t size);
// Push an item.
//
// Returns false if the queue was full and the item was not pushed.
bool push(T&& a);
// pops an item.
T pop();
// Consumes items from the queue, passing them to @func, until @func
// returns false or the queue it empty
//
// Returns false if func returned false.
template <typename Func>
bool consume(Func&& func);
// Returns true when the queue is empty.
bool empty() const;
// Returns true when the queue is full.
bool full() const;
// Returns a future<> that becomes available when pop() or consume()
// can be called.
future<> not_empty();
// Returns a future<> that becomes available when push() can be called.
future<> not_full();
// Pops element now or when there is some. Returns a future that becomes
// available when some element is available.
// If the queue is, or already was, abort()ed, the future resolves with
// the exception provided to abort().
future<T> pop_eventually();
// Pushes the element now or when there is room. Returns a future<> which
// resolves when data was pushed.
// If the queue is, or already was, abort()ed, the future resolves with
// the exception provided to abort().
future<> push_eventually(T&& data);
size_t size() const { return _q.size(); }
size_t max_size() const { return _max; }
// Set the maximum size to a new value. If the queue's max size is reduced,
// items already in the queue will not be expunged and the queue will be temporarily
// bigger than its max_size.
void set_max_size(size_t max) {
_max = max;
if (!full()) {
notify_not_full();
}
}
// Destroy any items in the queue, and pass the provided exception to any
// waiting readers or writers - or to any later read or write attempts.
void abort(std::exception_ptr ex) {
while (!_q.empty()) {
_q.pop();
}
_ex = ex;
if (_not_full) {
_not_full->set_exception(ex);
_not_full= std::experimental::nullopt;
}
if (_not_empty) {
_not_empty->set_exception(std::move(ex));
_not_empty = std::experimental::nullopt;
}
}
};
template <typename T>
inline
queue<T>::queue(size_t size)
: _max(size) {
}
template <typename T>
inline
void queue<T>::notify_not_empty() {
if (_not_empty) {
_not_empty->set_value();
_not_empty = std::experimental::optional<promise<>>();
}
}
template <typename T>
inline
void queue<T>::notify_not_full() {
if (_not_full) {
_not_full->set_value();
_not_full = std::experimental::optional<promise<>>();
}
}
template <typename T>
inline
bool queue<T>::push(T&& data) {
if (_q.size() < _max) {
_q.push(std::move(data));
notify_not_empty();
return true;
} else {
return false;
}
}
template <typename T>
inline
T queue<T>::pop() {
if (_q.size() == _max) {
notify_not_full();
}
T data = std::move(_q.front());
_q.pop();
return data;
}
template <typename T>
inline
future<T> queue<T>::pop_eventually() {
if (_ex) {
return make_exception_future<T>(_ex);
}
if (empty()) {
return not_empty().then([this] {
if (_ex) {
return make_exception_future<T>(_ex);
} else {
return make_ready_future<T>(pop());
}
});
} else {
return make_ready_future<T>(pop());
}
}
template <typename T>
inline
future<> queue<T>::push_eventually(T&& data) {
if (_ex) {
return make_exception_future<>(_ex);
}
if (full()) {
return not_full().then([this, data = std::move(data)] () mutable {
_q.push(std::move(data));
notify_not_empty();
});
} else {
_q.push(std::move(data));
notify_not_empty();
return make_ready_future<>();
}
}
template <typename T>
template <typename Func>
inline
bool queue<T>::consume(Func&& func) {
bool running = true;
while (!_q.empty() && running) {
running = func(std::move(_q.front()));
_q.pop();
}
if (!full()) {
notify_not_full();
}
return running;
}
template <typename T>
inline
bool queue<T>::empty() const {
return _q.empty();
}
template <typename T>
inline
bool queue<T>::full() const {
return _q.size() >= _max;
}
template <typename T>
inline
future<> queue<T>::not_empty() {
if (!empty()) {
return make_ready_future<>();
} else {
_not_empty = promise<>();
return _not_empty->get_future();
}
}
template <typename T>
inline
future<> queue<T>::not_full() {
if (!full()) {
return make_ready_future<>();
} else {
_not_full = promise<>();
return _not_full->get_future();
}
}
}
#endif /* QUEUE_HH_ */
<commit_msg>queue: doxygen documentation<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef QUEUE_HH_
#define QUEUE_HH_
#include "circular_buffer.hh"
#include "future.hh"
#include <queue>
#include <experimental/optional>
namespace seastar {
template <typename T>
class queue {
std::queue<T, circular_buffer<T>> _q;
size_t _max;
std::experimental::optional<promise<>> _not_empty;
std::experimental::optional<promise<>> _not_full;
std::exception_ptr _ex = nullptr;
private:
void notify_not_empty();
void notify_not_full();
public:
explicit queue(size_t size);
/// \brief Push an item.
///
/// Returns false if the queue was full and the item was not pushed.
bool push(T&& a);
/// \brief Pop an item.
///
/// Popping from an empty queue will result in undefined behavior.
T pop();
/// Consumes items from the queue, passing them to @func, until @func
/// returns false or the queue it empty
///
/// Returns false if func returned false.
template <typename Func>
bool consume(Func&& func);
/// Returns true when the queue is empty.
bool empty() const;
/// Returns true when the queue is full.
bool full() const;
/// Returns a future<> that becomes available when pop() or consume()
/// can be called.
future<> not_empty();
/// Returns a future<> that becomes available when push() can be called.
future<> not_full();
/// Pops element now or when there is some. Returns a future that becomes
/// available when some element is available.
/// If the queue is, or already was, abort()ed, the future resolves with
/// the exception provided to abort().
future<T> pop_eventually();
/// Pushes the element now or when there is room. Returns a future<> which
/// resolves when data was pushed.
/// If the queue is, or already was, abort()ed, the future resolves with
/// the exception provided to abort().
future<> push_eventually(T&& data);
/// Returns the number of items currently in the queue.
size_t size() const { return _q.size(); }
/// Returns the size limit imposed on the queue during its construction
/// or by a call to set_max_size(). If the queue contains max_size()
/// items (or more), further items cannot be pushed until some are popped.
size_t max_size() const { return _max; }
/// Set the maximum size to a new value. If the queue's max size is reduced,
/// items already in the queue will not be expunged and the queue will be temporarily
/// bigger than its max_size.
void set_max_size(size_t max) {
_max = max;
if (!full()) {
notify_not_full();
}
}
/// Destroy any items in the queue, and pass the provided exception to any
/// waiting readers or writers - or to any later read or write attempts.
void abort(std::exception_ptr ex) {
while (!_q.empty()) {
_q.pop();
}
_ex = ex;
if (_not_full) {
_not_full->set_exception(ex);
_not_full= std::experimental::nullopt;
}
if (_not_empty) {
_not_empty->set_exception(std::move(ex));
_not_empty = std::experimental::nullopt;
}
}
};
template <typename T>
inline
queue<T>::queue(size_t size)
: _max(size) {
}
template <typename T>
inline
void queue<T>::notify_not_empty() {
if (_not_empty) {
_not_empty->set_value();
_not_empty = std::experimental::optional<promise<>>();
}
}
template <typename T>
inline
void queue<T>::notify_not_full() {
if (_not_full) {
_not_full->set_value();
_not_full = std::experimental::optional<promise<>>();
}
}
template <typename T>
inline
bool queue<T>::push(T&& data) {
if (_q.size() < _max) {
_q.push(std::move(data));
notify_not_empty();
return true;
} else {
return false;
}
}
template <typename T>
inline
T queue<T>::pop() {
if (_q.size() == _max) {
notify_not_full();
}
T data = std::move(_q.front());
_q.pop();
return data;
}
template <typename T>
inline
future<T> queue<T>::pop_eventually() {
if (_ex) {
return make_exception_future<T>(_ex);
}
if (empty()) {
return not_empty().then([this] {
if (_ex) {
return make_exception_future<T>(_ex);
} else {
return make_ready_future<T>(pop());
}
});
} else {
return make_ready_future<T>(pop());
}
}
template <typename T>
inline
future<> queue<T>::push_eventually(T&& data) {
if (_ex) {
return make_exception_future<>(_ex);
}
if (full()) {
return not_full().then([this, data = std::move(data)] () mutable {
_q.push(std::move(data));
notify_not_empty();
});
} else {
_q.push(std::move(data));
notify_not_empty();
return make_ready_future<>();
}
}
template <typename T>
template <typename Func>
inline
bool queue<T>::consume(Func&& func) {
bool running = true;
while (!_q.empty() && running) {
running = func(std::move(_q.front()));
_q.pop();
}
if (!full()) {
notify_not_full();
}
return running;
}
template <typename T>
inline
bool queue<T>::empty() const {
return _q.empty();
}
template <typename T>
inline
bool queue<T>::full() const {
return _q.size() >= _max;
}
template <typename T>
inline
future<> queue<T>::not_empty() {
if (!empty()) {
return make_ready_future<>();
} else {
_not_empty = promise<>();
return _not_empty->get_future();
}
}
template <typename T>
inline
future<> queue<T>::not_full() {
if (!full()) {
return make_ready_future<>();
} else {
_not_full = promise<>();
return _not_full->get_future();
}
}
}
#endif /* QUEUE_HH_ */
<|endoftext|> |
<commit_before>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* 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.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include "RhodesApp.h"
#include "common/RhoMutexLock.h"
#include "common/IRhoClassFactory.h"
#include "common/RhoFile.h"
#include "common/RhoConf.h"
#include "common/RhoFilePath.h"
#include "common/Tokenizer.h"
using namespace rho;
using namespace rho::common;
extern "C" void rho_sys_app_exit();
extern "C" void rho_sys_impl_exit_with_errormessage(const char* szTitle, const char* szMsg);
#if !defined(OS_WINDOWS) && !defined(OS_WINCE) && !defined(OS_MACOSX)
void rho_sys_impl_exit_with_errormessage(const char* szTitle, const char* szMsg)
{
}
#endif
namespace rho {
namespace common {
class CFileTransaction
{
unsigned int m_nError;
String m_strError;
String m_strFolder;
public:
CFileTransaction(const String& strFolder);
~CFileTransaction();
unsigned int start();
void commit();
unsigned int rollback();
boolean isError(){ return m_nError != 0; }
unsigned int getError(){ return m_nError; }
String getErrorText(){ return m_strError; }
};
class CReplaceBundleThread : public rho::common::CRhoThread
{
DEFINE_LOGCLASS;
String m_bundle_path;
void doReplaceBundle();
public:
CReplaceBundleThread(const char* root_path)
{
m_bundle_path = root_path;
start(rho::common::IRhoRunnable::epNormal);
}
virtual ~CReplaceBundleThread() {}
virtual void run();
static void showError(int nError, const String& strError );
static unsigned int removeFilesByList( const String& strListPath, const String& strSrcFolder );
static unsigned int moveFilesByList( const String& strListPath, const String& strSrcFolder, const String& strDstFolder );
};
IMPLEMENT_LOGCLASS(CReplaceBundleThread,"RhoBundle");
CFileTransaction::CFileTransaction(const String& strFolder) : m_strFolder(strFolder)
{
}
unsigned int CFileTransaction::start()
{
LOG(TRACE) + "FileTransaction is starting: " + m_strFolder;
LOG(TRACE) + "Creating folder" + m_strFolder + "_temp_journal";
CRhoFile::createFolder((m_strFolder + "_temp_journal").c_str());
LOG(TRACE) + "Coping: " + CFilePath::join(m_strFolder, "") + " -> " + m_strFolder + "_temp_journal";
m_nError = CRhoFile::copyFoldersContentToAnotherFolder( CFilePath::join(m_strFolder, "").c_str(), (m_strFolder + "_temp_journal").c_str() );
if (m_nError)
{
m_strError = "Unable to copy folder: " + m_strFolder + " to : " + m_strFolder + "_temp_journal";
return m_nError;
}
LOG(TRACE) + "Renaming: " + m_strFolder + "_temp_journal" + " -> " + m_strFolder + "_journal";
m_nError = CRhoFile::renameFile( (m_strFolder + "_temp_journal").c_str(), (m_strFolder + "_journal").c_str());
if (m_nError)
{
m_strError = "Unable to rename folder: " + m_strFolder + "_temp_journal to : " + m_strFolder + "_journal";
return m_nError;
}
LOG(TRACE) + "FileTransaction has started";
return m_nError;
}
CFileTransaction::~CFileTransaction()
{
rollback();
}
void CFileTransaction::commit()
{
LOG(TRACE) + "FileTransaction is committing: " + m_strFolder;
String strFolder = m_strFolder;
LOG(TRACE) + "Renaming: " + strFolder + "_journal" + " -> " + strFolder + "_temp_journal";
m_nError = CRhoFile::renameFile( (strFolder + "_journal").c_str(), (strFolder + "_temp_journal").c_str() );
if (m_nError)
{
m_strError = "Unable to rename folder: " + strFolder + "_journal to : " + strFolder + "_temp_journal";
return;
}
m_strFolder = "";
LOG(TRACE) + "Deleting: " + strFolder + "_temp_journal";
m_nError = CRhoFile::deleteFolder( (strFolder + "_temp_journal").c_str() );
if (m_nError)
{
m_strError = "Unable to delete folder: " + strFolder + "_temp_journal";
return;
}
LOG(TRACE) + "FileTransaction has committed";
}
unsigned int CFileTransaction::rollback()
{
LOG(TRACE) + "FileTransaction is rolling back: " + m_strFolder;
String strFolder = m_strFolder;
m_strFolder = "";
if ( strFolder.length() == 0 )
return 0;
CRhoFile::deleteFolder( CFilePath(strFolder).changeBaseName("RhoBundle").c_str() );
CRhoFile::deleteFolder( (strFolder + "_temp_journal").c_str() );
if ( !CRhoFile::isFileExist((strFolder + "_journal").c_str()) )
return 0;
m_nError = CRhoFile::deleteFolder( (strFolder).c_str() );
if (m_nError)
{
m_strError = "Unable to delete folder: " + strFolder;
CReplaceBundleThread::showError(m_nError, m_strError);
return m_nError;
}
m_nError = CRhoFile::renameFile( (strFolder + "_journal").c_str(), (strFolder).c_str() );
if (m_nError)
{
m_strError = "Unable to rename folder: " + strFolder + "_journal" + " to : " + strFolder;
CReplaceBundleThread::showError(m_nError, m_strError);
return m_nError;
}
LOG(TRACE) + "FileTransaction has rolled back";
return m_nError;
}
unsigned int CReplaceBundleThread::removeFilesByList( const String& strListPath, const String& strSrcFolder )
{
LOG(TRACE) + "Removing files by list: " + strSrcFolder + ", list: " + strListPath;
unsigned int nError = 0;
String strList;
CRhoFile::loadTextFile(strListPath.c_str(), strList);
CTokenizer oTokenizer( strList, "\n" );
while (oTokenizer.hasMoreTokens())
{
String strLine = oTokenizer.nextToken();
CTokenizer oLineTok( strLine, "\t" );
if ( !oLineTok.hasMoreTokens() )
continue;
String strPath = oLineTok.nextToken();
if ( !oLineTok.hasMoreTokens() )
continue;
String strType = oLineTok.nextToken();
if ( strType.compare("file") == 0)
{
LOG(TRACE) + "Deleting file: " + CFilePath::join( strSrcFolder,strPath);
nError = CRhoFile::deleteFile( CFilePath::join( strSrcFolder,strPath).c_str() );
if (nError != 0)
{
LOG(ERROR) + "Cannot remove file: " + CFilePath::join( strSrcFolder,strPath);
break;
}
}
}
return nError;
}
unsigned int CReplaceBundleThread::moveFilesByList( const String& strListPath, const String& strSrcFolder, const String& strDestFolder )
{
LOG(TRACE) + "Moving files by list: " + strSrcFolder + " -> " + strDestFolder;
unsigned int nError = 0;
String strList;
CRhoFile::loadTextFile(strListPath.c_str(), strList);
CTokenizer oTokenizer( strList, "\n" );
while (oTokenizer.hasMoreTokens())
{
String strLine = oTokenizer.nextToken();
CTokenizer oLineTok( strLine, "\t" );
if ( !oLineTok.hasMoreTokens() )
continue;
String strPath = oLineTok.nextToken();
if ( !oLineTok.hasMoreTokens() )
continue;
String strType = oLineTok.nextToken();
String strSrcPath = CFilePath::join( strSrcFolder,strPath);
String strDstPath = CFilePath::join( strDestFolder, strPath );
if ( strType.compare("dir") == 0)
{
LOG(TRACE) + "Creating folder: " + strDstPath;
CRhoFile::createFolder(strDstPath.c_str());
}else if ( strType.compare("file") == 0)
{
LOG(TRACE) + "Renaming file: " + strSrcPath + " -> " + strDstPath;
nError = CRhoFile::renameFile( strSrcPath.c_str(), strDstPath.c_str() );
if (nError != 0)
{
LOG(ERROR) + "Cannot rename file from : " + strSrcPath + "; to: " + strDstPath;
break;
}
}
}
return nError;
}
void CReplaceBundleThread::showError(int nError, const String& strError )
{
LOG(ERROR) + "Error happen when replace bundle: " + strError + "; Code: " + LOGFMT("%d") + nError;
String strMsg = "Error happen when replace bundle: " + strError;
rho_sys_impl_exit_with_errormessage("Bundle update", strMsg.c_str());
}
void CReplaceBundleThread::run()
{
//Stop application
rho_rhodesapp_callAppActiveCallback(0);
rho_rhodesapp_callUiDestroyedCallback();
RHODESAPP().stopApp();
doReplaceBundle();
rho_platform_restart_application();
rho_sys_app_exit();
}
void CReplaceBundleThread::doReplaceBundle()
{
CFileTransaction oFT( RHODESAPP().getAppRootPath());
if (oFT.start())
{
showError(oFT.getError(), oFT.getErrorText());
return;
}
//Remove current files
unsigned int nError = removeFilesByList( CFilePath::join( RHODESAPP().getAppRootPath(), "rhofilelist.txt"), ::RHODESAPP().getAppRootPath() );
if ( nError != 0 )
{
showError(nError, "Remove files from bundle failed." );
return;
}
LOG(INFO) + "START";
//Copy new bundle
//nError = CRhoFile::moveFoldersContentToAnotherFolder( CFilePath::join(m_bundle_path, "RhoBundle/apps").c_str(), ::RHODESAPP().getAppRootPath().c_str() );
nError = moveFilesByList( CFilePath::join(m_bundle_path, "RhoBundle/apps/rhofilelist.txt").c_str(), CFilePath::join(m_bundle_path, "RhoBundle/apps"), ::RHODESAPP().getAppRootPath().c_str() );
if ( nError != 0 )
{
showError(nError, "Copy files to bundle failed." );
return;
}
LOG(INFO) + "STOP";
oFT.commit();
#ifdef OS_ANDROID
//rho_file_patch_stat_table(CFilePath::join(m_bundle_path, "RhoBundle/apps/rhofilelist.txt"))
if (CRhoFile::copyFile(CFilePath::join(m_bundle_path, "RhoBundle/rho.dat").c_str(), CFilePath::join(RHODESAPP().getRhoRootPath().c_str(), "rho.dat").c_str()))
{
int err = errno;
LOG(ERROR) + "Cannot copy rho.dat, errno: " + LOGFMT("%d") + err;
}
#endif
//Delete bundle folder
CRhoFile::deleteFolder( m_bundle_path.c_str());
}
}
}
extern "C"
{
void rho_sys_replace_current_bundle(const char* path)
{
new CReplaceBundleThread(path);
}
int rho_sys_check_rollback_bundle(const char* szRhoPath)
{
CFileTransaction oFT( CFilePath::join(szRhoPath, "apps") );
return oFT.rollback() != 0 ? 0 : 1;
}
int rho_sys_delete_folder(const char* szRhoPath)
{
return CRhoFile::deleteFolder(szRhoPath);
}
int rho_sysimpl_remove_bundle_files(const char* path, const char* fileListName)
{
unsigned int nError = CReplaceBundleThread::removeFilesByList(CFilePath::join(path, fileListName), path);
if ( nError != 0 )
{
CReplaceBundleThread::showError(nError, String("Remove of bundle files is failed: ") += path);
}
return nError;
}
} //extern "C"
<commit_msg>optimize bundle manager<commit_after>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* 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.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include "RhodesApp.h"
#include "common/RhoMutexLock.h"
#include "common/IRhoClassFactory.h"
#include "common/RhoFile.h"
#include "common/RhoConf.h"
#include "common/RhoFilePath.h"
#include "common/Tokenizer.h"
using namespace rho;
using namespace rho::common;
extern "C" void rho_sys_app_exit();
extern "C" void rho_sys_impl_exit_with_errormessage(const char* szTitle, const char* szMsg);
#if !defined(OS_WINDOWS) && !defined(OS_WINCE) && !defined(OS_MACOSX)
void rho_sys_impl_exit_with_errormessage(const char* szTitle, const char* szMsg)
{
}
#endif
namespace rho {
namespace common {
class CFileTransaction
{
unsigned int m_nError;
String m_strError;
String m_strFolder;
boolean m_bRollbackInDestr;
public:
CFileTransaction(const String& strFolder, boolean bRollbackInDestr = true);
~CFileTransaction();
unsigned int start();
void commit();
unsigned int rollback();
boolean isError(){ return m_nError != 0; }
unsigned int getError(){ return m_nError; }
String getErrorText(){ return m_strError; }
};
class CReplaceBundleThread : public rho::common::CRhoThread
{
DEFINE_LOGCLASS;
String m_bundle_path;
void doReplaceBundle();
public:
CReplaceBundleThread(const char* root_path)
{
m_bundle_path = root_path;
start(rho::common::IRhoRunnable::epNormal);
}
virtual ~CReplaceBundleThread() {}
virtual void run();
static void showError(int nError, const String& strError );
static unsigned int removeFilesByList( const String& strListPath, const String& strSrcFolder );
static unsigned int moveFilesByList( const String& strListPath, const String& strSrcFolder, const String& strDstFolder );
};
IMPLEMENT_LOGCLASS(CReplaceBundleThread,"RhoBundle");
CFileTransaction::CFileTransaction(const String& strFolder, boolean bRollbackInDestr) : m_strFolder(strFolder), m_bRollbackInDestr(bRollbackInDestr)
{
}
unsigned int CFileTransaction::start()
{
LOG(TRACE) + "FileTransaction is starting: " + m_strFolder;
LOG(TRACE) + "Creating folder" + m_strFolder + "_temp_journal";
CRhoFile::createFolder((m_strFolder + "_temp_journal").c_str());
LOG(TRACE) + "Coping: " + CFilePath::join(m_strFolder, "") + " -> " + m_strFolder + "_temp_journal";
m_nError = CRhoFile::copyFoldersContentToAnotherFolder( CFilePath::join(m_strFolder, "").c_str(), (m_strFolder + "_temp_journal").c_str() );
if (m_nError)
{
m_strError = "Unable to copy folder: " + m_strFolder + " to : " + m_strFolder + "_temp_journal";
return m_nError;
}
LOG(TRACE) + "Renaming: " + m_strFolder + "_temp_journal" + " -> " + m_strFolder + "_journal";
m_nError = CRhoFile::renameFile( (m_strFolder + "_temp_journal").c_str(), (m_strFolder + "_journal").c_str());
if (m_nError)
{
m_strError = "Unable to rename folder: " + m_strFolder + "_temp_journal to : " + m_strFolder + "_journal";
return m_nError;
}
LOG(TRACE) + "FileTransaction has started";
return m_nError;
}
CFileTransaction::~CFileTransaction()
{
if (m_bRollbackInDestr)
rollback();
}
void CFileTransaction::commit()
{
LOG(TRACE) + "FileTransaction is committing: " + m_strFolder;
String strFolder = m_strFolder;
LOG(TRACE) + "Renaming: " + strFolder + "_journal" + " -> " + strFolder + "_temp_journal";
m_nError = CRhoFile::renameFile( (strFolder + "_journal").c_str(), (strFolder + "_temp_journal").c_str() );
if (m_nError)
{
m_strError = "Unable to rename folder: " + strFolder + "_journal to : " + strFolder + "_temp_journal";
return;
}
m_strFolder = "";
LOG(TRACE) + "Deleting: " + strFolder + "_temp_journal";
m_nError = CRhoFile::deleteFolder( (strFolder + "_temp_journal").c_str() );
if (m_nError)
{
m_strError = "Unable to delete folder: " + strFolder + "_temp_journal";
return;
}
LOG(TRACE) + "FileTransaction has committed";
}
unsigned int CFileTransaction::rollback()
{
LOG(TRACE) + "FileTransaction is rolling back: " + m_strFolder;
String strFolder = m_strFolder;
m_strFolder = "";
if ( strFolder.length() == 0 )
return 0;
CRhoFile::deleteFolder( CFilePath(strFolder).changeBaseName("RhoBundle").c_str() );
CRhoFile::deleteFolder( (strFolder + "_temp_journal").c_str() );
if ( !CRhoFile::isFileExist((strFolder + "_journal").c_str()) )
return 0;
m_nError = CRhoFile::deleteFolder( (strFolder).c_str() );
if (m_nError)
{
m_strError = "Unable to delete folder: " + strFolder;
CReplaceBundleThread::showError(m_nError, m_strError);
return m_nError;
}
m_nError = CRhoFile::renameFile( (strFolder + "_journal").c_str(), (strFolder).c_str() );
if (m_nError)
{
m_strError = "Unable to rename folder: " + strFolder + "_journal" + " to : " + strFolder;
CReplaceBundleThread::showError(m_nError, m_strError);
return m_nError;
}
LOG(TRACE) + "FileTransaction has rolled back";
return m_nError;
}
unsigned int CReplaceBundleThread::removeFilesByList( const String& strListPath, const String& strSrcFolder )
{
LOG(TRACE) + "Removing files by list: " + strSrcFolder + ", list: " + strListPath;
unsigned int nError = 0;
String strList;
CRhoFile::loadTextFile(strListPath.c_str(), strList);
CTokenizer oTokenizer( strList, "\n" );
while (oTokenizer.hasMoreTokens())
{
String strLine = oTokenizer.nextToken();
CTokenizer oLineTok( strLine, "\t" );
if ( !oLineTok.hasMoreTokens() )
continue;
String strPath = oLineTok.nextToken();
if ( !oLineTok.hasMoreTokens() )
continue;
String strType = oLineTok.nextToken();
if ( strType.compare("file") == 0)
{
LOG(TRACE) + "Deleting file: " + CFilePath::join( strSrcFolder,strPath);
nError = CRhoFile::deleteFile( CFilePath::join( strSrcFolder,strPath).c_str() );
if (nError != 0)
{
LOG(ERROR) + "Cannot remove file: " + CFilePath::join( strSrcFolder,strPath);
break;
}
}
}
return nError;
}
unsigned int CReplaceBundleThread::moveFilesByList( const String& strListPath, const String& strSrcFolder, const String& strDestFolder )
{
LOG(TRACE) + "Moving files by list: " + strSrcFolder + " -> " + strDestFolder;
unsigned int nError = 0;
String strList;
CRhoFile::loadTextFile(strListPath.c_str(), strList);
CTokenizer oTokenizer( strList, "\n" );
while (oTokenizer.hasMoreTokens())
{
String strLine = oTokenizer.nextToken();
CTokenizer oLineTok( strLine, "\t" );
if ( !oLineTok.hasMoreTokens() )
continue;
String strPath = oLineTok.nextToken();
if ( !oLineTok.hasMoreTokens() )
continue;
String strType = oLineTok.nextToken();
String strSrcPath = CFilePath::join( strSrcFolder,strPath);
String strDstPath = CFilePath::join( strDestFolder, strPath );
if ( strType.compare("dir") == 0)
{
LOG(TRACE) + "Creating folder: " + strDstPath;
CRhoFile::createFolder(strDstPath.c_str());
}else if ( strType.compare("file") == 0)
{
LOG(TRACE) + "Renaming file: " + strSrcPath + " -> " + strDstPath;
nError = CRhoFile::renameFile( strSrcPath.c_str(), strDstPath.c_str() );
if (nError != 0)
{
LOG(ERROR) + "Cannot rename file from : " + strSrcPath + "; to: " + strDstPath;
break;
}
}
}
return nError;
}
void CReplaceBundleThread::showError(int nError, const String& strError )
{
LOG(ERROR) + "Error happen when replace bundle: " + strError + "; Code: " + LOGFMT("%d") + nError;
String strMsg = "Error happen when replace bundle: " + strError;
rho_sys_impl_exit_with_errormessage("Bundle update", strMsg.c_str());
}
void CReplaceBundleThread::run()
{
//Stop application
rho_rhodesapp_callAppActiveCallback(0);
rho_rhodesapp_callUiDestroyedCallback();
RHODESAPP().stopApp();
doReplaceBundle();
rho_platform_restart_application();
rho_sys_app_exit();
}
void CReplaceBundleThread::doReplaceBundle()
{
CFileTransaction oFT( RHODESAPP().getAppRootPath());
if (oFT.start())
{
showError(oFT.getError(), oFT.getErrorText());
return;
}
//Remove current files
unsigned int nError = removeFilesByList( CFilePath::join( RHODESAPP().getAppRootPath(), "rhofilelist.txt"), ::RHODESAPP().getAppRootPath() );
if ( nError != 0 )
{
showError(nError, "Remove files from bundle failed." );
return;
}
LOG(INFO) + "START";
//Copy new bundle
//nError = CRhoFile::moveFoldersContentToAnotherFolder( CFilePath::join(m_bundle_path, "RhoBundle/apps").c_str(), ::RHODESAPP().getAppRootPath().c_str() );
nError = moveFilesByList( CFilePath::join(m_bundle_path, "RhoBundle/apps/rhofilelist.txt").c_str(), CFilePath::join(m_bundle_path, "RhoBundle/apps"), ::RHODESAPP().getAppRootPath().c_str() );
if ( nError != 0 )
{
showError(nError, "Copy files to bundle failed." );
return;
}
LOG(INFO) + "STOP";
oFT.commit();
#ifdef OS_ANDROID
//rho_file_patch_stat_table(CFilePath::join(m_bundle_path, "RhoBundle/apps/rhofilelist.txt"))
if (CRhoFile::copyFile(CFilePath::join(m_bundle_path, "RhoBundle/rho.dat").c_str(), CFilePath::join(RHODESAPP().getRhoRootPath().c_str(), "rho.dat").c_str()))
{
int err = errno;
LOG(ERROR) + "Cannot copy rho.dat, errno: " + LOGFMT("%d") + err;
}
#endif
//Delete bundle folder
CRhoFile::deleteFolder( m_bundle_path.c_str());
}
}
}
extern "C"
{
void rho_sys_replace_current_bundle(const char* path)
{
new CReplaceBundleThread(path);
}
int rho_sys_check_rollback_bundle(const char* szRhoPath)
{
CFileTransaction oFT( CFilePath::join(szRhoPath, "apps"), false );
return oFT.rollback() != 0 ? 0 : 1;
}
int rho_sys_delete_folder(const char* szRhoPath)
{
return CRhoFile::deleteFolder(szRhoPath);
}
int rho_sysimpl_remove_bundle_files(const char* path, const char* fileListName)
{
unsigned int nError = CReplaceBundleThread::removeFilesByList(CFilePath::join(path, fileListName), path);
if ( nError != 0 )
{
CReplaceBundleThread::showError(nError, String("Remove of bundle files is failed: ") += path);
}
return nError;
}
} //extern "C"
<|endoftext|> |
<commit_before>e0211e61-313a-11e5-a529-3c15c2e10482<commit_msg>e0275f47-313a-11e5-b640-3c15c2e10482<commit_after>e0275f47-313a-11e5-b640-3c15c2e10482<|endoftext|> |
<commit_before>f243e4f5-327f-11e5-a568-9cf387a8033e<commit_msg>f24a3459-327f-11e5-83b4-9cf387a8033e<commit_after>f24a3459-327f-11e5-83b4-9cf387a8033e<|endoftext|> |
<commit_before>256025f8-2e4f-11e5-852a-28cfe91dbc4b<commit_msg>2566f74a-2e4f-11e5-982d-28cfe91dbc4b<commit_after>2566f74a-2e4f-11e5-982d-28cfe91dbc4b<|endoftext|> |
<commit_before>85627994-2d15-11e5-af21-0401358ea401<commit_msg>85627995-2d15-11e5-af21-0401358ea401<commit_after>85627995-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>9c6440d9-ad5c-11e7-bdd9-ac87a332f658<commit_msg>NO CHANGES<commit_after>9cdbaa9e-ad5c-11e7-a1be-ac87a332f658<|endoftext|> |
<commit_before>cb1e5052-35ca-11e5-9ab8-6c40088e03e4<commit_msg>cb24bd9a-35ca-11e5-a62e-6c40088e03e4<commit_after>cb24bd9a-35ca-11e5-a62e-6c40088e03e4<|endoftext|> |
<commit_before>c7c0c917-2747-11e6-a919-e0f84713e7b8<commit_msg>Put the thingie in the thingie<commit_after>c7db5c99-2747-11e6-8f5c-e0f84713e7b8<|endoftext|> |
<commit_before>5a460ec5-2e4f-11e5-a225-28cfe91dbc4b<commit_msg>5a4e2d66-2e4f-11e5-adfd-28cfe91dbc4b<commit_after>5a4e2d66-2e4f-11e5-adfd-28cfe91dbc4b<|endoftext|> |
<commit_before>34c0d1f5-ad5b-11e7-9130-ac87a332f658<commit_msg>fix for the previous fix<commit_after>3530afb3-ad5b-11e7-9b87-ac87a332f658<|endoftext|> |
<commit_before>95953887-4b02-11e5-bb1f-28cfe9171a43<commit_msg>I am finally done<commit_after>95a21e5c-4b02-11e5-96dc-28cfe9171a43<|endoftext|> |
<commit_before>809e9204-2d15-11e5-af21-0401358ea401<commit_msg>809e9205-2d15-11e5-af21-0401358ea401<commit_after>809e9205-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>8431fc3d-2d15-11e5-af21-0401358ea401<commit_msg>8431fc3e-2d15-11e5-af21-0401358ea401<commit_after>8431fc3e-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>ec3598ec-585a-11e5-925a-6c40088e03e4<commit_msg>ec3bf21e-585a-11e5-98f2-6c40088e03e4<commit_after>ec3bf21e-585a-11e5-98f2-6c40088e03e4<|endoftext|> |
<commit_before>c7e55188-35ca-11e5-8d2b-6c40088e03e4<commit_msg>c7ebd8dc-35ca-11e5-8d3c-6c40088e03e4<commit_after>c7ebd8dc-35ca-11e5-8d3c-6c40088e03e4<|endoftext|> |
<commit_before>/* main.cpp
*
* Copyright (c) 2011, 2012 Chantilly Robotics <chantilly612@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Implement robot_class to provide functionality for robot.
*/
#include "612.h"
#include "main.h"
#include "ports.h"
#include "update.h"
#include "vision/vision_processing.h"
#include "state_tracker.h"
#include "visionalg.h"
//constructor - initialize drive
robot_class::robot_class() {
//do nothing
GetWatchdog().SetEnabled(false); //we don't want Watchdog
}
void robot_class::RobotInit() {
//Run-Time INIT
//set necessary inversions
drive.SetInvertedMotor(left_front_motor.type, left_front_motor.reverse);
drive.SetInvertedMotor(left_rear_motor.type, left_rear_motor.reverse);
drive.SetInvertedMotor(right_front_motor.type, right_front_motor.reverse);
drive.SetInvertedMotor(right_rear_motor.type, right_rear_motor.reverse);
init_camera();
}
void robot_class::DisabledInit() {
//do nothing
}
void robot_class::AutonomousInit() {
//do nothing
}
void robot_class::TeleopInit() {
//do nothing
}
void robot_class::DisabledPeriodic() {
//do nothing
}
void robot_class::AutonomousPeriodic() {
update_sensors();
}
void robot_class::TeleopPeriodic() {
update_sensors();
}
void robot_class::DisabledContinuous() {
//do nothing
}
void robot_class::AutonomousContinuous() {
//do nothing
}
void robot_class::TeleopContinuous() {
if(global_state.get_state() == STATE_DRIVING) {
if (left_joystick.GetRawButton(1)) {
//arcade drive
drive.ArcadeDrive(left_joystick); //arcade drive on left joystick
}
else {
//tank drive
float left = left_joystick.GetY();
float right = right_joystick.GetY();
//explicitly state drive power is based on Y axis of that side joy
drive.TankDrive(left, right);
}
if (left_joystick.GetRawButton(11)) {
right_servo_shift.Set(0.7);
left_servo_shift.Set(0.7);
// set servo to high gear
}
else if (left_joystick.GetRawButton(10)) {
right_servo_shift.Set(0.3);
left_servo_shift.Set(0.3);
//Sets servo to low gear
}
}
//stuff goes under
if (left_joystick.GetRawButton(3)) {
left_launcher_jag.Set(0.1);
right_launcher_jag.Set(0.1);
}
//stuff goes over
else if(global_state.get_state() == STATE_AIMING) {
// disable motor safety check to stop wasting netconsole space
drive.SetSafetyEnabled(false);
ColorImage* camera_image = vision_processing::get_image();
vector<double> target_degrees = vision_processing::get_degrees_from_image(camera_image);
vector<double> target_distances = vision_processing::get_distance_from_image(camera_image);
// printf("Angle (degrees) of camera: %f", target_degrees[vision_processing::determine_aim_target_from_image(vision_processing::get_image())]);
if(target_degrees.size() >= 1) {
printf("Angle (degrees) of camera: %f\n", target_degrees[0]);
}
else {
printf("No target detected\n");
}
if(target_distances.size() >= 1) {
printf("Distance of target: %f\n", target_distances[0]);
}
if(!left_joystick.GetRawButton(3)) {
global_state.set_state(STATE_DRIVING);
drive.SetSafetyEnabled(true);
}
}
if(global_state.get_state() != STATE_AIMING) {
Wait(0.005); //let the CPU rest a little - 5 ms isn't too long
}
}
void robot_class::update_sensors() {
//run functions in update registry
registry().update();
}
//the following macro tells the library that we want to generate code
//for our class robot_class
START_ROBOT_CLASS(robot_class);
<commit_msg>Moved If Statement<commit_after>/* main.cpp
*
* Copyright (c) 2011, 2012 Chantilly Robotics <chantilly612@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Implement robot_class to provide functionality for robot.
*/
#include "612.h"
#include "main.h"
#include "ports.h"
#include "update.h"
#include "vision/vision_processing.h"
#include "state_tracker.h"
#include "visionalg.h"
//constructor - initialize drive
robot_class::robot_class() {
//do nothing
GetWatchdog().SetEnabled(false); //we don't want Watchdog
}
void robot_class::RobotInit() {
//Run-Time INIT
//set necessary inversions
drive.SetInvertedMotor(left_front_motor.type, left_front_motor.reverse);
drive.SetInvertedMotor(left_rear_motor.type, left_rear_motor.reverse);
drive.SetInvertedMotor(right_front_motor.type, right_front_motor.reverse);
drive.SetInvertedMotor(right_rear_motor.type, right_rear_motor.reverse);
init_camera();
}
void robot_class::DisabledInit() {
//do nothing
}
void robot_class::AutonomousInit() {
//do nothing
}
void robot_class::TeleopInit() {
//do nothing
}
void robot_class::DisabledPeriodic() {
//do nothing
}
void robot_class::AutonomousPeriodic() {
update_sensors();
}
void robot_class::TeleopPeriodic() {
update_sensors();
}
void robot_class::DisabledContinuous() {
//do nothing
}
void robot_class::AutonomousContinuous() {
//do nothing
}
void robot_class::TeleopContinuous() {
if(global_state.get_state() == STATE_DRIVING) {
if (left_joystick.GetRawButton(1)) {
//arcade drive
drive.ArcadeDrive(left_joystick); //arcade drive on left joystick
}
else {
//tank drive
float left = left_joystick.GetY();
float right = right_joystick.GetY();
//explicitly state drive power is based on Y axis of that side joy
drive.TankDrive(left, right);
}
if (left_joystick.GetRawButton(11)) {
right_servo_shift.Set(0.7);
left_servo_shift.Set(0.7);
// set servo to high gear
}
else if (left_joystick.GetRawButton(10)) {
right_servo_shift.Set(0.3);
left_servo_shift.Set(0.3);
//Sets servo to low gear
}
}
else if(global_state.get_state() == STATE_AIMING) {
// disable motor safety check to stop wasting netconsole space
drive.SetSafetyEnabled(false);
ColorImage* camera_image = vision_processing::get_image();
vector<double> target_degrees = vision_processing::get_degrees_from_image(camera_image);
vector<double> target_distances = vision_processing::get_distance_from_image(camera_image);
// printf("Angle (degrees) of camera: %f", target_degrees[vision_processing::determine_aim_target_from_image(vision_processing::get_image())]);
if(target_degrees.size() >= 1) {
printf("Angle (degrees) of camera: %f\n", target_degrees[0]);
}
else {
printf("No target detected\n");
}
if(target_distances.size() >= 1) {
printf("Distance of target: %f\n", target_distances[0]);
}
if(!left_joystick.GetRawButton(3)) {
global_state.set_state(STATE_DRIVING);
drive.SetSafetyEnabled(true);
}
}
//stuff goes under
if (left_joystick.GetRawButton(3)) {
left_launcher_jag.Set(0.1);
right_launcher_jag.Set(0.1);
}
//stuff goes over
if(global_state.get_state() != STATE_AIMING) {
Wait(0.005); //let the CPU rest a little - 5 ms isn't too long
}
}
void robot_class::update_sensors() {
//run functions in update registry
registry().update();
}
//the following macro tells the library that we want to generate code
//for our class robot_class
START_ROBOT_CLASS(robot_class);
<|endoftext|> |
<commit_before>6c31f1b4-2fa5-11e5-922c-00012e3d3f12<commit_msg>6c341494-2fa5-11e5-be6b-00012e3d3f12<commit_after>6c341494-2fa5-11e5-be6b-00012e3d3f12<|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include <array>
#include <SFML/Graphics.hpp>
#define WIDTH 640
#define HEIGHT 480
//french : fortune, aptitude, maitrise, infortune, difficulte, defi
enum DiceType {BOOST, ABILITY, PROFICIENCY, SETBACK, DIFFICULTY, CHALLENGE, D100};
enum ResultType {EMPTY, MINOR, MAJOR, MASSIVE, DOUBLE_MINOR, DOUBLE_MAJOR, MIXED};
//these tables are used to correspond to the actual placement in the real dices
// 1 2 3 4 5 6 7 8 9 10 11 12
const int boostResult[] = {EMPTY, DOUBLE_MINOR, MINOR, MAJOR, MIXED, EMPTY};
const int abilityResult[] = {EMPTY, DOUBLE_MAJOR, MINOR, MAJOR, MAJOR, MINOR, DOUBLE_MINOR, MIXED};
const int proficiencyResult[] = {EMPTY, MIXED, DOUBLE_MINOR, MIXED, MAJOR, MAJOR, MAJOR, MAJOR, MINOR, DOUBLE_MINOR, MIXED, MASSIVE};
const int setbackResult[] = {EMPTY, MAJOR, MINOR, MINOR, MAJOR, EMPTY};
const int difficultyResult[] = {EMPTY, MINOR, MIXED, DOUBLE_MAJOR, MINOR, MINOR, DOUBLE_MINOR, MAJOR};
const int challengeResult[] = {MASSIVE, DOUBLE_MINOR, DOUBLE_MAJOR, MAJOR, DOUBLE_MAJOR, MINOR, MAJOR, MINOR, DOUBLE_MINOR, MIXED, MIXED, EMPTY};
const int diceSize = 139;
void drawDice(sf::RenderTarget& target, int x, int y, sf::RectangleShape& dice, DiceType type, ResultType result, float scale)
{
dice.setScale(scale, scale);
dice.setPosition(x, y);
dice.setTextureRect(sf::IntRect(type*diceSize, type*diceSize, diceSize, diceSize));
target.draw(dice);
}
int main(int argc, char** argv)
{
/** SFML STUFF **/
sf::RenderWindow window(sf::VideoMode(WIDTH, HEIGHT), "SW FaD Dice Roller");
sf::Font font;
if(!font.loadFromFile("data\\Rebellion.otf"))
{
std::cerr << "Impossible to load font" << std::endl;
return -1;
}
sf::Texture diceTexture;
if(!diceTexture.loadFromFile("data\\dices.png"))
{
std::cerr << "Impossible to load dice picture" << std::endl;
return -1;
}
sf::RectangleShape rectangle;
rectangle.setSize(sf::Vector2f(diceSize, diceSize));
float scale = 0.3f;
rectangle.setScale(scale,scale);
rectangle.setTexture(&diceTexture);
rectangle.setTextureRect(sf::IntRect(0,0,diceSize,diceSize));
int x = 0;
int y = 0;
int diceCount[MIXED + 1] = { 0 };
//the loop
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
else if (event.type == sf::Event::KeyPressed || event.type == sf::Event::KeyReleased)
{
switch (event.key.code)
{
case sf::Keyboard::Escape:
window.close();
break;
}
}
else if (event.type == sf::Event::MouseButtonPressed)
{
//event.mouseButton.x, event.mouseButton.y
}
else if (event.type == sf::Event::MouseButtonReleased)
{
}
}
window.clear(sf::Color(127,127,127));
drawDice(window, 0, 0, rectangle, DiceType(x), ResultType(y), 0.3);
window.display();
++x;
if(x > CHALLENGE)
{
x = 0;
++y;
if(y > MIXED)
{
y = 0;
}
}
sf::sleep(sf::milliseconds(100));
}
return 0;
}
<commit_msg>Basic UI with magic numbers<commit_after>#include <iostream>
#include <sstream>
#include <array>
#include <SFML/Graphics.hpp>
#define WIDTH 640
#define HEIGHT 480
//french : fortune, aptitude, maitrise, infortune, difficulte, defi
enum DiceType {BOOST, ABILITY, PROFICIENCY, SETBACK, DIFFICULTY, CHALLENGE, D100};
enum ResultType {EMPTY, MINOR, MAJOR, MASSIVE, DOUBLE_MINOR, DOUBLE_MAJOR, MIXED};
//these tables are used to correspond to the actual placement in the real dices
// 1 2 3 4 5 6 7 8 9 10 11 12
const int boostResult[] = {EMPTY, DOUBLE_MINOR, MINOR, MAJOR, MIXED, EMPTY};
const int abilityResult[] = {EMPTY, DOUBLE_MAJOR, MINOR, MAJOR, MAJOR, MINOR, DOUBLE_MINOR, MIXED};
const int proficiencyResult[] = {EMPTY, MIXED, DOUBLE_MINOR, MIXED, MAJOR, MAJOR, MAJOR, MAJOR, MINOR, DOUBLE_MINOR, MIXED, MASSIVE};
const int setbackResult[] = {EMPTY, MAJOR, MINOR, MINOR, MAJOR, EMPTY};
const int difficultyResult[] = {EMPTY, MINOR, MIXED, DOUBLE_MAJOR, MINOR, MINOR, DOUBLE_MINOR, MAJOR};
const int challengeResult[] = {MASSIVE, DOUBLE_MINOR, DOUBLE_MAJOR, MAJOR, DOUBLE_MAJOR, MINOR, MAJOR, MINOR, DOUBLE_MINOR, MIXED, MIXED, EMPTY};
const int diceSize = 139;
const sf::Color diceColors[] = { {194,227,238}, {65,167,21}, {248,240,53}, {53,53,53}, {38,0,70}, {234,0,0}, { 250, 250, 180 } };
const float uiScale = 0.5f;
const sf::Vector2f delta(10, 10);
const sf::Color buttonColor(190, 150, 70);
void drawDice(sf::RenderTarget& target, int x, int y, sf::RectangleShape& dice, DiceType type, ResultType result, float scale = 1.0f)
{
dice.setScale(scale, scale);
dice.setPosition((float)x, (float)y);
dice.setTextureRect(sf::IntRect(type*diceSize, result*diceSize, diceSize, diceSize));
target.draw(dice);
}
void drawD100(sf::RenderTarget& target, int x, int y, sf::ConvexShape& shape, float scale = 1.0f)
{
shape.setScale(scale, scale);
shape.setPosition((float)x, (float)y);
target.draw(shape);
}
void drawArrow(sf::RenderTarget& target, sf::ConvexShape& arrow, int x, int y, sf::Color color, bool up)
{
arrow.setFillColor(color);
arrow.setPosition((float)x, (float)y);
arrow.setScale(1.0f, up ? 1.0f : -1.0f);
target.draw(arrow);
}
void drawUi(sf::RenderTarget& target, sf::ConvexShape& d100, sf::RectangleShape& dices, sf::ConvexShape& arrow)
{
drawD100(target, (int)(diceSize*uiScale / 2.0f + delta.x), (int)(diceSize*uiScale + delta.y*2) , d100, uiScale);
for (int i = 0; i < D100; ++i)
{
drawDice(target, (int)((i+1.5f)*(diceSize*uiScale + delta.x)), (int)(diceSize*uiScale + delta.y*2), dices, DiceType(i), EMPTY, uiScale);
}
drawArrow(target, arrow, (int)(diceSize*uiScale / 2.0f + delta.x), (int)(delta.y - arrow.getPoint(0).y), diceColors[D100], true);
drawArrow(target, arrow, (int)(diceSize*uiScale / 2.0f + delta.x), (int)(3*delta.y - arrow.getPoint(0).y + diceSize*uiScale), diceColors[D100], false);
for (int i = 0; i < D100; ++i)
{
drawArrow(target, arrow, (int)((i + 1.5f)*(diceSize*uiScale + delta.x)), (int)(delta.y - arrow.getPoint(0).y), diceColors[i], true);
drawArrow(target, arrow, (int)((i + 1.5f)*(diceSize*uiScale + delta.x)), (int)(3 * delta.y - arrow.getPoint(0).y + diceSize*uiScale), diceColors[i], false);
}
sf::RectangleShape button;
button.setSize(sf::Vector2f(139.0f, 139.0f / 2.0f));
button.setOrigin(button.getSize() / 2.0f);
button.setScale(uiScale, uiScale);
button.setFillColor(buttonColor);
//button reset
button.setPosition(WIDTH - delta.x - button.getSize().x / 2.0f * uiScale, (int)(diceSize*uiScale - delta.y*(1 + uiScale)));
target.draw(button);
//button Roll
button.setPosition(WIDTH - delta.x - button.getSize().x / 2.0f * uiScale, (int)(diceSize*uiScale + delta.y*(5 + uiScale)));
target.draw(button);
}
int main(int argc, char** argv)
{
/** SFML STUFF **/
sf::RenderWindow window(sf::VideoMode(WIDTH, HEIGHT), "SW FaD Dice Roller");
sf::Font font;
if(!font.loadFromFile("data\\Rebellion.otf"))
{
std::cerr << "Impossible to load font" << std::endl;
return -1;
}
sf::Texture diceTexture;
if(!diceTexture.loadFromFile("data\\dices.png"))
{
std::cerr << "Impossible to load dice picture" << std::endl;
return -1;
}
sf::RectangleShape diceSheet;
diceSheet.setSize(sf::Vector2f((float)diceSize, (float)diceSize));
diceSheet.setTexture(&diceTexture);
diceSheet.setTextureRect(sf::IntRect(0,0,diceSize,diceSize));
diceSheet.setOrigin(sf::Vector2f(diceSize / 2.0f, diceSize / 2.0f));
sf::ConvexShape d100Shape;
d100Shape.setPointCount(4);
d100Shape.setPoint(0, sf::Vector2f(0, -66));
d100Shape.setPoint(1, sf::Vector2f(66, 0));
d100Shape.setPoint(2, sf::Vector2f(0, 66));
d100Shape.setPoint(3, sf::Vector2f(-66, 0));
d100Shape.setFillColor(sf::Color(250, 250, 180));
sf::ConvexShape arrow;
arrow.setPointCount(3);
arrow.setPoint(0, sf::Vector2f(0, -33));
arrow.setPoint(1, sf::Vector2f(20, 0));
arrow.setPoint(2, sf::Vector2f(-20, 0));
int dicesToThrow[D100 + 1] = { 0 };
float uiScale = 0.5f;
//the loop
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
else if (event.type == sf::Event::KeyPressed || event.type == sf::Event::KeyReleased)
{
switch (event.key.code)
{
case sf::Keyboard::Escape:
window.close();
break;
}
}
else if (event.type == sf::Event::MouseButtonPressed)
{
//event.mouseButton.x, event.mouseButton.y
}
else if (event.type == sf::Event::MouseButtonReleased)
{
}
}
window.clear(sf::Color(30,30,30));
drawUi(window, d100Shape, diceSheet, arrow);
window.display();
sf::sleep(sf::milliseconds(100));
}
return 0;
}
<|endoftext|> |
<commit_before>12296a48-2f67-11e5-a472-6c40088e03e4<commit_msg>1230564c-2f67-11e5-8e7e-6c40088e03e4<commit_after>1230564c-2f67-11e5-8e7e-6c40088e03e4<|endoftext|> |
<commit_before>e9f2d199-2e4e-11e5-b3d1-28cfe91dbc4b<commit_msg>e9faebf8-2e4e-11e5-ae2d-28cfe91dbc4b<commit_after>e9faebf8-2e4e-11e5-ae2d-28cfe91dbc4b<|endoftext|> |
<commit_before>dba086dc-313a-11e5-8d55-3c15c2e10482<commit_msg>dba6dd99-313a-11e5-8789-3c15c2e10482<commit_after>dba6dd99-313a-11e5-8789-3c15c2e10482<|endoftext|> |
<commit_before>273742d8-2e3a-11e5-aaab-c03896053bdd<commit_msg>274b91de-2e3a-11e5-b2c3-c03896053bdd<commit_after>274b91de-2e3a-11e5-b2c3-c03896053bdd<|endoftext|> |
<commit_before>276a7468-2f67-11e5-8095-6c40088e03e4<commit_msg>27717146-2f67-11e5-9432-6c40088e03e4<commit_after>27717146-2f67-11e5-9432-6c40088e03e4<|endoftext|> |
<commit_before>/**
Copyright 2014 PotcFdk
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/
#include <iostream>
#include <fEEAt.hpp>
using namespace std;
using namespace fEEAt;
int main()
{
uint64_t a = 639826407500980799, b = 4848944590680906856;
EEAResult * result = eea(a, b);
cout << "Using numbers " << a << ", " << b << ":" << endl << endl
///
<< "gcd: " << result->gcd << endl
<< "s: " << result->s << endl
<< "t: " << result->t << endl
///
<< endl << result->s << " * " << a
<< " + " << result->t << " * " << b
<< " = " << result->gcd << endl;
return 0;
}
<commit_msg>Added interactive mode.<commit_after>/**
Copyright 2014 PotcFdk
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/
#include <iostream>
#include <fEEAt.hpp>
using namespace std;
using namespace fEEAt;
int main()
{
cout << "fEEAt." << endl << "=======" << endl << endl;
int64_t a, b;
while (true)
{
cout << "> a = ";
cin >> a;
cout << "> b = ";
cin >> b;
EEAResult * result = eea(a, b);
cout << endl
<< " gcd = " << result->gcd << endl
<< " s = " << result->s << " (= " << a << "^-1 mod " << b << ")" << endl
<< " t = " << result->t << endl
///
<< endl << ' ' << result->s << " * " << a
<< " + " << result->t << " * " << b
<< " = " << result->gcd << endl << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>016b147a-2e4f-11e5-b7e5-28cfe91dbc4b<commit_msg>0171b775-2e4f-11e5-ab9a-28cfe91dbc4b<commit_after>0171b775-2e4f-11e5-ab9a-28cfe91dbc4b<|endoftext|> |
<commit_before>052b3c90-2f67-11e5-b95f-6c40088e03e4<commit_msg>053244c0-2f67-11e5-884d-6c40088e03e4<commit_after>053244c0-2f67-11e5-884d-6c40088e03e4<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
int main(int argc, char const* argv[])
{
return 0;
}
<commit_msg>first implementation<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
namespace argparse {
class parser
{
public:
parser() = default;
~parser() = default;
void parse(int argc, char const** argv)
{
prog_name_.assign(argv[0]);
for (int i = 1; i < argc; ++i) {
remains_.emplace_back(argv[i]);
}
short_options_['a'] = "hogehoge";
long_options_["fuga"] = "foo";
}
void dump_result() const {
std::cout << "Program name: " << prog_name_ << std::endl;
std::cout << "short options: " << std::endl;
for (auto& itm: short_options_) {
std::cout << " - " << itm.second << " (-" << itm.first << ")\n";
}
std::cout << "long options: " << std::endl;
for (auto& itm: long_options_) {
std::cout << " - " << itm.second << " (--" << itm.first << ")\n";
}
std::cout << "Remaining arguments: " << std::endl;
for (auto& itm: remains_) {
std::cout << " - " << itm << std::endl;
}
}
private:
// parsed options
std::string prog_name_;
std::unordered_map<char, std::string> short_options_;
std::unordered_map<std::string, std::string> long_options_;
std::vector<std::string> remains_;
};
} // namespace argparse;
int main(int argc, char const* argv[])
{
argparse::parser parser;
parser.parse(argc, argv);
parser.dump_result();
}
<|endoftext|> |
<commit_before>bb808ffa-35ca-11e5-b88c-6c40088e03e4<commit_msg>bb8734b0-35ca-11e5-8571-6c40088e03e4<commit_after>bb8734b0-35ca-11e5-8571-6c40088e03e4<|endoftext|> |
<commit_before>ba5d93f0-327f-11e5-b07c-9cf387a8033e<commit_msg>ba64abe1-327f-11e5-a2c3-9cf387a8033e<commit_after>ba64abe1-327f-11e5-a2c3-9cf387a8033e<|endoftext|> |
<commit_before>333469ca-2e4f-11e5-83a9-28cfe91dbc4b<commit_msg>333b32a8-2e4f-11e5-a05a-28cfe91dbc4b<commit_after>333b32a8-2e4f-11e5-a05a-28cfe91dbc4b<|endoftext|> |
<commit_before>// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <fstream>
#include <iostream>
#include <map>
#include <spii/auto_diff_term.h>
#include <spii/dynamic_auto_diff_term.h>
#include <spii/large_auto_diff_term.h>
#include <spii/function.h>
#include <spii/solver.h>
#include <spii/term.h>
#include "util.hpp"
#include "functionsimhash.hpp"
#include "simhashtrainer.hpp"
#include "trainingdata.hpp"
using namespace std;
void CalculateHashStats(TrainingData* data, FunctionSimHasher* not_trained,
FunctionSimHasher* trained, std::vector<std::pair<uint32_t, uint32_t>>* pairs,
double* trained_mean, double* untrained_mean) {
// Calculate the hashes for all elements in the attraction set.
for (const auto& pair : *pairs) {
std::vector<FeatureHash> features_A;
std::vector<FeatureHash> features_B;
for (uint32_t index : data->GetFunctions()->at(pair.first)) {
features_A.push_back(data->GetFeaturesVector()->at(index));
}
for (uint32_t index : data->GetFunctions()->at(pair.second)) {
features_B.push_back(data->GetFeaturesVector()->at(index));
}
std::vector<uint64_t> function_A_hash_trained;
std::vector<uint64_t> function_B_hash_trained;
std::vector<uint64_t> function_A_hash_untrained;
std::vector<uint64_t> function_B_hash_untrained;
// Calculate the hashes for the trained version.
trained->CalculateFunctionSimHash(
&features_A, &function_A_hash_trained);
trained->CalculateFunctionSimHash(
&features_B, &function_B_hash_trained);
// Calculate the hashes for the untrained version.
not_trained->CalculateFunctionSimHash(
&features_A, &function_A_hash_untrained);
not_trained->CalculateFunctionSimHash(
&features_B, &function_B_hash_untrained);
uint32_t hamming_trained = HammingDistance(function_A_hash_trained[0],
function_A_hash_trained[1], function_B_hash_trained[0],
function_B_hash_trained[1]);
uint32_t hamming_untrained = HammingDistance(function_A_hash_untrained[0],
function_A_hash_untrained[1], function_B_hash_untrained[0],
function_B_hash_untrained[1]);
*trained_mean += hamming_trained;
*untrained_mean += hamming_untrained;
}
*trained_mean /= pairs->size();
*untrained_mean /= pairs->size();
}
// The code expects the following files to be present inside the data directory
// (which is passed in as first argument):
//
// functions.txt - a text file formed by concatenating the output of the
// functionfingerprints tool in verbose mode. Each line starts
// with [file_id]:[address], and is followed by the various
// features that make up the function.
// attract.txt - a file with pairs of [file_id]:[address] [file_id]:[address]
// indicating which functions should be the same.
// repulse.txt - a file with pairs of [file_id]:[address] [file_id]:[address]
// indicating which functions should NOT be the same.
//
// It also expects a weights file to evaluate against the data in question.
int main(int argc, char** argv) {
if (argc != 3) {
printf("Evaluate a weights file against labelled data.\n");
printf("Usage: %s <data directory> <weights file>\n", argv[0]);
printf("Refer to the source code of this utility for detailed usage.\n");
return -1;
}
std::string directory(argv[1]);
std::string outputfile(argv[2]);
TrainingData data(directory);
if (!data.Load()) {
printf("[!] Failure to load the training data, exiting.\n");
return -1;
}
printf("[!] Training data parsed, beginning the evaluation process.\n");
// Training has been performed. Instantiate two FunctionSimHasher, one with
// the new weights, one without.
FunctionSimHasher hash_no_weight("", false);
FunctionSimHasher hash_weights(outputfile, false);
double attraction_mean_trained = 0;
double attraction_mean_untrained = 0;
CalculateHashStats(&data, &hash_no_weight, &hash_weights,
data.GetAttractionSet(), &attraction_mean_trained,
&attraction_mean_untrained);
double repulsion_mean_trained = 0;
double repulsion_mean_untrained = 0;
CalculateHashStats(&data, &hash_no_weight, &hash_weights,
data.GetAttractionSet(), &repulsion_mean_trained,
&repulsion_mean_untrained);
printf("Attraction mean trained: %.10e\n", attraction_mean_trained);
printf("Attraction mean untrained: %.10e\n", attraction_mean_untrained);
printf("Repulsion mean trained: %.10e\n", repulsion_mean_trained);
printf("Repulsion mean untrained: %.10e\n", repulsion_mean_untrained);
}
<commit_msg>Fixed a silly bug where statistics were calculated on the same set instead of repulsion & attraction sets<commit_after>// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <fstream>
#include <iostream>
#include <map>
#include <spii/auto_diff_term.h>
#include <spii/dynamic_auto_diff_term.h>
#include <spii/large_auto_diff_term.h>
#include <spii/function.h>
#include <spii/solver.h>
#include <spii/term.h>
#include "util.hpp"
#include "functionsimhash.hpp"
#include "simhashtrainer.hpp"
#include "trainingdata.hpp"
using namespace std;
void CalculateHashStats(TrainingData* data, FunctionSimHasher* not_trained,
FunctionSimHasher* trained, std::vector<std::pair<uint32_t, uint32_t>>* pairs,
double* trained_mean, double* untrained_mean) {
// Calculate the hashes for all elements in the attraction set.
for (const auto& pair : *pairs) {
std::vector<FeatureHash> features_A;
std::vector<FeatureHash> features_B;
for (uint32_t index : data->GetFunctions()->at(pair.first)) {
features_A.push_back(data->GetFeaturesVector()->at(index));
}
for (uint32_t index : data->GetFunctions()->at(pair.second)) {
features_B.push_back(data->GetFeaturesVector()->at(index));
}
std::vector<uint64_t> function_A_hash_trained;
std::vector<uint64_t> function_B_hash_trained;
std::vector<uint64_t> function_A_hash_untrained;
std::vector<uint64_t> function_B_hash_untrained;
// Calculate the hashes for the trained version.
trained->CalculateFunctionSimHash(
&features_A, &function_A_hash_trained);
trained->CalculateFunctionSimHash(
&features_B, &function_B_hash_trained);
// Calculate the hashes for the untrained version.
not_trained->CalculateFunctionSimHash(
&features_A, &function_A_hash_untrained);
not_trained->CalculateFunctionSimHash(
&features_B, &function_B_hash_untrained);
uint32_t hamming_trained = HammingDistance(function_A_hash_trained[0],
function_A_hash_trained[1], function_B_hash_trained[0],
function_B_hash_trained[1]);
uint32_t hamming_untrained = HammingDistance(function_A_hash_untrained[0],
function_A_hash_untrained[1], function_B_hash_untrained[0],
function_B_hash_untrained[1]);
printf("Trained Hamming distance: %d Untrained: %d\n", hamming_trained,
hamming_untrained);
*trained_mean += hamming_trained;
*untrained_mean += hamming_untrained;
}
*trained_mean /= pairs->size();
*untrained_mean /= pairs->size();
}
// The code expects the following files to be present inside the data directory
// (which is passed in as first argument):
//
// functions.txt - a text file formed by concatenating the output of the
// functionfingerprints tool in verbose mode. Each line starts
// with [file_id]:[address], and is followed by the various
// features that make up the function.
// attract.txt - a file with pairs of [file_id]:[address] [file_id]:[address]
// indicating which functions should be the same.
// repulse.txt - a file with pairs of [file_id]:[address] [file_id]:[address]
// indicating which functions should NOT be the same.
//
// It also expects a weights file to evaluate against the data in question.
int main(int argc, char** argv) {
if (argc != 3) {
printf("Evaluate a weights file against labelled data.\n");
printf("Usage: %s <data directory> <weights file>\n", argv[0]);
printf("Refer to the source code of this utility for detailed usage.\n");
return -1;
}
std::string directory(argv[1]);
std::string outputfile(argv[2]);
TrainingData data(directory);
if (!data.Load()) {
printf("[!] Failure to load the training data, exiting.\n");
return -1;
}
printf("[!] Training data parsed, beginning the evaluation process.\n");
// Training has been performed. Instantiate two FunctionSimHasher, one with
// the new weights, one without.
FunctionSimHasher hash_no_weight("", false);
FunctionSimHasher hash_weights(outputfile, false);
double attraction_mean_trained = 0;
double attraction_mean_untrained = 0;
CalculateHashStats(&data, &hash_no_weight, &hash_weights,
data.GetAttractionSet(), &attraction_mean_trained,
&attraction_mean_untrained);
double repulsion_mean_trained = 0;
double repulsion_mean_untrained = 0;
CalculateHashStats(&data, &hash_no_weight, &hash_weights,
data.GetRepulsionSet(), &repulsion_mean_trained,
&repulsion_mean_untrained);
printf("Attraction mean trained: %.10e\n", attraction_mean_trained);
printf("Attraction mean untrained: %.10e\n", attraction_mean_untrained);
printf("Repulsion mean trained: %.10e\n", repulsion_mean_trained);
printf("Repulsion mean untrained: %.10e\n", repulsion_mean_untrained);
}
<|endoftext|> |
<commit_before>79206e70-2e4f-11e5-93f5-28cfe91dbc4b<commit_msg>79273dae-2e4f-11e5-97e1-28cfe91dbc4b<commit_after>79273dae-2e4f-11e5-97e1-28cfe91dbc4b<|endoftext|> |
<commit_before>
#include "qv4isel_masm_p.h"
#include "qmljs_runtime.h"
#include "qmljs_objects.h"
#include <assembler/LinkBuffer.h>
#include <sys/mman.h>
#include <iostream>
#include <cassert>
#ifndef NO_UDIS86
# include <udis86.h>
#endif
using namespace QQmlJS;
using namespace QQmlJS::MASM;
using namespace QQmlJS::VM;
namespace {
QTextStream qout(stdout, QIODevice::WriteOnly);
}
InstructionSelection::InstructionSelection(VM::ExecutionEngine *engine, IR::Module *module, uchar *buffer)
: _engine(engine)
, _module(module)
, _function(0)
, _block(0)
, _buffer(buffer)
, _code(buffer)
, _codePtr(buffer)
{
}
InstructionSelection::~InstructionSelection()
{
}
void InstructionSelection::operator()(IR::Function *function)
{
qSwap(_function, function);
enterStandardStackFrame();
int locals = (_function->tempCount - _function->locals.size() + _function->maxNumberOfArguments) * sizeof(Value);
locals = (locals + 15) & ~15;
sub32(TrustedImm32(locals), StackPointerRegister);
push(ContextRegister);
loadPtr(addressForArgument(0), ContextRegister);
foreach (IR::BasicBlock *block, _function->basicBlocks) {
_block = block;
_addrs[block] = label();
foreach (IR::Stmt *s, block->statements) {
s->accept(this);
}
}
pop(ContextRegister);
add32(TrustedImm32(locals), StackPointerRegister);
leaveStandardStackFrame();
ret();
QHashIterator<IR::BasicBlock *, QVector<Jump> > it(_patches);
while (it.hasNext()) {
it.next();
IR::BasicBlock *block = it.key();
Label target = _addrs.value(block);
assert(target.isSet());
foreach (Jump jump, it.value())
jump.linkTo(target, this);
}
JSC::JSGlobalData dummy;
JSC::LinkBuffer linkBuffer(dummy, this, 0);
foreach (CallToLink ctl, _callsToLink)
linkBuffer.link(ctl.call, ctl.externalFunction);
_function->codeRef = linkBuffer.finalizeCodeWithDisassembly("operator()(IR::Function*)");
_function->code = (void (*)(VM::Context *, const uchar *)) _function->codeRef.code().executableAddress();
qSwap(_function, function);
}
String *InstructionSelection::identifier(const QString &s)
{
return _engine->identifier(s);
}
JSC::MacroAssembler::Address InstructionSelection::loadTempAddress(RegisterID reg, IR::Temp *t)
{
int32_t offset = 0;
if (t->index < 0) {
const int arg = -t->index - 1;
loadPtr(Address(ContextRegister, offsetof(Context, arguments)), reg);
offset = arg * sizeof(Value);
} else if (t->index < _function->locals.size()) {
loadPtr(Address(ContextRegister, offsetof(Context, locals)), reg);
offset = t->index * sizeof(Value);
} else {
const int arg = _function->maxNumberOfArguments + t->index - _function->locals.size();
offset = sizeof(Value) * (-arg - 1)
- sizeof(void*); // size of ebp
reg = StackFrameRegister;
}
return Address(reg, offset);
}
void InstructionSelection::callActivationProperty(IR::Call *call, IR::Temp *result)
{
IR::Name *baseName = call->base->asName();
assert(baseName != 0);
int argc = 0;
for (IR::ExprList *it = call->args; it; it = it->next) {
++argc;
}
int i = 0;
for (IR::ExprList *it = call->args; it; it = it->next, ++i) {
IR::Temp *arg = it->expr->asTemp();
assert(arg != 0);
Address tempAddress = loadTempAddress(Gpr0, arg);
FunctionCall fc(this);
fc.addArgumentAsAddress(argumentAddressForCall(i));
fc.addArgumentAsAddress(tempAddress);
fc.call(__qmljs_copy);
}
FunctionCall activationCall(this);
activationCall.addArgumentFromRegister(ContextRegister);
if (result) {
activationCall.addArgumentAsAddress(loadTempAddress(Gpr0, result));
} else {
xor32(Gpr0, Gpr0);
activationCall.addArgumentFromRegister(Gpr0);
}
if (baseName->id) {
move(TrustedImmPtr(identifier(*baseName->id)), Gpr1);
activationCall.addArgumentFromRegister(Gpr1);
activationCall.addArgumentAsAddress(baseAddressForCallArguments());
activationCall.addArgumentByValue(TrustedImm32(argc));
activationCall.call(__qmljs_call_activation_property);
} else {
switch (baseName->builtin) {
case IR::Name::builtin_invalid:
Q_UNREACHABLE();
break;
case IR::Name::builtin_typeof:
activationCall.addArgumentAsAddress(baseAddressForCallArguments());
activationCall.addArgumentByValue(TrustedImm32(argc));
activationCall.call(__qmljs_builtin_typeof);
break;
case IR::Name::builtin_delete:
Q_UNREACHABLE();
break;
case IR::Name::builtin_throw:
activationCall.addArgumentAsAddress(baseAddressForCallArguments());
activationCall.addArgumentByValue(TrustedImm32(argc));
activationCall.call(__qmljs_builtin_throw);
break;
case IR::Name::builtin_rethrow:
activationCall.addArgumentAsAddress(baseAddressForCallArguments());
activationCall.addArgumentByValue(TrustedImm32(argc));
activationCall.call(__qmljs_builtin_rethrow);
return; // we need to return to avoid checking the exceptions
}
}
checkExceptions();
}
void InstructionSelection::callValue(IR::Call *call, IR::Temp *result)
{
}
void InstructionSelection::callProperty(IR::Call *call, IR::Temp *result)
{
}
void InstructionSelection::constructActivationProperty(IR::New *call, IR::Temp *result)
{
}
void InstructionSelection::constructProperty(IR::New *call, IR::Temp *result)
{
}
void InstructionSelection::constructValue(IR::New *call, IR::Temp *result)
{
}
void InstructionSelection::checkExceptions()
{
Address addr(ContextRegister, offsetof(Context, hasUncaughtException));
Jump jmp = branch8(Equal, addr, TrustedImm32(1));
_patches[_function->handlersBlock].append(jmp);
}
void InstructionSelection::visitExp(IR::Exp *s)
{
Q_UNIMPLEMENTED();
assert(!"TODO");
}
void InstructionSelection::visitEnter(IR::Enter *)
{
Q_UNIMPLEMENTED();
assert(!"TODO");
}
void InstructionSelection::visitLeave(IR::Leave *)
{
Q_UNIMPLEMENTED();
assert(!"TODO");
}
void InstructionSelection::visitMove(IR::Move *s)
{
if (s->op == IR::OpInvalid) {
if (IR::Name *n = s->target->asName()) {
String *propertyName = identifier(*n->id);
if (IR::Temp *t = s->source->asTemp()) {
FunctionCall fct(this);
fct.addArgumentFromRegister(ContextRegister);
move(TrustedImmPtr(propertyName), Gpr1);
fct.addArgumentFromRegister(Gpr1);
fct.addArgumentAsAddress(loadTempAddress(Gpr2, t));
fct.call(__qmljs_set_activation_property);
checkExceptions();
return;
} else {
Q_UNREACHABLE();
}
} else if (IR::Temp *t = s->target->asTemp()) {
if (IR::Name *n = s->source->asName()) {
Address temp = loadTempAddress(Gpr0, t);
FunctionCall fc(this);
fc.addArgumentFromRegister(ContextRegister);
fc.addArgumentAsAddress(temp);
if (*n->id == QStringLiteral("this")) { // ### `this' should be a builtin.
fc.call(__qmljs_get_thisObject);
} else {
String *propertyName = identifier(*n->id);
move(TrustedImmPtr(propertyName), Gpr1);
fc.addArgumentFromRegister(Gpr1);
fc.call(__qmljs_get_activation_property);
checkExceptions();
}
return;
} else if (IR::Const *c = s->source->asConst()) {
Address dest = loadTempAddress(Gpr0, t);
switch (c->type) {
case IR::NullType:
storeValue<Value::Null_Type>(TrustedImm32(0), dest);
break;
case IR::UndefinedType:
storeValue<Value::Undefined_Type>(TrustedImm32(0), dest);
break;
case IR::BoolType:
storeValue<Value::Boolean_Type>(TrustedImm32(c->value != 0), dest);
break;
case IR::NumberType:
// ### Taking address of pointer inside IR.
loadDouble(&c->value, FPGpr0);
storeDouble(FPGpr0, dest);
break;
default:
Q_UNIMPLEMENTED();
assert(!"TODO");
}
return;
} else if (IR::Closure *clos = s->source->asClosure()) {
FunctionCall fct(this);
fct.addArgumentFromRegister(ContextRegister);
fct.addArgumentAsAddress(loadTempAddress(Gpr0, t));
move(TrustedImmPtr(clos->value), Gpr1);
fct.addArgumentFromRegister(Gpr1);
fct.call(__qmljs_init_closure);
return;
} else if (IR::Call *c = s->source->asCall()) {
if (c->base->asName()) {
callActivationProperty(c, t);
return;
} else if (c->base->asMember()) {
callProperty(c, t);
return;
} else if (c->base->asTemp()) {
callValue(c, t);
return;
}
}
}
}
Q_UNIMPLEMENTED();
s->dump(qout, IR::Stmt::MIR);
qout << endl;
assert(!"TODO");
}
void InstructionSelection::visitJump(IR::Jump *s)
{
jumpToBlock(s->target);
}
void InstructionSelection::jumpToBlock(IR::BasicBlock *target)
{
if (_block->index + 1 != target->index)
_patches[target].append(jump());
}
void InstructionSelection::visitCJump(IR::CJump *s)
{
if (IR::Temp *t = s->cond->asTemp()) {
Address temp = loadTempAddress(Gpr1, t);
Address tag = temp;
tag.offset += offsetof(VM::ValueData, tag);
Jump booleanConversion = branch32(NotEqual, tag, TrustedImm32(VM::Value::Boolean_Type));
Address data = temp;
data.offset += offsetof(VM::ValueData, b);
load32(data, Gpr1);
Jump testBoolean = jump();
booleanConversion.link(this);
{
FunctionCall fct(this);
fct.addArgumentFromRegister(ContextRegister);
fct.addArgumentAsAddress(temp);
fct.call(__qmljs_to_boolean);
move(ReturnValueRegister, Gpr1);
}
testBoolean.link(this);
move(TrustedImm32(1), Gpr0);
Jump target = branch32(Equal, Gpr1, Gpr0);
_patches[s->iftrue].append(target);
jumpToBlock(s->iffalse);
return;
}
Q_UNIMPLEMENTED();
assert(!"TODO");
}
void InstructionSelection::visitRet(IR::Ret *s)
{
if (IR::Temp *t = s->expr->asTemp()) {
Address source = loadTempAddress(Gpr0, t);
Address result = Address(ContextRegister, offsetof(Context, result));
FunctionCall fc(this);
fc.addArgumentAsAddress(result);
fc.addArgumentAsAddress(source);
fc.call(__qmljs_copy);
return;
}
Q_UNIMPLEMENTED();
Q_UNUSED(s);
}
<commit_msg>Fix move temp -> temp<commit_after>
#include "qv4isel_masm_p.h"
#include "qmljs_runtime.h"
#include "qmljs_objects.h"
#include <assembler/LinkBuffer.h>
#include <sys/mman.h>
#include <iostream>
#include <cassert>
#ifndef NO_UDIS86
# include <udis86.h>
#endif
using namespace QQmlJS;
using namespace QQmlJS::MASM;
using namespace QQmlJS::VM;
namespace {
QTextStream qout(stdout, QIODevice::WriteOnly);
}
InstructionSelection::InstructionSelection(VM::ExecutionEngine *engine, IR::Module *module, uchar *buffer)
: _engine(engine)
, _module(module)
, _function(0)
, _block(0)
, _buffer(buffer)
, _code(buffer)
, _codePtr(buffer)
{
}
InstructionSelection::~InstructionSelection()
{
}
void InstructionSelection::operator()(IR::Function *function)
{
qSwap(_function, function);
enterStandardStackFrame();
int locals = (_function->tempCount - _function->locals.size() + _function->maxNumberOfArguments) * sizeof(Value);
locals = (locals + 15) & ~15;
sub32(TrustedImm32(locals), StackPointerRegister);
push(ContextRegister);
loadPtr(addressForArgument(0), ContextRegister);
foreach (IR::BasicBlock *block, _function->basicBlocks) {
_block = block;
_addrs[block] = label();
foreach (IR::Stmt *s, block->statements) {
s->accept(this);
}
}
pop(ContextRegister);
add32(TrustedImm32(locals), StackPointerRegister);
leaveStandardStackFrame();
ret();
QHashIterator<IR::BasicBlock *, QVector<Jump> > it(_patches);
while (it.hasNext()) {
it.next();
IR::BasicBlock *block = it.key();
Label target = _addrs.value(block);
assert(target.isSet());
foreach (Jump jump, it.value())
jump.linkTo(target, this);
}
JSC::JSGlobalData dummy;
JSC::LinkBuffer linkBuffer(dummy, this, 0);
foreach (CallToLink ctl, _callsToLink)
linkBuffer.link(ctl.call, ctl.externalFunction);
_function->codeRef = linkBuffer.finalizeCodeWithDisassembly("operator()(IR::Function*)");
_function->code = (void (*)(VM::Context *, const uchar *)) _function->codeRef.code().executableAddress();
qSwap(_function, function);
}
String *InstructionSelection::identifier(const QString &s)
{
return _engine->identifier(s);
}
JSC::MacroAssembler::Address InstructionSelection::loadTempAddress(RegisterID reg, IR::Temp *t)
{
int32_t offset = 0;
if (t->index < 0) {
const int arg = -t->index - 1;
loadPtr(Address(ContextRegister, offsetof(Context, arguments)), reg);
offset = arg * sizeof(Value);
} else if (t->index < _function->locals.size()) {
loadPtr(Address(ContextRegister, offsetof(Context, locals)), reg);
offset = t->index * sizeof(Value);
} else {
const int arg = _function->maxNumberOfArguments + t->index - _function->locals.size();
offset = sizeof(Value) * (-arg - 1)
- sizeof(void*); // size of ebp
reg = StackFrameRegister;
}
return Address(reg, offset);
}
void InstructionSelection::callActivationProperty(IR::Call *call, IR::Temp *result)
{
IR::Name *baseName = call->base->asName();
assert(baseName != 0);
int argc = 0;
for (IR::ExprList *it = call->args; it; it = it->next) {
++argc;
}
int i = 0;
for (IR::ExprList *it = call->args; it; it = it->next, ++i) {
IR::Temp *arg = it->expr->asTemp();
assert(arg != 0);
Address tempAddress = loadTempAddress(Gpr0, arg);
FunctionCall fc(this);
fc.addArgumentAsAddress(argumentAddressForCall(i));
fc.addArgumentAsAddress(tempAddress);
fc.call(__qmljs_copy);
}
FunctionCall activationCall(this);
activationCall.addArgumentFromRegister(ContextRegister);
if (result) {
activationCall.addArgumentAsAddress(loadTempAddress(Gpr0, result));
} else {
xor32(Gpr0, Gpr0);
activationCall.addArgumentFromRegister(Gpr0);
}
if (baseName->id) {
move(TrustedImmPtr(identifier(*baseName->id)), Gpr1);
activationCall.addArgumentFromRegister(Gpr1);
activationCall.addArgumentAsAddress(baseAddressForCallArguments());
activationCall.addArgumentByValue(TrustedImm32(argc));
activationCall.call(__qmljs_call_activation_property);
} else {
switch (baseName->builtin) {
case IR::Name::builtin_invalid:
Q_UNREACHABLE();
break;
case IR::Name::builtin_typeof:
activationCall.addArgumentAsAddress(baseAddressForCallArguments());
activationCall.addArgumentByValue(TrustedImm32(argc));
activationCall.call(__qmljs_builtin_typeof);
break;
case IR::Name::builtin_delete:
Q_UNREACHABLE();
break;
case IR::Name::builtin_throw:
activationCall.addArgumentAsAddress(baseAddressForCallArguments());
activationCall.addArgumentByValue(TrustedImm32(argc));
activationCall.call(__qmljs_builtin_throw);
break;
case IR::Name::builtin_rethrow:
activationCall.addArgumentAsAddress(baseAddressForCallArguments());
activationCall.addArgumentByValue(TrustedImm32(argc));
activationCall.call(__qmljs_builtin_rethrow);
return; // we need to return to avoid checking the exceptions
}
}
checkExceptions();
}
void InstructionSelection::callValue(IR::Call *call, IR::Temp *result)
{
}
void InstructionSelection::callProperty(IR::Call *call, IR::Temp *result)
{
}
void InstructionSelection::constructActivationProperty(IR::New *call, IR::Temp *result)
{
}
void InstructionSelection::constructProperty(IR::New *call, IR::Temp *result)
{
}
void InstructionSelection::constructValue(IR::New *call, IR::Temp *result)
{
}
void InstructionSelection::checkExceptions()
{
Address addr(ContextRegister, offsetof(Context, hasUncaughtException));
Jump jmp = branch8(Equal, addr, TrustedImm32(1));
_patches[_function->handlersBlock].append(jmp);
}
void InstructionSelection::visitExp(IR::Exp *s)
{
Q_UNIMPLEMENTED();
assert(!"TODO");
}
void InstructionSelection::visitEnter(IR::Enter *)
{
Q_UNIMPLEMENTED();
assert(!"TODO");
}
void InstructionSelection::visitLeave(IR::Leave *)
{
Q_UNIMPLEMENTED();
assert(!"TODO");
}
void InstructionSelection::visitMove(IR::Move *s)
{
if (s->op == IR::OpInvalid) {
if (IR::Name *n = s->target->asName()) {
String *propertyName = identifier(*n->id);
if (IR::Temp *t = s->source->asTemp()) {
FunctionCall fct(this);
fct.addArgumentFromRegister(ContextRegister);
move(TrustedImmPtr(propertyName), Gpr1);
fct.addArgumentFromRegister(Gpr1);
fct.addArgumentAsAddress(loadTempAddress(Gpr2, t));
fct.call(__qmljs_set_activation_property);
checkExceptions();
return;
} else {
Q_UNREACHABLE();
}
} else if (IR::Temp *t = s->target->asTemp()) {
if (IR::Name *n = s->source->asName()) {
Address temp = loadTempAddress(Gpr0, t);
FunctionCall fc(this);
fc.addArgumentFromRegister(ContextRegister);
fc.addArgumentAsAddress(temp);
if (*n->id == QStringLiteral("this")) { // ### `this' should be a builtin.
fc.call(__qmljs_get_thisObject);
} else {
String *propertyName = identifier(*n->id);
move(TrustedImmPtr(propertyName), Gpr1);
fc.addArgumentFromRegister(Gpr1);
fc.call(__qmljs_get_activation_property);
checkExceptions();
}
return;
} else if (IR::Const *c = s->source->asConst()) {
Address dest = loadTempAddress(Gpr0, t);
switch (c->type) {
case IR::NullType:
storeValue<Value::Null_Type>(TrustedImm32(0), dest);
break;
case IR::UndefinedType:
storeValue<Value::Undefined_Type>(TrustedImm32(0), dest);
break;
case IR::BoolType:
storeValue<Value::Boolean_Type>(TrustedImm32(c->value != 0), dest);
break;
case IR::NumberType:
// ### Taking address of pointer inside IR.
loadDouble(&c->value, FPGpr0);
storeDouble(FPGpr0, dest);
break;
default:
Q_UNIMPLEMENTED();
assert(!"TODO");
}
return;
} else if (IR::Temp *t2 = s->source->asTemp()) {
Address dest = loadTempAddress(Gpr1, t);
Address source = loadTempAddress(Gpr2, t2);
FunctionCall fc(this);
fc.addArgumentAsAddress(dest);
fc.addArgumentAsAddress(source);
fc.call(__qmljs_copy);
} else if (IR::Closure *clos = s->source->asClosure()) {
FunctionCall fct(this);
fct.addArgumentFromRegister(ContextRegister);
fct.addArgumentAsAddress(loadTempAddress(Gpr0, t));
move(TrustedImmPtr(clos->value), Gpr1);
fct.addArgumentFromRegister(Gpr1);
fct.call(__qmljs_init_closure);
return;
} else if (IR::Call *c = s->source->asCall()) {
if (c->base->asName()) {
callActivationProperty(c, t);
return;
} else if (c->base->asMember()) {
callProperty(c, t);
return;
} else if (c->base->asTemp()) {
callValue(c, t);
return;
}
}
}
}
Q_UNIMPLEMENTED();
s->dump(qout, IR::Stmt::MIR);
qout << endl;
assert(!"TODO");
}
void InstructionSelection::visitJump(IR::Jump *s)
{
jumpToBlock(s->target);
}
void InstructionSelection::jumpToBlock(IR::BasicBlock *target)
{
if (_block->index + 1 != target->index)
_patches[target].append(jump());
}
void InstructionSelection::visitCJump(IR::CJump *s)
{
if (IR::Temp *t = s->cond->asTemp()) {
Address temp = loadTempAddress(Gpr1, t);
Address tag = temp;
tag.offset += offsetof(VM::ValueData, tag);
Jump booleanConversion = branch32(NotEqual, tag, TrustedImm32(VM::Value::Boolean_Type));
Address data = temp;
data.offset += offsetof(VM::ValueData, b);
load32(data, Gpr1);
Jump testBoolean = jump();
booleanConversion.link(this);
{
FunctionCall fct(this);
fct.addArgumentFromRegister(ContextRegister);
fct.addArgumentAsAddress(temp);
fct.call(__qmljs_to_boolean);
move(ReturnValueRegister, Gpr1);
}
testBoolean.link(this);
move(TrustedImm32(1), Gpr0);
Jump target = branch32(Equal, Gpr1, Gpr0);
_patches[s->iftrue].append(target);
jumpToBlock(s->iffalse);
return;
}
Q_UNIMPLEMENTED();
assert(!"TODO");
}
void InstructionSelection::visitRet(IR::Ret *s)
{
if (IR::Temp *t = s->expr->asTemp()) {
Address source = loadTempAddress(Gpr0, t);
Address result = Address(ContextRegister, offsetof(Context, result));
FunctionCall fc(this);
fc.addArgumentAsAddress(result);
fc.addArgumentAsAddress(source);
fc.call(__qmljs_copy);
return;
}
Q_UNIMPLEMENTED();
Q_UNUSED(s);
}
<|endoftext|> |
<commit_before>56382e76-5216-11e5-a3b2-6c40088e03e4<commit_msg>5641f2da-5216-11e5-ab48-6c40088e03e4<commit_after>5641f2da-5216-11e5-ab48-6c40088e03e4<|endoftext|> |
<commit_before>f8cd4322-585a-11e5-ba08-6c40088e03e4<commit_msg>f8d64efa-585a-11e5-9ee5-6c40088e03e4<commit_after>f8d64efa-585a-11e5-9ee5-6c40088e03e4<|endoftext|> |
<commit_before>b07c7428-327f-11e5-9a7f-9cf387a8033e<commit_msg>b081edba-327f-11e5-b114-9cf387a8033e<commit_after>b081edba-327f-11e5-b114-9cf387a8033e<|endoftext|> |
<commit_before>46d07668-2e4f-11e5-a5cc-28cfe91dbc4b<commit_msg>46d822f0-2e4f-11e5-857e-28cfe91dbc4b<commit_after>46d822f0-2e4f-11e5-857e-28cfe91dbc4b<|endoftext|> |
<commit_before>5f894910-2d16-11e5-af21-0401358ea401<commit_msg>5f894911-2d16-11e5-af21-0401358ea401<commit_after>5f894911-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>92701b8a-2e4f-11e5-bfd2-28cfe91dbc4b<commit_msg>9276d0b3-2e4f-11e5-b6ce-28cfe91dbc4b<commit_after>9276d0b3-2e4f-11e5-b6ce-28cfe91dbc4b<|endoftext|> |
<commit_before>#include "server.h"
#include <QCommandLineOption>
#include <QCommandLineParser>
#include <QCoreApplication>
#include <QDir>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QCoreApplication::setApplicationName("cutehttpd");
QCoreApplication::setApplicationVersion("0.1");
QCommandLineParser parser;
parser.setApplicationDescription("Qt-based HTTP server for file sharing");
parser.addHelpOption();
parser.addVersionOption();
QCommandLineOption portOption(QStringList() << "p" << "port", "Port number, default 4242", "number");
portOption.setDefaultValue(QString::number(4242));
parser.addOption(portOption);
parser.process(a);
//Folder is args.at(0)
QStringList args = parser.positionalArguments();
int portNumber = parser.value(portOption).toInt();
QDir folder = args.size() ? QDir(args.at(0)) : QDir::currentPath();
if (!folder.exists()) {
qDebug() << "[Error] Folder" << folder.absolutePath() << "not found";
exit(EXIT_FAILURE);
}
qDebug() << "Shared folder: " << folder.absolutePath();
Server server(portNumber, folder.absolutePath());
server.startServer();
return a.exec();
}
<commit_msg>Preparing for 0.3 version<commit_after>#include "server.h"
#include <QCommandLineOption>
#include <QCommandLineParser>
#include <QCoreApplication>
#include <QDir>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QCoreApplication::setApplicationName("cutehttpd");
QCoreApplication::setApplicationVersion("0.3");
QCommandLineParser parser;
parser.setApplicationDescription("Qt-based HTTP server for file sharing.");
parser.
parser.addHelpOption();
parser.addVersionOption();
QCommandLineOption portOption(QStringList() << "p" << "port", "Port number, default 4242", "number");
portOption.setDefaultValue(QString::number(4242));
parser.addOption(portOption);
parser.process(a);
//Folder is args.at(0)
QStringList args = parser.positionalArguments();
int portNumber = parser.value(portOption).toInt();
QDir folder = args.size() ? QDir(args.at(0)) : QDir::currentPath();
if (!folder.exists()) {
qDebug() << "[Error] Folder" << folder.absolutePath() << "not found";
exit(EXIT_FAILURE);
}
qDebug() << "Shared folder: " << folder.absolutePath();
Server server(portNumber, folder.absolutePath());
server.startServer();
return a.exec();
}
<|endoftext|> |
<commit_before>8e9fac94-2d14-11e5-af21-0401358ea401<commit_msg>8e9fac95-2d14-11e5-af21-0401358ea401<commit_after>8e9fac95-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>60f990f5-2e4f-11e5-849f-28cfe91dbc4b<commit_msg>61002e8c-2e4f-11e5-ade3-28cfe91dbc4b<commit_after>61002e8c-2e4f-11e5-ade3-28cfe91dbc4b<|endoftext|> |
<commit_before>5ae7ec28-2d16-11e5-af21-0401358ea401<commit_msg>5ae7ec29-2d16-11e5-af21-0401358ea401<commit_after>5ae7ec29-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>#include <iostream>
#include <math.h>
#include <string>
#include <vector>
#include "mex.h"
#include <nix.hpp>
// *** nix entities holder ***
template<typename T>
struct holder {
T obj;
};
template<typename T>
struct box {
box() : ptr(nullptr) { }
box(T entity) : ptr(nullptr) {
set(entity);
}
box(uint64_t handle) {
ptr = reinterpret_cast<holder<T>*>(handle);
}
void set(T obj) {
if (ptr == nullptr) {
ptr = new holder<T>();
}
ptr->obj = obj;
}
T get() {
return ptr->obj;
}
uint64_t handle() const {
return reinterpret_cast<uint64_t >(ptr);
}
holder<T> *ptr;
};
// *** argument helpers ***
template<typename T>
class argument_helper {
public:
argument_helper(T **arg, size_t n) : array(arg), number(n) { }
bool check_size(int pos, bool fatal = false) const {
bool res = pos + 1 > number;
return res;
}
bool require_arguments(const std::vector<mxClassID> &args, bool fatal = false) const {
bool res = true;
if (args.size() > number) {
res = false;
} else {
for (size_t i = 0; i < args.size(); i++) {
if (mxGetClassID(array[i]) != args[i]) {
res = false;
break;
}
}
}
if (!res && fatal) {
mexErrMsgIdAndTxt("MATLAB:args:numortype", "Wrong number or types of arguments.");
}
return res;
}
protected:
T **array;
size_t number;
};
class extractor : public argument_helper<const mxArray> {
public:
extractor(const mxArray **arr, int n) : argument_helper(arr, n) { }
std::string str(int pos) const {
//make sure it is a string
char *tmp = mxArrayToString(array[pos]);
std::string the_string(tmp);
mxFree(tmp);
return the_string;
}
uint64_t uint64(int pos) const {
const void *data = mxGetData(array[pos]);
uint64_t res;
memcpy(&res, data, sizeof(uint64_t));
return res;
}
template<typename T>
box<T> handle(int pos) const {
uint64_t address = uint64(pos);
box<T> eb(address);
return eb;
}
mxClassID class_id(int pos) const {
return mxGetClassID(array[pos]);
}
bool is_str(int pos) const {
mxClassID category = class_id(pos);
return category == mxCHAR_CLASS;
}
private:
};
class infusor : public argument_helper<mxArray> {
public:
infusor(mxArray **arr, int n) : argument_helper(arr, n) { }
void set(int pos, std::string str) {
if (check_size(pos)) {
return;
}
array[pos] = mxCreateString(str.c_str());
}
void set(int pos, uint64_t v) {
array[pos] = mxCreateNumericMatrix(1, 1, mxUINT64_CLASS, mxREAL);
void *pointer = mxGetPr(array[pos]);
memcpy(pointer, &v, sizeof(v));
}
void set(int pos, mxArray *arr) {
array[pos] = arr;
}
template<typename T>
void set(int pos, box<T> &eb) {
set(pos, eb.handle());
}
private:
};
// *** functions ***
static void open_file(const extractor &input, infusor &output)
{
input.require_arguments({mxCHAR_CLASS, mxCHAR_CLASS}, true);
mexPrintf("[+] open_file\n");
std::string name = input.str(1);
nix::File fn = nix::File::open(name, nix::FileMode::ReadWrite);
box<nix::File> fb = box<nix::File>(fn);
output.set(0, fb);
}
static void list_blocks(const extractor &input, infusor &output)
{
mexPrintf("[+] list_blocks\n");
box<nix::File> eb = input.handle<nix::File>(1);
std::vector<nix::Block> blocks = eb.get().blocks();
std::vector<const char *> fields = { "name", "id" };
mxArray *sa = mxCreateStructMatrix(blocks.size(), 1, fields.size(), fields.data());
for (size_t n = 0; n < blocks.size(); n++) {
mxSetFieldByNumber(sa, n, 0, mxCreateString(blocks[n].name().c_str()));
mxSetFieldByNumber(sa, n, 1, mxCreateString(blocks[n].id().c_str()));
}
output.set(0, sa);
}
static void list_data_arrays(const extractor &input, infusor &output)
{
mexPrintf("[+] list_data_arrays\n");
box<nix::File> eb = input.handle<nix::File>(1);
nix::File nf = eb.get();
nix::Block block = nf.getBlock(input.str(2));
std::vector<nix::DataArray> arr = block.dataArrays();
std::vector<const char *> fields = { "name", "id" };
mxArray *sa = mxCreateStructMatrix(arr.size(), 1, fields.size(), fields.data());
for (size_t n = 0; n < arr.size(); n++) {
mxSetFieldByNumber(sa, n, 0, mxCreateString(arr[n].name().c_str()));
mxSetFieldByNumber(sa, n, 1, mxCreateString(arr[n].id().c_str()));
}
output.set(0, sa);
}
static void open_block(const extractor &input, infusor &output)
{
mexPrintf("[+] list_data_arrays\n");
box<nix::File> eb = input.handle<nix::File>(1);
nix::File nf = eb.get();
nix::Block block = nf.getBlock(input.str(2));
box<nix::Block> bb = box<nix::Block>(block);
output.set(0, bb);
}
static void open_data_array(const extractor &input, infusor &output)
{
mexPrintf("[+] list_data_arrays\n");
box<nix::Block> eb = input.handle<nix::Block>(1);
nix::Block block = eb.get();
nix::DataArray da = block.getDataArray(input.str(2));
box<nix::DataArray> bd = box<nix::DataArray>(da);
output.set(0, bd);
}
static mxArray * ndsize_to_mxarray(const nix::NDSize &size)
{
mxArray *res = mxCreateNumericMatrix(1, size.size(), mxUINT64_CLASS, mxREAL);
void *ptr = mxGetData(res);
uint64_t *data = static_cast<uint64_t *>(ptr);
for (size_t i = 0; i < size.size(); i++) {
data[i] = static_cast<uint64_t>(size[i]);
}
return res;
}
static nix::NDSize mx_array_to_ndsize(const mxArray *arr) {
size_t m = mxGetM(arr);
size_t n = mxGetN(arr);
//if (m != 1 && n != 1)
size_t k = std::max(n, m);
nix::NDSize size(k);
double *data = mxGetPr(arr);
for (size_t i = 0; i < size.size(); i++) {
size[i] = static_cast<nix::NDSize::value_type>(data[i]);
}
return size;
}
static mxArray *nmCreateScalar(uint32_t val) {
mxArray *arr = mxCreateNumericMatrix(1, 1, mxUINT32_CLASS, mxREAL);
void *data = mxGetData(arr);
memcpy(data, &val, sizeof(uint32_t));
return arr;
}
static mxArray *dim_to_struct(nix::SetDimension dim) {
std::vector<const char *> fields = { "type", "type_id", "label" };
mxArray *sa = mxCreateStructMatrix(1, 1, fields.size(), fields.data());
mxSetFieldByNumber(sa, 0, 0, mxCreateString("set"));
mxSetFieldByNumber(sa, 0, 1, nmCreateScalar(1));
std::vector<std::string> labels = dim.labels();
return sa;
}
static mxArray *dim_to_struct(nix::SampledDimension dim) {
std::vector<const char *> fields = { "type", "type_id", "interval", "label", "unit"};
mxArray *sa = mxCreateStructMatrix(1, 1, fields.size(), fields.data());
mxSetFieldByNumber(sa, 0, 0, mxCreateString("sampled"));
mxSetFieldByNumber(sa, 0, 1, nmCreateScalar(2));
mxSetFieldByNumber(sa, 0, 2, mxCreateDoubleScalar(dim.samplingInterval()));
boost::optional<std::string> label = dim.label();
if (label) {
mxSetFieldByNumber(sa, 0, 3, mxCreateString(label->c_str()));
}
boost::optional<std::string> unit = dim.unit();
if (unit) {
mxSetFieldByNumber(sa, 0, 4, mxCreateString(unit->c_str()));
}
return sa;
}
static mxArray *dim_to_struct(nix::RangeDimension dim) {
std::vector<const char *> fields = { "type", "type_id" };
mxArray *sa = mxCreateStructMatrix(1, 1, fields.size(), fields.data());
mxSetFieldByNumber(sa, 0, 0, mxCreateString("range"));
mxSetFieldByNumber(sa, 0, 1, nmCreateScalar(3));
return sa;
}
static void data_array_describe(const extractor &input, infusor &output)
{
mexPrintf("[+] block_describe_data_array\n");
box<nix::DataArray> eb = input.handle<nix::DataArray>(1);
nix::DataArray da = eb.get();
std::vector<const char *> fields = { "name", "id", "shape", "unit", "dimensions", "label"};
mxArray *sa = mxCreateStructMatrix(1, 1, fields.size(), fields.data());
mxSetFieldByNumber(sa, 0, 0, mxCreateString(da.name().c_str()));
mxSetFieldByNumber(sa, 0, 1, mxCreateString(da.id().c_str()));
mxSetFieldByNumber(sa, 0, 2, ndsize_to_mxarray(da.dataExtent()));
boost::optional<std::string> unit = da.unit();
if (unit) {
mxSetFieldByNumber(sa, 0, 3, mxCreateString(unit->c_str()));
}
size_t ndims = da.dimensionCount();
mxArray *dims = mxCreateCellMatrix(1, ndims);
std::vector<nix::Dimension> da_dims = da.dimensions();
for(size_t i = 0; i < ndims; i++) {
mxArray *ca;
switch(da_dims[i].dimensionType()) {
case nix::DimensionType::Set:
ca = dim_to_struct(da_dims[i].asSetDimension());
break;
case nix::DimensionType::Range:
ca = dim_to_struct(da_dims[i].asRangeDimension());
break;
case nix::DimensionType::Sample:
ca = dim_to_struct(da_dims[i].asSampledDimension());
break;
}
mxSetCell(dims, i, ca);
}
mxSetFieldByNumber(sa, 0, 4, dims);
boost::optional<std::string> label = da.label();
if (unit) {
mxSetFieldByNumber(sa, 0, 5, mxCreateString(label->c_str()));
}
output.set(0, sa);
}
static void data_array_read_all(const extractor &input, infusor &output)
{
mexPrintf("[+] block_describe_data_array\n");
box<nix::DataArray> eb = input.handle<nix::DataArray>(1);
nix::DataArray da = eb.get();
nix::NDSize size = da.dataExtent();
std::vector<mwSize> dims(size.size());
for (size_t i = 0; i < size.size(); i++) {
dims[i] = static_cast<mwSize>(size[i]);
}
mxArray *data = mxCreateNumericArray(size.size(), dims.data(), mxDOUBLE_CLASS, mxREAL);
double *ptr = mxGetPr(data);
nix::NDSize offset(size.size(), 0);
da.getData(nix::DataType::Double , ptr, size, offset);
output.set(0, data);
}
// *** ***
typedef void (*fn_t)(const extractor &input, infusor &output);
struct fendpoint {
fendpoint(std::string name, fn_t fn) : name(name), fn(fn) {}
std::string name;
fn_t fn;
};
const std::vector<fendpoint> funcs = {
{"File::open", open_file},
{"File::listBlocks", list_blocks},
{"File::listDataArrays", list_data_arrays},
{"File::openBlock", open_block},
{"Block::openDataArray", open_data_array},
{"DataArray::describe", data_array_describe},
{"DataArray::readAll", data_array_read_all}
};
// main entry point
void mexFunction(int nlhs,
mxArray *lhs[],
int nrhs,
const mxArray *rhs[])
{
extractor input(rhs, nrhs);
infusor output(lhs, nlhs);
std::string cmd = input.str(0);
mexPrintf("[F] %s\n", cmd.c_str());
bool processed = false;
for (const auto &fn : funcs) {
if (fn.name == cmd) {
try {
fn.fn(input, output);
} catch (std::exception &e) {
mexErrMsgIdAndTxt("MATLAB:arg:dispatch", e.what());
} catch (...) {
mexErrMsgIdAndTxt("MATLAB:arg:dispatch", "unkown exception");
}
processed = true;
break;
}
}
if (!processed) {
mexErrMsgIdAndTxt("MATLAB:arg:dispatch", "Unkown command");
}
}
<commit_msg>Add vector_to_array<commit_after>#include <iostream>
#include <math.h>
#include <string>
#include <vector>
#include "mex.h"
#include <nix.hpp>
// *** datatype converter
template<typename T>
struct to_mx_class_id {
static mxClassID value() {
nix::DataType dtype = nix::to_data_type<T>::value;
switch (dtype) {
case nix::DataType::Double:
return mxDOUBLE_CLASS;
default:
mexErrMsgIdAndTxt("MATLAB:toclassid:notimplemented", "Implement me!");
return mxVOID_CLASS;
}
}
};
template<typename T>
mxArray* vector_to_array(const std::vector<T> &v) {
mxClassID klass_id = to_mx_class_id<T>::value();
mxArray *data = mxCreateNumericMatrix(1, v.size(), klass_id, mxREAL);
double *ptr = mxGetPr(data);
memcpy(ptr, v.data(), sizeof(T) * v.size());
return data;
}
// *** nix entities holder ***
template<typename T>
struct holder {
T obj;
};
template<typename T>
struct box {
box() : ptr(nullptr) { }
box(T entity) : ptr(nullptr) {
set(entity);
}
box(uint64_t handle) {
ptr = reinterpret_cast<holder<T>*>(handle);
}
void set(T obj) {
if (ptr == nullptr) {
ptr = new holder<T>();
}
ptr->obj = obj;
}
T get() {
return ptr->obj;
}
uint64_t handle() const {
return reinterpret_cast<uint64_t >(ptr);
}
holder<T> *ptr;
};
// *** argument helpers ***
template<typename T>
class argument_helper {
public:
argument_helper(T **arg, size_t n) : array(arg), number(n) { }
bool check_size(int pos, bool fatal = false) const {
bool res = pos + 1 > number;
return res;
}
bool require_arguments(const std::vector<mxClassID> &args, bool fatal = false) const {
bool res = true;
if (args.size() > number) {
res = false;
} else {
for (size_t i = 0; i < args.size(); i++) {
if (mxGetClassID(array[i]) != args[i]) {
res = false;
break;
}
}
}
if (!res && fatal) {
mexErrMsgIdAndTxt("MATLAB:args:numortype", "Wrong number or types of arguments.");
}
return res;
}
protected:
T **array;
size_t number;
};
class extractor : public argument_helper<const mxArray> {
public:
extractor(const mxArray **arr, int n) : argument_helper(arr, n) { }
std::string str(int pos) const {
//make sure it is a string
char *tmp = mxArrayToString(array[pos]);
std::string the_string(tmp);
mxFree(tmp);
return the_string;
}
uint64_t uint64(int pos) const {
const void *data = mxGetData(array[pos]);
uint64_t res;
memcpy(&res, data, sizeof(uint64_t));
return res;
}
template<typename T>
box<T> handle(int pos) const {
uint64_t address = uint64(pos);
box<T> eb(address);
return eb;
}
mxClassID class_id(int pos) const {
return mxGetClassID(array[pos]);
}
bool is_str(int pos) const {
mxClassID category = class_id(pos);
return category == mxCHAR_CLASS;
}
private:
};
class infusor : public argument_helper<mxArray> {
public:
infusor(mxArray **arr, int n) : argument_helper(arr, n) { }
void set(int pos, std::string str) {
if (check_size(pos)) {
return;
}
array[pos] = mxCreateString(str.c_str());
}
void set(int pos, uint64_t v) {
array[pos] = mxCreateNumericMatrix(1, 1, mxUINT64_CLASS, mxREAL);
void *pointer = mxGetPr(array[pos]);
memcpy(pointer, &v, sizeof(v));
}
void set(int pos, mxArray *arr) {
array[pos] = arr;
}
template<typename T>
void set(int pos, box<T> &eb) {
set(pos, eb.handle());
}
private:
};
// *** functions ***
static void open_file(const extractor &input, infusor &output)
{
input.require_arguments({mxCHAR_CLASS, mxCHAR_CLASS}, true);
mexPrintf("[+] open_file\n");
std::string name = input.str(1);
nix::File fn = nix::File::open(name, nix::FileMode::ReadWrite);
box<nix::File> fb = box<nix::File>(fn);
output.set(0, fb);
}
static void list_blocks(const extractor &input, infusor &output)
{
mexPrintf("[+] list_blocks\n");
box<nix::File> eb = input.handle<nix::File>(1);
std::vector<nix::Block> blocks = eb.get().blocks();
std::vector<const char *> fields = { "name", "id" };
mxArray *sa = mxCreateStructMatrix(blocks.size(), 1, fields.size(), fields.data());
for (size_t n = 0; n < blocks.size(); n++) {
mxSetFieldByNumber(sa, n, 0, mxCreateString(blocks[n].name().c_str()));
mxSetFieldByNumber(sa, n, 1, mxCreateString(blocks[n].id().c_str()));
}
output.set(0, sa);
}
static void list_data_arrays(const extractor &input, infusor &output)
{
mexPrintf("[+] list_data_arrays\n");
box<nix::File> eb = input.handle<nix::File>(1);
nix::File nf = eb.get();
nix::Block block = nf.getBlock(input.str(2));
std::vector<nix::DataArray> arr = block.dataArrays();
std::vector<const char *> fields = { "name", "id" };
mxArray *sa = mxCreateStructMatrix(arr.size(), 1, fields.size(), fields.data());
for (size_t n = 0; n < arr.size(); n++) {
mxSetFieldByNumber(sa, n, 0, mxCreateString(arr[n].name().c_str()));
mxSetFieldByNumber(sa, n, 1, mxCreateString(arr[n].id().c_str()));
}
output.set(0, sa);
}
static void open_block(const extractor &input, infusor &output)
{
mexPrintf("[+] list_data_arrays\n");
box<nix::File> eb = input.handle<nix::File>(1);
nix::File nf = eb.get();
nix::Block block = nf.getBlock(input.str(2));
box<nix::Block> bb = box<nix::Block>(block);
output.set(0, bb);
}
static void open_data_array(const extractor &input, infusor &output)
{
mexPrintf("[+] list_data_arrays\n");
box<nix::Block> eb = input.handle<nix::Block>(1);
nix::Block block = eb.get();
nix::DataArray da = block.getDataArray(input.str(2));
box<nix::DataArray> bd = box<nix::DataArray>(da);
output.set(0, bd);
}
static mxArray * ndsize_to_mxarray(const nix::NDSize &size)
{
mxArray *res = mxCreateNumericMatrix(1, size.size(), mxUINT64_CLASS, mxREAL);
void *ptr = mxGetData(res);
uint64_t *data = static_cast<uint64_t *>(ptr);
for (size_t i = 0; i < size.size(); i++) {
data[i] = static_cast<uint64_t>(size[i]);
}
return res;
}
static nix::NDSize mx_array_to_ndsize(const mxArray *arr) {
size_t m = mxGetM(arr);
size_t n = mxGetN(arr);
//if (m != 1 && n != 1)
size_t k = std::max(n, m);
nix::NDSize size(k);
double *data = mxGetPr(arr);
for (size_t i = 0; i < size.size(); i++) {
size[i] = static_cast<nix::NDSize::value_type>(data[i]);
}
return size;
}
static mxArray *nmCreateScalar(uint32_t val) {
mxArray *arr = mxCreateNumericMatrix(1, 1, mxUINT32_CLASS, mxREAL);
void *data = mxGetData(arr);
memcpy(data, &val, sizeof(uint32_t));
return arr;
}
static mxArray *dim_to_struct(nix::SetDimension dim) {
std::vector<const char *> fields = { "type", "type_id", "label" };
mxArray *sa = mxCreateStructMatrix(1, 1, fields.size(), fields.data());
mxSetFieldByNumber(sa, 0, 0, mxCreateString("set"));
mxSetFieldByNumber(sa, 0, 1, nmCreateScalar(1));
std::vector<std::string> labels = dim.labels();
return sa;
}
static mxArray *dim_to_struct(nix::SampledDimension dim) {
std::vector<const char *> fields = { "type", "type_id", "interval", "label", "unit"};
mxArray *sa = mxCreateStructMatrix(1, 1, fields.size(), fields.data());
mxSetFieldByNumber(sa, 0, 0, mxCreateString("sampled"));
mxSetFieldByNumber(sa, 0, 1, nmCreateScalar(2));
mxSetFieldByNumber(sa, 0, 2, mxCreateDoubleScalar(dim.samplingInterval()));
boost::optional<std::string> label = dim.label();
if (label) {
mxSetFieldByNumber(sa, 0, 3, mxCreateString(label->c_str()));
}
boost::optional<std::string> unit = dim.unit();
if (unit) {
mxSetFieldByNumber(sa, 0, 4, mxCreateString(unit->c_str()));
}
return sa;
}
static mxArray *dim_to_struct(nix::RangeDimension dim) {
std::vector<const char *> fields = { "type", "type_id" };
mxArray *sa = mxCreateStructMatrix(1, 1, fields.size(), fields.data());
mxSetFieldByNumber(sa, 0, 0, mxCreateString("range"));
mxSetFieldByNumber(sa, 0, 1, nmCreateScalar(3));
return sa;
}
static void data_array_describe(const extractor &input, infusor &output)
{
mexPrintf("[+] block_describe_data_array\n");
box<nix::DataArray> eb = input.handle<nix::DataArray>(1);
nix::DataArray da = eb.get();
std::vector<const char *> fields = { "name", "id", "shape", "unit", "dimensions", "label"};
mxArray *sa = mxCreateStructMatrix(1, 1, fields.size(), fields.data());
mxSetFieldByNumber(sa, 0, 0, mxCreateString(da.name().c_str()));
mxSetFieldByNumber(sa, 0, 1, mxCreateString(da.id().c_str()));
mxSetFieldByNumber(sa, 0, 2, ndsize_to_mxarray(da.dataExtent()));
boost::optional<std::string> unit = da.unit();
if (unit) {
mxSetFieldByNumber(sa, 0, 3, mxCreateString(unit->c_str()));
}
size_t ndims = da.dimensionCount();
mxArray *dims = mxCreateCellMatrix(1, ndims);
std::vector<nix::Dimension> da_dims = da.dimensions();
for(size_t i = 0; i < ndims; i++) {
mxArray *ca;
switch(da_dims[i].dimensionType()) {
case nix::DimensionType::Set:
ca = dim_to_struct(da_dims[i].asSetDimension());
break;
case nix::DimensionType::Range:
ca = dim_to_struct(da_dims[i].asRangeDimension());
break;
case nix::DimensionType::Sample:
ca = dim_to_struct(da_dims[i].asSampledDimension());
break;
}
mxSetCell(dims, i, ca);
}
mxSetFieldByNumber(sa, 0, 4, dims);
boost::optional<std::string> label = da.label();
if (unit) {
mxSetFieldByNumber(sa, 0, 5, mxCreateString(label->c_str()));
}
output.set(0, sa);
}
static void data_array_read_all(const extractor &input, infusor &output)
{
mexPrintf("[+] block_describe_data_array\n");
box<nix::DataArray> eb = input.handle<nix::DataArray>(1);
nix::DataArray da = eb.get();
nix::NDSize size = da.dataExtent();
std::vector<mwSize> dims(size.size());
for (size_t i = 0; i < size.size(); i++) {
dims[i] = static_cast<mwSize>(size[i]);
}
mxArray *data = mxCreateNumericArray(size.size(), dims.data(), mxDOUBLE_CLASS, mxREAL);
double *ptr = mxGetPr(data);
nix::NDSize offset(size.size(), 0);
da.getData(nix::DataType::Double , ptr, size, offset);
output.set(0, data);
}
// *** ***
typedef void (*fn_t)(const extractor &input, infusor &output);
struct fendpoint {
fendpoint(std::string name, fn_t fn) : name(name), fn(fn) {}
std::string name;
fn_t fn;
};
const std::vector<fendpoint> funcs = {
{"File::open", open_file},
{"File::listBlocks", list_blocks},
{"File::listDataArrays", list_data_arrays},
{"File::openBlock", open_block},
{"Block::openDataArray", open_data_array},
{"DataArray::describe", data_array_describe},
{"DataArray::readAll", data_array_read_all}
};
// main entry point
void mexFunction(int nlhs,
mxArray *lhs[],
int nrhs,
const mxArray *rhs[])
{
extractor input(rhs, nrhs);
infusor output(lhs, nlhs);
std::string cmd = input.str(0);
mexPrintf("[F] %s\n", cmd.c_str());
bool processed = false;
for (const auto &fn : funcs) {
if (fn.name == cmd) {
try {
fn.fn(input, output);
} catch (std::exception &e) {
mexErrMsgIdAndTxt("MATLAB:arg:dispatch", e.what());
} catch (...) {
mexErrMsgIdAndTxt("MATLAB:arg:dispatch", "unkown exception");
}
processed = true;
break;
}
}
if (!processed) {
mexErrMsgIdAndTxt("MATLAB:arg:dispatch", "Unkown command");
}
}
<|endoftext|> |
<commit_before>3877dd45-2d3d-11e5-8e72-c82a142b6f9b<commit_msg>38fc8cf8-2d3d-11e5-8a7e-c82a142b6f9b<commit_after>38fc8cf8-2d3d-11e5-8a7e-c82a142b6f9b<|endoftext|> |
<commit_before>0f37d576-585b-11e5-a8f6-6c40088e03e4<commit_msg>0f3f9f2e-585b-11e5-bd95-6c40088e03e4<commit_after>0f3f9f2e-585b-11e5-bd95-6c40088e03e4<|endoftext|> |
<commit_before>0e59c0fa-2e4f-11e5-aba3-28cfe91dbc4b<commit_msg>0e61615c-2e4f-11e5-9f81-28cfe91dbc4b<commit_after>0e61615c-2e4f-11e5-9f81-28cfe91dbc4b<|endoftext|> |
<commit_before>9ba6f28c-327f-11e5-9cca-9cf387a8033e<commit_msg>9bad8547-327f-11e5-a1a1-9cf387a8033e<commit_after>9bad8547-327f-11e5-a1a1-9cf387a8033e<|endoftext|> |
<commit_before>5a8a5526-5216-11e5-a4a6-6c40088e03e4<commit_msg>5a90ef30-5216-11e5-ac1f-6c40088e03e4<commit_after>5a90ef30-5216-11e5-ac1f-6c40088e03e4<|endoftext|> |
<commit_before>55748b19-ad59-11e7-b8aa-ac87a332f658<commit_msg>Gapjgjchguagdmg<commit_after>55e04b02-ad59-11e7-94b9-ac87a332f658<|endoftext|> |
<commit_before>734d3e8c-5216-11e5-8218-6c40088e03e4<commit_msg>73574300-5216-11e5-947e-6c40088e03e4<commit_after>73574300-5216-11e5-947e-6c40088e03e4<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <c@ethdev.com>
* @date 2014
* Solidity commandline compiler.
*/
#include <string>
#include <iostream>
#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/ASTPrinter.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Exceptions.h>
#include <libsolidity/Compiler.h>
#include <libsolidity/SourceReferenceFormatter.h>
using namespace std;
using namespace dev;
using namespace solidity;
void help()
{
cout << "Usage solc [OPTIONS] <file>" << endl
<< "Options:" << endl
<< " -h,--help Show this help message and exit." << endl
<< " -V,--version Show the version and exit." << endl;
exit(0);
}
void version()
{
cout << "solc, the solidity complier commandline interface " << dev::Version << endl
<< " by Christian <c@ethdev.com>, (c) 2014." << endl
<< "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl;
exit(0);
}
/// Helper class that extracts the first expression in an AST.
class FirstExpressionExtractor: private ASTVisitor
{
public:
FirstExpressionExtractor(ASTNode& _node): m_expression(nullptr) { _node.accept(*this); }
Expression* getExpression() const { return m_expression; }
private:
virtual bool visit(Expression& _expression) override { return checkExpression(_expression); }
virtual bool visit(Assignment& _expression) override { return checkExpression(_expression); }
virtual bool visit(UnaryOperation& _expression) override { return checkExpression(_expression); }
virtual bool visit(BinaryOperation& _expression) override { return checkExpression(_expression); }
virtual bool visit(FunctionCall& _expression) override { return checkExpression(_expression); }
virtual bool visit(MemberAccess& _expression) override { return checkExpression(_expression); }
virtual bool visit(IndexAccess& _expression) override { return checkExpression(_expression); }
virtual bool visit(PrimaryExpression& _expression) override { return checkExpression(_expression); }
virtual bool visit(Identifier& _expression) override { return checkExpression(_expression); }
virtual bool visit(ElementaryTypeNameExpression& _expression) override { return checkExpression(_expression); }
virtual bool visit(Literal& _expression) override { return checkExpression(_expression); }
bool checkExpression(Expression& _expression)
{
if (m_expression == nullptr)
m_expression = &_expression;
return false;
}
private:
Expression* m_expression;
};
int main(int argc, char** argv)
{
string infile;
for (int i = 1; i < argc; ++i)
{
string arg = argv[i];
if (arg == "-h" || arg == "--help")
help();
else if (arg == "-V" || arg == "--version")
version();
else
infile = argv[i];
}
string sourceCode;
if (infile.empty())
{
string s;
while (!cin.eof())
{
getline(cin, s);
sourceCode.append(s);
}
}
else
sourceCode = asString(dev::contents(infile));
ASTPointer<ContractDefinition> ast;
shared_ptr<Scanner> scanner = make_shared<Scanner>(CharStream(sourceCode));
Parser parser;
try
{
ast = parser.parse(scanner);
}
catch (ParserError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", *scanner);
return -1;
}
NameAndTypeResolver resolver;
try
{
resolver.resolveNamesAndTypes(*ast.get());
}
catch (DeclarationError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", *scanner);
return -1;
}
catch (TypeError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", *scanner);
return -1;
}
cout << "Syntax tree for the contract:" << endl;
dev::solidity::ASTPrinter printer(ast, sourceCode);
printer.print(cout);
FirstExpressionExtractor extractor(*ast);
CompilerContext context;
ExpressionCompiler compiler(context);
try
{
compiler.compile(*extractor.getExpression());
}
catch (CompilerError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", *scanner);
return -1;
}
bytes instructions = compiler.getAssembledBytecode();
cout << "Bytecode for the first expression: " << endl;
cout << eth::disassemble(instructions) << endl;
return 0;
}
<commit_msg>Contract compiler and also add ExpressionStatement to AST.<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <c@ethdev.com>
* @date 2014
* Solidity commandline compiler.
*/
#include <string>
#include <iostream>
#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/ASTPrinter.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Exceptions.h>
#include <libsolidity/Compiler.h>
#include <libsolidity/SourceReferenceFormatter.h>
using namespace std;
using namespace dev;
using namespace solidity;
void help()
{
cout << "Usage solc [OPTIONS] <file>" << endl
<< "Options:" << endl
<< " -h,--help Show this help message and exit." << endl
<< " -V,--version Show the version and exit." << endl;
exit(0);
}
void version()
{
cout << "solc, the solidity complier commandline interface " << dev::Version << endl
<< " by Christian <c@ethdev.com>, (c) 2014." << endl
<< "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl;
exit(0);
}
int main(int argc, char** argv)
{
string infile;
for (int i = 1; i < argc; ++i)
{
string arg = argv[i];
if (arg == "-h" || arg == "--help")
help();
else if (arg == "-V" || arg == "--version")
version();
else
infile = argv[i];
}
string sourceCode;
if (infile.empty())
{
string s;
while (!cin.eof())
{
getline(cin, s);
sourceCode.append(s);
}
}
else
sourceCode = asString(dev::contents(infile));
ASTPointer<ContractDefinition> ast;
shared_ptr<Scanner> scanner = make_shared<Scanner>(CharStream(sourceCode));
Parser parser;
try
{
ast = parser.parse(scanner);
}
catch (ParserError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", *scanner);
return -1;
}
NameAndTypeResolver resolver;
try
{
resolver.resolveNamesAndTypes(*ast.get());
}
catch (DeclarationError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", *scanner);
return -1;
}
catch (TypeError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", *scanner);
return -1;
}
cout << "Syntax tree for the contract:" << endl;
dev::solidity::ASTPrinter printer(ast, sourceCode);
printer.print(cout);
bytes instructions;
try
{
instructions = Compiler::compile(*ast);
}
catch (CompilerError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", *scanner);
return -1;
}
cout << "EVM assembly: " << endl;
cout << eth::disassemble(instructions) << endl;
cout << "Binary: " << toHex(instructions) << endl;
return 0;
}
<|endoftext|> |
<commit_before>c48263e8-ad5b-11e7-9012-ac87a332f658<commit_msg>I hope I am done<commit_after>c532c06e-ad5b-11e7-b20d-ac87a332f658<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <functional>
template <typename value_t>
struct range_itr
{
value_t m_begin;
value_t m_end;
bool m_reverse;
range_itr (value_t begin, value_t end) : m_begin (begin), m_end (end)
{
m_reverse = m_end < m_begin;
}
struct iterator
{
value_t value;
bool reverse;
const value_t& operator *()
{
return value;
}
iterator& operator++()
{
if (reverse)
--value;
else
++value;
return *this;
}
bool operator != (const iterator& that)
{
return value != that.value;
}
};
iterator begin ()
{
return iterator{m_begin, m_reverse};
}
iterator end ()
{
return iterator{m_end, m_reverse};
}
template <typename collection_t>
operator collection_t ()
{
collection_t c;
for (auto n : *this)
{
c.push_back(n);
}
return c;
}
};
template <typename value_t>
inline range_itr<value_t> range (value_t begin, value_t end)
{
return range_itr<value_t> (begin, end);
}
template <typename value_t>
inline range_itr<value_t> range (value_t end)
{
return range_itr<value_t> (0, end);
}
template <typename value_t, typename range_t>
struct generate_itr
{
generate_itr (std::function <value_t (const value_t&) output_expr,
range_t range,
std::function<bool (const value_t&) predictate)
{
}
}
int main ()
{
for (int n : range(10))
{
std::cout << n << std::endl;
}
std::list<int> x = range(200, 190);
for (int n : x)
{
std::cout << n << std::endl;
}
// std::vector<int> y = generate ([](int x){ return x * 2;}, range<int> (10, 20), [](int x){ return x & 1; });
}
<commit_msg>initial implementation of generator<commit_after>#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <functional>
template <typename value_t>
struct range_itr
{
typedef value_t value_type;
value_t m_begin;
value_t m_end;
bool m_reverse;
range_itr (value_t begin, value_t end) : m_begin (begin), m_end (end)
{
m_reverse = m_end < m_begin;
}
struct iterator
{
value_t value;
bool reverse;
const value_t& operator *()
{
return value;
}
iterator& operator++()
{
if (reverse)
--value;
else
++value;
return *this;
}
bool operator != (const iterator& that)
{
return value != that.value;
}
};
iterator begin ()
{
return iterator{m_begin, m_reverse};
}
iterator end ()
{
return iterator{m_end, m_reverse};
}
template <typename collection_t>
operator collection_t ()
{
collection_t c;
for (auto n : *this)
{
c.push_back(n);
}
return c;
}
};
template <typename value_t>
inline range_itr<value_t> range (value_t begin, value_t end)
{
return range_itr<value_t> (begin, end);
}
template <typename value_t>
inline range_itr<value_t> range (value_t end)
{
return range_itr<value_t> (0, end);
}
template <typename output_expr_t, typename range_t, typename predictate_t>
struct generate_itr
{
output_expr_t m_output_expr;
range_t m_range;
predictate_t m_predictate;
typedef typename range_t::value_type value_t;
generate_itr (output_expr_t output_expr, range_t range, predictate_t predictate) :
m_output_expr(output_expr), m_range(range), m_predictate(predictate)
{
}
template <typename collection_t>
operator collection_t ()
{
collection_t c;
for (auto n : m_range)
{
if (m_predictate(n))
c.push_back(m_output_expr(n));
}
return c;
}
};
template <typename output_expr_t, typename range_t, typename predictate_t>
generate_itr<output_expr_t, range_t, predictate_t> generate (output_expr_t expr, range_t r, predictate_t p)
{
return generate_itr<output_expr_t, range_t, predictate_t> (expr, r, p);
}
int main ()
{
for (int n : range(10))
{
std::cout << n << std::endl;
}
std::list<int> x = range(200, 190);
for (int n : x)
{
std::cout << n << std::endl;
}
std::vector<int> test = generate ([](int x){ return x * 2;}, range (10), [](int x){ return x & 1; });
for (int n : test)
{
std::cout << n << std::endl;
}
}
<|endoftext|> |
<commit_before>4b654846-2e3a-11e5-b917-c03896053bdd<commit_msg>4b730664-2e3a-11e5-913c-c03896053bdd<commit_after>4b730664-2e3a-11e5-913c-c03896053bdd<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.