text
stringlengths 54
60.6k
|
---|
<commit_before>#include <queue>
#include <cstring>
#include <iostream>
#include <vector>
#include <string.h>
#include <unistd.h>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
#include <sys/utsname.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
using namespace boost;
// Cases to test:
// cd Desktop&&ls -a
// cd Desktop&[ENTER] ls -a
// cd Desktop;ls -a
// cd Desktop;ls
// ls;ls;ls;ls
// cd Desktop & ls -a
// cd Desktop;
// ls;
// cd Desktop||ls -a;vim touch.cpp&&[ENTER] ls -a
// cd Desktop
// ; clear
// && ls
// || ls -a
// NOTE: cd will NOT be tested or used!
// Re-read specs if unsure!!
// prints user and machine info
void pcmd_prompt() {
string login(getlogin());
struct utsname hostname;
uname(&hostname);
string nodeName(hostname.nodename);
cout << login << "@" << nodeName << "$ ";
}
// parses input into queue for execution
void parse_into_queue(queue<string> &l, const string &s) {
char_separator<char> delim(" ", ";&|#") ;
tokenizer<char_separator<char>> mytok(s, delim);
for (auto i = mytok.begin(); i != mytok.end(); ++i) {
l.push(*i);
}
}
// for testing purposes
void print_queue (queue<string> q) {
if (q.empty()) {
return;
}
while (!q.empty()) {
cout << "[" << q.front() << "] ";
q.pop();
}
cout << endl;
}
// for testing purposes
void qinfo(queue<string> q) {
cout << "Size: " << q.size() << endl;
print_queue(q);
}
// reinitializes v with q until connector
void parse_connectors(vector<string> &v, queue<string> &q) {
while (!q.empty() && q.front() != "&" && q.front() != "|" && q.front() != ";") {
v.push_back(q.front());
q.pop();
}
}
bool cmd_exit(vector<string> &v) {
if (iequals(v.at(0), "exit")) {
return true;
}
return false;
}
void to_arr_cstring(vector<string> &s, vector<char*> &cs) {
for (auto i = 0; i != s.size(); ++i) {
cs[i] = &s[i][0];
}
}
// exec cmd and if success
bool begin_exec(vector<char*> &cs) {
int status;
int pid = fork();
if (pid < 0) { // error
perror("FORK");
_exit(-1);
}
else if (pid == 0) { // child
cout << "child process" << endl;
if (-1 == execvp(cs[0], cs.data())) {
perror("EXEC");
_exit(-1);
}
_exit(0);
}
else if (pid > 0) { // parent
if (-1 == wait(&status)) {
perror("WAIT");
}
if (status != 0) {
return false;
}
}
return true;
}
// checks connector logic
bool connect_success(bool status, queue<string> &q) {
if (!q.empty() && q.front() == "&") {
q.pop();
if (!q.empty() && q.front() == "&") {
q.pop();
if (!status) {
cout << "prev cmd fail - ending" << endl;
return false;
}
else {
return true;
}
}
else if (q.empty()) {
cout << "error with connector \"&\"" << endl;
return false;
}
else {
cout << "&" << q.front() << " is not a connector!" << endl;
return false;
}
}
else if (!q.empty() && q.front() == "|") {
q.pop();
if (!q.empty() && q.front() == "|") {
q.pop();
if (status) {
cout << "prev cmd success - ending" << endl;
return false;
}
else {
return true;
}
}
else if (q.empty()) {
cout << "error with connector \"|\"" << endl;
return false;
}
else {
cout << "|" << q.front() << " is not a connector!" << endl;
return false;
}
}
else if (!q.empty() && q.front() == ";") {
q.pop();
return true;
}
else if (!q.empty()) {
cout << q.front() << " is not a connector!" << endl;
return false;
}
else {
cout << "queue size: " << q.size() << endl;
print_queue(q);
cout << "something MIGHT be wrong!" << endl;
return false;
}
}
int main(int argc, char* argv[]) {
while (1) {
string cmd_input;
queue<string> list;
pcmd_prompt();
getline(cin, cmd_input);
parse_into_queue(list, cmd_input);
vector<string> cmd;
while (!list.empty()) {
qinfo(list); // debugger
bool exec_success = false;
parse_connectors(cmd, list);
if (cmd.size() == 0) {
cout << "ERROR!" << endl;
break;
}
else if (cmd_exit(cmd)) {
cout << "Exiting RShell" << endl;
return 0;
}
else {
vector<char*> cmd_cstring(cmd.size() + 1);
to_arr_cstring(cmd, cmd_cstring);
exec_success = begin_exec(cmd_cstring);
}
if (!connect_success(exec_success, list)) {
break;
}
cmd.clear();
}
}
return 0;
}
<commit_msg>Added comment support<commit_after>#include <queue>
#include <cstring>
#include <iostream>
#include <vector>
#include <string.h>
#include <unistd.h>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
#include <sys/utsname.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
using namespace boost;
// Cases to test:
// cd Desktop&&ls -a
// cd Desktop&[ENTER] ls -a
// cd Desktop;ls -a
// cd Desktop;ls
// ls;ls;ls;ls
// cd Desktop & ls -a
// cd Desktop;
// ls;
// cd Desktop||ls -a;vim touch.cpp&&[ENTER] ls -a
// cd Desktop
// ; clear
// && ls
// || ls -a
// NOTE: cd will NOT be tested or used!
// Re-read specs if unsure!!
// prints user and machine info
void pcmd_prompt() {
string login(getlogin());
struct utsname hostname;
uname(&hostname);
string nodeName(hostname.nodename);
cout << login << "@" << nodeName << "$ ";
}
// parses input into queue for execution
void parse_into_queue(queue<string> &l, const string &s) {
char_separator<char> delim(" ", ";&|#") ;
tokenizer<char_separator<char>> mytok(s, delim);
for (auto i = mytok.begin(); i != mytok.end(); ++i) {
l.push(*i);
}
}
// for testing purposes
void print_queue (queue<string> q) {
if (q.empty()) {
return;
}
while (!q.empty()) {
cout << "[" << q.front() << "] ";
q.pop();
}
cout << endl;
}
// for testing purposes
void qinfo(queue<string> q) {
cout << "Size: " << q.size() << endl;
print_queue(q);
}
// reinitializes v with q until connector
void parse_connectors(vector<string> &v, queue<string> &q) {
while (!q.empty() && q.front() != "&" && q.front() != "|" && q.front() != ";" && q.front() != "#")
{
v.push_back(q.front());
q.pop();
}
}
bool cmd_exit(vector<string> &v) {
if (iequals(v.at(0), "exit")) {
return true;
}
return false;
}
void to_arr_cstring(vector<string> &s, vector<char*> &cs) {
for (auto i = 0; i != s.size(); ++i) {
cs[i] = &s[i][0];
}
}
// exec cmd and if success
bool begin_exec(vector<char*> &cs) {
int status;
int pid = fork();
if (pid < 0) { // error
perror("FORK");
_exit(-1);
}
else if (pid == 0) { // child
cout << "child process" << endl;
if (-1 == execvp(cs[0], cs.data())) {
perror("EXEC");
_exit(-1);
}
_exit(0);
}
else if (pid > 0) { // parent
if (-1 == wait(&status)) {
perror("WAIT");
}
if (status != 0) {
return false;
}
}
return true;
}
// checks connector logic
bool connect_success(bool status, queue<string> &q) {
if (!q.empty() && q.front() == "&") {
q.pop();
if (!q.empty() && q.front() == "&") {
q.pop();
if (!status) {
cout << "prev cmd fail - ending" << endl;
return false;
}
else {
return true;
}
}
else if (q.empty()) {
cout << "Syntax error: incorrect usage of \"&&\"" << endl;
return false;
}
else {
cout << "Syntax error: incorrect usage of \"&&\"" << endl;
return false;
}
}
else if (!q.empty() && q.front() == "|") {
q.pop();
if (!q.empty() && q.front() == "|") {
q.pop();
if (status) {
cout << "prev cmd success - ending" << endl;
return false;
}
else {
return true;
}
}
else if (q.empty()) {
cout << "Syntax error: incorrect usage of \"||\"" << endl;
return false;
}
else {
cout << "Syntax error: incorrect usage of \"||\"" << endl;
return false;
}
}
else if (!q.empty() && q.front() == ";") {
q.pop();
return true;
}
else if (!q.empty() && q.front() == "#") {
return false;
}
else if (!q.empty()) {
cout << "Syntax error: " << q.front() << " is not a valid connector!" << endl;
return false;
}
else {
cout << "done" << endl;
return false;
}
}
int main(int argc, char* argv[]) {
while (1) {
string cmd_input;
queue<string> list;
pcmd_prompt();
getline(cin, cmd_input);
parse_into_queue(list, cmd_input);
vector<string> cmd;
while (!list.empty()) {
qinfo(list); // debugger
bool exec_success = false;
if (list.front() == "#") {
break;
}
parse_connectors(cmd, list);
if (cmd.size() == 0) {
cout << "Syntax error: formatting issue in command" << endl;
break;
}
else if (cmd_exit(cmd)) {
cout << "Exiting RShell" << endl;
return 0;
}
else {
vector<char*> cmd_cstring(cmd.size() + 1);
to_arr_cstring(cmd, cmd_cstring);
exec_success = begin_exec(cmd_cstring);
}
if (!connect_success(exec_success, list)) {
break;
}
cmd.clear();
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include<iostream>
#include<string.h>
#include<vector>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<cstring>
#include<boost/tokenizer.hpp>
#include<algorithm>
#include<iterator>
#include<sstream>
using namespace std;
using namespace boost;
void parse_line(char c_line[], char *command_line[]);
void run_line(char *command_line[]);
int main()
{
string str;
string arg = "";
while(1)
{
str = "";
char userName[100] = "";
if(getlogin_r(userName, sizeof(userName)-1) != 0) //Getting username, and returns null if cant be found
{
perror("Error getting username");
}
cout << '[' << userName << '@';
char hostName[100] = "";
if(gethostname(hostName, sizeof(hostName)-1) != 0) // Getting host name, returns numm if it cannot be found
{
perror("Error getting hostname");
}
cout << hostName << ']';
cout << "$";
getline(cin,str); //Gets a command
if(str == "exit") //If the command is exit the program stops
{
break;
}
if(str.size() != 0 && str.at(0) == '#')
{
str = "";
}
if(str != "")
{
for(int i = 0; i < str.size(); i++)
{
if(str.at(i) == ';') //Looks for semicolons and adds a space in order to make parsing easier
{
str.insert(i, " ");
i++;
}
if(str.at(i) == '#') //Removes all part of the command after the comment
{
str = str.substr(0,i);
}
}
char c_line[str.size() + 1];
char *command_line[64];
strcpy(c_line,str.c_str());
c_line[str.size()] = '\0';
parse_line(c_line, command_line);
run_line(command_line);
}
}
return 0;
}
void parse_line(char c_line[], char *command_line[])
{
while(*c_line != '\0')
{
while(*c_line == ' ' || *c_line == '\n')
{
*c_line++ = '\0';
}
*command_line++ = c_line;
while(*c_line != '\0' && *c_line != ' ')
{
c_line++;
}
*command_line = '\0';
}
}
void run_line(char *command_line[])
{
pid_t pid;
int status;
if((pid = fork()) < 0)
{
perror("forking failed");
}
else if(pid == 0)
{
if(execvp(*command_line,command_line) < 0)
{
perror("execvp failed");
exit(1);
}
}
else
{
while(wait(&status) != pid)
;
}
return;
}
<commit_msg>fixed a bug with spaces at end of command<commit_after>#include<iostream>
#include<string.h>
#include<string>
#include<vector>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<cstring>
#include<boost/tokenizer.hpp>
#include<algorithm>
#include<iterator>
#include<sstream>
using namespace std;
using namespace boost;
void parse_line(char c_line[], char *command_line[]);
void run_line(char *command_line[]);
int main()
{
string str;
string arg = "";
while(1)
{
str = "";
char userName[100] = "";
if(getlogin_r(userName, sizeof(userName)-1) != 0) //Getting username, and returns null if cant be found
{
perror("Error getting username");
}
cout << '[' << userName << '@';
char hostName[100] = "";
if(gethostname(hostName, sizeof(hostName)-1) != 0) // Getting host name, returns numm if it cannot be found
{
perror("Error getting hostname");
}
cout << hostName << ']';
cout << "$";
getline(cin,str); //Gets a command
if(str == "exit") //If the command is exit the program stops
{
break;
}
if(str.size() != 0 && str.at(0) == '#')
{
str = "";
}
if(str != "")
{
for(int i = 0; i < str.size(); i++)
{
if(str.at(i) == ';') //Looks for semicolons and adds a space in order to make parsing easier
{
str.insert(i, " ");
i++;
}
if(str.at(i) == '#') //Removes all part of the command after the comment
{
str = str.substr(0,i);
}
}
while(str.find(" ") != string::npos)
{
str.erase(str.find(" "));
}
if(str.at(str.size() - 1 ) == ' ')
{
str = str.substr(0,str.size()-1);
}
char c_line[str.size() + 1];
char *command_line[64];
strcpy(c_line,str.c_str());
c_line[str.size()] = '\0';
parse_line(c_line, command_line);
run_line(command_line);
}
}
return 0;
}
void parse_line(char c_line[], char *command_line[])
{
while(*c_line != '\0')
{
while(*c_line == ' ' || *c_line == '\n' || *c_line == '\t')
{
*c_line++ = '\0';
}
*command_line++ = c_line;
while(*c_line != '\0' && *c_line != ' ' && *c_line != '\n' && *c_line != '\t')
{
c_line++;
}
*command_line = '\0';
}
return;
}
void run_line(char *command_line[])
{
pid_t pid;
int status;
if((pid = fork()) < 0)
{
perror("forking failed");
}
else if(pid == 0)
{
if(execvp(*command_line,command_line) < 0)
{
perror("execvp failed");
exit(1);
}
}
else
{
while(wait(&status) != pid)
;
}
return;
}
<|endoftext|> |
<commit_before>#include "desktop.h"
#define TAB 9
using namespace std;
void open_menu(vector <string>& app_list) {
Init_MENSTR(menu_panel);
menu_panel.posX = 1;
menu_panel.posY = 1;
unsigned int selected_menu = menu_winV2(&menu_panel, "", app_list, main_system_color);
if (selected_menu) {
app_start(selected_menu, NULL);
}
/*DLGSTR menu_panel = {};
bool cycle = true;
int key;
menu_panel.xpos = 1;
menu_panel.ypos = 1;
menu_panel.style = BLUE_WIN;
menu_panel.border_menu = true;
while (cycle) {
menu_win(menu_panel, app_list);
key = getch();
switch (key) {
case 27: cycle = false;
break;
case KEY_UP: if (menu_panel.selected != 1)
menu_panel.selected--;
break;
case KEY_DOWN: if (menu_panel.selected != menu_panel.second_border)
menu_panel.selected++;
break;
case '\n': app_start(menu_panel.selected, NULL);
return;
break;
}
}*/
}
int draw_desktop(int selected, bool open_label, unsigned int maxX, unsigned int maxY, int color, int sel_color) {
attron(COLOR_PAIR(color) | A_BOLD);
for (unsigned int x = 0; x < maxX; x++) {
mvprintw(maxY - 1, x, "-");
mvprintw(0, x, "-");
}
for (unsigned int y = 0; y < maxY; y++) {mvprintw(y, 0, "|"); mvprintw(y, maxX - 1, "|");}
local_time t_n = get_time_now();
mvprintw(0, maxX - 10, "%d:%d:%d", t_n.hours, t_n.min, t_n.sec);
attroff(COLOR_PAIR(color) | A_BOLD);
if (selected == 0) attron(COLOR_PAIR(sel_color) | A_BOLD);
else attron(COLOR_PAIR(color) | A_BOLD);
mvprintw(0, 1, "Menu");
if (selected == 0) attroff(COLOR_PAIR(sel_color) | A_BOLD);
else attroff(COLOR_PAIR(color) | A_BOLD);
if (selected == 1) attron(COLOR_PAIR(sel_color) | A_BOLD);
else attron(COLOR_PAIR(color) | A_BOLD);
mvprintw(0, 6, "Edit");
if (selected == 1) attroff(COLOR_PAIR(sel_color) | A_BOLD);
else attroff(COLOR_PAIR(color) | A_BOLD);
if (selected == 2) attron(COLOR_PAIR(sel_color) | A_BOLD);
else attron(COLOR_PAIR(color) | A_BOLD);
mvprintw(0, 11, "Exit");
if (selected == 2) attroff(COLOR_PAIR(sel_color) | A_BOLD);
else attroff(COLOR_PAIR(color) | A_BOLD);
return 0;
}
int work_desktop(vector <string> app_list, string user_name) {
unsigned int maxY,
maxYb = 0,
maxX,
maxXb = 0;
bool cycle = true,
open_label = false;
int key_pressed,
selected = 0,
color = 0,
sel_color = 0;
get_normal_inv_color(conf("system_color", main_config_base), color, sel_color);
while (cycle) {
getmaxyx(stdscr, maxY, maxX); // Получение размера терминала
if ((maxX != maxXb) || (maxY != maxYb)) {
erase();
}
timeout(500);
draw_desktop(selected, open_label, maxX, maxY, color, sel_color);
key_pressed = getch();
switch (key_pressed) {
case KEY_RIGHT: if (selected != 2)
selected++;
break;
case KEY_LEFT: if (selected != 0)
selected--;
break;
case '\n': switch (selected) {
case 0: open_menu(app_list);
break;
case 1: settings(MAIN_SETFILE);
get_normal_inv_color(conf("system_color", main_config_base), color, sel_color);
break;
case 2: cycle = false;
break;
}
break;
case 27: if (open_label) {
open_label = false;
}
/*else shutdown_process();*/
break;
case TAB: list_process();
break;
}
}
return 0;
}
int main_desktop(string user_name/*...*/) {
vector <string> app_list;
get_apps_list(app_list);
work_desktop(app_list, user_name);
return 0;
}<commit_msg>Добавлена анимация списка приложений<commit_after>#include "desktop.h"
#define TAB 9
using namespace std;
void open_menu(vector <string>& app_list) {
Init_MENSTR(menu_panel);
menu_panel.posX = 1;
menu_panel.posY = 1;
menu_panel.animation_delay = 100;
unsigned int selected_menu = menu_winV2(&menu_panel, "", app_list, main_system_color);
if (selected_menu) {
app_start(selected_menu, NULL);
}
}
int draw_desktop(int selected, bool open_label, unsigned int maxX, unsigned int maxY, int color, int sel_color) {
attron(COLOR_PAIR(color) | A_BOLD);
for (unsigned int x = 0; x < maxX; x++) {
mvprintw(maxY - 1, x, "-");
mvprintw(0, x, "-");
}
for (unsigned int y = 0; y < maxY; y++) {mvprintw(y, 0, "|"); mvprintw(y, maxX - 1, "|");}
local_time t_n = get_time_now();
mvprintw(0, maxX - 10, "%d:%d:%d", t_n.hours, t_n.min, t_n.sec);
attroff(COLOR_PAIR(color) | A_BOLD);
if (selected == 0) attron(COLOR_PAIR(sel_color) | A_BOLD);
else attron(COLOR_PAIR(color) | A_BOLD);
mvprintw(0, 1, "Menu");
if (selected == 0) attroff(COLOR_PAIR(sel_color) | A_BOLD);
else attroff(COLOR_PAIR(color) | A_BOLD);
if (selected == 1) attron(COLOR_PAIR(sel_color) | A_BOLD);
else attron(COLOR_PAIR(color) | A_BOLD);
mvprintw(0, 6, "Edit");
if (selected == 1) attroff(COLOR_PAIR(sel_color) | A_BOLD);
else attroff(COLOR_PAIR(color) | A_BOLD);
if (selected == 2) attron(COLOR_PAIR(sel_color) | A_BOLD);
else attron(COLOR_PAIR(color) | A_BOLD);
mvprintw(0, 11, "Exit");
if (selected == 2) attroff(COLOR_PAIR(sel_color) | A_BOLD);
else attroff(COLOR_PAIR(color) | A_BOLD);
return 0;
}
int work_desktop(vector <string> app_list, string user_name) {
unsigned int maxY,
maxYb = 0,
maxX,
maxXb = 0;
bool cycle = true,
open_label = false;
int key_pressed,
selected = 0,
color = 0,
sel_color = 0;
get_normal_inv_color(conf("system_color", main_config_base), color, sel_color);
while (cycle) {
getmaxyx(stdscr, maxY, maxX); // Получение размера терминала
if ((maxX != maxXb) || (maxY != maxYb)) {
erase();
}
timeout(500);
draw_desktop(selected, open_label, maxX, maxY, color, sel_color);
key_pressed = getch();
switch (key_pressed) {
case KEY_RIGHT: if (selected != 2)
selected++;
break;
case KEY_LEFT: if (selected != 0)
selected--;
break;
case '\n': switch (selected) {
case 0: open_menu(app_list);
break;
case 1: settings(MAIN_SETFILE);
get_normal_inv_color(conf("system_color", main_config_base), color, sel_color);
break;
case 2: cycle = false;
break;
}
break;
case 27: if (open_label) {
open_label = false;
}
/*else shutdown_process();*/
break;
case TAB: list_process();
break;
}
}
return 0;
}
int main_desktop(string user_name/*...*/) {
vector <string> app_list;
get_apps_list(app_list);
work_desktop(app_list, user_name);
return 0;
}<|endoftext|> |
<commit_before>//===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is emits an assembly printer for the current target.
// Note that this is currently fairly skeletal, but will grow over time.
//
//===----------------------------------------------------------------------===//
#include "AsmWriterEmitter.h"
#include "CodeGenTarget.h"
#include "Record.h"
#include <ostream>
using namespace llvm;
static bool isIdentChar(char C) {
return (C >= 'a' && C <= 'z') ||
(C >= 'A' && C <= 'Z') ||
(C >= '0' && C <= '9') ||
C == '_';
}
void AsmWriterEmitter::run(std::ostream &O) {
EmitSourceFileHeader("Assembly Writer Source Fragment", O);
O << "namespace llvm {\n\n";
CodeGenTarget Target;
Record *AsmWriter = Target.getAsmWriter();
std::string AsmWriterClassName =
AsmWriter->getValueAsString("AsmWriterClassName");
O <<
"/// printInstruction - This method is automatically generated by tablegen\n"
"/// from the instruction set description. This method returns true if the\n"
"/// machine instruction was sufficiently described to print it, otherwise\n"
"/// it returns false.\n"
"bool " << Target.getName() << AsmWriterClassName
<< "::printInstruction(const MachineInstr *MI) {\n";
O << " switch (MI->getOpcode()) {\n"
" default: return false;\n";
std::string Namespace = Target.inst_begin()->second.Namespace;
for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
E = Target.inst_end(); I != E; ++I)
if (!I->second.AsmString.empty()) {
const std::string &AsmString = I->second.AsmString;
O << " case " << Namespace << "::" << I->first << ": O ";
std::string::size_type LastEmitted = 0;
while (LastEmitted != AsmString.size()) {
std::string::size_type DollarPos = AsmString.find('$', LastEmitted);
if (DollarPos == std::string::npos) DollarPos = AsmString.size();
// Emit a constant string fragment.
if (DollarPos != LastEmitted) {
// TODO: this should eventually handle escaping.
O << " << \"" << std::string(AsmString.begin()+LastEmitted,
AsmString.begin()+DollarPos) << "\"";
LastEmitted = DollarPos;
} else if (DollarPos+1 != AsmString.size() &&
AsmString[DollarPos+1] == '$') {
O << " << '$'"; // "$$" -> $
} else {
// Get the name of the variable.
// TODO: should eventually handle ${foo}bar as $foo
std::string::size_type VarEnd = DollarPos+1;
while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
++VarEnd;
std::string VarName(AsmString.begin()+DollarPos+1,
AsmString.begin()+VarEnd);
if (VarName.empty())
throw "Stray '$' in '" + I->first +
"' asm string, maybe you want $$?";
unsigned OpNo = I->second.getOperandNamed(VarName);
// If this is a two-address instruction and we are not accessing the
// 0th operand, remove an operand.
unsigned MIOp = I->second.OperandList[OpNo].MIOperandNo;
if (I->second.isTwoAddress && MIOp != 0) {
if (MIOp == 1)
throw "Should refer to operand #0 instead of #1 for two-address"
" instruction '" + I->first + "'!";
--MIOp;
}
O << "; " << I->second.OperandList[OpNo].PrinterMethodName
<< "(MI, " << MIOp << ", MVT::"
<< getName(I->second.OperandList[OpNo].Ty) << "); O ";
LastEmitted = VarEnd;
}
}
O << " << '\\n'; break;\n";
}
O << " }\n"
" return true;\n"
"}\n";
O << "} // End llvm namespace \n";
}
<commit_msg>Correctly parse variant notation<commit_after>//===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is emits an assembly printer for the current target.
// Note that this is currently fairly skeletal, but will grow over time.
//
//===----------------------------------------------------------------------===//
#include "AsmWriterEmitter.h"
#include "CodeGenTarget.h"
#include "Record.h"
#include <ostream>
using namespace llvm;
static bool isIdentChar(char C) {
return (C >= 'a' && C <= 'z') ||
(C >= 'A' && C <= 'Z') ||
(C >= '0' && C <= '9') ||
C == '_';
}
void AsmWriterEmitter::run(std::ostream &O) {
EmitSourceFileHeader("Assembly Writer Source Fragment", O);
O << "namespace llvm {\n\n";
CodeGenTarget Target;
Record *AsmWriter = Target.getAsmWriter();
std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
unsigned Variant = AsmWriter->getValueAsInt("Variant");
O <<
"/// printInstruction - This method is automatically generated by tablegen\n"
"/// from the instruction set description. This method returns true if the\n"
"/// machine instruction was sufficiently described to print it, otherwise\n"
"/// it returns false.\n"
"bool " << Target.getName() << ClassName
<< "::printInstruction(const MachineInstr *MI) {\n";
O << " switch (MI->getOpcode()) {\n"
" default: return false;\n";
std::string Namespace = Target.inst_begin()->second.Namespace;
bool inVariant = false; // True if we are inside a {.|.|.} region.
for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
E = Target.inst_end(); I != E; ++I)
if (!I->second.AsmString.empty()) {
const std::string &AsmString = I->second.AsmString;
O << " case " << Namespace << "::" << I->first << ": O ";
std::string::size_type LastEmitted = 0;
while (LastEmitted != AsmString.size()) {
std::string::size_type DollarPos =
AsmString.find_first_of("${|}", LastEmitted);
if (DollarPos == std::string::npos) DollarPos = AsmString.size();
// Emit a constant string fragment.
if (DollarPos != LastEmitted) {
// TODO: this should eventually handle escaping.
O << " << \"" << std::string(AsmString.begin()+LastEmitted,
AsmString.begin()+DollarPos) << "\"";
LastEmitted = DollarPos;
} else if (AsmString[DollarPos] == '{') {
if (inVariant)
throw "Nested variants found for instruction '" + I->first + "'!";
LastEmitted = DollarPos+1;
inVariant = true; // We are now inside of the variant!
for (unsigned i = 0; i != Variant; ++i) {
// Skip over all of the text for an irrelevant variant here. The
// next variant starts at |, or there may not be text for this
// variant if we see a }.
std::string::size_type NP =
AsmString.find_first_of("|}", LastEmitted);
if (NP == std::string::npos)
throw "Incomplete variant for instruction '" + I->first + "'!";
LastEmitted = NP+1;
if (AsmString[NP] == '}') {
inVariant = false; // No text for this variant.
break;
}
}
} else if (AsmString[DollarPos] == '|') {
if (!inVariant)
throw "'|' character found outside of a variant in instruction '"
+ I->first + "'!";
// Move to the end of variant list.
std::string::size_type NP = AsmString.find('}', LastEmitted);
if (NP == std::string::npos)
throw "Incomplete variant for instruction '" + I->first + "'!";
LastEmitted = NP+1;
inVariant = false;
} else if (AsmString[DollarPos] == '}') {
if (!inVariant)
throw "'}' character found outside of a variant in instruction '"
+ I->first + "'!";
LastEmitted = DollarPos+1;
inVariant = false;
} else if (DollarPos+1 != AsmString.size() &&
AsmString[DollarPos+1] == '$') {
O << " << '$'"; // "$$" -> $
} else {
// Get the name of the variable.
// TODO: should eventually handle ${foo}bar as $foo
std::string::size_type VarEnd = DollarPos+1;
while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
++VarEnd;
std::string VarName(AsmString.begin()+DollarPos+1,
AsmString.begin()+VarEnd);
if (VarName.empty())
throw "Stray '$' in '" + I->first +
"' asm string, maybe you want $$?";
unsigned OpNo = I->second.getOperandNamed(VarName);
// If this is a two-address instruction and we are not accessing the
// 0th operand, remove an operand.
unsigned MIOp = I->second.OperandList[OpNo].MIOperandNo;
if (I->second.isTwoAddress && MIOp != 0) {
if (MIOp == 1)
throw "Should refer to operand #0 instead of #1 for two-address"
" instruction '" + I->first + "'!";
--MIOp;
}
O << "; " << I->second.OperandList[OpNo].PrinterMethodName
<< "(MI, " << MIOp << ", MVT::"
<< getName(I->second.OperandList[OpNo].Ty) << "); O ";
LastEmitted = VarEnd;
}
}
O << " << '\\n'; break;\n";
}
O << " }\n"
" return true;\n"
"}\n";
O << "} // End llvm namespace \n";
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string>
using namespace std;
int main(int argc, char** argv){
char *user = getlogin(); //syscall for getting username
//perror check for getlogin()
if(user == NULL){
perror("getlogin");
exit(1);
}
char hostname[100]; //create a char array for the hostname
if((gethostname(hostname, sizeof(hostname))) == -1){
perror("hostname");
exit(1);
}
cout << user << '@' << hostname << '$' << endl; //output user and host
return 0;
}
<commit_msg>added executeCommand function<commit_after>#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <boost/tokenizer.hpp>
using namespace boost;
using namespace std;
void displayPrompt(){
char *user = getlogin(); //I assign the login name to a user pointer
if(user == NULL){
perror("getlogin");
exit(1);
}
char hostname[100]; //I allocate space for the hostname
if(gethostname(hostname, sizeof(hostname)) == -1){ //checking for errors withostname
perror("gethostname");
exit(1);
}
cout << user << '@' << hostname << '$' << ' '; //here I output the user and hostanme to the screen.
}
/*void parseCommand(string &cmd){
char_separator<char> delim;
tokenizer< char_separator<char> > mytok(cmd, delim);
}*/
void executeCommand(char **argv){
int pid = fork();
if(pid == -1){
perror("There was some error with fork()");
exit(1);
}
else if(pid == 0){
cout << "We are in the child process!";
if(-1 == execvp(*argv, argv)){
perror("There was an error with execvp");
exit(1);
}
}
else if(pid > 0){
if(-1 == wait(0)){
perror("There was an error with wait()");
}
}
}
int main(void){
string cmd;
while(cmd != "exit"){
displayPrompt(); //display the username and hostname
getline(cin, cmd);
}
return 0;
}
//notes to try
//------------
// if(strcmp(argv[0], "exit") == 0){
// exit(0);
// }
//------------
//execute command needs work
<|endoftext|> |
<commit_before>// Copyright (C) 2015, 2016 Pierre-Luc Perrier <[email protected]>
//
// 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.
#ifndef abz_random_random_hpp
#define abz_random_random_hpp
/// @file abz/random/random.hpp
/// Pseudorandom numbers generation.
#include "abz/detail/macros.hpp"
#include <cmath> // std::nextafter
#include <limits>
#include <random>
#include <type_traits>
ABZ_NAMESPACE_BEGIN
/// @cond ABZ_INTERNAL
namespace _ {
/// Returns a per-thread PRNG engine.
/// @return A reference to a thread local instance of Engine.
template <class Engine>
Engine &thread_local_engine()
{
// TODO random_device can actually throw: "Throws an implementation-defined
// exception derived from std::exception if a random number could not be
// generated."
thread_local Engine g{std::random_device{}()};
return g;
}
template <class T, class Engine, class Enabled = void>
struct uniform_distribution;
template <class Integral, class Engine>
struct uniform_distribution<Integral,
Engine,
typename std::enable_if<std::is_integral<Integral>::value>::type> {
static inline constexpr Integral default_min() { return Integral{0}; }
static inline constexpr Integral default_max() { return std::numeric_limits<Integral>::max(); }
static inline Integral get(Engine &g, const Integral a, const Integral b)
{
return std::uniform_int_distribution<Integral>{}(
g, typename std::uniform_int_distribution<Integral>::param_type{a, b});
}
};
template <class Real, class Engine>
struct uniform_distribution<Real, Engine, typename std::enable_if<std::is_floating_point<Real>::value>::type> {
static inline constexpr Real default_min() { return Real{0}; }
static inline constexpr Real default_max() { return Real{1}; }
static inline Real get(Engine &g, const Real a, const Real b)
{
return std::uniform_real_distribution<Real>{}(
g, typename std::uniform_real_distribution<Real>::param_type{
a, std::nextafter(b, std::numeric_limits<Real>::max())});
}
};
} // namespace _
/// @endcond ABZ_INTERNAL
namespace random {
/// @brief Seeds the internal thread local engine with a new value.
///
/// The seed value is generated using std::random_device.
///
/// The library keep a local thread instance of each engine. Multiple calls from the same thread and
/// using the same Engine type will use the same generator. This function seeds the Engine's
/// instance of the calling thread.
///
/// @tparam Engine The type of engine for which the instance will be seeded.
///
/// @see seed(const Engine::result_type) rand
template <class Engine = std::default_random_engine>
inline void seed()
{
_::thread_local_engine<Engine>().seed(std::random_device{}());
}
/// @overload
///
/// @param value The new seed value
///
/// @see seed rand
template <class Engine = std::default_random_engine>
inline void seed(const typename Engine::result_type value)
{
_::thread_local_engine<Engine>().seed(value);
}
} // namespace random
/// Gets a (pseudo) random number uniformly distributed on the interval \f$[a, b]\f$.
///
/// Default paramaters are
/// @li \f$\{0, MAX(T)\}\f$ for integral types
/// @li \f$\{0.0, 1.0\}\f$ for floating point types
///
/// Requires that
/// @li \f$a \leq b\f$ for integral types
/// @li \f$(a \leq b) \land (b < MAX(T)) \land ((b - a) < MAX(T))\f$ for floating point
/// types
///
/// @note This functions uses a thread_local instance of the engine. To reinitialize this engine
/// with a new seed, see random::seed.
///
/// @warning For floating point types, some existing implementations have a bug where they may
/// occasionally return b (that is, std::nextafter(b, std::numeric_limits<Real>::max()) for this
/// function). <a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63176" target="_blank">GCC
/// #63176</a> <a href="https://llvm.org/bugs/show_bug.cgi?id=18767" target="_blank">#LLVM
/// #18767</a> <a href="http://open-std.org/JTC1/SC22/WG21/docs/lwg-active.html#2524"
/// target="_blank">LWG #2524</a>.
///
/// @see random::seed()
///
/// @param a, b The interval of the generated numbers
///
/// @tparam T The type of number to generate (must be integral or floating point).
/// @tparam Engine The random number generator to use (must satisfy
/// UniformRandomNumberGenerator concept).
template <class T, class Engine = std::default_random_engine>
inline T rand(T a = _::uniform_distribution<T, Engine>::default_min(),
T b = _::uniform_distribution<T, Engine>::default_max())
{
return _::uniform_distribution<T, Engine>::get(_::thread_local_engine<Engine>(), a, b);
}
ABZ_NAMESPACE_END
#endif // abz_random_random_hpp
<commit_msg>Add type aliases to uniform_distribution<commit_after>// Copyright (C) 2015, 2016 Pierre-Luc Perrier <[email protected]>
//
// 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.
#ifndef abz_random_random_hpp
#define abz_random_random_hpp
/// @file abz/random/random.hpp
/// Pseudorandom numbers generation.
#include "abz/detail/macros.hpp"
#include <cmath> // std::nextafter
#include <limits>
#include <random>
#include <type_traits>
ABZ_NAMESPACE_BEGIN
/// @cond ABZ_INTERNAL
namespace _ {
/// Returns a per-thread PRNG engine.
/// @return A reference to a thread local instance of Engine.
template <class Engine>
Engine &thread_local_engine()
{
// NOTE(pluc) random_device can actually throw: "Throws an implementation-defined exception
// derived from std::exception if a random number could not be generated."
thread_local Engine g{std::random_device{}()};
return g;
}
template <class T, class Engine, class Enabled = void>
struct uniform_distribution;
template <class Integral, class Engine>
struct uniform_distribution<Integral, Engine, typename std::enable_if<std::is_integral<Integral>::value>::type> {
using distribution_type = std::uniform_int_distribution<Integral>;
using param_type = typename distribution_type::param_type;
using result_type = Integral;
static inline constexpr result_type default_min() { return result_type{0}; }
static inline constexpr result_type default_max()
{
return std::numeric_limits<result_type>::max();
}
static inline result_type get(Engine &g, const Integral a, const Integral b)
{
return distribution_type{}(g, param_type{a, b});
}
};
template <class Real, class Engine>
struct uniform_distribution<Real, Engine, typename std::enable_if<std::is_floating_point<Real>::value>::type> {
using distribution_type = std::uniform_real_distribution<Real>;
using param_type = typename distribution_type::param_type;
using result_type = Real;
static inline constexpr result_type default_min() { return Real{0}; }
static inline constexpr result_type default_max() { return Real{1}; }
static inline result_type get(Engine &g, const Real a, const Real b)
{
return distribution_type{}(
g, param_type{a, std::nextafter(b, std::numeric_limits<result_type>::max())});
}
};
} // namespace _
/// @endcond ABZ_INTERNAL
namespace random {
/// @brief Seeds the internal thread local engine with a new value.
///
/// The seed value is generated using std::random_device.
///
/// The library keep a local thread instance of each engine. Multiple calls from the same thread and
/// using the same Engine type will use the same generator. This function seeds the Engine's
/// instance of the calling thread.
///
/// @tparam Engine The type of engine for which the instance will be seeded.
///
/// @see seed(const Engine::result_type) rand
template <class Engine = std::default_random_engine>
inline void seed()
{
_::thread_local_engine<Engine>().seed(std::random_device{}());
}
/// @overload
///
/// @param value The new seed value
///
/// @see seed rand
template <class Engine = std::default_random_engine>
inline void seed(const typename Engine::result_type value)
{
_::thread_local_engine<Engine>().seed(value);
}
} // namespace random
/// Gets a (pseudo) random number uniformly distributed on the interval \f$[a, b]\f$.
///
/// Default paramaters are
/// @li \f$\{0, MAX(T)\}\f$ for integral types
/// @li \f$\{0.0, 1.0\}\f$ for floating point types
///
/// Requires that
/// @li \f$a \leq b\f$ for integral types
/// @li \f$(a \leq b) \land (b < MAX(T)) \land ((b - a) < MAX(T))\f$ for floating point
/// types
///
/// @note This functions uses a thread_local instance of the engine. To reinitialize this engine
/// with a new seed, see random::seed.
///
/// @warning For floating point types, some existing implementations have a bug where they may
/// occasionally return b (that is, std::nextafter(b, std::numeric_limits<Real>::max()) for this
/// function). <a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63176" target="_blank">GCC
/// #63176</a> <a href="https://llvm.org/bugs/show_bug.cgi?id=18767" target="_blank">#LLVM
/// #18767</a> <a href="http://open-std.org/JTC1/SC22/WG21/docs/lwg-active.html#2524"
/// target="_blank">LWG #2524</a>.
///
/// @see random::seed()
///
/// @param a, b The interval of the generated numbers
///
/// @tparam T The type of number to generate (must be integral or floating point).
/// @tparam Engine The random number generator to use (must satisfy
/// UniformRandomNumberGenerator concept).
template <class T, class Engine = std::default_random_engine>
inline T rand(T a = _::uniform_distribution<T, Engine>::default_min(),
T b = _::uniform_distribution<T, Engine>::default_max())
{
return _::uniform_distribution<T, Engine>::get(_::thread_local_engine<Engine>(), a, b);
}
ABZ_NAMESPACE_END
#endif // abz_random_random_hpp
<|endoftext|> |
<commit_before>// This is a regression test on debug info to make sure that we can access
// qualified global names.
// RUN: %llvmgcc -S -O0 -g %s -o - | \
// RUN: llc -disable-cfi --disable-fp-elim -o %t.s -O0
// RUN: %compile_c %t.s -o %t.o
// RUN: %link %t.o -o %t.exe
// RUN: %llvmdsymutil %t.exe
// RUN: echo {break main\nrun\np Pubnames::pubname} > %t.in
// RUN: gdb -q -batch -n -x %t.in %t.exe | tee %t.out | grep {\$1 = 10}
//
// XFAIL: alpha,arm
struct Pubnames {
static int pubname;
};
int Pubnames::pubname = 10;
int main (int argc, char** argv) {
Pubnames p;
return 0;
}
<commit_msg>Remove obsolete test.<commit_after><|endoftext|> |
<commit_before>// -*- c-basic-offset: 8; indent-tabs: nil -*-
//
// See LICENSE for details.
//
#include <smoke.h>
#include <Qt/qstring.h>
#include <Qt/qstringlist.h>
#include <Qt/qpointer.h>
#include <Qt/qmetaobject.h>
#include <QtCore/qobject.h>
#include <QtGui/qapplication.h>
#include "commonqt.h"
// work around bugs in CCL cdecl callback support
#ifdef COMMONQT_USE_STDCALL
#define MAYBE_STDCALL __stdcall
#else
#define MAYBE_STDCALL
#endif
// #define DEBUG 1
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
typedef void (MAYBE_STDCALL *t_deletion_callback)(void*, void*);
typedef bool (MAYBE_STDCALL *t_callmethod_callback)(void*, short, void*, void*, bool);
typedef void (MAYBE_STDCALL *t_child_callback)(void*, bool, void*);
class ThinBinding : public SmokeBinding
{
public:
ThinBinding(Smoke* s) : SmokeBinding(s) {}
t_deletion_callback deletion_callback;
t_callmethod_callback callmethod_callback;
t_child_callback child_callback;
void deleted(Smoke::Index classId, void* obj) {
deletion_callback(smoke, obj);
}
bool callMethod(Smoke::Index method, void* obj,
Smoke::Stack args, bool isAbstract)
{
Smoke::Method* m = &smoke->methods[method];
const char* name = smoke->methodNames[m->name];
Smoke::Class* c = &smoke->classes[m->classId];
if (*name == '~')
callmethod_callback(smoke, method, obj, args, isAbstract);
else if (!strcmp(name, "notify")
&& (!strcmp(c->className, "QApplication")
|| !strcmp(c->className, "QCoreApplication")))
{
QEvent* e = (QEvent*) args[2].s_voidp;
if (e->type() == QEvent::ChildAdded
|| e->type() == QEvent::ChildRemoved)
{
QChildEvent* f = (QChildEvent*) e;
child_callback(smoke, f->added(), f->child());
}
}
return false;
}
char* className(Smoke::Index classId) {
return (char*) smoke->classes[classId].className;
}
};
class FatBinding : public SmokeBinding
{
public:
FatBinding(Smoke* s) : SmokeBinding(s) {}
t_deletion_callback deletion_callback;
t_callmethod_callback callmethod_callback;
t_child_callback child_callback;
void deleted(Smoke::Index classId, void* obj) {
deletion_callback(smoke, obj);
}
bool callMethod(Smoke::Index method, void* obj,
Smoke::Stack args, bool isAbstract)
{
return callmethod_callback(smoke, method, obj, args, isAbstract);
}
char* className(Smoke::Index classId) {
return (char*) smoke->classes[classId].className;
}
};
void
sw_smoke(Smoke* smoke,
SmokeData* data,
void* deletion_callback,
void* method_callback,
void* child_callback)
{
ThinBinding* thinBinding = new ThinBinding(smoke);
FatBinding* fatBinding = new FatBinding(smoke);
data->name = smoke->moduleName();
data->classes = smoke->classes;
data->numClasses = smoke->numClasses;
data->methods = smoke->methods;
data->numMethods = smoke->numMethods;
data->methodMaps = smoke->methodMaps;
data->numMethodMaps = smoke->numMethodMaps;
data->methodNames = smoke->methodNames;
data->numMethodNames = smoke->numMethodNames;
data->types = smoke->types;
data->numTypes = smoke->numTypes;
data->inheritanceList = smoke->inheritanceList;
data->argumentList = smoke->argumentList;
data->ambiguousMethodList = smoke->ambiguousMethodList;
data->castFn = (void *) smoke->castFn;
fatBinding->deletion_callback
= (t_deletion_callback) deletion_callback;
fatBinding->callmethod_callback
= (t_callmethod_callback) method_callback;
fatBinding->child_callback
= (t_child_callback) child_callback;
thinBinding->deletion_callback = fatBinding->deletion_callback;
thinBinding->callmethod_callback = fatBinding->callmethod_callback;
thinBinding->child_callback = fatBinding->child_callback;
data->thin = thinBinding;
data->fat = fatBinding;
}
int
sw_windows_version()
{
#ifdef WINDOWS
return QSysInfo::windowsVersion();
#else
return -1;
#endif
}
void*
sw_make_qstring(char *str)
{
return new QString(str);
}
void*
sw_qstring_to_utf8(void* s)
{
QString* str = (QString*) s;
return new QByteArray(str->toUtf8());
}
void
sw_delete_qstring(void *q)
{
delete (QString*) q;
}
void*
sw_make_qstringlist()
{
return new QStringList();
}
void
sw_delete_qstringlist(void *q)
{
delete static_cast<QStringList*>(q);
}
void
sw_qstringlist_append(void *q, char *x)
{
static_cast<QStringList*>(q)->append(QString(x));
}
void*
sw_make_metaobject(void *p, char *strings, int *d)
{
QMetaObject* parent = (QMetaObject*) p;
const uint* data = (const uint*) d;
QMetaObject tmp = { { parent, strings, data, 0 } };
QMetaObject* ptr = new QMetaObject;
*ptr = tmp;
return ptr;
}
void
sw_delete(void *p)
{
QObject* q = (QObject*) p;
delete q;
}
typedef void (*t_ptr_callback)(void *);
// quick hack, to be rewritten once we have QList marshalling support
void
sw_map_children(void *x, void *y)
{
t_ptr_callback cb = (t_ptr_callback) y;
QObject* o = (QObject*) x;
const QList<QObject*> l = o->children();
for (int i=0; i < l.size(); ++i)
cb(l.at(i));
}
void*
sw_make_qpointer(void* target)
{
return new QPointer<QObject>((QObject*) target);
}
bool
sw_qpointer_is_null(void* x)
{
QPointer<QObject>* ptr = (QPointer<QObject>*) x;
return ptr->isNull();
}
void
sw_delete_qpointer(void* x)
{
QPointer<QObject>* ptr = (QPointer<QObject>*) x;
delete ptr;
}
extern Smoke *qt_Smoke;
void
sw_find_class(char *name, Smoke **smoke, short *index)
{
Smoke::ModuleIndex mi = qt_Smoke->findClass(name);
*smoke = mi.smoke;
*index = mi.index;
}
short
sw_find_name(Smoke *smoke, char *name)
{
Smoke::ModuleIndex mi = smoke->idMethodName(name);
return mi.index;
}
short
sw_id_method(Smoke *smoke, short classIndex, short name)
{
Smoke::ModuleIndex mi = smoke->idMethod(classIndex, name);
return mi.index;
}
short
sw_id_type(Smoke *smoke, char *name)
{
return smoke->idType(name);
}
<commit_msg>use qtcore instead of the old qt module<commit_after>// -*- c-basic-offset: 8; indent-tabs: nil -*-
//
// See LICENSE for details.
//
#include <smoke.h>
#include <Qt/qstring.h>
#include <Qt/qstringlist.h>
#include <Qt/qpointer.h>
#include <Qt/qmetaobject.h>
#include <QtCore/qobject.h>
#include <QtGui/qapplication.h>
#include "commonqt.h"
// work around bugs in CCL cdecl callback support
#ifdef COMMONQT_USE_STDCALL
#define MAYBE_STDCALL __stdcall
#else
#define MAYBE_STDCALL
#endif
// #define DEBUG 1
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
typedef void (MAYBE_STDCALL *t_deletion_callback)(void*, void*);
typedef bool (MAYBE_STDCALL *t_callmethod_callback)(void*, short, void*, void*, bool);
typedef void (MAYBE_STDCALL *t_child_callback)(void*, bool, void*);
class ThinBinding : public SmokeBinding
{
public:
ThinBinding(Smoke* s) : SmokeBinding(s) {}
t_deletion_callback deletion_callback;
t_callmethod_callback callmethod_callback;
t_child_callback child_callback;
void deleted(Smoke::Index classId, void* obj) {
deletion_callback(smoke, obj);
}
bool callMethod(Smoke::Index method, void* obj,
Smoke::Stack args, bool isAbstract)
{
Smoke::Method* m = &smoke->methods[method];
const char* name = smoke->methodNames[m->name];
Smoke::Class* c = &smoke->classes[m->classId];
if (*name == '~')
callmethod_callback(smoke, method, obj, args, isAbstract);
else if (!strcmp(name, "notify")
&& (!strcmp(c->className, "QApplication")
|| !strcmp(c->className, "QCoreApplication")))
{
QEvent* e = (QEvent*) args[2].s_voidp;
if (e->type() == QEvent::ChildAdded
|| e->type() == QEvent::ChildRemoved)
{
QChildEvent* f = (QChildEvent*) e;
child_callback(smoke, f->added(), f->child());
}
}
return false;
}
char* className(Smoke::Index classId) {
return (char*) smoke->classes[classId].className;
}
};
class FatBinding : public SmokeBinding
{
public:
FatBinding(Smoke* s) : SmokeBinding(s) {}
t_deletion_callback deletion_callback;
t_callmethod_callback callmethod_callback;
t_child_callback child_callback;
void deleted(Smoke::Index classId, void* obj) {
deletion_callback(smoke, obj);
}
bool callMethod(Smoke::Index method, void* obj,
Smoke::Stack args, bool isAbstract)
{
return callmethod_callback(smoke, method, obj, args, isAbstract);
}
char* className(Smoke::Index classId) {
return (char*) smoke->classes[classId].className;
}
};
void
sw_smoke(Smoke* smoke,
SmokeData* data,
void* deletion_callback,
void* method_callback,
void* child_callback)
{
ThinBinding* thinBinding = new ThinBinding(smoke);
FatBinding* fatBinding = new FatBinding(smoke);
data->name = smoke->moduleName();
data->classes = smoke->classes;
data->numClasses = smoke->numClasses;
data->methods = smoke->methods;
data->numMethods = smoke->numMethods;
data->methodMaps = smoke->methodMaps;
data->numMethodMaps = smoke->numMethodMaps;
data->methodNames = smoke->methodNames;
data->numMethodNames = smoke->numMethodNames;
data->types = smoke->types;
data->numTypes = smoke->numTypes;
data->inheritanceList = smoke->inheritanceList;
data->argumentList = smoke->argumentList;
data->ambiguousMethodList = smoke->ambiguousMethodList;
data->castFn = (void *) smoke->castFn;
fatBinding->deletion_callback
= (t_deletion_callback) deletion_callback;
fatBinding->callmethod_callback
= (t_callmethod_callback) method_callback;
fatBinding->child_callback
= (t_child_callback) child_callback;
thinBinding->deletion_callback = fatBinding->deletion_callback;
thinBinding->callmethod_callback = fatBinding->callmethod_callback;
thinBinding->child_callback = fatBinding->child_callback;
data->thin = thinBinding;
data->fat = fatBinding;
}
int
sw_windows_version()
{
#ifdef WINDOWS
return QSysInfo::windowsVersion();
#else
return -1;
#endif
}
void*
sw_make_qstring(char *str)
{
return new QString(str);
}
void*
sw_qstring_to_utf8(void* s)
{
QString* str = (QString*) s;
return new QByteArray(str->toUtf8());
}
void
sw_delete_qstring(void *q)
{
delete (QString*) q;
}
void*
sw_make_qstringlist()
{
return new QStringList();
}
void
sw_delete_qstringlist(void *q)
{
delete static_cast<QStringList*>(q);
}
void
sw_qstringlist_append(void *q, char *x)
{
static_cast<QStringList*>(q)->append(QString(x));
}
void*
sw_make_metaobject(void *p, char *strings, int *d)
{
QMetaObject* parent = (QMetaObject*) p;
const uint* data = (const uint*) d;
QMetaObject tmp = { { parent, strings, data, 0 } };
QMetaObject* ptr = new QMetaObject;
*ptr = tmp;
return ptr;
}
void
sw_delete(void *p)
{
QObject* q = (QObject*) p;
delete q;
}
typedef void (*t_ptr_callback)(void *);
// quick hack, to be rewritten once we have QList marshalling support
void
sw_map_children(void *x, void *y)
{
t_ptr_callback cb = (t_ptr_callback) y;
QObject* o = (QObject*) x;
const QList<QObject*> l = o->children();
for (int i=0; i < l.size(); ++i)
cb(l.at(i));
}
void*
sw_make_qpointer(void* target)
{
return new QPointer<QObject>((QObject*) target);
}
bool
sw_qpointer_is_null(void* x)
{
QPointer<QObject>* ptr = (QPointer<QObject>*) x;
return ptr->isNull();
}
void
sw_delete_qpointer(void* x)
{
QPointer<QObject>* ptr = (QPointer<QObject>*) x;
delete ptr;
}
extern Smoke *qtcore_Smoke;
void
sw_find_class(char *name, Smoke **smoke, short *index)
{
Smoke::ModuleIndex mi = qtcore_Smoke->findClass(name);
*smoke = mi.smoke;
*index = mi.index;
}
short
sw_find_name(Smoke *smoke, char *name)
{
Smoke::ModuleIndex mi = smoke->idMethodName(name);
return mi.index;
}
short
sw_id_method(Smoke *smoke, short classIndex, short name)
{
Smoke::ModuleIndex mi = smoke->idMethod(classIndex, name);
return mi.index;
}
short
sw_id_type(Smoke *smoke, char *name)
{
return smoke->idType(name);
}
<|endoftext|> |
<commit_before>#pragma once
#include "bdd_model.hpp"
#include "graph_algorithm.hpp"
#include "graph_model.hpp"
#include <vector>
namespace verilog
{
//using namespace bdd;
//using namespace graph;
struct BDD_Builder {
graph::G & g;
bdd::BDD & bdds;
std::vector<bdd::Node*> bdd_nodes;
BDD_Builder(graph::G & g, bdd::BDD & bdds): g(g), bdds(bdds), bdd_nodes(num_vertices(g.graph)) {
}
bdd::Node * sum_nodes_group_ands_and_ors(int node) {
auto p = in_edges(node, g.graph);
bdd::Node * sum_or = bdds.zero;
bdd::Node * sum_and = bdds.one;
for (auto e = p.first; e != p.second; ++e) {
bdd::Node * s = bdd_nodes[source(*e, g.graph)];
if(g.graph[*e] == NegP::Positive) {
sum_and = bdds.land(sum_and, s);
}
else {
sum_or = bdds.lor(sum_or, s);
}
//bdd::Node * s2 = g.graph[*e] == NegP::Positive ? s : bdds.negate(s);
}
return bdds.land(sum_and, bdds.negate(sum_or));
}
bdd::Node * sum_nodes(int node) {
auto p = in_edges(node, g.graph);
bdd::Node * sum = bdds.one;
for (auto e = p.first; e != p.second; ++e) {
bdd::Node * s = bdd_nodes[source(*e, g.graph)];
bdd::Node * s2 = g.graph[*e] == NegP::Positive ? s : bdds.negate(s);
sum = bdds.land(sum, s);
}
return sum;
}
bdd::Node * sum_nodes_lor(int node) {
auto p = in_edges(node, g.graph);
bdd::Node * sum = bdds.zero;
for (auto e = p.first; e != p.second; ++e) {
bdd::Node * s = bdd_nodes[source(*e, g.graph)];
bdd::Node * s2 = g.graph[*e] == NegP::Positive ? bdds.negate(s) : s;
sum = bdds.lor(sum, s);
}
return bdds.negate(sum);
}
void build() {
auto topo_order = topological_sort(g);
for (int node : topo_order) {
if(node == g.zero) {
bdd_nodes[node] = bdds.zero;
}
else if(node == g.one) {
bdd_nodes[node] = bdds.one;
}
else if(in_degree(node, g.graph) == 0) {
printf("// adding input node %d\n", node);
bdd_nodes[node] = bdds.add_simple_input(g.graph[node].identifier);
}
else {
//bdd_nodes[node] = sum_nodes_lor(node);
//bdd_nodes[node] = sum_nodes(node);
bdd_nodes[node] = sum_nodes_group_ands_and_ors(node);
if(bdd_nodes[node]->r_t) {
printf("// replacing representative of node %p: %d -> %d\n", bdd_nodes[node], *bdd_nodes[node]->r_t, node);
}
else {
printf("// adding representative to node %p: %d\n", bdd_nodes[node], node);
}
bdd_nodes[node]->r_t = node;
}
}
}
};
}
<commit_msg>Using just nands.<commit_after>#pragma once
#include "bdd_model.hpp"
#include "graph_algorithm.hpp"
#include "graph_model.hpp"
#include <vector>
namespace verilog
{
//using namespace bdd;
//using namespace graph;
struct BDD_Builder {
graph::G & g;
bdd::BDD & bdds;
std::vector<bdd::Node*> bdd_nodes;
BDD_Builder(graph::G & g, bdd::BDD & bdds): g(g), bdds(bdds), bdd_nodes(num_vertices(g.graph)) {
}
bdd::Node * sum_nodes_group_ands_and_ors(int node) {
auto p = in_edges(node, g.graph);
bdd::Node * sum_or = bdds.zero;
bdd::Node * sum_and = bdds.one;
for (auto e = p.first; e != p.second; ++e) {
bdd::Node * s = bdd_nodes[source(*e, g.graph)];
if(g.graph[*e] == NegP::Positive) {
sum_and = bdds.land(sum_and, s);
}
else {
sum_or = bdds.lor(sum_or, s);
}
//bdd::Node * s2 = g.graph[*e] == NegP::Positive ? s : bdds.negate(s);
}
return bdds.land(sum_and, bdds.negate(sum_or));
}
bdd::Node * sum_nodes(int node) {
auto p = in_edges(node, g.graph);
bdd::Node * sum = bdds.one;
for (auto e = p.first; e != p.second; ++e) {
bdd::Node * s = bdd_nodes[source(*e, g.graph)];
bdd::Node * s2 = g.graph[*e] == NegP::Positive ? s : bdds.negate(s);
sum = bdds.land(sum, s);
}
return sum;
}
bdd::Node * sum_nodes_lor(int node) {
auto p = in_edges(node, g.graph);
bdd::Node * sum = bdds.zero;
for (auto e = p.first; e != p.second; ++e) {
bdd::Node * s = bdd_nodes[source(*e, g.graph)];
bdd::Node * s2 = g.graph[*e] == NegP::Positive ? bdds.negate(s) : s;
sum = bdds.lor(sum, s);
}
return bdds.negate(sum);
}
void build() {
auto topo_order = topological_sort(g);
for (int node : topo_order) {
if(node == g.zero) {
bdd_nodes[node] = bdds.zero;
}
else if(node == g.one) {
bdd_nodes[node] = bdds.one;
}
else if(in_degree(node, g.graph) == 0) {
printf("// adding input node %d\n", node);
bdd_nodes[node] = bdds.add_simple_input(g.graph[node].identifier);
}
else {
// TODO check which of these 3 is best.
//bdd_nodes[node] = sum_nodes_lor(node);
bdd_nodes[node] = sum_nodes(node);
//bdd_nodes[node] = sum_nodes_group_ands_and_ors(node);
if(bdd_nodes[node]->r_t) {
printf("// replacing representative of node %p: %d -> %d\n", bdd_nodes[node], *bdd_nodes[node]->r_t, node);
}
else {
printf("// adding representative to node %p: %d\n", bdd_nodes[node], node);
}
bdd_nodes[node]->r_t = node;
}
}
}
};
}
<|endoftext|> |
<commit_before>//===- IntrinsicEmitter.cpp - Generate intrinsic information --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend emits information about intrinsic functions.
//
//===----------------------------------------------------------------------===//
#include "IntrinsicEmitter.h"
#include "Record.h"
#include "llvm/ADT/StringExtras.h"
#include <algorithm>
using namespace llvm;
//===----------------------------------------------------------------------===//
// IntrinsicEmitter Implementation
//===----------------------------------------------------------------------===//
void IntrinsicEmitter::run(std::ostream &OS) {
EmitSourceFileHeader("Intrinsic Function Source Fragment", OS);
std::vector<CodeGenIntrinsic> Ints = LoadIntrinsics(Records);
// Emit the enum information.
EmitEnumInfo(Ints, OS);
// Emit the intrinsic ID -> name table.
EmitIntrinsicToNameTable(Ints, OS);
// Emit the function name recognizer.
EmitFnNameRecognizer(Ints, OS);
// Emit the intrinsic verifier.
EmitVerifier(Ints, OS);
// Emit mod/ref info for each function.
EmitModRefInfo(Ints, OS);
// Emit table of non-memory accessing intrinsics.
EmitNoMemoryInfo(Ints, OS);
// Emit side effect info for each intrinsic.
EmitSideEffectInfo(Ints, OS);
// Emit a list of intrinsics with corresponding GCC builtins.
EmitGCCBuiltinList(Ints, OS);
// Emit code to translate GCC builtins into LLVM intrinsics.
EmitIntrinsicToGCCBuiltinMap(Ints, OS);
}
void IntrinsicEmitter::EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints,
std::ostream &OS) {
OS << "// Enum values for Intrinsics.h\n";
OS << "#ifdef GET_INTRINSIC_ENUM_VALUES\n";
for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
OS << " " << Ints[i].EnumName;
OS << ((i != e-1) ? ", " : " ");
OS << std::string(40-Ints[i].EnumName.size(), ' ')
<< "// " << Ints[i].Name << "\n";
}
OS << "#endif\n\n";
}
void IntrinsicEmitter::
EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints,
std::ostream &OS) {
// Build a function name -> intrinsic name mapping.
std::map<std::string, std::string> IntMapping;
for (unsigned i = 0, e = Ints.size(); i != e; ++i)
IntMapping[Ints[i].Name] = Ints[i].EnumName;
OS << "// Function name -> enum value recognizer code.\n";
OS << "#ifdef GET_FUNCTION_RECOGNIZER\n";
OS << " switch (Name[5]) {\n";
OS << " default: break;\n";
// Emit the intrinsics in sorted order.
char LastChar = 0;
for (std::map<std::string, std::string>::iterator I = IntMapping.begin(),
E = IntMapping.end(); I != E; ++I) {
if (I->first[5] != LastChar) {
LastChar = I->first[5];
OS << " case '" << LastChar << "':\n";
}
OS << " if (Name == \"" << I->first << "\") return Intrinsic::"
<< I->second << ";\n";
}
OS << " }\n";
OS << " // The 'llvm.' namespace is reserved!\n";
OS << " assert(0 && \"Unknown LLVM intrinsic function!\");\n";
OS << "#endif\n\n";
}
void IntrinsicEmitter::
EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> &Ints,
std::ostream &OS) {
OS << "// Intrinsic ID to name table\n";
OS << "#ifdef GET_INTRINSIC_NAME_TABLE\n";
OS << " // Note that entry #0 is the invalid intrinsic!\n";
for (unsigned i = 0, e = Ints.size(); i != e; ++i)
OS << " \"" << Ints[i].Name << "\",\n";
OS << "#endif\n\n";
}
static void EmitTypeVerify(std::ostream &OS, const std::string &Val,
Record *ArgType) {
OS << " Assert1(" << Val << "->getTypeID() == "
<< ArgType->getValueAsString("TypeVal") << ",\n"
<< " \"Illegal intrinsic type!\", IF);\n";
// If this is a packed type, check that the subtype and size are correct.
if (ArgType->isSubClassOf("LLVMPackedType")) {
Record *SubType = ArgType->getValueAsDef("ElTy");
OS << " Assert1(cast<PackedType>(" << Val
<< ")->getElementType()->getTypeID() == "
<< SubType->getValueAsString("TypeVal") << ",\n"
<< " \"Illegal intrinsic type!\", IF);\n";
OS << " Assert1(cast<PackedType>(" << Val << ")->getNumElements() == "
<< ArgType->getValueAsInt("NumElts") << ",\n"
<< " \"Illegal intrinsic type!\", IF);\n";
}
}
void IntrinsicEmitter::EmitVerifier(const std::vector<CodeGenIntrinsic> &Ints,
std::ostream &OS) {
OS << "// Verifier::visitIntrinsicFunctionCall code.\n";
OS << "#ifdef GET_INTRINSIC_VERIFIER\n";
OS << " switch (ID) {\n";
OS << " default: assert(0 && \"Invalid intrinsic!\");\n";
for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
OS << " case Intrinsic::" << Ints[i].EnumName << ":\t\t// "
<< Ints[i].Name << "\n";
OS << " Assert1(FTy->getNumParams() == " << Ints[i].ArgTypes.size()-1
<< ",\n"
<< " \"Illegal # arguments for intrinsic function!\", IF);\n";
EmitTypeVerify(OS, "FTy->getReturnType()", Ints[i].ArgTypeDefs[0]);
for (unsigned j = 1; j != Ints[i].ArgTypes.size(); ++j)
EmitTypeVerify(OS, "FTy->getParamType(" + utostr(j-1) + ")",
Ints[i].ArgTypeDefs[j]);
OS << " break;\n";
}
OS << " }\n";
OS << "#endif\n\n";
}
void IntrinsicEmitter::EmitModRefInfo(const std::vector<CodeGenIntrinsic> &Ints,
std::ostream &OS) {
OS << "// BasicAliasAnalysis code.\n";
OS << "#ifdef GET_MODREF_BEHAVIOR\n";
for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
switch (Ints[i].ModRef) {
default: break;
case CodeGenIntrinsic::NoMem:
OS << " NoMemoryTable.push_back(\"" << Ints[i].Name << "\");\n";
break;
case CodeGenIntrinsic::ReadArgMem:
case CodeGenIntrinsic::ReadMem:
OS << " OnlyReadsMemoryTable.push_back(\"" << Ints[i].Name << "\");\n";
break;
}
}
OS << "#endif\n\n";
}
void IntrinsicEmitter::
EmitNoMemoryInfo(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS) {
OS << "// SelectionDAGIsel code.\n";
OS << "#ifdef GET_NO_MEMORY_INTRINSICS\n";
OS << " switch (IntrinsicID) {\n";
OS << " default: break;\n";
for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
switch (Ints[i].ModRef) {
default: break;
case CodeGenIntrinsic::NoMem:
OS << " case Intrinsic::" << Ints[i].EnumName << ":\n";
break;
}
}
OS << " return true; // These intrinsics have no side effects.\n";
OS << " }\n";
OS << "#endif\n\n";
}
void IntrinsicEmitter::
EmitSideEffectInfo(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS){
OS << "// isInstructionTriviallyDead code.\n";
OS << "#ifdef GET_SIDE_EFFECT_INFO\n";
OS << " switch (F->getIntrinsicID()) {\n";
OS << " default: break;\n";
for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
switch (Ints[i].ModRef) {
default: break;
case CodeGenIntrinsic::NoMem:
case CodeGenIntrinsic::ReadArgMem:
case CodeGenIntrinsic::ReadMem:
OS << " case Intrinsic::" << Ints[i].EnumName << ":\n";
break;
}
}
OS << " return true; // These intrinsics have no side effects.\n";
OS << " }\n";
OS << "#endif\n\n";
}
void IntrinsicEmitter::
EmitGCCBuiltinList(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS){
OS << "// Get the GCC builtin that corresponds to an LLVM intrinsic.\n";
OS << "#ifdef GET_GCC_BUILTIN_NAME\n";
OS << " switch (F->getIntrinsicID()) {\n";
OS << " default: BuiltinName = \"\"; break;\n";
for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
if (!Ints[i].GCCBuiltinName.empty()) {
OS << " case Intrinsic::" << Ints[i].EnumName << ": BuiltinName = \""
<< Ints[i].GCCBuiltinName << "\"; break;\n";
}
}
OS << " }\n";
OS << "#endif\n\n";
}
void IntrinsicEmitter::
EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints,
std::ostream &OS) {
typedef std::map<std::pair<std::string, std::string>, std::string> BIMTy;
BIMTy BuiltinMap;
for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
if (!Ints[i].GCCBuiltinName.empty()) {
std::pair<std::string, std::string> Key(Ints[i].GCCBuiltinName,
Ints[i].TargetPrefix);
if (!BuiltinMap.insert(std::make_pair(Key, Ints[i].EnumName)).second)
throw "Intrinsic '" + Ints[i].TheDef->getName() +
"': duplicate GCC builtin name!";
}
}
OS << "// Get the LLVM intrinsic that corresponds to a GCC builtin.\n";
OS << "// This is used by the C front-end. The GCC builtin name is passed\n";
OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
OS << "// in as TargetPrefix. The result is assigned to 'IntrinsicID'.\n";
OS << "#ifdef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN\n";
OS << " if (0);\n";
// Note: this could emit significantly better code if we cared.
for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){
OS << " else if (";
if (!I->first.second.empty()) {
// Emit this as a strcmp, so it can be constant folded by the FE.
OS << "!strcmp(TargetPrefix, \"" << I->first.second << "\") &&\n"
<< " ";
}
OS << "!strcmp(BuiltinName, \"" << I->first.first << "\"))\n";
OS << " IntrinsicID = Intrinsic::" << I->second << ";\n";
}
OS << " else\n";
OS << " IntrinsicID = Intrinsic::not_intrinsic;\n";
OS << "#endif\n\n";
}
<commit_msg>When emitting code for the verifier, instead of emitting each case statement independently, batch up checks so that identically typed intrinsics share verifier code. This dramatically reduces the size of the verifier function, which should help avoid GCC running out of memory compiling Verifier.cpp.<commit_after>//===- IntrinsicEmitter.cpp - Generate intrinsic information --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend emits information about intrinsic functions.
//
//===----------------------------------------------------------------------===//
#include "IntrinsicEmitter.h"
#include "Record.h"
#include "llvm/ADT/StringExtras.h"
#include <algorithm>
using namespace llvm;
//===----------------------------------------------------------------------===//
// IntrinsicEmitter Implementation
//===----------------------------------------------------------------------===//
void IntrinsicEmitter::run(std::ostream &OS) {
EmitSourceFileHeader("Intrinsic Function Source Fragment", OS);
std::vector<CodeGenIntrinsic> Ints = LoadIntrinsics(Records);
// Emit the enum information.
EmitEnumInfo(Ints, OS);
// Emit the intrinsic ID -> name table.
EmitIntrinsicToNameTable(Ints, OS);
// Emit the function name recognizer.
EmitFnNameRecognizer(Ints, OS);
// Emit the intrinsic verifier.
EmitVerifier(Ints, OS);
// Emit mod/ref info for each function.
EmitModRefInfo(Ints, OS);
// Emit table of non-memory accessing intrinsics.
EmitNoMemoryInfo(Ints, OS);
// Emit side effect info for each intrinsic.
EmitSideEffectInfo(Ints, OS);
// Emit a list of intrinsics with corresponding GCC builtins.
EmitGCCBuiltinList(Ints, OS);
// Emit code to translate GCC builtins into LLVM intrinsics.
EmitIntrinsicToGCCBuiltinMap(Ints, OS);
}
void IntrinsicEmitter::EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints,
std::ostream &OS) {
OS << "// Enum values for Intrinsics.h\n";
OS << "#ifdef GET_INTRINSIC_ENUM_VALUES\n";
for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
OS << " " << Ints[i].EnumName;
OS << ((i != e-1) ? ", " : " ");
OS << std::string(40-Ints[i].EnumName.size(), ' ')
<< "// " << Ints[i].Name << "\n";
}
OS << "#endif\n\n";
}
void IntrinsicEmitter::
EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints,
std::ostream &OS) {
// Build a function name -> intrinsic name mapping.
std::map<std::string, std::string> IntMapping;
for (unsigned i = 0, e = Ints.size(); i != e; ++i)
IntMapping[Ints[i].Name] = Ints[i].EnumName;
OS << "// Function name -> enum value recognizer code.\n";
OS << "#ifdef GET_FUNCTION_RECOGNIZER\n";
OS << " switch (Name[5]) {\n";
OS << " default: break;\n";
// Emit the intrinsics in sorted order.
char LastChar = 0;
for (std::map<std::string, std::string>::iterator I = IntMapping.begin(),
E = IntMapping.end(); I != E; ++I) {
if (I->first[5] != LastChar) {
LastChar = I->first[5];
OS << " case '" << LastChar << "':\n";
}
OS << " if (Name == \"" << I->first << "\") return Intrinsic::"
<< I->second << ";\n";
}
OS << " }\n";
OS << " // The 'llvm.' namespace is reserved!\n";
OS << " assert(0 && \"Unknown LLVM intrinsic function!\");\n";
OS << "#endif\n\n";
}
void IntrinsicEmitter::
EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> &Ints,
std::ostream &OS) {
OS << "// Intrinsic ID to name table\n";
OS << "#ifdef GET_INTRINSIC_NAME_TABLE\n";
OS << " // Note that entry #0 is the invalid intrinsic!\n";
for (unsigned i = 0, e = Ints.size(); i != e; ++i)
OS << " \"" << Ints[i].Name << "\",\n";
OS << "#endif\n\n";
}
static void EmitTypeVerify(std::ostream &OS, const std::string &Val,
Record *ArgType) {
OS << " Assert1(" << Val << "->getTypeID() == "
<< ArgType->getValueAsString("TypeVal") << ",\n"
<< " \"Illegal intrinsic type!\", IF);\n";
// If this is a packed type, check that the subtype and size are correct.
if (ArgType->isSubClassOf("LLVMPackedType")) {
Record *SubType = ArgType->getValueAsDef("ElTy");
OS << " Assert1(cast<PackedType>(" << Val
<< ")->getElementType()->getTypeID() == "
<< SubType->getValueAsString("TypeVal") << ",\n"
<< " \"Illegal intrinsic type!\", IF);\n";
OS << " Assert1(cast<PackedType>(" << Val << ")->getNumElements() == "
<< ArgType->getValueAsInt("NumElts") << ",\n"
<< " \"Illegal intrinsic type!\", IF);\n";
}
}
/// RecordListComparator - Provide a determinstic comparator for lists of
/// records.
namespace {
struct RecordListComparator {
bool operator()(const std::vector<Record*> &LHS,
const std::vector<Record*> &RHS) const {
unsigned i = 0;
do {
if (i == RHS.size()) return false; // RHS is shorter than LHS.
if (LHS[i] != RHS[i])
return LHS[i]->getName() < RHS[i]->getName();
} while (++i != LHS.size());
return i != RHS.size();
}
};
}
void IntrinsicEmitter::EmitVerifier(const std::vector<CodeGenIntrinsic> &Ints,
std::ostream &OS) {
OS << "// Verifier::visitIntrinsicFunctionCall code.\n";
OS << "#ifdef GET_INTRINSIC_VERIFIER\n";
OS << " switch (ID) {\n";
OS << " default: assert(0 && \"Invalid intrinsic!\");\n";
// This checking can emit a lot of very common code. To reduce the amount of
// code that we emit, batch up cases that have identical types. This avoids
// problems where GCC can run out of memory compiling Verifier.cpp.
typedef std::map<std::vector<Record*>, std::vector<unsigned>,
RecordListComparator> MapTy;
MapTy UniqueArgInfos;
// Compute the unique argument type info.
for (unsigned i = 0, e = Ints.size(); i != e; ++i)
UniqueArgInfos[Ints[i].ArgTypeDefs].push_back(i);
// Loop through the array, emitting one comparison for each batch.
for (MapTy::iterator I = UniqueArgInfos.begin(),
E = UniqueArgInfos.end(); I != E; ++I) {
for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
OS << " case Intrinsic::" << Ints[I->second[i]].EnumName << ":\t\t// "
<< Ints[I->second[i]].Name << "\n";
}
const std::vector<Record*> &ArgTypes = I->first;
OS << " Assert1(FTy->getNumParams() == " << ArgTypes.size()-1 << ",\n"
<< " \"Illegal # arguments for intrinsic function!\", IF);\n";
EmitTypeVerify(OS, "FTy->getReturnType()", ArgTypes[0]);
for (unsigned j = 1; j != ArgTypes.size(); ++j)
EmitTypeVerify(OS, "FTy->getParamType(" + utostr(j-1) + ")", ArgTypes[j]);
OS << " break;\n";
}
OS << " }\n";
OS << "#endif\n\n";
}
void IntrinsicEmitter::EmitModRefInfo(const std::vector<CodeGenIntrinsic> &Ints,
std::ostream &OS) {
OS << "// BasicAliasAnalysis code.\n";
OS << "#ifdef GET_MODREF_BEHAVIOR\n";
for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
switch (Ints[i].ModRef) {
default: break;
case CodeGenIntrinsic::NoMem:
OS << " NoMemoryTable.push_back(\"" << Ints[i].Name << "\");\n";
break;
case CodeGenIntrinsic::ReadArgMem:
case CodeGenIntrinsic::ReadMem:
OS << " OnlyReadsMemoryTable.push_back(\"" << Ints[i].Name << "\");\n";
break;
}
}
OS << "#endif\n\n";
}
void IntrinsicEmitter::
EmitNoMemoryInfo(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS) {
OS << "// SelectionDAGIsel code.\n";
OS << "#ifdef GET_NO_MEMORY_INTRINSICS\n";
OS << " switch (IntrinsicID) {\n";
OS << " default: break;\n";
for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
switch (Ints[i].ModRef) {
default: break;
case CodeGenIntrinsic::NoMem:
OS << " case Intrinsic::" << Ints[i].EnumName << ":\n";
break;
}
}
OS << " return true; // These intrinsics have no side effects.\n";
OS << " }\n";
OS << "#endif\n\n";
}
void IntrinsicEmitter::
EmitSideEffectInfo(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS){
OS << "// isInstructionTriviallyDead code.\n";
OS << "#ifdef GET_SIDE_EFFECT_INFO\n";
OS << " switch (F->getIntrinsicID()) {\n";
OS << " default: break;\n";
for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
switch (Ints[i].ModRef) {
default: break;
case CodeGenIntrinsic::NoMem:
case CodeGenIntrinsic::ReadArgMem:
case CodeGenIntrinsic::ReadMem:
OS << " case Intrinsic::" << Ints[i].EnumName << ":\n";
break;
}
}
OS << " return true; // These intrinsics have no side effects.\n";
OS << " }\n";
OS << "#endif\n\n";
}
void IntrinsicEmitter::
EmitGCCBuiltinList(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS){
OS << "// Get the GCC builtin that corresponds to an LLVM intrinsic.\n";
OS << "#ifdef GET_GCC_BUILTIN_NAME\n";
OS << " switch (F->getIntrinsicID()) {\n";
OS << " default: BuiltinName = \"\"; break;\n";
for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
if (!Ints[i].GCCBuiltinName.empty()) {
OS << " case Intrinsic::" << Ints[i].EnumName << ": BuiltinName = \""
<< Ints[i].GCCBuiltinName << "\"; break;\n";
}
}
OS << " }\n";
OS << "#endif\n\n";
}
void IntrinsicEmitter::
EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints,
std::ostream &OS) {
typedef std::map<std::pair<std::string, std::string>, std::string> BIMTy;
BIMTy BuiltinMap;
for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
if (!Ints[i].GCCBuiltinName.empty()) {
std::pair<std::string, std::string> Key(Ints[i].GCCBuiltinName,
Ints[i].TargetPrefix);
if (!BuiltinMap.insert(std::make_pair(Key, Ints[i].EnumName)).second)
throw "Intrinsic '" + Ints[i].TheDef->getName() +
"': duplicate GCC builtin name!";
}
}
OS << "// Get the LLVM intrinsic that corresponds to a GCC builtin.\n";
OS << "// This is used by the C front-end. The GCC builtin name is passed\n";
OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
OS << "// in as TargetPrefix. The result is assigned to 'IntrinsicID'.\n";
OS << "#ifdef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN\n";
OS << " if (0);\n";
// Note: this could emit significantly better code if we cared.
for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){
OS << " else if (";
if (!I->first.second.empty()) {
// Emit this as a strcmp, so it can be constant folded by the FE.
OS << "!strcmp(TargetPrefix, \"" << I->first.second << "\") &&\n"
<< " ";
}
OS << "!strcmp(BuiltinName, \"" << I->first.first << "\"))\n";
OS << " IntrinsicID = Intrinsic::" << I->second << ";\n";
}
OS << " else\n";
OS << " IntrinsicID = Intrinsic::not_intrinsic;\n";
OS << "#endif\n\n";
}
<|endoftext|> |
<commit_before>#include <string>
#include <vector>
#include <boost/tokenizer.hpp>
#include <iostream>
#include <stdlib.h>
#include <cstdio>
#include <sys/wait.h>
using namespace boost;
using namespace std;
class rshell{
protected:
//Data Members
string commands;
string nextConnector;
vector<string> commandlist;
bool prevCommandPass;
bool allCount;
bool forceExit;
public:
//Constructor
rshell(){
commands = "";
nextConnector = ";";
prevCommandPass = true;
forceExit = false;
allCount = true;
}
// Parses the string (strings ending in ';' will keep the ';')
void parseAllCommands(){
char_separator<char> delims(" ");
tokenizer<char_separator<char> > tokenlist(commands, delims);
for (tokenizer<char_separator<char> >::iterator i = tokenlist.begin(); i != tokenlist.end(); i++){
string com(*i);
commandlist.push_back(com);
}
}
// Executes one command and sets prevCommandPass to true or false.
void executeCommand(vector<string> com){
char* argv[1024];
pid_t p = getpid();
pid_t pid = fork();
int status;
for(unsigned int i = 0; i < com.size(); i++){
argv[i] = (char*)com.at(i).c_str();
}
argv[com.size()] = NULL;
if (pid == 0){
if (execvp(argv[0], argv)){
prevCommandPass = true;
}
perror("execvp failed: ");
prevCommandPass = false;
_exit(1);
}
else if (pid > 0){
if ((p = wait(&status)) < 0){
perror("child failed: ");
prevCommandPass = false;
_exit(1);
}
}
else{
perror("fork failed: ");
_exit(1);
}
}
//Splits commandlist into commands with their arguments then calls executeCommand to run them.
void executeAllCommands(){
vector<string> commandsublist;
unsigned int i = 0;
unsigned int j = 0;
while (i < commandlist.size()){
j = 0;
if (checkCommandRun()){
while (!checkBreaker(i)){
//Exit check
if (commandlist.at(i) == "exit"){
cout << "Forced Exit." << endl;
forceExit = true;
_Exit(0);
}
// Comment check
if (commandlist.at(i) == "#" || checkComment(commandlist.at(i))){
executeCommand(commandsublist);
return;
}
//Adds command to the list
commandsublist.push_back(commandlist.at(i));
i++;
j++;
if (i == commandlist.size()){
executeCommand(commandsublist);
return;
}
}
if (checkBreaker(i)){
if (nextConnector == "||"){
if (allCount == true){
prevCommandPass = true;
}
else{
if (prevCommandPass == false){
allCount = false;
}
else{
allCount = true;
}
}
}
else if (nextConnector == "&&"){
if (allCount == true){
if (prevCommandPass == false){
allCount = false;
}
}
else{
allCount = false;
prevCommandPass = false;
}
}
else if (nextConnector == ";"){
allCount = true;
prevCommandPass = true;
}
nextConnector = commandlist.at(i);
}
i++;
}
executeCommand(commandsublist);
commandsublist.clear();
}
}
// Checks if there is a '#' at the front of the string
bool checkComment(string str){
if (str.at(0) == '#'){
return true;
}
return false
}
// Checks if the string is a breaker
bool checkBreaker(int i){
if (i < commandlist.size() + 1){
if (commandlist.at(i) == "|" && commandlist.at(i + 1) == "|"){
return true;
}
else if (commandlist.at(i) == "&" && commandlist.at(i + 1) == "&"){
return true;
}
else if (commandlist.at(i) == ";"){
return true;
else{
return false;
}
}
else
return false;
}
}
// Checks if the next command should be run
bool checkCommandRun(){
if (nextConnector == "||"){
if(allCount == true){
return false;
}
else{
return true;
}
}
else if (nextConnector == "&&"){
if(allCount == true){
return true;
}
else{
return false;
}
}
else if (nextConnector == ";"){
return true;
}
else{
return false;
}
}
//Starts the program.
void run(){
while (!forceExit && commands != "exit"){
cout << "$";
getline(cin, commands);
parseAllCommands();
executeAllCommands();
commandlist.clear();
nextConnector = ";";
prevCommandPass = true;
}
}
};
<commit_msg>Edits to execute function checking<commit_after>#include <string>
#include <vector>
#include <boost/tokenizer.hpp>
#include <iostream>
#include <stdlib.h>
#include <cstdio>
#include <sys/wait.h>
using namespace boost;
using namespace std;
class rshell{
protected:
//Data Members
string commands;
string nextConnector;
vector<string> commandlist;
bool prevCommandPass;
bool allCount;
bool forceExit;
public:
//Constructor
rshell(){
commands = "";
nextConnector = ";";
prevCommandPass = true;
forceExit = false;
allCount = true;
}
// Parses the string (strings ending in ';' will keep the ';')
void parseAllCommands(){
char_separator<char> delims(" ");
tokenizer<char_separator<char> > tokenlist(commands, delims);
for (tokenizer<char_separator<char> >::iterator i = tokenlist.begin(); i != tokenlist.end(); i++){
string com(*i);
commandlist.push_back(com);
}
}
// Executes one command and sets prevCommandPass to true or false.
void executeCommand(vector<string> com){
char* argv[1024];
pid_t p = getpid();
pid_t pid = fork();
int status;
for(unsigned int i = 0; i < com.size(); i++){
argv[i] = (char*)com.at(i).c_str();
}
argv[com.size()] = NULL;
if (pid == 0){
prevCommandPass = true;
execvp(argv[0], argv);
perror("execvp failed: ");
prevCommandPass = false;
_exit(1);
}
else if (pid > 0){
if ((p = wait(&status)) < 0){
perror("child failed: ");
prevCommandPass = false;
_exit(1);
}
}
else{
perror("fork failed: ");
_exit(1);
}
}
//Splits commandlist into commands with their arguments then calls executeCommand to run them.
void executeAllCommands(){
vector<string> commandsublist;
unsigned int i = 0;
unsigned int j = 0;
while (i < commandlist.size()){
j = 0;
if (checkCommandRun()){
while (!checkBreaker(i)){
//Exit check
if (commandlist.at(i) == "exit"){
cout << "Forced Exit." << endl;
forceExit = true;
_Exit(0);
}
// Comment check
if (commandlist.at(i) == "#" || checkComment(commandlist.at(i))){
executeCommand(commandsublist);
return;
}
//Adds command to the list
commandsublist.push_back(commandlist.at(i));
i++;
j++;
if (i == commandlist.size()){
executeCommand(commandsublist);
return;
}
}
if (checkBreaker(i)){
if (nextConnector == "||"){
if (allCount == true){
prevCommandPass = true;
}
else{
if (prevCommandPass == false){
allCount = false;
}
else{
allCount = true;
}
}
}
else if (nextConnector == "&&"){
if (allCount == true){
if (prevCommandPass == false){
allCount = false;
}
}
else{
allCount = false;
prevCommandPass = false;
}
}
else if (nextConnector == ";"){
allCount = true;
prevCommandPass = true;
}
if (commandlist.at(i) == "|"){
nextConnector = "||";
}
else if (commandlist.at(i) == "&"){
nextConnector = "&&";
}
else if (commandlist.at(i) == ";"){
nextConnector = ";";
}
}
i++;
}
executeCommand(commandsublist);
commandsublist.clear();
}
}
// Checks if there is a '#' at the front of the string
bool checkComment(string str){
if (str.at(0) == '#'){
return true;
}
return false;
}
// Checks if the string is a breaker
bool checkBreaker(unsigned int i){
if (i < (commandlist.size() + 1)){
if (commandlist.at(i) == "|" && commandlist.at(i + 1) == "|"){
return true;
}
else if (commandlist.at(i) == "&" && commandlist.at(i + 1) == "&"){
return true;
}
else if (commandlist.at(i) == ";"){
return true;
}
else{
return false;
}
}
else{
return false;
}
}
// Checks if the next command should be run
bool checkCommandRun(){
if (nextConnector == "||"){
if(allCount == true){
return false;
}
else{
return true;
}
}
else if (nextConnector == "&&"){
if(allCount == true){
return true;
}
else{
return false;
}
}
else if (nextConnector == ";"){
return true;
}
else{
return false;
}
}
//Starts the program.
void run(){
while (!forceExit && commands != "exit"){
cout << "$";
getline(cin, commands);
parseAllCommands();
executeAllCommands();
commandlist.clear();
nextConnector = ";";
prevCommandPass = true;
}
}
};
<|endoftext|> |
<commit_before>// Copyright 2014 BVLC and contributors.
#ifndef CAFFE_DATA_LAYERS_HPP_
#define CAFFE_DATA_LAYERS_HPP_
#include <string>
#include <utility>
#include <vector>
#include "leveldb/db.h"
#include "lmdb.h"
#include "pthread.h"
#include "hdf5.h"
#include "boost/scoped_ptr.hpp"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
#define HDF5_DATA_DATASET_NAME "data"
#define HDF5_DATA_LABEL_NAME "label"
template <typename Dtype>
class HDF5OutputLayer : public Layer<Dtype> {
public:
explicit HDF5OutputLayer(const LayerParameter& param);
virtual ~HDF5OutputLayer();
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {}
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_HDF5_OUTPUT;
}
// TODO: no limit on the number of blobs
virtual inline int ExactNumBottomBlobs() const { return 2; }
virtual inline int ExactNumTopBlobs() const { return 0; }
inline std::string file_name() const { return file_name_; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void SaveBlobs();
std::string file_name_;
hid_t file_id_;
Blob<Dtype> data_blob_;
Blob<Dtype> label_blob_;
};
template <typename Dtype>
class HDF5DataLayer : public Layer<Dtype> {
public:
explicit HDF5DataLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual ~HDF5DataLayer();
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_HDF5_DATA;
}
virtual inline int ExactNumBottomBlobs() const { return 0; }
virtual inline int ExactNumTopBlobs() const { return 2; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void LoadHDF5FileData(const char* filename);
std::vector<std::string> hdf_filenames_;
unsigned int num_files_;
unsigned int current_file_;
hsize_t current_row_;
Blob<Dtype> data_blob_;
Blob<Dtype> label_blob_;
};
// TODO: DataLayer, ImageDataLayer, and WindowDataLayer all have the
// same basic structure and a lot of duplicated code.
// This function is used to create a pthread that prefetches the data.
template <typename Dtype>
void* DataLayerPrefetch(void* layer_pointer);
template <typename Dtype>
class DataLayer : public Layer<Dtype> {
// The function used to perform prefetching.
friend void* DataLayerPrefetch<Dtype>(void* layer_pointer);
public:
explicit DataLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual ~DataLayer();
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_DATA;
}
virtual inline int ExactNumBottomBlobs() const { return 0; }
virtual inline int MinTopBlobs() const { return 1; }
virtual inline int MaxTopBlobs() const { return 2; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void CreatePrefetchThread();
virtual void JoinPrefetchThread();
virtual unsigned int PrefetchRand();
shared_ptr<Caffe::RNG> prefetch_rng_;
// LEVELDB
shared_ptr<leveldb::DB> db_;
shared_ptr<leveldb::Iterator> iter_;
// LMDB
MDB_env* mdb_env_;
MDB_dbi mdb_dbi_;
MDB_txn* mdb_txn_;
MDB_cursor* mdb_cursor_;
MDB_val mdb_key_, mdb_value_;
int datum_channels_;
int datum_height_;
int datum_width_;
int datum_size_;
pthread_t thread_;
shared_ptr<Blob<Dtype> > prefetch_data_;
shared_ptr<Blob<Dtype> > prefetch_label_;
Blob<Dtype> data_mean_;
bool output_labels_;
Caffe::Phase phase_;
};
template <typename Dtype>
class DummyDataLayer : public Layer<Dtype> {
public:
explicit DummyDataLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_DUMMY_DATA;
}
virtual inline int ExactNumBottomBlobs() const { return 0; }
virtual inline int MinTopBlobs() const { return 1; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
vector<shared_ptr<Filler<Dtype> > > fillers_;
vector<bool> refill_;
};
// This function is used to create a pthread that prefetches the data.
template <typename Dtype>
void* ImageDataLayerPrefetch(void* layer_pointer);
template <typename Dtype>
class ImageDataLayer : public Layer<Dtype> {
// The function used to perform prefetching.
friend void* ImageDataLayerPrefetch<Dtype>(void* layer_pointer);
public:
explicit ImageDataLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual ~ImageDataLayer();
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_IMAGE_DATA;
}
virtual inline int ExactNumBottomBlobs() const { return 0; }
virtual inline int ExactNumTopBlobs() const { return 2; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void ShuffleImages();
virtual void CreatePrefetchThread();
virtual void JoinPrefetchThread();
virtual unsigned int PrefetchRand();
shared_ptr<Caffe::RNG> prefetch_rng_;
vector<std::pair<std::string, int> > lines_;
int lines_id_;
int datum_channels_;
int datum_height_;
int datum_width_;
int datum_size_;
pthread_t thread_;
shared_ptr<Blob<Dtype> > prefetch_data_;
shared_ptr<Blob<Dtype> > prefetch_label_;
Blob<Dtype> data_mean_;
Caffe::Phase phase_;
};
/* MemoryDataLayer
*/
template <typename Dtype>
class MemoryDataLayer : public Layer<Dtype> {
public:
explicit MemoryDataLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_MEMORY_DATA;
}
virtual inline int ExactNumBottomBlobs() const { return 0; }
virtual inline int ExactNumTopBlobs() const { return 2; }
// Reset should accept const pointers, but can't, because the memory
// will be given to Blob, which is mutable
void Reset(Dtype* data, Dtype* label, int n);
int datum_channels() { return datum_channels_; }
int datum_height() { return datum_height_; }
int datum_width() { return datum_width_; }
int batch_size() { return batch_size_; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
Dtype* data_;
Dtype* labels_;
int datum_channels_;
int datum_height_;
int datum_width_;
int datum_size_;
int batch_size_;
int n_;
int pos_;
};
// This function is used to create a pthread that prefetches the window data.
template <typename Dtype>
void* WindowDataLayerPrefetch(void* layer_pointer);
template <typename Dtype>
class WindowDataLayer : public Layer<Dtype> {
// The function used to perform prefetching.
friend void* WindowDataLayerPrefetch<Dtype>(void* layer_pointer);
public:
explicit WindowDataLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual ~WindowDataLayer();
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_WINDOW_DATA;
}
virtual inline int ExactNumBottomBlobs() const { return 0; }
virtual inline int ExactNumTopBlobs() const { return 2; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void CreatePrefetchThread();
virtual void JoinPrefetchThread();
virtual unsigned int PrefetchRand();
shared_ptr<Caffe::RNG> prefetch_rng_;
pthread_t thread_;
shared_ptr<Blob<Dtype> > prefetch_data_;
shared_ptr<Blob<Dtype> > prefetch_label_;
Blob<Dtype> data_mean_;
vector<std::pair<std::string, vector<int> > > image_database_;
enum WindowField { IMAGE_INDEX, LABEL, OVERLAP, X1, Y1, X2, Y2, NUM };
vector<vector<float> > fg_windows_;
vector<vector<float> > bg_windows_;
};
} // namespace caffe
#endif // CAFFE_DATA_LAYERS_HPP_
<commit_msg>Arrange the data layers to be in alphabetical order<commit_after>// Copyright 2014 BVLC and contributors.
#ifndef CAFFE_DATA_LAYERS_HPP_
#define CAFFE_DATA_LAYERS_HPP_
#include <string>
#include <utility>
#include <vector>
#include "leveldb/db.h"
#include "lmdb.h"
#include "pthread.h"
#include "hdf5.h"
#include "boost/scoped_ptr.hpp"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
#define HDF5_DATA_DATASET_NAME "data"
#define HDF5_DATA_LABEL_NAME "label"
// TODO: DataLayer, ImageDataLayer, and WindowDataLayer all have the
// same basic structure and a lot of duplicated code.
// This function is used to create a pthread that prefetches the data.
template <typename Dtype>
void* DataLayerPrefetch(void* layer_pointer);
template <typename Dtype>
class DataLayer : public Layer<Dtype> {
// The function used to perform prefetching.
friend void* DataLayerPrefetch<Dtype>(void* layer_pointer);
public:
explicit DataLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual ~DataLayer();
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_DATA;
}
virtual inline int ExactNumBottomBlobs() const { return 0; }
virtual inline int MinTopBlobs() const { return 1; }
virtual inline int MaxTopBlobs() const { return 2; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void CreatePrefetchThread();
virtual void JoinPrefetchThread();
virtual unsigned int PrefetchRand();
shared_ptr<Caffe::RNG> prefetch_rng_;
// LEVELDB
shared_ptr<leveldb::DB> db_;
shared_ptr<leveldb::Iterator> iter_;
// LMDB
MDB_env* mdb_env_;
MDB_dbi mdb_dbi_;
MDB_txn* mdb_txn_;
MDB_cursor* mdb_cursor_;
MDB_val mdb_key_, mdb_value_;
int datum_channels_;
int datum_height_;
int datum_width_;
int datum_size_;
pthread_t thread_;
shared_ptr<Blob<Dtype> > prefetch_data_;
shared_ptr<Blob<Dtype> > prefetch_label_;
Blob<Dtype> data_mean_;
bool output_labels_;
Caffe::Phase phase_;
};
template <typename Dtype>
class DummyDataLayer : public Layer<Dtype> {
public:
explicit DummyDataLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_DUMMY_DATA;
}
virtual inline int ExactNumBottomBlobs() const { return 0; }
virtual inline int MinTopBlobs() const { return 1; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
vector<shared_ptr<Filler<Dtype> > > fillers_;
vector<bool> refill_;
};
template <typename Dtype>
class HDF5DataLayer : public Layer<Dtype> {
public:
explicit HDF5DataLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual ~HDF5DataLayer();
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_HDF5_DATA;
}
virtual inline int ExactNumBottomBlobs() const { return 0; }
virtual inline int ExactNumTopBlobs() const { return 2; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void LoadHDF5FileData(const char* filename);
std::vector<std::string> hdf_filenames_;
unsigned int num_files_;
unsigned int current_file_;
hsize_t current_row_;
Blob<Dtype> data_blob_;
Blob<Dtype> label_blob_;
};
template <typename Dtype>
class HDF5OutputLayer : public Layer<Dtype> {
public:
explicit HDF5OutputLayer(const LayerParameter& param);
virtual ~HDF5OutputLayer();
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {}
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_HDF5_OUTPUT;
}
// TODO: no limit on the number of blobs
virtual inline int ExactNumBottomBlobs() const { return 2; }
virtual inline int ExactNumTopBlobs() const { return 0; }
inline std::string file_name() const { return file_name_; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void SaveBlobs();
std::string file_name_;
hid_t file_id_;
Blob<Dtype> data_blob_;
Blob<Dtype> label_blob_;
};
// This function is used to create a pthread that prefetches the data.
template <typename Dtype>
void* ImageDataLayerPrefetch(void* layer_pointer);
template <typename Dtype>
class ImageDataLayer : public Layer<Dtype> {
// The function used to perform prefetching.
friend void* ImageDataLayerPrefetch<Dtype>(void* layer_pointer);
public:
explicit ImageDataLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual ~ImageDataLayer();
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_IMAGE_DATA;
}
virtual inline int ExactNumBottomBlobs() const { return 0; }
virtual inline int ExactNumTopBlobs() const { return 2; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void ShuffleImages();
virtual void CreatePrefetchThread();
virtual void JoinPrefetchThread();
virtual unsigned int PrefetchRand();
shared_ptr<Caffe::RNG> prefetch_rng_;
vector<std::pair<std::string, int> > lines_;
int lines_id_;
int datum_channels_;
int datum_height_;
int datum_width_;
int datum_size_;
pthread_t thread_;
shared_ptr<Blob<Dtype> > prefetch_data_;
shared_ptr<Blob<Dtype> > prefetch_label_;
Blob<Dtype> data_mean_;
Caffe::Phase phase_;
};
/* MemoryDataLayer
*/
template <typename Dtype>
class MemoryDataLayer : public Layer<Dtype> {
public:
explicit MemoryDataLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_MEMORY_DATA;
}
virtual inline int ExactNumBottomBlobs() const { return 0; }
virtual inline int ExactNumTopBlobs() const { return 2; }
// Reset should accept const pointers, but can't, because the memory
// will be given to Blob, which is mutable
void Reset(Dtype* data, Dtype* label, int n);
int datum_channels() { return datum_channels_; }
int datum_height() { return datum_height_; }
int datum_width() { return datum_width_; }
int batch_size() { return batch_size_; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
Dtype* data_;
Dtype* labels_;
int datum_channels_;
int datum_height_;
int datum_width_;
int datum_size_;
int batch_size_;
int n_;
int pos_;
};
// This function is used to create a pthread that prefetches the window data.
template <typename Dtype>
void* WindowDataLayerPrefetch(void* layer_pointer);
template <typename Dtype>
class WindowDataLayer : public Layer<Dtype> {
// The function used to perform prefetching.
friend void* WindowDataLayerPrefetch<Dtype>(void* layer_pointer);
public:
explicit WindowDataLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual ~WindowDataLayer();
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_WINDOW_DATA;
}
virtual inline int ExactNumBottomBlobs() const { return 0; }
virtual inline int ExactNumTopBlobs() const { return 2; }
protected:
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
virtual void CreatePrefetchThread();
virtual void JoinPrefetchThread();
virtual unsigned int PrefetchRand();
shared_ptr<Caffe::RNG> prefetch_rng_;
pthread_t thread_;
shared_ptr<Blob<Dtype> > prefetch_data_;
shared_ptr<Blob<Dtype> > prefetch_label_;
Blob<Dtype> data_mean_;
vector<std::pair<std::string, vector<int> > > image_database_;
enum WindowField { IMAGE_INDEX, LABEL, OVERLAP, X1, Y1, X2, Y2, NUM };
vector<vector<float> > fg_windows_;
vector<vector<float> > bg_windows_;
};
} // namespace caffe
#endif // CAFFE_DATA_LAYERS_HPP_
<|endoftext|> |
<commit_before>/*** Copyright (c), The Regents of the University of California ***
*** For more information please refer to files in the COPYRIGHT directory ***/
/* See genQuery.h for a description of this API call.*/
#include "reFuncDefs.hpp"
#include "genQuery.hpp"
#include "icatHighLevelRoutines.hpp"
#include "miscUtil.hpp"
#include "cache.hpp"
#include "rsGlobalExtern.hpp"
#include "irods_server_properties.hpp"
#include "boost/format.hpp"
#include <string>
static
irods::error strip_irods_query_terms(
genQueryInp_t* _inp ) {
// =-=-=-=-=-=-=-
// cache pointers to the incoming inxIvalPair
inxIvalPair_t tmp;
tmp.len = _inp->selectInp.len;
tmp.inx = _inp->selectInp.inx;
tmp.value = _inp->selectInp.value;
// =-=-=-=-=-=-=-
// zero out the selectInp to copy
// fresh non-irods indexes and values
bzero( &_inp->selectInp, sizeof( _inp->selectInp ) );
// =-=-=-=-=-=-=-
// iterate over the tmp and copy non irods values
for ( int i = 0; i < tmp.len; ++i ) {
if ( tmp.inx[ i ] == COL_R_RESC_CHILDREN ||
tmp.inx[ i ] == COL_R_RESC_CONTEXT ||
tmp.inx[ i ] == COL_R_RESC_PARENT ||
tmp.inx[ i ] == COL_R_RESC_OBJCOUNT ||
tmp.inx[ i ] == COL_D_RESC_HIER ) {
continue;
}
else {
addInxIval( &_inp->selectInp, tmp.inx[ i ], tmp.value[ i ] );
}
} // for i
return SUCCESS();
} // strip_irods_query_terms
static
irods::error proc_query_terms_for_non_irods_server(
const std::string& _zone_hint,
genQueryInp_t* _inp ) {
bool done = false;
zoneInfo_t* tmp_zone = ZoneInfoHead;
// =-=-=-=-=-=-=-
// if the zone hint starts with a / we
// will need to pull out just the zone
std::string zone_hint = _zone_hint;
if ( _zone_hint[0] == '/' ) {
size_t pos = _zone_hint.find( "/", 1 );
if ( std::string::npos != pos ) {
zone_hint = _zone_hint.substr( 1, pos - 1 );
}
else {
zone_hint = _zone_hint.substr( 1 );
}
}
else {
return SUCCESS();
}
// =-=-=-=-=-=-=-
// grind through the zones and find the match to the kw
while ( !done && tmp_zone ) {
if ( zone_hint == tmp_zone->zoneName &&
tmp_zone->masterServerHost->conn &&
tmp_zone->masterServerHost->conn->svrVersion &&
tmp_zone->masterServerHost->conn->svrVersion->cookie < 301 ) {
return strip_irods_query_terms( _inp );
}
else {
tmp_zone = tmp_zone->next;
}
}
return SUCCESS();
} // proc_query_terms_for_non_irods_server
/* can be used for debug: */
/* extern int printGenQI( genQueryInp_t *genQueryInp); */
;
int
rsGenQuery( rsComm_t *rsComm, genQueryInp_t *genQueryInp,
genQueryOut_t **genQueryOut ) {
rodsServerHost_t *rodsServerHost;
int status;
char *zoneHint;
zoneHint = getZoneHintForGenQuery( genQueryInp );
std::string zone_hint_str;
if ( zoneHint ) {
zone_hint_str = zoneHint;
}
status = getAndConnRcatHost( rsComm, SLAVE_RCAT, ( const char* )zoneHint,
&rodsServerHost );
if ( status < 0 ) {
return status;
}
// =-=-=-=-=-=-=-
// handle non-irods connections
if ( !zone_hint_str.empty() ) {
irods::error ret = proc_query_terms_for_non_irods_server( zone_hint_str, genQueryInp );
if ( !ret.ok() ) {
irods::log( PASS( ret ) );
}
}
if ( rodsServerHost->localFlag == LOCAL_HOST ) {
#ifdef RODS_CAT
status = _rsGenQuery( rsComm, genQueryInp, genQueryOut );
#else
rodsLog( LOG_NOTICE,
"rsGenQuery error. RCAT is not configured on this host" );
return SYS_NO_RCAT_SERVER_ERR;
#endif
}
else {
// =-=-=-=-=-=-=-
// strip disable strict acl flag if the agent conn flag is missing
char* dis_kw = getValByKey( &genQueryInp->condInput, DISABLE_STRICT_ACL_KW );
if ( dis_kw ) {
irods::server_properties& props = irods::server_properties::getInstance();
props.capture_if_needed();
std::string svr_sid;
irods::error err = props.get_property< std::string >( irods::AGENT_CONN_KW, svr_sid );
if ( !err.ok() ) {
rmKeyVal( &genQueryInp->condInput, DISABLE_STRICT_ACL_KW );
}
} // if dis_kw
status = rcGenQuery( rodsServerHost->conn,
genQueryInp, genQueryOut );
}
if ( status < 0 && status != CAT_NO_ROWS_FOUND ) {
std::string prefix = ( rodsServerHost->localFlag == LOCAL_HOST ) ? "_rs" : "rc";
rodsLog( LOG_NOTICE,
"rsGenQuery: %sGenQuery failed, status = %d", prefix.c_str(), status );
}
return status;
}
#ifdef RODS_CAT
int
_rsGenQuery( rsComm_t *rsComm, genQueryInp_t *genQueryInp,
genQueryOut_t **genQueryOut ) {
int status;
static int ruleExecuted = 0;
ruleExecInfo_t rei;
static int PrePostProcForGenQueryFlag = -2;
int i, argc;
ruleExecInfo_t rei2;
const char *args[MAX_NUM_OF_ARGS_IN_ACTION];
if ( PrePostProcForGenQueryFlag < 0 ) {
if ( getenv( "PREPOSTPROCFORGENQUERYFLAG" ) != NULL ) {
PrePostProcForGenQueryFlag = 1;
}
else {
PrePostProcForGenQueryFlag = 0;
}
}
memset( ( char* )&rei2, 0, sizeof( ruleExecInfo_t ) );
rei2.rsComm = rsComm;
if ( rsComm != NULL ) {
rei2.uoic = &rsComm->clientUser;
rei2.uoip = &rsComm->proxyUser;
}
/* printGenQI(genQueryInp); for debug */
*genQueryOut = ( genQueryOut_t* )malloc( sizeof( genQueryOut_t ) );
memset( ( char * )*genQueryOut, 0, sizeof( genQueryOut_t ) );
if ( ruleExecuted == 0 ) {
memset( ( char* )&rei, 0, sizeof( rei ) );
rei.rsComm = rsComm;
if ( rsComm != NULL ) {
/* Include the user info for possible use by the rule. Note
that when this is called (as the agent is initializing),
this user info is not confirmed yet. For password
authentication though, the agent will soon exit if this
is not valid. But tor GSI, the user information may not
be present and/or may be changed when the authentication
completes, so it may not be safe to use this in a GSI
enabled environment. This addition of user information
was requested by ARCS/IVEC (Sean Fleming) to avoid a
local patch.
*/
rei.uoic = &rsComm->clientUser;
rei.uoip = &rsComm->proxyUser;
}
if ( getRuleEngineStatus() == UNINITIALIZED ) {
/* Skip the call to run acAclPolicy if the Rule Engine
hasn't been initialized yet, which happens for a couple
initial queries made by the agent when starting up. The
new RE logs these types of errors and so this avoids that.
*/
status = -1;
}
else {
status = applyRule( "acAclPolicy", NULL, &rei, NO_SAVE_REI );
}
if ( status == 0 ) {
ruleExecuted = 1; /* No need to retry next time since it
succeeded. Since this is called at
startup, the Rule Engine may not be
initialized yet, in which case the
default setting is fine and we should
retry next time. */
}
}
// =-=-=-=-=-=-=-
// verify that we are running a query for another agent connection
irods::server_properties& props = irods::server_properties::getInstance();
props.capture_if_needed();
std::string svr_sid;
irods::error err = props.get_property< std::string >( irods::AGENT_CONN_KW, svr_sid );
bool agent_conn_flg = err.ok();
// =-=-=-=-=-=-=-
// detect if a request for disable of strict acls is made
int acl_val = -1;
char* dis_kw = getValByKey( &genQueryInp->condInput, DISABLE_STRICT_ACL_KW );
if ( agent_conn_flg && dis_kw ) {
acl_val = 0;
}
// =-=-=-=-=-=-=-
// cache the old acl value for reuse later if necessary
int old_acl_val = chlGenQueryAccessControlSetup(
rsComm->clientUser.userName,
rsComm->clientUser.rodsZone,
rsComm->clientAddr,
rsComm->clientUser.authInfo.authFlag,
acl_val );
if ( PrePostProcForGenQueryFlag == 1 ) {
std::string arg = str( boost::format( "%ld" ) % ( ( long )genQueryInp ) );
args[0] = arg.c_str();
argc = 1;
i = applyRuleArg( "acPreProcForGenQuery", args, argc, &rei2, NO_SAVE_REI );
if ( i < 0 ) {
rodsLog( LOG_ERROR,
"rsGenQuery:acPreProcForGenQuery error,stat=%d", i );
if ( i != NO_MICROSERVICE_FOUND_ERR ) {
return i;
}
}
}
/** June 1 2009 for pre-post processing rule hooks **/
status = chlGenQuery( *genQueryInp, *genQueryOut );
// =-=-=-=-=-=-=-
// if a disable was requested, repave with old value immediately
if ( agent_conn_flg && dis_kw ) {
chlGenQueryAccessControlSetup(
rsComm->clientUser.userName,
rsComm->clientUser.rodsZone,
rsComm->clientAddr,
rsComm->clientUser.authInfo.authFlag,
old_acl_val );
}
/** June 1 2009 for pre-post processing rule hooks **/
if ( PrePostProcForGenQueryFlag == 1 ) {
std::string in_string = str( boost::format( "%ld" ) % ( ( long )genQueryInp ) );
std::string out_string = str( boost::format( "%ld" ) % ( ( long )genQueryOut ) );
std::string status_string = str( boost::format( "%d" ) % ( ( long )status ) );
args[0] = in_string.c_str();
args[1] = out_string.c_str();
args[2] = status_string.c_str();
argc = 3;
i = applyRuleArg( "acPostProcForGenQuery", args, argc, &rei2, NO_SAVE_REI );
if ( i < 0 ) {
rodsLog( LOG_ERROR,
"rsGenQuery:acPostProcForGenQuery error,stat=%d", i );
if ( i != NO_MICROSERVICE_FOUND_ERR ) {
return i;
}
}
}
/** June 1 2009 for pre-post processing rule hooks **/
if ( status < 0 ) {
clearGenQueryOut( *genQueryOut );
free( *genQueryOut );
*genQueryOut = NULL;
if ( status != CAT_NO_ROWS_FOUND ) {
rodsLog( LOG_NOTICE,
"_rsGenQuery: genQuery status = %d", status );
}
return status;
}
return status;
}
#endif
<commit_msg>[#858] typo<commit_after>/*** Copyright (c), The Regents of the University of California ***
*** For more information please refer to files in the COPYRIGHT directory ***/
/* See genQuery.h for a description of this API call.*/
#include "reFuncDefs.hpp"
#include "genQuery.hpp"
#include "icatHighLevelRoutines.hpp"
#include "miscUtil.hpp"
#include "cache.hpp"
#include "rsGlobalExtern.hpp"
#include "irods_server_properties.hpp"
#include "boost/format.hpp"
#include <string>
static
irods::error strip_irods_query_terms(
genQueryInp_t* _inp ) {
// =-=-=-=-=-=-=-
// cache pointers to the incoming inxIvalPair
inxIvalPair_t tmp;
tmp.len = _inp->selectInp.len;
tmp.inx = _inp->selectInp.inx;
tmp.value = _inp->selectInp.value;
// =-=-=-=-=-=-=-
// zero out the selectInp to copy
// fresh non-irods indices and values
bzero( &_inp->selectInp, sizeof( _inp->selectInp ) );
// =-=-=-=-=-=-=-
// iterate over the tmp and copy non irods values
for ( int i = 0; i < tmp.len; ++i ) {
if ( tmp.inx[ i ] == COL_R_RESC_CHILDREN ||
tmp.inx[ i ] == COL_R_RESC_CONTEXT ||
tmp.inx[ i ] == COL_R_RESC_PARENT ||
tmp.inx[ i ] == COL_R_RESC_OBJCOUNT ||
tmp.inx[ i ] == COL_D_RESC_HIER ) {
continue;
}
else {
addInxIval( &_inp->selectInp, tmp.inx[ i ], tmp.value[ i ] );
}
} // for i
return SUCCESS();
} // strip_irods_query_terms
static
irods::error proc_query_terms_for_non_irods_server(
const std::string& _zone_hint,
genQueryInp_t* _inp ) {
bool done = false;
zoneInfo_t* tmp_zone = ZoneInfoHead;
// =-=-=-=-=-=-=-
// if the zone hint starts with a / we
// will need to pull out just the zone
std::string zone_hint = _zone_hint;
if ( _zone_hint[0] == '/' ) {
size_t pos = _zone_hint.find( "/", 1 );
if ( std::string::npos != pos ) {
zone_hint = _zone_hint.substr( 1, pos - 1 );
}
else {
zone_hint = _zone_hint.substr( 1 );
}
}
else {
return SUCCESS();
}
// =-=-=-=-=-=-=-
// grind through the zones and find the match to the kw
while ( !done && tmp_zone ) {
if ( zone_hint == tmp_zone->zoneName &&
tmp_zone->masterServerHost->conn &&
tmp_zone->masterServerHost->conn->svrVersion &&
tmp_zone->masterServerHost->conn->svrVersion->cookie < 301 ) {
return strip_irods_query_terms( _inp );
}
else {
tmp_zone = tmp_zone->next;
}
}
return SUCCESS();
} // proc_query_terms_for_non_irods_server
/* can be used for debug: */
/* extern int printGenQI( genQueryInp_t *genQueryInp); */
;
int
rsGenQuery( rsComm_t *rsComm, genQueryInp_t *genQueryInp,
genQueryOut_t **genQueryOut ) {
rodsServerHost_t *rodsServerHost;
int status;
char *zoneHint;
zoneHint = getZoneHintForGenQuery( genQueryInp );
std::string zone_hint_str;
if ( zoneHint ) {
zone_hint_str = zoneHint;
}
status = getAndConnRcatHost( rsComm, SLAVE_RCAT, ( const char* )zoneHint,
&rodsServerHost );
if ( status < 0 ) {
return status;
}
// =-=-=-=-=-=-=-
// handle non-irods connections
if ( !zone_hint_str.empty() ) {
irods::error ret = proc_query_terms_for_non_irods_server( zone_hint_str, genQueryInp );
if ( !ret.ok() ) {
irods::log( PASS( ret ) );
}
}
if ( rodsServerHost->localFlag == LOCAL_HOST ) {
#ifdef RODS_CAT
status = _rsGenQuery( rsComm, genQueryInp, genQueryOut );
#else
rodsLog( LOG_NOTICE,
"rsGenQuery error. RCAT is not configured on this host" );
return SYS_NO_RCAT_SERVER_ERR;
#endif
}
else {
// =-=-=-=-=-=-=-
// strip disable strict acl flag if the agent conn flag is missing
char* dis_kw = getValByKey( &genQueryInp->condInput, DISABLE_STRICT_ACL_KW );
if ( dis_kw ) {
irods::server_properties& props = irods::server_properties::getInstance();
props.capture_if_needed();
std::string svr_sid;
irods::error err = props.get_property< std::string >( irods::AGENT_CONN_KW, svr_sid );
if ( !err.ok() ) {
rmKeyVal( &genQueryInp->condInput, DISABLE_STRICT_ACL_KW );
}
} // if dis_kw
status = rcGenQuery( rodsServerHost->conn,
genQueryInp, genQueryOut );
}
if ( status < 0 && status != CAT_NO_ROWS_FOUND ) {
std::string prefix = ( rodsServerHost->localFlag == LOCAL_HOST ) ? "_rs" : "rc";
rodsLog( LOG_NOTICE,
"rsGenQuery: %sGenQuery failed, status = %d", prefix.c_str(), status );
}
return status;
}
#ifdef RODS_CAT
int
_rsGenQuery( rsComm_t *rsComm, genQueryInp_t *genQueryInp,
genQueryOut_t **genQueryOut ) {
int status;
static int ruleExecuted = 0;
ruleExecInfo_t rei;
static int PrePostProcForGenQueryFlag = -2;
int i, argc;
ruleExecInfo_t rei2;
const char *args[MAX_NUM_OF_ARGS_IN_ACTION];
if ( PrePostProcForGenQueryFlag < 0 ) {
if ( getenv( "PREPOSTPROCFORGENQUERYFLAG" ) != NULL ) {
PrePostProcForGenQueryFlag = 1;
}
else {
PrePostProcForGenQueryFlag = 0;
}
}
memset( ( char* )&rei2, 0, sizeof( ruleExecInfo_t ) );
rei2.rsComm = rsComm;
if ( rsComm != NULL ) {
rei2.uoic = &rsComm->clientUser;
rei2.uoip = &rsComm->proxyUser;
}
/* printGenQI(genQueryInp); for debug */
*genQueryOut = ( genQueryOut_t* )malloc( sizeof( genQueryOut_t ) );
memset( ( char * )*genQueryOut, 0, sizeof( genQueryOut_t ) );
if ( ruleExecuted == 0 ) {
memset( ( char* )&rei, 0, sizeof( rei ) );
rei.rsComm = rsComm;
if ( rsComm != NULL ) {
/* Include the user info for possible use by the rule. Note
that when this is called (as the agent is initializing),
this user info is not confirmed yet. For password
authentication though, the agent will soon exit if this
is not valid. But for GSI, the user information may not
be present and/or may be changed when the authentication
completes, so it may not be safe to use this in a GSI
enabled environment. This addition of user information
was requested by ARCS/IVEC (Sean Fleming) to avoid a
local patch.
*/
rei.uoic = &rsComm->clientUser;
rei.uoip = &rsComm->proxyUser;
}
if ( getRuleEngineStatus() == UNINITIALIZED ) {
/* Skip the call to run acAclPolicy if the Rule Engine
hasn't been initialized yet, which happens for a couple
initial queries made by the agent when starting up. The
new RE logs these types of errors and so this avoids that.
*/
status = -1;
}
else {
status = applyRule( "acAclPolicy", NULL, &rei, NO_SAVE_REI );
}
if ( status == 0 ) {
ruleExecuted = 1; /* No need to retry next time since it
succeeded. Since this is called at
startup, the Rule Engine may not be
initialized yet, in which case the
default setting is fine and we should
retry next time. */
}
}
// =-=-=-=-=-=-=-
// verify that we are running a query for another agent connection
irods::server_properties& props = irods::server_properties::getInstance();
props.capture_if_needed();
std::string svr_sid;
irods::error err = props.get_property< std::string >( irods::AGENT_CONN_KW, svr_sid );
bool agent_conn_flg = err.ok();
// =-=-=-=-=-=-=-
// detect if a request for disable of strict acls is made
int acl_val = -1;
char* dis_kw = getValByKey( &genQueryInp->condInput, DISABLE_STRICT_ACL_KW );
if ( agent_conn_flg && dis_kw ) {
acl_val = 0;
}
// =-=-=-=-=-=-=-
// cache the old acl value for reuse later if necessary
int old_acl_val = chlGenQueryAccessControlSetup(
rsComm->clientUser.userName,
rsComm->clientUser.rodsZone,
rsComm->clientAddr,
rsComm->clientUser.authInfo.authFlag,
acl_val );
if ( PrePostProcForGenQueryFlag == 1 ) {
std::string arg = str( boost::format( "%ld" ) % ( ( long )genQueryInp ) );
args[0] = arg.c_str();
argc = 1;
i = applyRuleArg( "acPreProcForGenQuery", args, argc, &rei2, NO_SAVE_REI );
if ( i < 0 ) {
rodsLog( LOG_ERROR,
"rsGenQuery:acPreProcForGenQuery error,stat=%d", i );
if ( i != NO_MICROSERVICE_FOUND_ERR ) {
return i;
}
}
}
/** June 1 2009 for pre-post processing rule hooks **/
status = chlGenQuery( *genQueryInp, *genQueryOut );
// =-=-=-=-=-=-=-
// if a disable was requested, repave with old value immediately
if ( agent_conn_flg && dis_kw ) {
chlGenQueryAccessControlSetup(
rsComm->clientUser.userName,
rsComm->clientUser.rodsZone,
rsComm->clientAddr,
rsComm->clientUser.authInfo.authFlag,
old_acl_val );
}
/** June 1 2009 for pre-post processing rule hooks **/
if ( PrePostProcForGenQueryFlag == 1 ) {
std::string in_string = str( boost::format( "%ld" ) % ( ( long )genQueryInp ) );
std::string out_string = str( boost::format( "%ld" ) % ( ( long )genQueryOut ) );
std::string status_string = str( boost::format( "%d" ) % ( ( long )status ) );
args[0] = in_string.c_str();
args[1] = out_string.c_str();
args[2] = status_string.c_str();
argc = 3;
i = applyRuleArg( "acPostProcForGenQuery", args, argc, &rei2, NO_SAVE_REI );
if ( i < 0 ) {
rodsLog( LOG_ERROR,
"rsGenQuery:acPostProcForGenQuery error,stat=%d", i );
if ( i != NO_MICROSERVICE_FOUND_ERR ) {
return i;
}
}
}
/** June 1 2009 for pre-post processing rule hooks **/
if ( status < 0 ) {
clearGenQueryOut( *genQueryOut );
free( *genQueryOut );
*genQueryOut = NULL;
if ( status != CAT_NO_ROWS_FOUND ) {
rodsLog( LOG_NOTICE,
"_rsGenQuery: genQuery status = %d", status );
}
return status;
}
return status;
}
#endif
<|endoftext|> |
<commit_before>#warning Use of defs.hpp is deprecated, please use either autodetect.hpp or generic.hpp
#include "internal/defs.hpp"
#ifndef STEP_INHERITANCE
#include "internal/drivers/GenericDriver.hpp"
#endif
<commit_msg>Fixing non valid preprocessor warning on msvc<commit_after>#ifdef __GNUC__
#warning "Use of defs.hpp is deprecated, please use either autodetect.hpp or generic.hpp"
#else
#pragma message( "Use of defs.hpp is deprecated, please use either autodetect.hpp or generic.hpp" )
#endif
#include "internal/defs.hpp"
#ifndef STEP_INHERITANCE
#include "internal/drivers/GenericDriver.hpp"
#endif
<|endoftext|> |
<commit_before>#ifndef GENERIC_CONTAINS_HPP
# define GENERIC_CONTAINS_HPP
# pragma once
namespace generic
{
// contains
//////////////////////////////////////////////////////////////////////////////
template <class Container, class Key>
inline bool contains(Container const& c, Key const& key) noexcept
{
return c.end() != c.find(key);
}
}
#endif // GENERIC_CONTAINS_HPP
<commit_msg>some fixes<commit_after>#ifndef GENERIC_CONTAINS_HPP
# define GENERIC_CONTAINS_HPP
# pragma once
namespace generic
{
// contains
//////////////////////////////////////////////////////////////////////////////
template <class Container>
inline bool contains(Container const& c,
typename Container::key_type const& key) noexcept
{
return c.end() != c.find(key);
}
}
#endif // GENERIC_CONTAINS_HPP
<|endoftext|> |
<commit_before>#include <algorithm>
#include <vector>
#include <iostream>
#include <stdio.h>
void countsort(std::vector<int> &, int);
void radixsort(std::vector<int> &);
void printVector(std::vector<int> &);
int main()
{
int mVecSize;
while (true)
{
// Load arrays from stdin
scanf("%d", &mVecSize);
if (mVecSize == 0) break;
std::vector<int> mVector(mVecSize);
for (int i = 0; i < mVecSize; i++)
{
scanf("%d", &mVector[i]);
}
// Apply radix sort
radixsort(mVector);
// print
printVector(mVector);
}
}
void countsort(std::vector<int> & aV, int aExp)
{
int maxValue = 9;
// Initialize a C vector of 0..maxValue
std::vector<int> C(maxValue + 1);
// Counting
for (int i = 0; i < aV.size(); i++)
{
C[(aV[i] / aExp) % 10]++;
}
// Sort
int j = 0;
for (int i = 0; i <= maxValue; i++)
{
while (C[i] > 0)
{
aV[j] = i;
j++;
C[i]--;
}
}
}
void radixsort(std::vector<int> & aV)
{
auto maxElement = std::max_element(aV.begin(), aV.end());
int maxValue = *maxElement;
for (int exp = 1; maxValue/exp > 0; exp *= 10)
{
std::vector<std::vector<int> > buckets(10);
for (int i : aV)
{
buckets[(i / exp) % 10].push_back(i);
}
int j = 0;
for (auto it = buckets.begin(); it != buckets.end(); ++it)
{
for (int i : *it)
{
aV[j] = i;
j++;
}
}
}
}
void printVector(std::vector<int> & aV)
{
// Print vector
for (int i : aV)
{
printf("%d ", i);
}
printf("\n");
}<commit_msg>Organizado identação do código.<commit_after>#include <algorithm>
#include <vector>
#include <iostream>
#include <stdio.h>
void countsort(std::vector<int> &, int);
void radixsort(std::vector<int> &);
void printVector(std::vector<int> &);
int main()
{
int mVecSize;
while (true)
{
// Load arrays from stdin
scanf("%d", &mVecSize);
if (mVecSize == 0) break;
std::vector<int> mVector(mVecSize);
for (int i = 0; i < mVecSize; i++)
scanf("%d", &mVector[i]);
radixsort(mVector); // Apply radix sort
printVector(mVector); // print vector
}
}
void radixsort(std::vector<int> & aV)
{
auto maxElement = std::max_element(aV.begin(), aV.end());
int maxValue = *maxElement;
for (int exp = 1; maxValue/exp > 0; exp *= 10)
{
std::vector<std::vector<int> > buckets(10);
for (int i : aV)
buckets[(i / exp) % 10].push_back(i);
int j = 0;
for (auto it = buckets.begin(); it != buckets.end(); ++it)
{
for (int i : *it)
{
aV[j] = i;
j++;
}
}
}
}
void printVector(std::vector<int> & aV)
{
for (int i : aV)
printf("%d ", i);
printf("\n");
}<|endoftext|> |
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_ASSERT
#include "libtorrent/config.hpp"
#if (!defined TORRENT_DEBUG && !TORRENT_PRODUCTION_ASSERTS && TORRENT_RELEASE_ASSERTS) \
|| TORRENT_NO_ASSERTS
#define TORRENT_ASSERT(a) do {} while(false)
#define TORRENT_ASSERT_VAL(a, b) do {} while(false)
#else
#if TORRENT_PRODUCTION_ASSERTS
extern char const* libtorrent_assert_log;
#endif
#include <string>
#ifdef __GNUC__
std::string demangle(char const* name);
#endif
#if (defined __linux__ || defined __MACH__) && defined __GNUC__ && !TORRENT_USE_SYSTEM_ASSERT
#if TORRENT_USE_IOSTREAM
#include <sstream>
#endif
TORRENT_EXPORT void assert_fail(const char* expr, int line, char const* file, char const* function, char const* val);
#define TORRENT_ASSERT(x) do { if (x) {} else assert_fail(#x, __LINE__, __FILE__, __PRETTY_FUNCTION__, 0); } while (false)
#if TORRENT_USE_IOSTREAM
#define TORRENT_ASSERT_VAL(x, y) do { if (x) {} else { std::stringstream __s__; __s__ << #y ": " << y; assert_fail(#x, __LINE__, __FILE__, __PRETTY_FUNCTION__, __s__.str().c_str()); } } while (false)
#else
#define TORRENT_ASSERT_VAL(x, y) TORRENT_ASSERT(x)
#endif
#else
#include <cassert>
#define TORRENT_ASSERT(x) assert(x)
#define TORRENT_ASSERT_VAL(x, y) assert(x)
#endif
#endif
#endif
<commit_msg>fixed typo in release assert support<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_ASSERT
#include "libtorrent/config.hpp"
#if (!defined TORRENT_DEBUG && !TORRENT_PRODUCTION_ASSERTS && !TORRENT_RELEASE_ASSERTS) \
|| TORRENT_NO_ASSERTS
#define TORRENT_ASSERT(a) do {} while(false)
#define TORRENT_ASSERT_VAL(a, b) do {} while(false)
#else
#if TORRENT_PRODUCTION_ASSERTS
extern char const* libtorrent_assert_log;
#endif
#include <string>
#ifdef __GNUC__
std::string demangle(char const* name);
#endif
#if (defined __linux__ || defined __MACH__) && defined __GNUC__ && !TORRENT_USE_SYSTEM_ASSERT
#if TORRENT_USE_IOSTREAM
#include <sstream>
#endif
TORRENT_EXPORT void assert_fail(const char* expr, int line, char const* file, char const* function, char const* val);
#define TORRENT_ASSERT(x) do { if (x) {} else assert_fail(#x, __LINE__, __FILE__, __PRETTY_FUNCTION__, 0); } while (false)
#if TORRENT_USE_IOSTREAM
#define TORRENT_ASSERT_VAL(x, y) do { if (x) {} else { std::stringstream __s__; __s__ << #y ": " << y; assert_fail(#x, __LINE__, __FILE__, __PRETTY_FUNCTION__, __s__.str().c_str()); } } while (false)
#else
#define TORRENT_ASSERT_VAL(x, y) TORRENT_ASSERT(x)
#endif
#else
#include <cassert>
#define TORRENT_ASSERT(x) assert(x)
#define TORRENT_ASSERT_VAL(x, y) assert(x)
#endif
#endif
#endif
<|endoftext|> |
<commit_before>#include "cmbNucMainWindow.h"
#include "ui_qNucMainWindow.h"
#include <vtkActor.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkCompositePolyDataMapper2.h>
#include <QFileDialog>
#include <QStringList>
#include <QDebug>
#include <QDockWidget>
#include "cmbNucAssembly.h"
#include "cmbNucCore.h"
#include "cmbNucInputPropertiesWidget.h"
#include "cmbNucInputListWidget.h"
#include "vtkAxesActor.h"
#include "vtkProperty.h"
#include "vtkCompositeDataDisplayAttributes.h"
#include "vtkDataObjectTreeIterator.h"
#include "vtkInformation.h"
#include "vtkCompositeDataPipeline.h"
#include "vtkAlgorithm.h"
#include "vtkNew.h"
// Constructor
cmbNucMainWindow::cmbNucMainWindow()
{
// vtkNew<vtkCompositeDataPipeline> compositeExec;
// vtkAlgorithm::SetDefaultExecutivePrototype(compositeExec.GetPointer());
this->ui = new Ui_qNucMainWindow;
this->ui->setupUi(this);
this->NuclearCore = new cmbNucCore();
this->initPanels();
// VTK/Qt wedded
this->Renderer = vtkSmartPointer<vtkRenderer>::New();
this->ui->qvtkWidget->GetRenderWindow()->AddRenderer(this->Renderer);
this->Mapper = vtkSmartPointer<vtkCompositePolyDataMapper2>::New();
this->Actor = vtkSmartPointer<vtkActor>::New();
this->Actor->SetMapper(this->Mapper.GetPointer());
this->Actor->GetProperty()->SetShading(1);
this->Actor->GetProperty()->SetInterpolationToPhong();
// this->Actor->GetProperty()->EdgeVisibilityOn();
this->Renderer->AddActor(this->Actor);
vtkCompositeDataDisplayAttributes *attributes = vtkCompositeDataDisplayAttributes::New();
this->Mapper->SetCompositeDataDisplayAttributes(attributes);
attributes->Delete();
// add axes actor
vtkAxesActor *axesActor = vtkAxesActor::New();
this->Renderer->AddActor(axesActor);
axesActor->Delete();
// Set up action signals and slots
connect(this->ui->actionExit, SIGNAL(triggered()), this, SLOT(onExit()));
connect(this->ui->actionOpenFile, SIGNAL(triggered()), this, SLOT(onFileOpen()));
connect(this->ui->actionSaveFile, SIGNAL(triggered()), this, SLOT(onFileSave()));
connect(this->ui->actionNew, SIGNAL(triggered()), this, SLOT(onFileNew()));
// Hardcoded duct colors
this->MaterialColors.insert("g1", QColor::fromRgbF(1, 1, 1, 0.3));
this->MaterialColors.insert("c1", QColor::fromRgbF(0.6, 0.4, 0.2, 0.5));
this->MaterialColors.insert("m3", QColor::fromRgbF(0.8, 0.4, 0.0, 0.7));
// pin color
this->MaterialColors.insert("pin", QColor::fromRgbF(1.0, 0.4, 0.0));
}
cmbNucMainWindow::~cmbNucMainWindow()
{
this->PropertyWidget->setObject(NULL, NULL);
this->PropertyWidget->setAssembly(NULL);
this->InputsWidget->setCore(NULL);
delete this->NuclearCore;
}
void cmbNucMainWindow::initPanels()
{
this->InputsWidget = new cmbNucInputListWidget(this);
this->PropertyWidget = new cmbNucInputPropertiesWidget(this);
this->ui->InputsDock->setWidget(this->InputsWidget);
this->ui->PropertyDock->setWidget(this->PropertyWidget);
this->ui->PropertyDock->setEnabled(0);
this->InputsWidget->setEnabled(0);
this->InputsWidget->setCore(this->NuclearCore);
QObject::connect(this->InputsWidget,
SIGNAL(objectSelected(AssyPartObj*, const char*)), this,
SLOT(onObjectSelected(AssyPartObj*, const char*)));
QObject::connect(this->InputsWidget,
SIGNAL(objectRemoved()), this,
SLOT(onObjectModified()));
QObject::connect(this->PropertyWidget,
SIGNAL(currentObjectModified(AssyPartObj*)), this,
SLOT(onObjectModified(AssyPartObj*)));
}
void cmbNucMainWindow::onObjectSelected(AssyPartObj* selObj,
const char* name)
{
if(!selObj)
{
this->ui->PropertyDock->setEnabled(0);
return;
}
this->ui->PropertyDock->setEnabled(1);
this->PropertyWidget->setAssembly(this->InputsWidget->getCurrentAssembly());
this->PropertyWidget->setObject(selObj, name);
}
void cmbNucMainWindow::onObjectModified(AssyPartObj* obj)
{
// update material colors
this->updateMaterialColors();
if(obj && obj->GetType() == CMBNUC_CORE)
{
this->Renderer->ResetCamera();
}
// render
this->ui->qvtkWidget->update();
}
void cmbNucMainWindow::onExit()
{
qApp->exit();
}
void cmbNucMainWindow::onFileNew()
{
this->PropertyWidget->setObject(NULL, NULL);
this->PropertyWidget->setAssembly(NULL);
this->InputsWidget->onNewAssembly();
this->Renderer->ResetCamera();
this->Renderer->Render();
}
void cmbNucMainWindow::onFileOpen()
{
QStringList fileNames =
QFileDialog::getOpenFileNames(this,
"Open Assygen File...",
QDir::homePath(),
"INP Files (*.inp)");
if(fileNames.count()==0)
{
return;
}
this->setCursor(Qt::BusyCursor);
// clear old assembly
this->PropertyWidget->setObject(NULL, NULL);
this->PropertyWidget->setAssembly(NULL);
int numExistingAssy = this->NuclearCore->GetNumberOfAssemblies();
int numNewAssy = 0;
QList<cmbNucAssembly*> assemblies;
foreach(QString fileName, fileNames)
{
if(!fileName.isEmpty())
{
cmbNucAssembly* assy = this->openFile(fileName);
assemblies.append(assy);
numNewAssy++;
}
}
// the very first time
if(numExistingAssy == 0)
{
this->NuclearCore->SetDimensions(numNewAssy, numNewAssy);
for(int i=0; i<numNewAssy ; i++)
{
this->NuclearCore->SetAssemblyLabel(i, 0, assemblies.at(i)->label);
for(int j=1; j<numNewAssy ; j++)
{
this->NuclearCore->SetAssemblyLabel(i, j, "xx");
}
}
}
// update data colors
this->updateMaterialColors();
// render
this->Renderer->ResetCamera();
this->Renderer->Render();
this->InputsWidget->updateUI(numExistingAssy==0 && numNewAssy>1);
this->unsetCursor();
}
cmbNucAssembly* cmbNucMainWindow::openFile(const QString &fileName)
{
// read file and create new assembly
cmbNucAssembly* assembly = new cmbNucAssembly;
assembly->label = QString("Assembly").append(
QString::number(this->NuclearCore->GetNumberOfAssemblies()+1)).toStdString();
this->NuclearCore->AddAssembly(assembly);
assembly->ReadFile(fileName.toStdString());
return assembly;
}
void cmbNucMainWindow::onFileSave()
{
QString fileName =
QFileDialog::getSaveFileName(this,
"Save Assygen File...",
QDir::homePath(),
"INP Files (*.inp)");
if(!fileName.isEmpty())
{
this->setCursor(Qt::BusyCursor);
this->saveFile(fileName);
this->unsetCursor();
}
}
void cmbNucMainWindow::saveFile(const QString &fileName)
{
if(!this->InputsWidget->getCurrentAssembly())
{
qDebug() << "no assembly to save";
return;
}
this->InputsWidget->getCurrentAssembly()->WriteFile(fileName.toStdString());
}
void cmbNucMainWindow::updateMaterialColors()
{
// regenerate core and assembly view
vtkSmartPointer<vtkMultiBlockDataSet> coredata = this->NuclearCore->GetData();
this->Mapper->SetInputDataObject(coredata);
if(!coredata)
{
return;
}
unsigned int numCoreBlocks = coredata->GetNumberOfBlocks();
vtkCompositeDataDisplayAttributes *attributes =
this->Mapper->GetCompositeDataDisplayAttributes();
//vtkDataObjectTreeIterator *coreiter = coredata->NewTreeIterator();
//coreiter->SetSkipEmptyNodes(false);
unsigned int realflatidx=0;
for(unsigned int block=0; block<numCoreBlocks; block++)
{
realflatidx++;
if(!coredata->GetBlock(block))
{
continue;
}
vtkMultiBlockDataSet* data = vtkMultiBlockDataSet::SafeDownCast(coredata->GetBlock(block));
if(!data)
{
continue;
}
// for each assembly
if(coredata->GetMetaData(block)->Has(vtkCompositeDataSet::NAME()))
{
std::string assyLabel = coredata->GetMetaData(block)->Get(
vtkCompositeDataSet::NAME());
cmbNucAssembly* assy = this->NuclearCore->GetAssembly(assyLabel);
if(!assy)
{
qCritical() << "no specified assembly to found in core: " << assyLabel.c_str();
return;
}
std::pair<int, int> dimensions = assy->AssyLattice.GetDimensions();
int pins = dimensions.first * dimensions.second;
// vtkDataObjectTreeIterator *iter = data->NewTreeIterator();
// iter->SetSkipEmptyNodes(false);
int pin_count = 0;
// while(!iter->IsDoneWithTraversal())
int numAssyBlocks = data->GetNumberOfBlocks();
for(unsigned int idx=0; idx<numAssyBlocks; idx++)
{
realflatidx++;
if(pin_count < pins)
{
int i = realflatidx;
QColor pinColor = this->MaterialColors["pin"];
double color[] = { pinColor.redF(), pinColor.greenF(), pinColor.blueF() };
attributes->SetBlockColor(i, color);
attributes->SetBlockOpacity(i, pinColor.alphaF());
pin_count++;
}
else // ducts need to color by layers
{
if(vtkMultiBlockDataSet* ductBlock =
vtkMultiBlockDataSet::SafeDownCast(data->GetBlock(idx)))
{
unsigned int numBlocks = ductBlock->GetNumberOfBlocks();
for(unsigned int b=0; b<numBlocks; b++)
{
int iKey = b%3;
std::string strKey = "m3";
if(iKey == 1)
{
strKey = "c1";
}
else if(iKey == 2)
{
strKey = "g1";
}
int i = ++realflatidx;
QColor matColor = this->MaterialColors.value(strKey.c_str());
double color[] = { matColor.redF(), matColor.greenF(), matColor.blueF() };
attributes->SetBlockColor(i, color);
attributes->SetBlockOpacity(i, matColor.alphaF());
}
}
}
}
}
}
}
<commit_msg>ENH:Changed default colors<commit_after>#include "cmbNucMainWindow.h"
#include "ui_qNucMainWindow.h"
#include <vtkActor.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkCompositePolyDataMapper2.h>
#include <QFileDialog>
#include <QStringList>
#include <QDebug>
#include <QDockWidget>
#include "cmbNucAssembly.h"
#include "cmbNucCore.h"
#include "cmbNucInputPropertiesWidget.h"
#include "cmbNucInputListWidget.h"
#include "vtkAxesActor.h"
#include "vtkProperty.h"
#include "vtkCompositeDataDisplayAttributes.h"
#include "vtkDataObjectTreeIterator.h"
#include "vtkInformation.h"
#include "vtkCompositeDataPipeline.h"
#include "vtkAlgorithm.h"
#include "vtkNew.h"
// Constructor
cmbNucMainWindow::cmbNucMainWindow()
{
// vtkNew<vtkCompositeDataPipeline> compositeExec;
// vtkAlgorithm::SetDefaultExecutivePrototype(compositeExec.GetPointer());
this->ui = new Ui_qNucMainWindow;
this->ui->setupUi(this);
this->NuclearCore = new cmbNucCore();
this->initPanels();
// VTK/Qt wedded
this->Renderer = vtkSmartPointer<vtkRenderer>::New();
this->ui->qvtkWidget->GetRenderWindow()->AddRenderer(this->Renderer);
this->Mapper = vtkSmartPointer<vtkCompositePolyDataMapper2>::New();
this->Actor = vtkSmartPointer<vtkActor>::New();
this->Actor->SetMapper(this->Mapper.GetPointer());
this->Actor->GetProperty()->SetShading(1);
this->Actor->GetProperty()->SetInterpolationToPhong();
// this->Actor->GetProperty()->EdgeVisibilityOn();
this->Renderer->AddActor(this->Actor);
vtkCompositeDataDisplayAttributes *attributes = vtkCompositeDataDisplayAttributes::New();
this->Mapper->SetCompositeDataDisplayAttributes(attributes);
attributes->Delete();
// add axes actor
vtkAxesActor *axesActor = vtkAxesActor::New();
this->Renderer->AddActor(axesActor);
axesActor->Delete();
// Set up action signals and slots
connect(this->ui->actionExit, SIGNAL(triggered()), this, SLOT(onExit()));
connect(this->ui->actionOpenFile, SIGNAL(triggered()), this, SLOT(onFileOpen()));
connect(this->ui->actionSaveFile, SIGNAL(triggered()), this, SLOT(onFileSave()));
connect(this->ui->actionNew, SIGNAL(triggered()), this, SLOT(onFileNew()));
// Hardcoded duct colors
this->MaterialColors.insert("g1", QColor::fromRgbF(.7, .7, .7, 1.0));
this->MaterialColors.insert("c1", QColor::fromRgbF(0.3, 0.5, 1.0, 1.0));
this->MaterialColors.insert("m3", QColor::fromRgbF(0.8, 0.4, 0.0, 1.0));
// pin color
this->MaterialColors.insert("pin", QColor::fromRgbF(1.0, 0.1, 0.1));
}
cmbNucMainWindow::~cmbNucMainWindow()
{
this->PropertyWidget->setObject(NULL, NULL);
this->PropertyWidget->setAssembly(NULL);
this->InputsWidget->setCore(NULL);
delete this->NuclearCore;
}
void cmbNucMainWindow::initPanels()
{
this->InputsWidget = new cmbNucInputListWidget(this);
this->PropertyWidget = new cmbNucInputPropertiesWidget(this);
this->ui->InputsDock->setWidget(this->InputsWidget);
this->ui->PropertyDock->setWidget(this->PropertyWidget);
this->ui->PropertyDock->setEnabled(0);
this->InputsWidget->setEnabled(0);
this->InputsWidget->setCore(this->NuclearCore);
QObject::connect(this->InputsWidget,
SIGNAL(objectSelected(AssyPartObj*, const char*)), this,
SLOT(onObjectSelected(AssyPartObj*, const char*)));
QObject::connect(this->InputsWidget,
SIGNAL(objectRemoved()), this,
SLOT(onObjectModified()));
QObject::connect(this->PropertyWidget,
SIGNAL(currentObjectModified(AssyPartObj*)), this,
SLOT(onObjectModified(AssyPartObj*)));
}
void cmbNucMainWindow::onObjectSelected(AssyPartObj* selObj,
const char* name)
{
if(!selObj)
{
this->ui->PropertyDock->setEnabled(0);
return;
}
this->ui->PropertyDock->setEnabled(1);
this->PropertyWidget->setAssembly(this->InputsWidget->getCurrentAssembly());
this->PropertyWidget->setObject(selObj, name);
}
void cmbNucMainWindow::onObjectModified(AssyPartObj* obj)
{
// update material colors
this->updateMaterialColors();
if(obj && obj->GetType() == CMBNUC_CORE)
{
this->Renderer->ResetCamera();
}
// render
this->ui->qvtkWidget->update();
}
void cmbNucMainWindow::onExit()
{
qApp->exit();
}
void cmbNucMainWindow::onFileNew()
{
this->PropertyWidget->setObject(NULL, NULL);
this->PropertyWidget->setAssembly(NULL);
this->InputsWidget->onNewAssembly();
this->Renderer->ResetCamera();
this->Renderer->Render();
}
void cmbNucMainWindow::onFileOpen()
{
QStringList fileNames =
QFileDialog::getOpenFileNames(this,
"Open Assygen File...",
QDir::homePath(),
"INP Files (*.inp)");
if(fileNames.count()==0)
{
return;
}
this->setCursor(Qt::BusyCursor);
// clear old assembly
this->PropertyWidget->setObject(NULL, NULL);
this->PropertyWidget->setAssembly(NULL);
int numExistingAssy = this->NuclearCore->GetNumberOfAssemblies();
int numNewAssy = 0;
QList<cmbNucAssembly*> assemblies;
foreach(QString fileName, fileNames)
{
if(!fileName.isEmpty())
{
cmbNucAssembly* assy = this->openFile(fileName);
assemblies.append(assy);
numNewAssy++;
}
}
// the very first time
if(numExistingAssy == 0)
{
this->NuclearCore->SetDimensions(numNewAssy, numNewAssy);
for(int i=0; i<numNewAssy ; i++)
{
this->NuclearCore->SetAssemblyLabel(i, 0, assemblies.at(i)->label);
for(int j=1; j<numNewAssy ; j++)
{
this->NuclearCore->SetAssemblyLabel(i, j, "xx");
}
}
}
// update data colors
this->updateMaterialColors();
// render
this->Renderer->ResetCamera();
this->Renderer->Render();
this->InputsWidget->updateUI(numExistingAssy==0 && numNewAssy>1);
this->unsetCursor();
}
cmbNucAssembly* cmbNucMainWindow::openFile(const QString &fileName)
{
// read file and create new assembly
cmbNucAssembly* assembly = new cmbNucAssembly;
assembly->label = QString("Assembly").append(
QString::number(this->NuclearCore->GetNumberOfAssemblies()+1)).toStdString();
this->NuclearCore->AddAssembly(assembly);
assembly->ReadFile(fileName.toStdString());
return assembly;
}
void cmbNucMainWindow::onFileSave()
{
QString fileName =
QFileDialog::getSaveFileName(this,
"Save Assygen File...",
QDir::homePath(),
"INP Files (*.inp)");
if(!fileName.isEmpty())
{
this->setCursor(Qt::BusyCursor);
this->saveFile(fileName);
this->unsetCursor();
}
}
void cmbNucMainWindow::saveFile(const QString &fileName)
{
if(!this->InputsWidget->getCurrentAssembly())
{
qDebug() << "no assembly to save";
return;
}
this->InputsWidget->getCurrentAssembly()->WriteFile(fileName.toStdString());
}
void cmbNucMainWindow::updateMaterialColors()
{
// regenerate core and assembly view
vtkSmartPointer<vtkMultiBlockDataSet> coredata = this->NuclearCore->GetData();
this->Mapper->SetInputDataObject(coredata);
if(!coredata)
{
return;
}
unsigned int numCoreBlocks = coredata->GetNumberOfBlocks();
vtkCompositeDataDisplayAttributes *attributes =
this->Mapper->GetCompositeDataDisplayAttributes();
//vtkDataObjectTreeIterator *coreiter = coredata->NewTreeIterator();
//coreiter->SetSkipEmptyNodes(false);
unsigned int realflatidx=0;
for(unsigned int block=0; block<numCoreBlocks; block++)
{
realflatidx++;
if(!coredata->GetBlock(block))
{
continue;
}
vtkMultiBlockDataSet* data = vtkMultiBlockDataSet::SafeDownCast(coredata->GetBlock(block));
if(!data)
{
continue;
}
// for each assembly
if(coredata->GetMetaData(block)->Has(vtkCompositeDataSet::NAME()))
{
std::string assyLabel = coredata->GetMetaData(block)->Get(
vtkCompositeDataSet::NAME());
cmbNucAssembly* assy = this->NuclearCore->GetAssembly(assyLabel);
if(!assy)
{
qCritical() << "no specified assembly to found in core: " << assyLabel.c_str();
return;
}
std::pair<int, int> dimensions = assy->AssyLattice.GetDimensions();
int pins = dimensions.first * dimensions.second;
// vtkDataObjectTreeIterator *iter = data->NewTreeIterator();
// iter->SetSkipEmptyNodes(false);
int pin_count = 0;
// while(!iter->IsDoneWithTraversal())
int numAssyBlocks = data->GetNumberOfBlocks();
for(unsigned int idx=0; idx<numAssyBlocks; idx++)
{
realflatidx++;
if(pin_count < pins)
{
int i = realflatidx;
QColor pinColor = this->MaterialColors["pin"];
double color[] = { pinColor.redF(), pinColor.greenF(), pinColor.blueF() };
attributes->SetBlockColor(i, color);
attributes->SetBlockOpacity(i, pinColor.alphaF());
pin_count++;
}
else // ducts need to color by layers
{
if(vtkMultiBlockDataSet* ductBlock =
vtkMultiBlockDataSet::SafeDownCast(data->GetBlock(idx)))
{
unsigned int numBlocks = ductBlock->GetNumberOfBlocks();
for(unsigned int b=0; b<numBlocks; b++)
{
int iKey = b%3;
std::string strKey = "m3";
if(iKey == 1)
{
strKey = "c1";
}
else if(iKey == 2)
{
strKey = "g1";
}
int i = ++realflatidx;
QColor matColor = this->MaterialColors.value(strKey.c_str());
double color[] = { matColor.redF(), matColor.greenF(), matColor.blueF() };
attributes->SetBlockColor(i, color);
attributes->SetBlockOpacity(i, matColor.alphaF());
}
}
}
}
}
}
}
<|endoftext|> |
<commit_before>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Kirsten Weber
#ifndef DUNE_STUFF_FUNCTIONS_EXPRESSION_HH
#define DUNE_STUFF_FUNCTIONS_EXPRESSION_HH
#include <vector>
#include <limits>
#include <dune/common/fvector.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/stuff/common/exceptions.hh>
#include "expression/base.hh"
#include "interfaces.hh"
#include "default.hh"
#include "constant.hh"
namespace Dune {
namespace Stuff {
namespace Functions {
/**
* \attention If you add the create() and default_config() method, do not forget to enable the matrix valued
* versions in test/function_expression.cc
*/
template< class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1 >
class Expression
: public LocalizableFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols >
{
typedef LocalizableFunctionInterface
< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType;
typedef Expression< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > ThisType;
typedef MathExpressionBase
< DomainFieldImp, domainDim, RangeFieldImp, rangeDim*rangeDimCols > MathExpressionFunctionType;
class Localfunction
: public LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols >
{
typedef LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType;
public:
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const size_t dimRange = BaseType::dimRange;
static const size_t dimRangeCols = BaseType::dimRangeCols;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
Localfunction(const EntityType& ent,
const std::shared_ptr< const MathExpressionFunctionType >& function,
const size_t ord)
: BaseType(ent)
, function_(function)
, order_(ord)
, tmp_vector_(0)
{}
Localfunction(const Localfunction& /*other*/) = delete;
Localfunction& operator=(const Localfunction& /*other*/) = delete;
virtual size_t order() const override
{
return order_;
}
virtual void evaluate(const DomainType& xx, RangeType& ret) const override
{
function_->evaluate(this->entity().geometry().global(xx), tmp_vector_);
for (size_t ii = 0; ii < dimRange; ++ii) {
auto& retRow = ret[ii];
for (size_t jj = 0; jj < dimRangeCols; ++jj) {
retRow[jj] = tmp_vector_[ii*dimRange + jj];
}
}
} // ... evaluate(...)
virtual void jacobian(const DomainType& /*xx*/, JacobianRangeType& /*ret*/) const override
{
DUNE_THROW(NotImplemented,
"Once we decided on the JacobianRangeType of matrix valued functions we have to implement "
<< "gradients for this function!");
}
private:
const std::shared_ptr< const MathExpressionFunctionType > function_;
const size_t order_;
mutable FieldVector< RangeFieldType, dimRange*dimRangeCols > tmp_vector_;
}; // class Localfunction
public:
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::LocalfunctionType LocalfunctionType;
static std::string static_id()
{
return BaseType::static_id() + ".expression";
}
Expression(const std::string variable,
const std::string expression,
const size_t ord = 0,
const std::string nm = static_id())
: function_(new MathExpressionFunctionType(variable, expression))
, order_(ord)
, name_(nm)
{}
Expression(const std::string variable,
const std::vector< std::string > expressions,
const size_t ord = 0,
const std::string nm = static_id())
: function_(new MathExpressionFunctionType(variable, expressions))
, order_(ord)
, name_(nm)
{}
Expression(const ThisType& other) = default;
ThisType& operator=(const ThisType& other)
{
if (this != &other) {
function_ = other.function_;
order_ = other.order_;
name_ = other.name_;
}
return *this;
}
virtual std::string type() const override final
{
return BaseType::static_id() + ".expression";
}
virtual std::string name() const override
{
return name_;
}
virtual std::unique_ptr< LocalfunctionType > local_function(const EntityType& entity) const override
{
return std::unique_ptr< Localfunction >(new Localfunction(entity, function_, order_));
}
private:
std::shared_ptr< const MathExpressionFunctionType > function_;
size_t order_;
std::string name_;
}; // class Expression
template< class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp, size_t rangeDim >
class Expression< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1 >
: public GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim >
{
typedef GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim > BaseType;
typedef Expression< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1 > ThisType;
typedef MathExpressionBase < DomainFieldImp, domainDim, RangeFieldImp, rangeDim > MathExpressionFunctionType;
typedef MathExpressionBase < DomainFieldImp, domainDim, RangeFieldImp, domainDim > MathExpressionGradientType;
public:
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::LocalfunctionType LocalfunctionType;
static const size_t dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
static const size_t dimRange = BaseType::dimRange;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
static const bool available = true;
static std::string static_id()
{
return BaseType::static_id() + ".expression";
}
static Common::Configuration default_config(const std::string sub_name = "")
{
Common::Configuration config;
config["variable"] = "x";
config["expression"] = "[x[0] sin(x[0]) exp(x[0])]";
config["order"] = "3";
config["name"] = static_id();
if (sub_name.empty())
return config;
else {
Common::Configuration tmp;
tmp.add(config, sub_name);
return tmp;
}
} // ... default_config(...)
static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(), const std::string sub_name = static_id())
{
// get correct config
const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;
const Common::Configuration default_cfg = default_config();
// create
return cfg.has_key("gradient")
? Common::make_unique< ThisType >(
cfg.get("variable", default_cfg.get< std::string >("variable")),
cfg.get("expression", default_cfg.get< std::vector< std::string > >("expression")),
cfg.get("order", default_cfg.get< size_t >("order")),
cfg.get("name", default_cfg.get< std::string >("name")),
cfg.get< Dune::FieldMatrix< std::string, dimRange, dimDomain > >("gradient"))
: Common::make_unique< ThisType >(
cfg.get("variable", default_cfg.get< std::string >("variable")),
cfg.get("expression", default_cfg.get< std::vector< std::string > >("expression")),
cfg.get("order", default_cfg.get< size_t >("order")),
cfg.get("name", default_cfg.get< std::string >("name")),
Dune::FieldMatrix< std::string, 0, 0 >());
} // ... create(...)
// constructors taking a std::vector< std::vector< std::string > > for the jacobian
Expression(const std::string variable,
const std::string expression,
const size_t ord = default_config().get< size_t >("order"),
const std::string nm = static_id(),
const std::vector< std::vector< std::string > > gradient_expressions
= std::vector< std::vector< std::string > >())
: function_(new MathExpressionFunctionType(variable, expression))
, order_(ord)
, name_(nm)
{
build_gradients(variable, gradient_expressions);
}
Expression(const std::string variable,
const std::vector< std::string > expressions,
const size_t ord = default_config().get< size_t >("order"),
const std::string nm = static_id(),
const std::vector< std::vector< std::string > > gradient_expressions
= std::vector< std::vector< std::string > >())
: function_(new MathExpressionFunctionType(variable, expressions))
, order_(ord)
, name_(nm)
{
build_gradients(variable, gradient_expressions);
}
// constructors taking a FieldMatrix for the jacobian
template< int rows, int cols >
Expression(const std::string variable,
const std::string expression,
const size_t ord = default_config().get< size_t >("order"),
const std::string nm = static_id(),
const Dune::FieldMatrix< std::string, rows, cols > jacobian
= Dune::FieldMatrix< std::string, 0, 0 >())
: function_(new MathExpressionFunctionType(variable, expression))
, order_(ord)
, name_(nm)
{
build_gradients(variable, jacobian);
}
template< int rows, int cols >
Expression(const std::string variable,
const std::vector< std::string > expressions,
const size_t ord = default_config().get< size_t >("order"),
const std::string nm = static_id(),
const Dune::FieldMatrix< std::string, rows, cols > jacobian
= Dune::FieldMatrix< std::string, 0, 0 >())
: function_(new MathExpressionFunctionType(variable, expressions))
, order_(ord)
, name_(nm)
{
build_gradients(variable, jacobian);
}
virtual std::string name() const override
{
return name_;
}
virtual size_t order() const override
{
return order_;
}
virtual void evaluate(const DomainType& xx, RangeType& ret) const override
{
function_->evaluate(xx, ret);
#ifndef NDEBUG
# ifndef DUNE_STUFF_FUNCTIONS_EXPRESSION_DISABLE_CHECKS
bool failure = false;
std::string type;
if (std::isnan(ret[0])) {
failure = true;
type = "NaN";
} else if (std::isinf(ret[0])) {
failure = true;
type = "inf";
} else if (std::abs(ret[0]) > (0.9 * std::numeric_limits< double >::max())) {
failure = true;
type = "an unlikely value";
}
if (failure)
DUNE_THROW(Stuff::Exceptions::internal_error,
"evaluating this function yielded " << type << "!\n"
<< "The variable of this function is: " << function_->variable() << "\n"
<< "The expression of this functional is: " << function_->expression().at(0) << "\n"
<< "You tried to evaluate it with: xx = " << xx << "\n"
<< "The result was: " << ret << "\n\n"
<< "You can disable this check by defining DUNE_STUFF_FUNCTIONS_EXPRESSION_DISABLE_CHECKS\n");
# endif // DUNE_STUFF_FUNCTIONS_EXPRESSION_DISABLE_CHECKS
#endif // NDEBUG
}
virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const override
{
if (gradients_.size() == 0)
DUNE_THROW(NotImplemented, "This function does not provide any gradients!");
assert(gradients_.size() == dimRange);
for (size_t ii = 0; ii < dimRange; ++ii) {
gradients_[ii]->evaluate(xx, ret[ii]);
}
} // ... jacobian(...)
private:
void build_gradients(const std::string variable,
const std::vector< std::vector< std::string > >& gradient_expressions)
{
assert(gradient_expressions.size() == 0 || gradient_expressions.size() >= dimRange);
if (gradient_expressions.size() > 0)
for (size_t rr = 0; rr < dimRange; ++rr) {
const auto& gradient_expression = gradient_expressions[rr];
assert(gradient_expression.size() >= dimDomain);
gradients_.emplace_back(new MathExpressionGradientType(variable, gradient_expression));
}
} // ... build_gradients(...)
template< int rows, int cols >
void build_gradients(const std::string variable,
Dune::FieldMatrix< std::string, rows, cols > jacobian)
{
assert(jacobian.rows == 0 || jacobian.rows >= dimRange);
assert(jacobian.cols == 0 || jacobian.cols >= dimDomain);
if (jacobian.rows > 0 && jacobian.cols > 0)
for (size_t rr = 0; rr < dimRange; ++rr) {
std::vector< std::string > gradient_expression;
for (size_t cc = 0; cc < dimDomain; ++cc)
gradient_expression.emplace_back(jacobian[rr][cc]);
gradients_.emplace_back(new MathExpressionGradientType(variable, gradient_expression));
}
} // ... build_gradients(...)
std::shared_ptr< const MathExpressionFunctionType > function_;
size_t order_;
std::string name_;
std::vector< std::shared_ptr< const MathExpressionGradientType > > gradients_;
}; // class Expression< ..., 1 >
} // namespace Functions
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_FUNCTIONS_EXPRESSION_HH
<commit_msg>[functions.expression] remove default arguments<commit_after>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Kirsten Weber
#ifndef DUNE_STUFF_FUNCTIONS_EXPRESSION_HH
#define DUNE_STUFF_FUNCTIONS_EXPRESSION_HH
#include <vector>
#include <limits>
#include <dune/common/fvector.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/stuff/common/exceptions.hh>
#include "expression/base.hh"
#include "interfaces.hh"
#include "default.hh"
#include "constant.hh"
namespace Dune {
namespace Stuff {
namespace Functions {
/**
* \attention If you add the create() and default_config() method, do not forget to enable the matrix valued
* versions in test/function_expression.cc
*/
template< class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1 >
class Expression
: public LocalizableFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols >
{
typedef LocalizableFunctionInterface
< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType;
typedef Expression< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > ThisType;
typedef MathExpressionBase
< DomainFieldImp, domainDim, RangeFieldImp, rangeDim*rangeDimCols > MathExpressionFunctionType;
class Localfunction
: public LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols >
{
typedef LocalfunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType;
public:
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const size_t dimRange = BaseType::dimRange;
static const size_t dimRangeCols = BaseType::dimRangeCols;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
Localfunction(const EntityType& ent,
const std::shared_ptr< const MathExpressionFunctionType >& function,
const size_t ord)
: BaseType(ent)
, function_(function)
, order_(ord)
, tmp_vector_(0)
{}
Localfunction(const Localfunction& /*other*/) = delete;
Localfunction& operator=(const Localfunction& /*other*/) = delete;
virtual size_t order() const override
{
return order_;
}
virtual void evaluate(const DomainType& xx, RangeType& ret) const override
{
function_->evaluate(this->entity().geometry().global(xx), tmp_vector_);
for (size_t ii = 0; ii < dimRange; ++ii) {
auto& retRow = ret[ii];
for (size_t jj = 0; jj < dimRangeCols; ++jj) {
retRow[jj] = tmp_vector_[ii*dimRange + jj];
}
}
} // ... evaluate(...)
virtual void jacobian(const DomainType& /*xx*/, JacobianRangeType& /*ret*/) const override
{
DUNE_THROW(NotImplemented,
"Once we decided on the JacobianRangeType of matrix valued functions we have to implement "
<< "gradients for this function!");
}
private:
const std::shared_ptr< const MathExpressionFunctionType > function_;
const size_t order_;
mutable FieldVector< RangeFieldType, dimRange*dimRangeCols > tmp_vector_;
}; // class Localfunction
public:
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::LocalfunctionType LocalfunctionType;
static std::string static_id()
{
return BaseType::static_id() + ".expression";
}
Expression(const std::string variable,
const std::string expression,
const size_t ord = 0,
const std::string nm = static_id())
: function_(new MathExpressionFunctionType(variable, expression))
, order_(ord)
, name_(nm)
{}
Expression(const std::string variable,
const std::vector< std::string > expressions,
const size_t ord = 0,
const std::string nm = static_id())
: function_(new MathExpressionFunctionType(variable, expressions))
, order_(ord)
, name_(nm)
{}
Expression(const ThisType& other) = default;
ThisType& operator=(const ThisType& other)
{
if (this != &other) {
function_ = other.function_;
order_ = other.order_;
name_ = other.name_;
}
return *this;
}
virtual std::string type() const override final
{
return BaseType::static_id() + ".expression";
}
virtual std::string name() const override
{
return name_;
}
virtual std::unique_ptr< LocalfunctionType > local_function(const EntityType& entity) const override
{
return std::unique_ptr< Localfunction >(new Localfunction(entity, function_, order_));
}
private:
std::shared_ptr< const MathExpressionFunctionType > function_;
size_t order_;
std::string name_;
}; // class Expression
template< class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp, size_t rangeDim >
class Expression< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1 >
: public GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim >
{
typedef GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim > BaseType;
typedef Expression< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1 > ThisType;
typedef MathExpressionBase < DomainFieldImp, domainDim, RangeFieldImp, rangeDim > MathExpressionFunctionType;
typedef MathExpressionBase < DomainFieldImp, domainDim, RangeFieldImp, domainDim > MathExpressionGradientType;
public:
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::LocalfunctionType LocalfunctionType;
static const size_t dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
static const size_t dimRange = BaseType::dimRange;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
static const bool available = true;
static std::string static_id()
{
return BaseType::static_id() + ".expression";
}
static Common::Configuration default_config(const std::string sub_name = "")
{
Common::Configuration config;
config["variable"] = "x";
config["expression"] = "[x[0] sin(x[0]) exp(x[0])]";
config["order"] = "3";
config["name"] = static_id();
if (sub_name.empty())
return config;
else {
Common::Configuration tmp;
tmp.add(config, sub_name);
return tmp;
}
} // ... default_config(...)
static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(), const std::string sub_name = static_id())
{
// get correct config
const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;
const Common::Configuration default_cfg = default_config();
// create
return cfg.has_key("gradient")
? Common::make_unique< ThisType >(
cfg.get("variable", default_cfg.get< std::string >("variable")),
cfg.get("expression", default_cfg.get< std::vector< std::string > >("expression")),
cfg.get("order", default_cfg.get< size_t >("order")),
cfg.get("name", default_cfg.get< std::string >("name")),
cfg.get< Dune::FieldMatrix< std::string, dimRange, dimDomain > >("gradient"))
: Common::make_unique< ThisType >(
cfg.get("variable", default_cfg.get< std::string >("variable")),
cfg.get("expression", default_cfg.get< std::vector< std::string > >("expression")),
cfg.get("order", default_cfg.get< size_t >("order")),
cfg.get("name", default_cfg.get< std::string >("name")),
Dune::FieldMatrix< std::string, 0, 0 >());
} // ... create(...)
// constructors taking a std::vector< std::vector< std::string > > for the jacobian
Expression(const std::string variable,
const std::string expression,
const size_t ord = default_config().get< size_t >("order"),
const std::string nm = static_id(),
const std::vector< std::vector< std::string > > gradient_expressions
= std::vector< std::vector< std::string > >())
: function_(new MathExpressionFunctionType(variable, expression))
, order_(ord)
, name_(nm)
{
build_gradients(variable, gradient_expressions);
}
Expression(const std::string variable,
const std::vector< std::string > expressions,
const size_t ord = default_config().get< size_t >("order"),
const std::string nm = static_id(),
const std::vector< std::vector< std::string > > gradient_expressions
= std::vector< std::vector< std::string > >())
: function_(new MathExpressionFunctionType(variable, expressions))
, order_(ord)
, name_(nm)
{
build_gradients(variable, gradient_expressions);
}
// constructors taking a FieldMatrix for the jacobian
template< int rows, int cols >
Expression(const std::string variable,
const std::string expression,
const size_t ord,
const std::string nm,
const Dune::FieldMatrix< std::string, rows, cols > jacobian)
: function_(new MathExpressionFunctionType(variable, expression))
, order_(ord)
, name_(nm)
{
build_gradients(variable, jacobian);
}
template< int rows, int cols >
Expression(const std::string variable,
const std::vector< std::string > expressions,
const size_t ord,
const std::string nm,
const Dune::FieldMatrix< std::string, rows, cols > jacobian)
: function_(new MathExpressionFunctionType(variable, expressions))
, order_(ord)
, name_(nm)
{
build_gradients(variable, jacobian);
}
virtual std::string name() const override
{
return name_;
}
virtual size_t order() const override
{
return order_;
}
virtual void evaluate(const DomainType& xx, RangeType& ret) const override
{
function_->evaluate(xx, ret);
#ifndef NDEBUG
# ifndef DUNE_STUFF_FUNCTIONS_EXPRESSION_DISABLE_CHECKS
bool failure = false;
std::string type;
if (std::isnan(ret[0])) {
failure = true;
type = "NaN";
} else if (std::isinf(ret[0])) {
failure = true;
type = "inf";
} else if (std::abs(ret[0]) > (0.9 * std::numeric_limits< double >::max())) {
failure = true;
type = "an unlikely value";
}
if (failure)
DUNE_THROW(Stuff::Exceptions::internal_error,
"evaluating this function yielded " << type << "!\n"
<< "The variable of this function is: " << function_->variable() << "\n"
<< "The expression of this functional is: " << function_->expression().at(0) << "\n"
<< "You tried to evaluate it with: xx = " << xx << "\n"
<< "The result was: " << ret << "\n\n"
<< "You can disable this check by defining DUNE_STUFF_FUNCTIONS_EXPRESSION_DISABLE_CHECKS\n");
# endif // DUNE_STUFF_FUNCTIONS_EXPRESSION_DISABLE_CHECKS
#endif // NDEBUG
}
virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const override
{
if (gradients_.size() == 0)
DUNE_THROW(NotImplemented, "This function does not provide any gradients!");
assert(gradients_.size() == dimRange);
for (size_t ii = 0; ii < dimRange; ++ii) {
gradients_[ii]->evaluate(xx, ret[ii]);
}
} // ... jacobian(...)
private:
void build_gradients(const std::string variable,
const std::vector< std::vector< std::string > >& gradient_expressions)
{
assert(gradient_expressions.size() == 0 || gradient_expressions.size() >= dimRange);
if (gradient_expressions.size() > 0)
for (size_t rr = 0; rr < dimRange; ++rr) {
const auto& gradient_expression = gradient_expressions[rr];
assert(gradient_expression.size() >= dimDomain);
gradients_.emplace_back(new MathExpressionGradientType(variable, gradient_expression));
}
} // ... build_gradients(...)
template< int rows, int cols >
void build_gradients(const std::string variable,
Dune::FieldMatrix< std::string, rows, cols > jacobian)
{
assert(jacobian.rows == 0 || jacobian.rows >= dimRange);
assert(jacobian.cols == 0 || jacobian.cols >= dimDomain);
if (jacobian.rows > 0 && jacobian.cols > 0)
for (size_t rr = 0; rr < dimRange; ++rr) {
std::vector< std::string > gradient_expression;
for (size_t cc = 0; cc < dimDomain; ++cc)
gradient_expression.emplace_back(jacobian[rr][cc]);
gradients_.emplace_back(new MathExpressionGradientType(variable, gradient_expression));
}
} // ... build_gradients(...)
std::shared_ptr< const MathExpressionFunctionType > function_;
size_t order_;
std::string name_;
std::vector< std::shared_ptr< const MathExpressionGradientType > > gradients_;
}; // class Expression< ..., 1 >
} // namespace Functions
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_FUNCTIONS_EXPRESSION_HH
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of Rasterbar Software nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef LIBTORRENT_BUFFER_HPP
#define LIBTORRENT_BUFFER_HPP
#include <memory>
#include <cstring>
#include "libtorrent/invariant_check.hpp"
#include "libtorrent/assert.hpp"
namespace libtorrent {
class buffer
{
public:
struct interval
{
interval(char* begin, char* end)
: begin(begin)
, end(end)
{}
char operator[](int index) const
{
TORRENT_ASSERT(begin + index < end);
return begin[index];
}
int left() const { TORRENT_ASSERT(end >= begin); return end - begin; }
char* begin;
char* end;
};
struct const_interval
{
const_interval(char const* begin, char const* end)
: begin(begin)
, end(end)
{}
char operator[](int index) const
{
TORRENT_ASSERT(begin + index < end);
return begin[index];
}
bool operator==(const const_interval& p_interval)
{
return (begin == p_interval.begin
&& end == p_interval.end);
}
int left() const { TORRENT_ASSERT(end >= begin); return end - begin; }
char const* begin;
char const* end;
};
buffer(std::size_t n = 0)
: m_begin(0)
, m_end(0)
, m_last(0)
{
if (n) resize(n);
}
buffer(buffer const& b)
: m_begin(0)
, m_end(0)
, m_last(0)
{
if (b.size() == 0) return;
resize(b.size());
std::memcpy(m_begin, b.begin(), b.size());
}
buffer& operator=(buffer const& b)
{
resize(b.size());
std::memcpy(m_begin, b.begin(), b.size());
return *this;
}
~buffer()
{
::operator delete (m_begin);
}
buffer::interval data() { return interval(m_begin, m_end); }
buffer::const_interval data() const { return const_interval(m_begin, m_end); }
void resize(std::size_t n)
{
reserve(n);
m_end = m_begin + n;
}
void insert(char* point, char const* first, char const* last)
{
std::size_t p = point - m_begin;
if (point == m_end)
{
resize(size() + last - first);
std::memcpy(m_begin + p, first, last - first);
return;
}
resize(size() + last - first);
std::memmove(m_begin + p + (last - first), m_begin + p, last - first);
std::memcpy(m_begin + p, first, last - first);
}
void erase(char* begin, char* end)
{
TORRENT_ASSERT(end <= m_end);
TORRENT_ASSERT(begin >= m_begin);
TORRENT_ASSERT(begin <= end);
if (end == m_end)
{
resize(begin - m_begin);
return;
}
std::memmove(begin, end, m_end - end);
m_end = begin + (m_end - end);
}
void clear() { m_end = m_begin; }
std::size_t size() const { return m_end - m_begin; }
std::size_t capacity() const { return m_last - m_begin; }
void reserve(std::size_t n)
{
if (n <= capacity()) return;
TORRENT_ASSERT(n > 0);
char* buf = (char*)::operator new(n);
std::size_t s = size();
std::memcpy(buf, m_begin, s);
::operator delete (m_begin);
m_begin = buf;
m_end = buf + s;
m_last = m_begin + n;
}
bool empty() const { return m_begin == m_end; }
char& operator[](std::size_t i) { TORRENT_ASSERT(i >= 0 && i < size()); return m_begin[i]; }
char const& operator[](std::size_t i) const { TORRENT_ASSERT(i >= 0 && i < size()); return m_begin[i]; }
char* begin() { return m_begin; }
char const* begin() const { return m_begin; }
char* end() { return m_end; }
char const* end() const { return m_end; }
void swap(buffer& b)
{
using std::swap;
swap(m_begin, b.m_begin);
swap(m_end, b.m_end);
swap(m_last, b.m_last);
}
private:
char* m_begin; // first
char* m_end; // one passed end of size
char* m_last; // one passed end of allocation
};
}
#endif // LIBTORRENT_BUFFER_HPP
<commit_msg>fixed warning in intel-9.0<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of Rasterbar Software nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef LIBTORRENT_BUFFER_HPP
#define LIBTORRENT_BUFFER_HPP
#include <memory>
#include <cstring>
#include "libtorrent/invariant_check.hpp"
#include "libtorrent/assert.hpp"
namespace libtorrent {
class buffer
{
public:
struct interval
{
interval(char* begin, char* end)
: begin(begin)
, end(end)
{}
char operator[](int index) const
{
TORRENT_ASSERT(begin + index < end);
return begin[index];
}
int left() const { TORRENT_ASSERT(end >= begin); return end - begin; }
char* begin;
char* end;
};
struct const_interval
{
const_interval(char const* begin, char const* end)
: begin(begin)
, end(end)
{}
char operator[](int index) const
{
TORRENT_ASSERT(begin + index < end);
return begin[index];
}
bool operator==(const const_interval& p_interval)
{
return (begin == p_interval.begin
&& end == p_interval.end);
}
int left() const { TORRENT_ASSERT(end >= begin); return end - begin; }
char const* begin;
char const* end;
};
buffer(std::size_t n = 0)
: m_begin(0)
, m_end(0)
, m_last(0)
{
if (n) resize(n);
}
buffer(buffer const& b)
: m_begin(0)
, m_end(0)
, m_last(0)
{
if (b.size() == 0) return;
resize(b.size());
std::memcpy(m_begin, b.begin(), b.size());
}
buffer& operator=(buffer const& b)
{
resize(b.size());
std::memcpy(m_begin, b.begin(), b.size());
return *this;
}
~buffer()
{
::operator delete (m_begin);
}
buffer::interval data() { return interval(m_begin, m_end); }
buffer::const_interval data() const { return const_interval(m_begin, m_end); }
void resize(std::size_t n)
{
reserve(n);
m_end = m_begin + n;
}
void insert(char* point, char const* first, char const* last)
{
std::size_t p = point - m_begin;
if (point == m_end)
{
resize(size() + last - first);
std::memcpy(m_begin + p, first, last - first);
return;
}
resize(size() + last - first);
std::memmove(m_begin + p + (last - first), m_begin + p, last - first);
std::memcpy(m_begin + p, first, last - first);
}
void erase(char* begin, char* end)
{
TORRENT_ASSERT(end <= m_end);
TORRENT_ASSERT(begin >= m_begin);
TORRENT_ASSERT(begin <= end);
if (end == m_end)
{
resize(begin - m_begin);
return;
}
std::memmove(begin, end, m_end - end);
m_end = begin + (m_end - end);
}
void clear() { m_end = m_begin; }
std::size_t size() const { return m_end - m_begin; }
std::size_t capacity() const { return m_last - m_begin; }
void reserve(std::size_t n)
{
if (n <= capacity()) return;
TORRENT_ASSERT(n > 0);
char* buf = (char*)::operator new(n);
std::size_t s = size();
std::memcpy(buf, m_begin, s);
::operator delete (m_begin);
m_begin = buf;
m_end = buf + s;
m_last = m_begin + n;
}
bool empty() const { return m_begin == m_end; }
char& operator[](std::size_t i) { TORRENT_ASSERT(i < size()); return m_begin[i]; }
char const& operator[](std::size_t i) const { TORRENT_ASSERT(i < size()); return m_begin[i]; }
char* begin() { return m_begin; }
char const* begin() const { return m_begin; }
char* end() { return m_end; }
char const* end() const { return m_end; }
void swap(buffer& b)
{
using std::swap;
swap(m_begin, b.m_begin);
swap(m_end, b.m_end);
swap(m_last, b.m_last);
}
private:
char* m_begin; // first
char* m_end; // one passed end of size
char* m_last; // one passed end of allocation
};
}
#endif // LIBTORRENT_BUFFER_HPP
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/shared_impl/audio_impl.h"
#include "base/atomicops.h"
#include "base/logging.h"
using base::subtle::Atomic32;
namespace ppapi {
AudioImpl::AudioImpl()
: playing_(false),
shared_memory_size_(0),
callback_(NULL),
user_data_(NULL) {
}
AudioImpl::~AudioImpl() {
// Closing the socket causes the thread to exit - wait for it.
if (socket_.get())
socket_->Close();
if (audio_thread_.get()) {
audio_thread_->Join();
audio_thread_.reset();
}
}
::ppapi::thunk::PPB_Audio_API* AudioImpl::AsPPB_Audio_API() {
return this;
}
void AudioImpl::SetCallback(PPB_Audio_Callback callback, void* user_data) {
callback_ = callback;
user_data_ = user_data;
}
void AudioImpl::SetStartPlaybackState() {
DCHECK(!playing_);
DCHECK(!audio_thread_.get());
// If the socket doesn't exist, that means that the plugin has started before
// the browser has had a chance to create all the shared memory info and
// notify us. This is a common case. In this case, we just set the playing_
// flag and the playback will automatically start when that data is available
// in SetStreamInfo.
if (callback_ && socket_.get())
StartThread();
playing_ = true;
}
void AudioImpl::SetStopPlaybackState() {
DCHECK(playing_);
if (audio_thread_.get()) {
audio_thread_->Join();
audio_thread_.reset();
}
playing_ = false;
}
void AudioImpl::SetStreamInfo(base::SharedMemoryHandle shared_memory_handle,
size_t shared_memory_size,
base::SyncSocket::Handle socket_handle) {
socket_.reset(new base::SyncSocket(socket_handle));
shared_memory_.reset(new base::SharedMemory(shared_memory_handle, false));
shared_memory_size_ = shared_memory_size;
if (callback_) {
shared_memory_->Map(shared_memory_size_);
// In common case StartPlayback() was called before StreamCreated().
if (playing_)
StartThread();
}
}
void AudioImpl::StartThread() {
DCHECK(callback_);
DCHECK(!audio_thread_.get());
audio_thread_.reset(new base::DelegateSimpleThread(
this, "plugin_audio_thread"));
audio_thread_->Start();
}
// PPB_AudioBuffersState defines the type of an audio buffer state structure
// sent when requesting to fill the audio buffer with data.
typedef struct {
int pending_bytes;
int hardware_delay_bytes;
uint64_t timestamp;
} PPB_AudioBuffersState;
PP_COMPILE_ASSERT_SIZE_IN_BYTES(PPB_AudioBuffersState, 16);
void AudioImpl::Run() {
PPB_AudioBuffersState buffer_state;
for (;;) {
int bytes_received = socket_->Receive(&buffer_state, sizeof(buffer_state));
if (bytes_received == sizeof(int)) {
// Accoding to C++ Standard, address of structure == address of its first
// member, so it is safe to use buffer_state.bytes_received when we
// receive just one int.
COMPILE_ASSERT(
offsetof(PPB_AudioBuffersState, pending_bytes) == 0,
pending_bytes_should_be_first_member_of_PPB_AudioBuffersState);
if (buffer_state.pending_bytes < 0)
break;
callback_(shared_memory_->memory(), shared_memory_size_, user_data_);
} else if (bytes_received == sizeof(buffer_state)) {
if (buffer_state.pending_bytes + buffer_state.hardware_delay_bytes < 0)
break;
// Assert that shared memory is properly aligned, so we can cast pointer
// to the pointer to Atomic32.
DCHECK_EQ(0u, reinterpret_cast<size_t>(shared_memory_->memory()) & 3);
// TODO(enal): Instead of address arithmetics use functions that
// encapsulate internal buffer structure. They should be moved somewhere
// into ppapi, right now they are defined in media/audio/audio_util.h.
uint32 data_size = shared_memory_size_ - sizeof(Atomic32);
callback_(static_cast<char*>(shared_memory_->memory()) + sizeof(Atomic32),
data_size,
user_data_);
base::subtle::Release_Store(
static_cast<volatile Atomic32*>(shared_memory_->memory()),
data_size);
} else {
break;
}
}
}
} // namespace ppapi
<commit_msg>Revert "Prepare ppapi for chrome audio changes..."<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/shared_impl/audio_impl.h"
#include "base/logging.h"
namespace ppapi {
AudioImpl::AudioImpl()
: playing_(false),
shared_memory_size_(0),
callback_(NULL),
user_data_(NULL) {
}
AudioImpl::~AudioImpl() {
// Closing the socket causes the thread to exit - wait for it.
if (socket_.get())
socket_->Close();
if (audio_thread_.get()) {
audio_thread_->Join();
audio_thread_.reset();
}
}
::ppapi::thunk::PPB_Audio_API* AudioImpl::AsPPB_Audio_API() {
return this;
}
void AudioImpl::SetCallback(PPB_Audio_Callback callback, void* user_data) {
callback_ = callback;
user_data_ = user_data;
}
void AudioImpl::SetStartPlaybackState() {
DCHECK(!playing_);
DCHECK(!audio_thread_.get());
// If the socket doesn't exist, that means that the plugin has started before
// the browser has had a chance to create all the shared memory info and
// notify us. This is a common case. In this case, we just set the playing_
// flag and the playback will automatically start when that data is available
// in SetStreamInfo.
if (callback_ && socket_.get())
StartThread();
playing_ = true;
}
void AudioImpl::SetStopPlaybackState() {
DCHECK(playing_);
if (audio_thread_.get()) {
audio_thread_->Join();
audio_thread_.reset();
}
playing_ = false;
}
void AudioImpl::SetStreamInfo(base::SharedMemoryHandle shared_memory_handle,
size_t shared_memory_size,
base::SyncSocket::Handle socket_handle) {
socket_.reset(new base::SyncSocket(socket_handle));
shared_memory_.reset(new base::SharedMemory(shared_memory_handle, false));
shared_memory_size_ = shared_memory_size;
if (callback_) {
shared_memory_->Map(shared_memory_size_);
// In common case StartPlayback() was called before StreamCreated().
if (playing_)
StartThread();
}
}
void AudioImpl::StartThread() {
DCHECK(callback_);
DCHECK(!audio_thread_.get());
audio_thread_.reset(new base::DelegateSimpleThread(
this, "plugin_audio_thread"));
audio_thread_->Start();
}
void AudioImpl::Run() {
int pending_data;
void* buffer = shared_memory_->memory();
while (sizeof(pending_data) ==
socket_->Receive(&pending_data, sizeof(pending_data)) &&
pending_data >= 0) {
callback_(buffer, shared_memory_size_, user_data_);
}
}
} // namespace ppapi
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- *
* OpenSim: forward.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Frank C. Anderson *
* *
* 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
#include <string>
#include <iostream>
#include <OpenSim/version.h>
#include <OpenSim/Common/IO.h>
#include <OpenSim/Common/LoadOpenSimLibrary.h>
#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Simulation/Model/BodySet.h>
#include <OpenSim/Actuators/Schutte1993Muscle_Deprecated.h>
#include <OpenSim/Tools/ForwardTool.h>
#include "SimTKsimbody.h"
#include <ctime> // clock(), clock_t, CLOCKS_PER_SEC
using namespace OpenSim;
using namespace std;
static void PrintUsage(const char *aProgName, ostream &aOStream);
//_____________________________________________________________________________
/**
* Main routine for executing a forward integration and running a set of
* analyses during the forward integration.
*/
int main(int argc,char **argv)
{
//----------------------
// Surrounding try block
//----------------------
try {
//----------------------
//LoadOpenSimLibrary("osimSdfastEngine");
// PARSE COMMAND LINE
int i;
string option = "";
string setupFileName = "";
if(argc<2) {
PrintUsage(argv[0], cout);
return(-1);
}
// Load libraries first
LoadOpenSimLibraries(argc,argv);
for(i=1;i<argc;i++) {
option = argv[i];
// PRINT THE USAGE OPTIONS
if((option=="-help")||(option=="-h")||(option=="-Help")||(option=="-H")||
(option=="-usage")||(option=="-u")||(option=="-Usage")||(option=="-U")) {
PrintUsage(argv[0], cout);
return(0);
// PRINT A DEFAULT SETUP FILE FOR THIS INVESTIGATION
} else if((option=="-PrintSetup")||(option=="-PS")) {
ForwardTool *tool = new ForwardTool();
tool->setName("default");
Object::setSerializeAllDefaults(true);
tool->print("default_Setup_Forward.xml");
Object::setSerializeAllDefaults(false);
cout << "Created file default_Setup_Forward.xml with default setup" << endl;
return(0);
// IDENTIFY SETUP FILE
} else if((option=="-Setup")||(option=="-S")) {
if((i+1)<argc) setupFileName = argv[i+1];
break;
// PRINT PROPERTY INFO
} else if((option=="-PropertyInfo")||(option=="-PI")) {
if((i+1)>=argc) {
Object::PrintPropertyInfo(cout,"");
} else {
char *compoundName = argv[i+1];
if(compoundName[0]=='-') {
Object::PrintPropertyInfo(cout,"");
} else {
Object::PrintPropertyInfo(cout,compoundName);
}
}
return(0);
}
}
// ERROR CHECK
if(setupFileName=="") {
cout<<"\n\nforward.exe: ERROR- A setup file must be specified.\n";
PrintUsage(argv[0], cout);
return(-1);
}
/*
ISSUE: need to explicitly laod the library osimActuators.
*/
LoadOpenSimLibrary("osimActuators");
// CONSTRUCT
cout<<"Constructing tool from setup file "<<setupFileName<<".\n\n";
ForwardTool forward(setupFileName);
//forward.print("check.xml");
// PRINT MODEL INFORMATION
Model& model = forward.getModel();
cout<<"-----------------------------------------------------------------------"<<endl;
cout<<"Loaded library\n";
cout<<"-----------------------------------------------------------------------"<<endl;
cout<<"-----------------------------------------------------------------------"<<endl<<endl;
// start timing
std::clock_t startTime = std::clock();
// RUN
forward.run();
std::cout << "Forward simulation time = " << 1.e3*(std::clock()-startTime)/CLOCKS_PER_SEC << "ms\n" << endl;
//----------------------------
// Catch any thrown exceptions
//----------------------------
} catch(const std::exception& x) {
cout << "Exception in forward: " << x.what() << endl;
return -1;
}
//----------------------------
return(0);
}
//_____________________________________________________________________________
/**
* Print the usage for this application
*/
void PrintUsage(const char *aProgName, ostream &aOStream)
{
string progName=IO::GetFileNameFromURI(aProgName);
aOStream<<"\n\n"<<progName<<":\n"<<GetVersionAndDate()<<"\n\n";
aOStream<<"Option Argument Action / Notes\n";
aOStream<<"------ -------- --------------\n";
aOStream<<"-Help, -H Print the command-line options for forward.exe.\n";
aOStream<<"-PrintSetup, -PS Print a default setup file for forward.exe (default_forward.xml).\n";
aOStream<<"-Setup, -S SetupFileName Specify the name of the XML setup file to use for this forward tool.\n";
aOStream<<"-PropertyInfo, -PI Print help information for properties in setup files.\n";
//aOStream<<"\nThe input to the -PropertyInfo option is the name of the class to which a property\n";
//aOStream<<"belongs, followed by a '.', followed by the name of the property. If a class name\n";
//aOStream<<"is not specified, a list of all registered classes is printed. If a class name is\n";
//aOStream<<"specified, but a property is not, a list of all properties in that class is printed.\n";
}
<commit_msg>Remove misleading debugging line from froward<commit_after>/* -------------------------------------------------------------------------- *
* OpenSim: forward.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Frank C. Anderson *
* *
* 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
#include <string>
#include <iostream>
#include <OpenSim/version.h>
#include <OpenSim/Common/IO.h>
#include <OpenSim/Common/LoadOpenSimLibrary.h>
#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Simulation/Model/BodySet.h>
#include <OpenSim/Actuators/Schutte1993Muscle_Deprecated.h>
#include <OpenSim/Tools/ForwardTool.h>
#include "SimTKsimbody.h"
#include <ctime> // clock(), clock_t, CLOCKS_PER_SEC
using namespace OpenSim;
using namespace std;
static void PrintUsage(const char *aProgName, ostream &aOStream);
//_____________________________________________________________________________
/**
* Main routine for executing a forward integration and running a set of
* analyses during the forward integration.
*/
int main(int argc,char **argv)
{
//----------------------
// Surrounding try block
//----------------------
try {
//----------------------
//LoadOpenSimLibrary("osimSdfastEngine");
// PARSE COMMAND LINE
int i;
string option = "";
string setupFileName = "";
if(argc<2) {
PrintUsage(argv[0], cout);
return(-1);
}
// Load libraries first
LoadOpenSimLibraries(argc,argv);
for(i=1;i<argc;i++) {
option = argv[i];
// PRINT THE USAGE OPTIONS
if((option=="-help")||(option=="-h")||(option=="-Help")||(option=="-H")||
(option=="-usage")||(option=="-u")||(option=="-Usage")||(option=="-U")) {
PrintUsage(argv[0], cout);
return(0);
// PRINT A DEFAULT SETUP FILE FOR THIS INVESTIGATION
} else if((option=="-PrintSetup")||(option=="-PS")) {
ForwardTool *tool = new ForwardTool();
tool->setName("default");
Object::setSerializeAllDefaults(true);
tool->print("default_Setup_Forward.xml");
Object::setSerializeAllDefaults(false);
cout << "Created file default_Setup_Forward.xml with default setup" << endl;
return(0);
// IDENTIFY SETUP FILE
} else if((option=="-Setup")||(option=="-S")) {
if((i+1)<argc) setupFileName = argv[i+1];
break;
// PRINT PROPERTY INFO
} else if((option=="-PropertyInfo")||(option=="-PI")) {
if((i+1)>=argc) {
Object::PrintPropertyInfo(cout,"");
} else {
char *compoundName = argv[i+1];
if(compoundName[0]=='-') {
Object::PrintPropertyInfo(cout,"");
} else {
Object::PrintPropertyInfo(cout,compoundName);
}
}
return(0);
}
}
// ERROR CHECK
if(setupFileName=="") {
cout<<"\n\nforward.exe: ERROR- A setup file must be specified.\n";
PrintUsage(argv[0], cout);
return(-1);
}
/*
ISSUE: need to explicitly laod the library osimActuators.
*/
LoadOpenSimLibrary("osimActuators");
// CONSTRUCT
cout<<"Constructing tool from setup file "<<setupFileName<<".\n\n";
ForwardTool forward(setupFileName);
// PRINT MODEL INFORMATION
Model& model = forward.getModel();
cout<<"-----------------------------------------------------------------------"<<endl;
// start timing
std::clock_t startTime = std::clock();
// RUN
forward.run();
std::cout << "Forward simulation time = " << 1.e3*(std::clock()-startTime)/CLOCKS_PER_SEC << "ms\n" << endl;
//----------------------------
// Catch any thrown exceptions
//----------------------------
} catch(const std::exception& x) {
cout << "Exception in forward: " << x.what() << endl;
return -1;
}
//----------------------------
return(0);
}
//_____________________________________________________________________________
/**
* Print the usage for this application
*/
void PrintUsage(const char *aProgName, ostream &aOStream)
{
string progName=IO::GetFileNameFromURI(aProgName);
aOStream<<"\n\n"<<progName<<":\n"<<GetVersionAndDate()<<"\n\n";
aOStream<<"Option Argument Action / Notes\n";
aOStream<<"------ -------- --------------\n";
aOStream<<"-Help, -H Print the command-line options for forward.exe.\n";
aOStream<<"-PrintSetup, -PS Print a default setup file for forward.exe (default_forward.xml).\n";
aOStream<<"-Setup, -S SetupFileName Specify the name of the XML setup file to use for this forward tool.\n";
aOStream<<"-PropertyInfo, -PI Print help information for properties in setup files.\n";
//aOStream<<"\nThe input to the -PropertyInfo option is the name of the class to which a property\n";
//aOStream<<"belongs, followed by a '.', followed by the name of the property. If a class name\n";
//aOStream<<"is not specified, a list of all registered classes is printed. If a class name is\n";
//aOStream<<"specified, but a property is not, a list of all properties in that class is printed.\n";
}
<|endoftext|> |
<commit_before>//
// Copyright (C) 2011-15 DyND Developers
// BSD 2-Clause License, see LICENSE.txt
//
#pragma once
#include <Python.h>
#include <dynd/type_registry.hpp>
#include "pyobject_type.hpp"
using namespace dynd;
// Unpack and convert a single element to a PyObject.
template <typename T>
inline std::enable_if_t<std::is_signed<T>::value && std::numeric_limits<T>::max() <= INT64_MAX, PyObject *>
unpack_single(const char *data)
{
return PyLong_FromLongLong(*reinterpret_cast<const T *>(data));
}
template <typename T>
inline std::enable_if_t<std::is_unsigned<T>::value && std::numeric_limits<T>::max() <= UINT64_MAX, PyObject *>
unpack_single(const char *data)
{
return PyLong_FromUnsignedLongLong(*reinterpret_cast<const T *>(data));
}
template <typename T>
inline std::enable_if_t<std::is_same<T, bool1>::value, PyObject *>
unpack_single(const char *data)
{
return PyBool_FromLong(*reinterpret_cast<const T *>(data));
}
template <typename T>
inline std::enable_if_t<std::is_same<T, float64>::value, PyObject *>
unpack_single(const char *data)
{
return PyFloat_FromDouble(*reinterpret_cast<const T *>(data));
}
template <typename T>
inline std::enable_if_t<std::is_same<T, complex128>::value, PyObject *>
unpack_single(const char *data)
{
complex128 c = *reinterpret_cast<const T *>(data);
return PyComplex_FromDoubles(c.real(), c.imag());
}
template <typename T>
inline std::enable_if_t<std::is_same<T, std::string>::value, PyObject *>
unpack_single(const char *data)
{
const std::string &s = *reinterpret_cast<const T *>(data);
return PyUnicode_FromString(s.data());
}
template <typename T>
inline std::enable_if_t<std::is_same<T, ndt::type>::value, PyObject *>
unpack_single(const char *data)
{
return pydynd::type_from_cpp(*reinterpret_cast<const T *>(data));
}
// Convert a single element to a PyObject.
template <typename T>
inline std::enable_if_t<std::is_signed<T>::value && std::numeric_limits<T>::max() <= INT64_MAX, PyObject *>
convert_single(T value)
{
return PyLong_FromLongLong(value);
}
template <typename T>
inline std::enable_if_t<std::is_unsigned<T>::value && std::numeric_limits<T>::max() <= UINT64_MAX, PyObject *>
convert_single(T value)
{
return PyLong_FromUnsignedLongLong(value);
}
template <typename T>
inline std::enable_if_t<std::is_same<T, bool1>::value, PyObject *>
convert_single(T value)
{
return PyBool_FromLong(value);
}
template <typename T>
inline std::enable_if_t<std::is_same<T, float64>::value, PyObject *>
convert_single(T value)
{
return PyFloat_FromDouble(value);
}
template <typename T>
inline std::enable_if_t<std::is_same<T, complex128>::value, PyObject *>
convert_single(T value)
{
return PyComplex_FromDoubles(value.real(), value.imag());
}
template <typename T>
inline std::enable_if_t<std::is_same<T, std::string>::value, PyObject *>
convert_single(const T &value)
{
return PyUnicode_FromString(value.data());
}
template <typename T>
inline std::enable_if_t<std::is_same<T, ndt::type>::value, PyObject *>
convert_single(const T &value)
{
return pydynd::type_from_cpp(value);
}
template <typename T>
PyObject *unpack_vector(const char *data)
{
auto &vec = *reinterpret_cast<const std::vector<T> *>(data);
PyObject *lst, *item;
lst = PyList_New(vec.size());
if (lst == NULL) {
return NULL;
}
for (size_t i = 0; i < vec.size(); ++i) {
item = convert_single<T>(vec[i]);
if (item == NULL) {
Py_DECREF(lst);
return NULL;
}
PyList_SET_ITEM(lst, i, item);
}
return lst;
}
template <typename T>
inline PyObject *unpack(bool is_vector, const char *data)
{
if (is_vector) {
return unpack_vector<T>(data);
}
else {
return unpack_single<T>(data);
}
}
PyObject *from_type_property(const std::pair<ndt::type, const char *> &pair)
{
type_id_t id = pair.first.get_id();
bool is_vector = false;
if (id == fixed_dim_id) {
id = pair.first.get_dtype().get_id();
is_vector = true;
}
switch (id) {
case bool_id:
return unpack<bool1>(is_vector, pair.second);
case int8_id:
return unpack<int8>(is_vector, pair.second);
case int16_id:
return unpack<int16>(is_vector, pair.second);
case int32_id:
return unpack<int32>(is_vector, pair.second);
case int64_id:
return unpack<int64>(is_vector, pair.second);
case uint8_id:
return unpack<uint8>(is_vector, pair.second);
case uint16_id:
return unpack<uint16>(is_vector, pair.second);
case uint32_id:
return unpack<uint32>(is_vector, pair.second);
case uint64_id:
return unpack<uint64>(is_vector, pair.second);
case float64_id:
return unpack<float64>(is_vector, pair.second);
case complex_float64_id:
return unpack<complex128>(is_vector, pair.second);
case type_id:
return unpack<ndt::type>(is_vector, pair.second);
case string_id:
return unpack<std::string>(is_vector, pair.second);
default:
throw std::runtime_error("invalid type property");
}
}
<commit_msg>Add include.<commit_after>//
// Copyright (C) 2011-15 DyND Developers
// BSD 2-Clause License, see LICENSE.txt
//
#pragma once
#include <Python.h>
#include <dynd/type_registry.hpp>
#include <type_traits>
#include "pyobject_type.hpp"
using namespace dynd;
// Unpack and convert a single element to a PyObject.
template <typename T>
inline std::enable_if_t<std::is_signed<T>::value && std::numeric_limits<T>::max() <= INT64_MAX, PyObject *>
unpack_single(const char *data)
{
return PyLong_FromLongLong(*reinterpret_cast<const T *>(data));
}
template <typename T>
inline std::enable_if_t<std::is_unsigned<T>::value && std::numeric_limits<T>::max() <= UINT64_MAX, PyObject *>
unpack_single(const char *data)
{
return PyLong_FromUnsignedLongLong(*reinterpret_cast<const T *>(data));
}
template <typename T>
inline std::enable_if_t<std::is_same<T, bool1>::value, PyObject *>
unpack_single(const char *data)
{
return PyBool_FromLong(*reinterpret_cast<const T *>(data));
}
template <typename T>
inline std::enable_if_t<std::is_same<T, float64>::value, PyObject *>
unpack_single(const char *data)
{
return PyFloat_FromDouble(*reinterpret_cast<const T *>(data));
}
template <typename T>
inline std::enable_if_t<std::is_same<T, complex128>::value, PyObject *>
unpack_single(const char *data)
{
complex128 c = *reinterpret_cast<const T *>(data);
return PyComplex_FromDoubles(c.real(), c.imag());
}
template <typename T>
inline std::enable_if_t<std::is_same<T, std::string>::value, PyObject *>
unpack_single(const char *data)
{
const std::string &s = *reinterpret_cast<const T *>(data);
return PyUnicode_FromString(s.data());
}
template <typename T>
inline std::enable_if_t<std::is_same<T, ndt::type>::value, PyObject *>
unpack_single(const char *data)
{
return pydynd::type_from_cpp(*reinterpret_cast<const T *>(data));
}
// Convert a single element to a PyObject.
template <typename T>
inline std::enable_if_t<std::is_signed<T>::value && std::numeric_limits<T>::max() <= INT64_MAX, PyObject *>
convert_single(T value)
{
return PyLong_FromLongLong(value);
}
template <typename T>
inline std::enable_if_t<std::is_unsigned<T>::value && std::numeric_limits<T>::max() <= UINT64_MAX, PyObject *>
convert_single(T value)
{
return PyLong_FromUnsignedLongLong(value);
}
template <typename T>
inline std::enable_if_t<std::is_same<T, bool1>::value, PyObject *>
convert_single(T value)
{
return PyBool_FromLong(value);
}
template <typename T>
inline std::enable_if_t<std::is_same<T, float64>::value, PyObject *>
convert_single(T value)
{
return PyFloat_FromDouble(value);
}
template <typename T>
inline std::enable_if_t<std::is_same<T, complex128>::value, PyObject *>
convert_single(T value)
{
return PyComplex_FromDoubles(value.real(), value.imag());
}
template <typename T>
inline std::enable_if_t<std::is_same<T, std::string>::value, PyObject *>
convert_single(const T &value)
{
return PyUnicode_FromString(value.data());
}
template <typename T>
inline std::enable_if_t<std::is_same<T, ndt::type>::value, PyObject *>
convert_single(const T &value)
{
return pydynd::type_from_cpp(value);
}
template <typename T>
PyObject *unpack_vector(const char *data)
{
auto &vec = *reinterpret_cast<const std::vector<T> *>(data);
PyObject *lst, *item;
lst = PyList_New(vec.size());
if (lst == NULL) {
return NULL;
}
for (size_t i = 0; i < vec.size(); ++i) {
item = convert_single<T>(vec[i]);
if (item == NULL) {
Py_DECREF(lst);
return NULL;
}
PyList_SET_ITEM(lst, i, item);
}
return lst;
}
template <typename T>
inline PyObject *unpack(bool is_vector, const char *data)
{
if (is_vector) {
return unpack_vector<T>(data);
}
else {
return unpack_single<T>(data);
}
}
PyObject *from_type_property(const std::pair<ndt::type, const char *> &pair)
{
type_id_t id = pair.first.get_id();
bool is_vector = false;
if (id == fixed_dim_id) {
id = pair.first.get_dtype().get_id();
is_vector = true;
}
switch (id) {
case bool_id:
return unpack<bool1>(is_vector, pair.second);
case int8_id:
return unpack<int8>(is_vector, pair.second);
case int16_id:
return unpack<int16>(is_vector, pair.second);
case int32_id:
return unpack<int32>(is_vector, pair.second);
case int64_id:
return unpack<int64>(is_vector, pair.second);
case uint8_id:
return unpack<uint8>(is_vector, pair.second);
case uint16_id:
return unpack<uint16>(is_vector, pair.second);
case uint32_id:
return unpack<uint32>(is_vector, pair.second);
case uint64_id:
return unpack<uint64>(is_vector, pair.second);
case float64_id:
return unpack<float64>(is_vector, pair.second);
case complex_float64_id:
return unpack<complex128>(is_vector, pair.second);
case type_id:
return unpack<ndt::type>(is_vector, pair.second);
case string_id:
return unpack<std::string>(is_vector, pair.second);
default:
throw std::runtime_error("invalid type property");
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2005, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf
#if defined TORRENT_DEBUG_BUFFERS && !defined TORRENT_DISABLE_POOL_ALLOCATOR
#error TORRENT_DEBUG_BUFFERS only works if you also disable pool allocators
#endif
#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif
#ifndef PRId64
#ifdef _MSC_VER
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif
// ======= GCC =========
#if defined __GNUC__
# if __GNUC__ >= 3
# define TORRENT_DEPRECATED __attribute__ ((deprecated))
# endif
// GCC pre 4.0 did not have support for the visibility attribute
# if __GNUC__ >= 4
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __attribute__ ((visibility("default")))
# endif
# endif
// ======= SUNPRO =========
#elif defined __SUNPRO_CC
# if __SUNPRO_CC >= 0x550
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __global
# endif
# endif
// SunPRO seems to have an overly-strict
// definition of POD types and doesn't
// seem to allow boost::array in unions
#define TORRENT_BROKEN_UNIONS 1
// ======= MSVC =========
#elif defined BOOST_MSVC
#pragma warning(disable: 4258)
#pragma warning(disable: 4251)
// class X needs to have dll-interface to be used by clients of class Y
#pragma warning(disable:4251)
// '_vsnprintf': This function or variable may be unsafe
#pragma warning(disable:4996)
// 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup
#pragma warning(disable: 4996)
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# endif
#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)
#endif
// ======= PLATFORMS =========
// set up defines for target environments
// ==== AMIGA ===
#if defined __AMIGA__ || defined __amigaos__ || defined __AROS__
#define TORRENT_AMIGA
#define TORRENT_USE_MLOCK 0
#define TORRENT_USE_WRITEV 0
#define TORRENT_USE_READV 0
#define TORRENT_USE_IPV6 0
#define TORRENT_USE_BOOST_THREAD 0
#define TORRENT_USE_IOSTREAM 0
// set this to 1 to disable all floating point operations
// (disables some float-dependent APIs)
#define TORRENT_NO_FPU 1
#define TORRENT_USE_I2P 0
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#endif
// ==== Darwin/BSD ===
#elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
|| defined __FreeBSD_kernel__
#define TORRENT_BSD
// we don't need iconv on mac, because
// the locale is always utf-8
#if defined __APPLE__
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 0
#endif
#endif
#define TORRENT_HAS_FALLOCATE 0
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_SYSCTL 1
#define TORRENT_USE_IFCONF 1
// ==== LINUX ===
#elif defined __linux__
#define TORRENT_LINUX
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_NETLINK 1
#define TORRENT_USE_IFCONF 1
#define TORRENT_HAS_SALEN 0
// ==== MINGW ===
#elif defined __MINGW32__
#define TORRENT_MINGW
#define TORRENT_WINDOWS
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 1
#endif
#define TORRENT_ICONV_ARG (const char**)
#define TORRENT_USE_RLIMIT 0
#define TORRENT_USE_NETLINK 0
#define TORRENT_USE_GETADAPTERSADDRESSES 1
#define TORRENT_HAS_SALEN 0
#define TORRENT_USE_GETIPFORWARDTABLE 1
// ==== WINDOWS ===
#elif defined WIN32
#define TORRENT_WINDOWS
#ifndef TORRENT_USE_GETIPFORWARDTABLE
#define TORRENT_USE_GETIPFORWARDTABLE 1
#endif
#define TORRENT_USE_GETADAPTERSADDRESSES 1
#define TORRENT_HAS_SALEN 0
// windows has its own functions to convert
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 1
#endif
#define TORRENT_USE_RLIMIT 0
#define TORRENT_HAS_FALLOCATE 0
// ==== SOLARIS ===
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#define TORRENT_COMPLETE_TYPES_REQUIRED 1
#define TORRENT_USE_IFCONF 1
// ==== BEOS ===
#elif defined __BEOS__ || defined __HAIKU__
#define TORRENT_BEOS
#include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH
#define TORRENT_HAS_FALLOCATE 0
#define TORRENT_USE_MLOCK 0
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#endif
#if __GNUCC__ == 2
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# endif
#endif
// ==== GNU/Hurd ===
#elif defined __GNU__
#define TORRENT_HURD
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_IFCONF 1
#else
#warning unknown OS, assuming BSD
#define TORRENT_BSD
#endif
// on windows, NAME_MAX refers to Unicode characters
// on linux it refers to bytes (utf-8 encoded)
// TODO: Make this count Unicode characters instead of bytes on windows
// windows
#if defined FILENAME_MAX
#define TORRENT_MAX_PATH FILENAME_MAX
// beos
#elif defined B_PATH_NAME_LENGTH
#define TORRENT_MAX_PATH B_PATH_NAME_LENGTH
// solaris
#elif defined MAXPATH
#define TORRENT_MAX_PATH MAXPATH
// posix
#elif defined NAME_MAX
#define TORRENT_MAX_PATH NAME_MAX
// none of the above
#else
// this is the maximum number of characters in a
// path element / filename on windows
#define TORRENT_MAX_PATH 255
#warning unknown platform, assuming the longest path is 255
#endif
#if defined TORRENT_WINDOWS && !defined TORRENT_MINGW
#include <stdarg.h>
inline int snprintf(char* buf, int len, char const* fmt, ...)
{
va_list lp;
va_start(lp, fmt);
int ret = _vsnprintf(buf, len, fmt, lp);
va_end(lp);
if (ret < 0) { buf[len-1] = 0; ret = len-1; }
return ret;
}
#define strtoll _strtoi64
#else
#include <limits.h>
#endif
#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \
&& !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM
#define TORRENT_UPNP_LOGGING
#endif
#ifndef TORRENT_ICONV_ARG
#define TORRENT_ICONV_ARG (char**)
#endif
// libiconv presence, not implemented yet
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 1
#endif
#ifndef TORRENT_HAS_SALEN
#define TORRENT_HAS_SALEN 1
#endif
#ifndef TORRENT_USE_GETADAPTERSADDRESSES
#define TORRENT_USE_GETADAPTERSADDRESSES 0
#endif
#ifndef TORRENT_USE_NETLINK
#define TORRENT_USE_NETLINK 0
#endif
#ifndef TORRENT_USE_SYSCTL
#define TORRENT_USE_SYSCTL 0
#endif
#ifndef TORRENT_USE_GETIPFORWARDTABLE
#define TORRENT_USE_GETIPFORWARDTABLE 0
#endif
#ifndef TORRENT_USE_LOCALE
#define TORRENT_USE_LOCALE 0
#endif
#ifndef TORRENT_BROKEN_UNIONS
#define TORRENT_BROKEN_UNIONS 0
#endif
#if defined UNICODE && !defined BOOST_NO_STD_WSTRING
#define TORRENT_USE_WSTRING 1
#else
#define TORRENT_USE_WSTRING 0
#endif // UNICODE
#ifndef TORRENT_HAS_FALLOCATE
#define TORRENT_HAS_FALLOCATE 1
#endif
#ifndef TORRENT_EXPORT
# define TORRENT_EXPORT
#endif
#ifndef TORRENT_DEPRECATED_PREFIX
#define TORRENT_DEPRECATED_PREFIX
#endif
#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif
#ifndef TORRENT_COMPLETE_TYPES_REQUIRED
#define TORRENT_COMPLETE_TYPES_REQUIRED 0
#endif
#ifndef TORRENT_USE_RLIMIT
#define TORRENT_USE_RLIMIT 1
#endif
#ifndef TORRENT_USE_IFADDRS
#define TORRENT_USE_IFADDRS 0
#endif
#ifndef TORRENT_USE_IPV6
#define TORRENT_USE_IPV6 1
#endif
#ifndef TORRENT_USE_MLOCK
#define TORRENT_USE_MLOCK 1
#endif
#ifndef TORRENT_USE_WRITEV
#define TORRENT_USE_WRITEV 1
#endif
#ifndef TORRENT_USE_READV
#define TORRENT_USE_READV 1
#endif
#ifndef TORRENT_NO_FPU
#define TORRENT_NO_FPU 0
#endif
#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM
#define TORRENT_USE_IOSTREAM 1
#else
#define TORRENT_USE_IOSTREAM 0
#endif
#ifndef TORRENT_USE_I2P
#define TORRENT_USE_I2P 1
#endif
#ifndef TORRENT_HAS_STRDUP
#define TORRENT_HAS_STRDUP 1
#endif
#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif
#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif
#if defined _MSC_VER && _MSC_VER <= 1200
#define for if (false) {} else for
#endif
#if TORRENT_BROKEN_UNIONS
#define TORRENT_UNION struct
#else
#define TORRENT_UNION union
#endif
// determine what timer implementation we can use
// if one is already defined, don't pick one
// autmatically. This lets the user control this
// from the Jamfile
#if !defined TORRENT_USE_ABSOLUTE_TIME \
&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \
&& !defined TORRENT_USE_CLOCK_GETTIME \
&& !defined TORRENT_USE_BOOST_DATE_TIME \
&& !defined TORRENT_USE_ECLOCK \
&& !defined TORRENT_USE_SYSTEM_TIME
#if defined __APPLE__ && defined __MACH__
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32) || defined TORRENT_MINGW
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#elif defined(TORRENT_AMIGA)
#define TORRENT_USE_ECLOCK 1
#elif defined(TORRENT_BEOS)
#define TORRENT_USE_SYSTEM_TIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif
#endif
#if !TORRENT_HAS_STRDUP
inline char* strdup(char const* str)
{
if (str == 0) return 0;
char* tmp = (char*)malloc(strlen(str) + 1);
if (tmp == 0) return 0;
strcpy(tmp, str);
return tmp;
}
#endif
// for non-exception builds
#ifdef BOOST_NO_EXCEPTIONS
#define TORRENT_TRY if (true)
#define TORRENT_CATCH(x) else if (false)
#define TORRENT_DECLARE_DUMMY(x, y) x y
#else
#define TORRENT_TRY try
#define TORRENT_CATCH(x) catch(x)
#define TORRENT_DECLARE_DUMMY(x, y)
#endif // BOOST_NO_EXCEPTIONS
#endif // TORRENT_CONFIG_HPP_INCLUDED
<commit_msg>fix PRId64 macro for mingw<commit_after>/*
Copyright (c) 2005, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf
#if defined TORRENT_DEBUG_BUFFERS && !defined TORRENT_DISABLE_POOL_ALLOCATOR
#error TORRENT_DEBUG_BUFFERS only works if you also disable pool allocators
#endif
#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif
#ifndef PRId64
// MinGW uses microsofts runtime
#if defined _MSC_VER || defined __MINGW32__
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif
// ======= GCC =========
#if defined __GNUC__
# if __GNUC__ >= 3
# define TORRENT_DEPRECATED __attribute__ ((deprecated))
# endif
// GCC pre 4.0 did not have support for the visibility attribute
# if __GNUC__ >= 4
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __attribute__ ((visibility("default")))
# endif
# endif
// ======= SUNPRO =========
#elif defined __SUNPRO_CC
# if __SUNPRO_CC >= 0x550
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __global
# endif
# endif
// SunPRO seems to have an overly-strict
// definition of POD types and doesn't
// seem to allow boost::array in unions
#define TORRENT_BROKEN_UNIONS 1
// ======= MSVC =========
#elif defined BOOST_MSVC
#pragma warning(disable: 4258)
#pragma warning(disable: 4251)
// class X needs to have dll-interface to be used by clients of class Y
#pragma warning(disable:4251)
// '_vsnprintf': This function or variable may be unsafe
#pragma warning(disable:4996)
// 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup
#pragma warning(disable: 4996)
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# endif
#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)
#endif
// ======= PLATFORMS =========
// set up defines for target environments
// ==== AMIGA ===
#if defined __AMIGA__ || defined __amigaos__ || defined __AROS__
#define TORRENT_AMIGA
#define TORRENT_USE_MLOCK 0
#define TORRENT_USE_WRITEV 0
#define TORRENT_USE_READV 0
#define TORRENT_USE_IPV6 0
#define TORRENT_USE_BOOST_THREAD 0
#define TORRENT_USE_IOSTREAM 0
// set this to 1 to disable all floating point operations
// (disables some float-dependent APIs)
#define TORRENT_NO_FPU 1
#define TORRENT_USE_I2P 0
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#endif
// ==== Darwin/BSD ===
#elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
|| defined __FreeBSD_kernel__
#define TORRENT_BSD
// we don't need iconv on mac, because
// the locale is always utf-8
#if defined __APPLE__
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 0
#endif
#endif
#define TORRENT_HAS_FALLOCATE 0
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_SYSCTL 1
#define TORRENT_USE_IFCONF 1
// ==== LINUX ===
#elif defined __linux__
#define TORRENT_LINUX
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_NETLINK 1
#define TORRENT_USE_IFCONF 1
#define TORRENT_HAS_SALEN 0
// ==== MINGW ===
#elif defined __MINGW32__
#define TORRENT_MINGW
#define TORRENT_WINDOWS
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 1
#endif
#define TORRENT_ICONV_ARG (const char**)
#define TORRENT_USE_RLIMIT 0
#define TORRENT_USE_NETLINK 0
#define TORRENT_USE_GETADAPTERSADDRESSES 1
#define TORRENT_HAS_SALEN 0
#define TORRENT_USE_GETIPFORWARDTABLE 1
// ==== WINDOWS ===
#elif defined WIN32
#define TORRENT_WINDOWS
#ifndef TORRENT_USE_GETIPFORWARDTABLE
#define TORRENT_USE_GETIPFORWARDTABLE 1
#endif
#define TORRENT_USE_GETADAPTERSADDRESSES 1
#define TORRENT_HAS_SALEN 0
// windows has its own functions to convert
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 1
#endif
#define TORRENT_USE_RLIMIT 0
#define TORRENT_HAS_FALLOCATE 0
// ==== SOLARIS ===
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#define TORRENT_COMPLETE_TYPES_REQUIRED 1
#define TORRENT_USE_IFCONF 1
// ==== BEOS ===
#elif defined __BEOS__ || defined __HAIKU__
#define TORRENT_BEOS
#include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH
#define TORRENT_HAS_FALLOCATE 0
#define TORRENT_USE_MLOCK 0
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#endif
#if __GNUCC__ == 2
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# endif
#endif
// ==== GNU/Hurd ===
#elif defined __GNU__
#define TORRENT_HURD
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_IFCONF 1
#else
#warning unknown OS, assuming BSD
#define TORRENT_BSD
#endif
// on windows, NAME_MAX refers to Unicode characters
// on linux it refers to bytes (utf-8 encoded)
// TODO: Make this count Unicode characters instead of bytes on windows
// windows
#if defined FILENAME_MAX
#define TORRENT_MAX_PATH FILENAME_MAX
// beos
#elif defined B_PATH_NAME_LENGTH
#define TORRENT_MAX_PATH B_PATH_NAME_LENGTH
// solaris
#elif defined MAXPATH
#define TORRENT_MAX_PATH MAXPATH
// posix
#elif defined NAME_MAX
#define TORRENT_MAX_PATH NAME_MAX
// none of the above
#else
// this is the maximum number of characters in a
// path element / filename on windows
#define TORRENT_MAX_PATH 255
#warning unknown platform, assuming the longest path is 255
#endif
#if defined TORRENT_WINDOWS && !defined TORRENT_MINGW
#include <stdarg.h>
inline int snprintf(char* buf, int len, char const* fmt, ...)
{
va_list lp;
va_start(lp, fmt);
int ret = _vsnprintf(buf, len, fmt, lp);
va_end(lp);
if (ret < 0) { buf[len-1] = 0; ret = len-1; }
return ret;
}
#define strtoll _strtoi64
#else
#include <limits.h>
#endif
#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \
&& !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM
#define TORRENT_UPNP_LOGGING
#endif
#ifndef TORRENT_ICONV_ARG
#define TORRENT_ICONV_ARG (char**)
#endif
// libiconv presence, not implemented yet
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 1
#endif
#ifndef TORRENT_HAS_SALEN
#define TORRENT_HAS_SALEN 1
#endif
#ifndef TORRENT_USE_GETADAPTERSADDRESSES
#define TORRENT_USE_GETADAPTERSADDRESSES 0
#endif
#ifndef TORRENT_USE_NETLINK
#define TORRENT_USE_NETLINK 0
#endif
#ifndef TORRENT_USE_SYSCTL
#define TORRENT_USE_SYSCTL 0
#endif
#ifndef TORRENT_USE_GETIPFORWARDTABLE
#define TORRENT_USE_GETIPFORWARDTABLE 0
#endif
#ifndef TORRENT_USE_LOCALE
#define TORRENT_USE_LOCALE 0
#endif
#ifndef TORRENT_BROKEN_UNIONS
#define TORRENT_BROKEN_UNIONS 0
#endif
#if defined UNICODE && !defined BOOST_NO_STD_WSTRING
#define TORRENT_USE_WSTRING 1
#else
#define TORRENT_USE_WSTRING 0
#endif // UNICODE
#ifndef TORRENT_HAS_FALLOCATE
#define TORRENT_HAS_FALLOCATE 1
#endif
#ifndef TORRENT_EXPORT
# define TORRENT_EXPORT
#endif
#ifndef TORRENT_DEPRECATED_PREFIX
#define TORRENT_DEPRECATED_PREFIX
#endif
#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif
#ifndef TORRENT_COMPLETE_TYPES_REQUIRED
#define TORRENT_COMPLETE_TYPES_REQUIRED 0
#endif
#ifndef TORRENT_USE_RLIMIT
#define TORRENT_USE_RLIMIT 1
#endif
#ifndef TORRENT_USE_IFADDRS
#define TORRENT_USE_IFADDRS 0
#endif
#ifndef TORRENT_USE_IPV6
#define TORRENT_USE_IPV6 1
#endif
#ifndef TORRENT_USE_MLOCK
#define TORRENT_USE_MLOCK 1
#endif
#ifndef TORRENT_USE_WRITEV
#define TORRENT_USE_WRITEV 1
#endif
#ifndef TORRENT_USE_READV
#define TORRENT_USE_READV 1
#endif
#ifndef TORRENT_NO_FPU
#define TORRENT_NO_FPU 0
#endif
#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM
#define TORRENT_USE_IOSTREAM 1
#else
#define TORRENT_USE_IOSTREAM 0
#endif
#ifndef TORRENT_USE_I2P
#define TORRENT_USE_I2P 1
#endif
#ifndef TORRENT_HAS_STRDUP
#define TORRENT_HAS_STRDUP 1
#endif
#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif
#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif
#if defined _MSC_VER && _MSC_VER <= 1200
#define for if (false) {} else for
#endif
#if TORRENT_BROKEN_UNIONS
#define TORRENT_UNION struct
#else
#define TORRENT_UNION union
#endif
// determine what timer implementation we can use
// if one is already defined, don't pick one
// autmatically. This lets the user control this
// from the Jamfile
#if !defined TORRENT_USE_ABSOLUTE_TIME \
&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \
&& !defined TORRENT_USE_CLOCK_GETTIME \
&& !defined TORRENT_USE_BOOST_DATE_TIME \
&& !defined TORRENT_USE_ECLOCK \
&& !defined TORRENT_USE_SYSTEM_TIME
#if defined __APPLE__ && defined __MACH__
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32) || defined TORRENT_MINGW
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#elif defined(TORRENT_AMIGA)
#define TORRENT_USE_ECLOCK 1
#elif defined(TORRENT_BEOS)
#define TORRENT_USE_SYSTEM_TIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif
#endif
#if !TORRENT_HAS_STRDUP
inline char* strdup(char const* str)
{
if (str == 0) return 0;
char* tmp = (char*)malloc(strlen(str) + 1);
if (tmp == 0) return 0;
strcpy(tmp, str);
return tmp;
}
#endif
// for non-exception builds
#ifdef BOOST_NO_EXCEPTIONS
#define TORRENT_TRY if (true)
#define TORRENT_CATCH(x) else if (false)
#define TORRENT_DECLARE_DUMMY(x, y) x y
#else
#define TORRENT_TRY try
#define TORRENT_CATCH(x) catch(x)
#define TORRENT_DECLARE_DUMMY(x, y)
#endif // BOOST_NO_EXCEPTIONS
#endif // TORRENT_CONFIG_HPP_INCLUDED
<|endoftext|> |
<commit_before>/*
Copyright (c) 2005, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf
#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif
#ifndef PRId64
#ifdef _WIN32
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif
// ======= GCC =========
#if defined __GNUC__
# if __GNUC__ >= 3
# define TORRENT_DEPRECATED __attribute__ ((deprecated))
# endif
// GCC pre 4.0 did not have support for the visibility attribute
# if __GNUC__ >= 4
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __attribute__ ((visibility("default")))
# endif
# endif
// ======= SUNPRO =========
#elif defined __SUNPRO_CC
# if __SUNPRO_CC >= 0x550
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __global
# endif
# endif
// ======= MSVC =========
#elif defined BOOST_MSVC
#pragma warning(disable: 4258)
#pragma warning(disable: 4251)
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# endif
#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)
#endif
// ======= PLATFORMS =========
// set up defines for target environments
#if (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
|| defined __FreeBSD_kernel__
#define TORRENT_BSD
#elif defined __linux__
#define TORRENT_LINUX
#elif defined __MINGW32__
#define TORRENT_MINGW
#elif defined WIN32
#define TORRENT_WINDOWS
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#elif defined __BEOS__ || defined __HAIKU__
#define TORRENT_BEOS
#include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH
#define TORRENT_HAS_FALLOCATE 0
#if __GNUCC__ == 2
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# endif
#endif
#else
#warning unknown OS, assuming BSD
#define TORRENT_BSD
#endif
#ifndef TORRENT_EXPORT
# define TORRENT_EXPORT
#endif
#ifndef TORRENT_DEPRECATED_PREFIX
#define TORRENT_DEPRECATED_PREFIX
#endif
#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif
#ifndef TORRENT_USE_IPV6
#define TORRENT_USE_IPV6 1
#endif
#define TORRENT_USE_MLOCK 1
#define TORRENT_USE_READV 1
#define TORRENT_USE_WRITEV 1
#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM
#define TORRENT_USE_IOSTREAM 1
#else
#define TORRENT_USE_IOSTREAM 0
#endif
#define TORRENT_USE_I2P 1
// set this to 1 to disable all floating point operations
// (disables some float-dependent APIs)
#define TORRENT_NO_FPU 0
// on windows, NAME_MAX refers to Unicode characters
// on linux it refers to bytes (utf-8 encoded)
// TODO: Make this count Unicode characters instead of bytes on windows
// windows
#if defined FILENAME_MAX
#define TORRENT_MAX_PATH FILENAME_MAX
// beos
#elif defined B_PATH_NAME_LENGTH
#defined TORRENT_MAX_PATH B_PATH_NAME_LENGTH
// solaris
#elif defined MAXPATH
#define TORRENT_MAX_PATH MAXPATH
// posix
#elif defined NAME_MAX
#define TORRENT_MAX_PATH NAME_MAX
// none of the above
#else
// this is the maximum number of characters in a
// path element / filename on windows
#define TORRENT_MAX_PATH 255
#warning unknown platform, assuming the longest path is 255
#endif
#ifdef TORRENT_WINDOWS
// class X needs to have dll-interface to be used by clients of class Y
#pragma warning(disable:4251)
// '_vsnprintf': This function or variable may be unsafe
#pragma warning(disable:4996)
#include <stdarg.h>
inline int snprintf(char* buf, int len, char const* fmt, ...)
{
va_list lp;
va_start(lp, fmt);
int ret = _vsnprintf(buf, len, fmt, lp);
va_end(lp);
if (ret < 0) { buf[len-1] = 0; ret = len-1; }
return ret;
}
#define strtoll _strtoi64
#else
#include <limits.h>
#endif
#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)
#define TORRENT_UPNP_LOGGING
#endif
// windows has its own functions to convert
// apple uses utf-8 as its locale, so no conversion
// is necessary
#if !defined TORRENT_WINDOWS && !defined __APPLE__
// libiconv presence, not implemented yet
#define TORRENT_USE_ICONV 1
#else
#define TORRENT_ISE_ICONV 0
#endif
#if defined UNICODE && !defined BOOST_NO_STD_WSTRING
#define TORRENT_USE_WSTRING 1
#else
#define TORRENT_USE_WSTRING 0
#endif // UNICODE
#ifndef TORRENT_HAS_FALLOCATE
#define TORRENT_HAS_FALLOCATE 1
#endif
#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif
#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif
#if defined _MSC_VER && _MSC_VER <= 1200
#define for if (false) {} else for
#endif
// determine what timer implementation we can use
// if one is already defined, don't pick one
// autmatically. This lets the user control this
// from the Jamfile
#if !defined TORRENT_USE_ABSOLUTE_TIME \
&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \
&& !defined TORRENT_USE_CLOCK_GETTIME \
&& !defined TORRENT_USE_BOOST_DATE_TIME \
&& !defined TORRENT_USE_SYSTEM_TIME
#if defined(__MACH__)
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32)
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#elif defined(TORRENT_BEOS)
#define TORRENT_USE_SYSTEM_TIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif
#endif
#endif // TORRENT_CONFIG_HPP_INCLUDED
<commit_msg>updated config header to be slightly more structured<commit_after>/*
Copyright (c) 2005, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf
#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif
#ifndef PRId64
#ifdef _WIN32
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif
// ======= GCC =========
#if defined __GNUC__
# if __GNUC__ >= 3
# define TORRENT_DEPRECATED __attribute__ ((deprecated))
# endif
// GCC pre 4.0 did not have support for the visibility attribute
# if __GNUC__ >= 4
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __attribute__ ((visibility("default")))
# endif
# endif
// ======= SUNPRO =========
#elif defined __SUNPRO_CC
# if __SUNPRO_CC >= 0x550
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __global
# endif
# endif
// ======= MSVC =========
#elif defined BOOST_MSVC
#pragma warning(disable: 4258)
#pragma warning(disable: 4251)
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# endif
#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)
#endif
// ======= PLATFORMS =========
// set up defines for target environments
// ==== AMIGA ===
#if defined __AMIGA__ || defined __amigaos__ || defined __AROS__
#define TORRENT_AMIGA
#define TORRENT_USE_MLOCK 0
#define TORRENT_USE_WRITEV 0
#define TORRENT_USE_READV 0
#define TORRENT_USE_IPV6 0
#define TORRENT_USE_BOOST_THREAD 0
#define TORRENT_USE_IOSTREAM 0
// set this to 1 to disable all floating point operations
// (disables some float-dependent APIs)
#define TORRENT_NO_FPU 1
#define TORRENT_USE_I2P 0
// ==== Darwin/BSD ===
#elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
|| defined __FreeBSD_kernel__
#define TORRENT_BSD
// ==== LINUX ===
#elif defined __linux__
#define TORRENT_LINUX
#elif defined __MINGW32__
#define TORRENT_MINGW
// ==== WINDOWS ===
#elif defined WIN32
#define TORRENT_WINDOWS
// ==== SOLARIS ===
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
// ==== BEOS ===
#elif defined __BEOS__ || defined __HAIKU__
#define TORRENT_BEOS
#include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH
#define TORRENT_HAS_FALLOCATE 0
#if __GNUCC__ == 2
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# endif
#endif
#else
#warning unknown OS, assuming BSD
#define TORRENT_BSD
#endif
// on windows, NAME_MAX refers to Unicode characters
// on linux it refers to bytes (utf-8 encoded)
// TODO: Make this count Unicode characters instead of bytes on windows
// windows
#if defined FILENAME_MAX
#define TORRENT_MAX_PATH FILENAME_MAX
// beos
#elif defined B_PATH_NAME_LENGTH
#define TORRENT_MAX_PATH B_PATH_NAME_LENGTH
// solaris
#elif defined MAXPATH
#define TORRENT_MAX_PATH MAXPATH
// posix
#elif defined NAME_MAX
#define TORRENT_MAX_PATH NAME_MAX
// none of the above
#else
// this is the maximum number of characters in a
// path element / filename on windows
#define TORRENT_MAX_PATH 255
#warning unknown platform, assuming the longest path is 255
#endif
#ifdef TORRENT_WINDOWS
// class X needs to have dll-interface to be used by clients of class Y
#pragma warning(disable:4251)
// '_vsnprintf': This function or variable may be unsafe
#pragma warning(disable:4996)
#include <stdarg.h>
inline int snprintf(char* buf, int len, char const* fmt, ...)
{
va_list lp;
va_start(lp, fmt);
int ret = _vsnprintf(buf, len, fmt, lp);
va_end(lp);
if (ret < 0) { buf[len-1] = 0; ret = len-1; }
return ret;
}
#define strtoll _strtoi64
#else
#include <limits.h>
#endif
#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \
&& !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM
#define TORRENT_UPNP_LOGGING
#endif
// windows has its own functions to convert
// apple uses utf-8 as its locale, so no conversion
// is necessary
#if !defined TORRENT_WINDOWS && !defined __APPLE__ && !defined TORRENT_AMIGA
// libiconv presence, not implemented yet
#define TORRENT_USE_ICONV 1
#else
#define TORRENT_ISE_ICONV 0
#endif
#if defined UNICODE && !defined BOOST_NO_STD_WSTRING
#define TORRENT_USE_WSTRING 1
#else
#define TORRENT_USE_WSTRING 0
#endif // UNICODE
#ifndef TORRENT_HAS_FALLOCATE
#define TORRENT_HAS_FALLOCATE 1
#endif
#ifndef TORRENT_EXPORT
# define TORRENT_EXPORT
#endif
#ifndef TORRENT_DEPRECATED_PREFIX
#define TORRENT_DEPRECATED_PREFIX
#endif
#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif
#ifndef TORRENT_USE_IPV6
#define TORRENT_USE_IPV6 1
#endif
#ifndef TORRENT_USE_MLOCK
#define TORRENT_USE_MLOCK 1
#endif
#ifndef TORRENT_USE_WRITEV
#define TORRENT_USE_WRITEV 1
#endif
#ifndef TORRENT_USE_READV
#define TORRENT_USE_READV 1
#endif
#ifndef TORRENT_NO_FPU
#define TORRENT_NO_FPU 0
#endif
#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM
#define TORRENT_USE_IOSTREAM 1
#else
#define TORRENT_USE_IOSTREAM 0
#endif
#ifndef TORRENT_USE_I2P
#define TORRENT_USE_I2P 1
#endif
#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif
#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif
#if defined _MSC_VER && _MSC_VER <= 1200
#define for if (false) {} else for
#endif
// determine what timer implementation we can use
// if one is already defined, don't pick one
// autmatically. This lets the user control this
// from the Jamfile
#if !defined TORRENT_USE_ABSOLUTE_TIME \
&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \
&& !defined TORRENT_USE_CLOCK_GETTIME \
&& !defined TORRENT_USE_BOOST_DATE_TIME \
&& !defined TORRENT_USE_ECLOCK \
&& !defined TORRENT_USE_SYSTEM_TIME
#if defined(__MACH__)
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32)
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#elif defined(TORRENT_AMIGA)
#define TORRENT_USE_ECLOCK 1
#elif defined(TORRENT_BEOS)
#define TORRENT_USE_SYSTEM_TIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif
#endif
#endif // TORRENT_CONFIG_HPP_INCLUDED
<|endoftext|> |
<commit_before>//Copyright (c) 2014 Naohiro Hayshi and ROS JAPAN Users Group ALL Rights Reserved
//Author Naohiro Hayashi 2014/11/07
#include "ros/ros.h"
#include <iostream>
#include <nextage_ros_seqplay_util/goPose.h>
#include <hrpsys_ros_bridge/OpenHRP_SequencePlayerService_waitInterpolation.h>
#include <hrpsys_ros_bridge/OpenHRP_SequencePlayerService_setTargetPose.h>
#include <hrpsys_ros_bridge/OpenHRP_SequencePlayerService_waitInterpolationOfGroup.h>
int main(int argc, char **argv)
{
ros::init(argc, argv, "ros_seqplay_utilclient");
ROS_INFO("test_move");
ros::NodeHandle n;
//goInitial
ros::ServiceClient initialclient = n.serviceClient<nextage_ros_seqplay_util::goPose>("/nextage_seqplay_util/goInitial");
nextage_ros_seqplay_util::goPose initialsrv;
initialsrv.request.tm =2.0;
//waitInterpolation
ros::ServiceClient waitclient = n.serviceClient<hrpsys_ros_bridge::OpenHRP_SequencePlayerService_waitInterpolation>("/SequencePlayerServiceROSBridge/waitInterpolation");
hrpsys_ros_bridge::OpenHRP_SequencePlayerService_waitInterpolation waitsrv;
//setTargetPoseRelative
ros::ServiceClient targetclient = n.serviceClient<hrpsys_ros_bridge::OpenHRP_SequencePlayerService_setTargetPose>("/nextage_seqplay_util/setTargetPoseRelative");
hrpsys_ros_bridge::OpenHRP_SequencePlayerService_setTargetPose targetsrv;
targetsrv.request.name = "larm";
targetsrv.request.xyz.resize(3);
targetsrv.request.xyz[0] = 0.0;
targetsrv.request.xyz[1] = 0.0;
targetsrv.request.xyz[2] = 0.1;
targetsrv.request.rpy.resize(3);
targetsrv.request.rpy[0] = 0.0;
targetsrv.request.rpy[1] = 0.0;
targetsrv.request.rpy[2] = 0.0;
targetsrv.request.tm = 2.0;
//leftwaitInterpolation
ros::ServiceClient leftwaitclient = n.serviceClient<hrpsys_ros_bridge::OpenHRP_SequencePlayerService_waitInterpolationOfGroup>("/SequencePlayerServiceROSBridge/waitInterpolationOfGroup");
hrpsys_ros_bridge::OpenHRP_SequencePlayerService_waitInterpolationOfGroup leftwaitsrv;
leftwaitsrv.request.gname = "larm";
//goOffPose
ros::ServiceClient gooffclient = n.serviceClient<nextage_ros_seqplay_util::goPose>("/nextage_seqplay_util/goOffPose");
nextage_ros_seqplay_util::goPose gooffsrv;
gooffsrv.request.tm =5.0;
//call service
std::cout << "initial" << std::endl;
if (initialclient.call(initialsrv))
{
ROS_INFO("Success goInitial");
}
else
{
ROS_ERROR("Error goInitial");
}
std::cout << "wait" << std::endl;
if (waitclient.call(waitsrv))
{
ROS_INFO("Success wait");
}
else
{
ROS_ERROR("Error wait");
}
std::cout << "target" << std::endl;
if (targetclient.call(targetsrv))
{
ROS_INFO("Success target");
}
else
{
ROS_ERROR("Error target");
}
std::cout << "leftwait" << std::endl;
if (leftwaitclient.call(leftwaitsrv))
{
ROS_INFO("Success left wait");
}
else
{
ROS_ERROR("Error leftwait");
}
std::cout << "gooff" << std::endl;
if (gooffclient.call(gooffsrv))
{
ROS_INFO("Success gooff");
}
else
{
ROS_ERROR("Error gooff");
}
//~
return 0;
}
<commit_msg>Update sample.cpp<commit_after>//Copyright (c) 2014 Naohiro Hayshi and ROS JAPAN Users Group ALL Rights Reserved
//Author Naohiro Hayashi 2014/11/07
#include "ros/ros.h"
#include <iostream>
#include <nextage_ros_seqplay_util/goPose.h>
#include <hrpsys_ros_bridge/OpenHRP_SequencePlayerService_waitInterpolation.h>
#include <hrpsys_ros_bridge/OpenHRP_SequencePlayerService_setTargetPose.h>
#include <hrpsys_ros_bridge/OpenHRP_SequencePlayerService_waitInterpolationOfGroup.h>
int main(int argc, char **argv)
{
ros::init(argc, argv, "ros_seqplay_utilclient");
ROS_INFO("test_move");
ros::NodeHandle n;
//goInitial
ros::ServiceClient initialclient = n.serviceClient<nextage_ros_seqplay_util::goPose>("/nextage_seqplay_util/goInitial");
nextage_ros_seqplay_util::goPose initialsrv;
initialsrv.request.tm =2.0;
//waitInterpolation
ros::ServiceClient waitclient = n.serviceClient<hrpsys_ros_bridge::OpenHRP_SequencePlayerService_waitInterpolation>("/SequencePlayerServiceROSBridge/waitInterpolation");
hrpsys_ros_bridge::OpenHRP_SequencePlayerService_waitInterpolation waitsrv;
//setTargetPoseRelative
ros::ServiceClient targetclient = n.serviceClient<hrpsys_ros_bridge::OpenHRP_SequencePlayerService_setTargetPose>("/nextage_seqplay_util/setTargetPoseRelative");
hrpsys_ros_bridge::OpenHRP_SequencePlayerService_setTargetPose targetsrv;
targetsrv.request.name = "larm";
targetsrv.request.xyz.resize(3);
targetsrv.request.xyz[0] = 0.0;
targetsrv.request.xyz[1] = 0.0;
targetsrv.request.xyz[2] = 0.1;
targetsrv.request.rpy.resize(3);
targetsrv.request.rpy[0] = 0.0;
targetsrv.request.rpy[1] = 0.0;
targetsrv.request.rpy[2] = 0.0;
targetsrv.request.tm = 2.0;
//leftwaitInterpolation
ros::ServiceClient leftwaitclient = n.serviceClient<hrpsys_ros_bridge::OpenHRP_SequencePlayerService_waitInterpolationOfGroup>("/SequencePlayerServiceROSBridge/waitInterpolationOfGroup");
hrpsys_ros_bridge::OpenHRP_SequencePlayerService_waitInterpolationOfGroup leftwaitsrv;
leftwaitsrv.request.gname = "larm";
//goOffPose
ros::ServiceClient gooffclient = n.serviceClient<nextage_ros_seqplay_util::goPose>("/nextage_seqplay_util/goOffPose");
nextage_ros_seqplay_util::goPose gooffsrv;
gooffsrv.request.tm =5.0;
//call service
//initial pose
std::cout << "initial" << std::endl;
if (initialclient.call(initialsrv))
{
ROS_INFO("Success goInitial");
}
else
{
ROS_ERROR("Error goInitial");
}
//wait
std::cout << "wait" << std::endl;
if (waitclient.call(waitsrv))
{
ROS_INFO("Success wait");
}
else
{
ROS_ERROR("Error wait");
}
//move left hand
std::cout << "target" << std::endl;
if (targetclient.call(targetsrv))
{
ROS_INFO("Success target");
}
else
{
ROS_ERROR("Error target");
}
//wait
std::cout << "leftwait" << std::endl;
if (leftwaitclient.call(leftwaitsrv))
{
ROS_INFO("Success left wait");
}
else
{
ROS_ERROR("Error leftwait");
}
//go off pose
std::cout << "gooff" << std::endl;
if (gooffclient.call(gooffsrv))
{
ROS_INFO("Success gooff");
}
else
{
ROS_ERROR("Error gooff");
}
//~
return 0;
}
<|endoftext|> |
<commit_before>#include <m7/AllocatorDeleterDef.H>
namespace m7 {
template <typename Alloc>
AllocatorDeleter<Alloc>::AllocatorDeleter(Alloc* alloc)
: _alloc(alloc)
{
}
template <typename Alloc>
template <typename T>
inline void AllocatorDeleter<Alloc>::operator()(T* p) const {
_alloc->free(p);
}
} //namespace m7
<commit_msg>Bugfix in AllocatorDeleter<commit_after>#include <m7/AllocatorDeleterDef.H>
namespace m7 {
template <typename Alloc>
AllocatorDeleter<Alloc>::AllocatorDeleter(Alloc* alloc)
: _alloc(alloc)
{
}
template <typename Alloc>
template <typename T>
inline void AllocatorDeleter<Alloc>::operator()(T* p) const {
p->~T();
_alloc->free(p);
}
} //namespace m7
<|endoftext|> |
<commit_before><commit_msg>Signed-off-by: xsmart <[email protected]><commit_after><|endoftext|> |
<commit_before><commit_msg>Remove captive portal check from oauth2 token fetcher.<commit_after><|endoftext|> |
<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_EVALUATION_INTERFACE_HH
#define DUNE_DETAILED_DISCRETIZATIONS_EVALUATION_INTERFACE_HH
#include <memory>
#include <dune/common/dynmatrix.hh>
#include <dune/common/fvector.hh>
#include <dune/stuff/localfunction/interface.hh>
#include <dune/detailed/discretizations/basefunctionset/interface.hh>
namespace Dune {
namespace Detailed {
namespace Discretizations {
template< class Traits >
class BinaryEvaluationInterface
{
public:
typedef typename Traits::derived_type derived_type;
/**
* \brief Computes a binary evaluation.
* \tparam L Traits of the Dune::Stuff::LocalFunctionInterface implementation
* \tparam T Traits of the test BaseFunctionSetInterface implementation
* \tparam A Traits of the ansatz BaseFunctionSetInterface implementation
*/
template< class L, class T, class A, class D, int d, class R, int rR, int rC >
static void evaluate(const Dune::Stuff::LocalFunctionInterface< L, D, d, R, rR, rC >& localFunction,
const BaseFunctionSetInterface< T >& testBase,
const BaseFunctionSetInterface< A >& ansatzBase,
const Dune::FieldVector< D, d >& localPoint,
Dune::DynamicMatrix< R >& ret)
{
derived_type::evaluate(localFunction, testBase, ansatzBase, localPoint, ret);
}
}; // class BinaryEvaluationInterface
} // namespace Discretizations
} // namespace Detailed
} // namespace Dune
#endif // DUNE_DETAILED_DISCRETIZATIONS_EVALUATION_INTERFACE_HH
<commit_msg>[evaluation.interface] added UnaryEvaluationInterface<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_EVALUATION_INTERFACE_HH
#define DUNE_DETAILED_DISCRETIZATIONS_EVALUATION_INTERFACE_HH
#include <memory>
#include <dune/common/dynmatrix.hh>
#include <dune/common/fvector.hh>
#include <dune/stuff/localfunction/interface.hh>
#include <dune/detailed/discretizations/basefunctionset/interface.hh>
namespace Dune {
namespace Detailed {
namespace Discretizations {
template< class Traits >
class BinaryEvaluationInterface
{
public:
typedef typename Traits::derived_type derived_type;
/**
* \brief Computes a binary evaluation.
* \tparam L Traits of the Dune::Stuff::LocalFunctionInterface implementation
* \tparam T Traits of the test BaseFunctionSetInterface implementation
* \tparam A Traits of the ansatz BaseFunctionSetInterface implementation
*/
template< class L, class T, class A, class D, int d, class R, int rR, int rC >
static void evaluate(const Dune::Stuff::LocalFunctionInterface< L, D, d, R, rR, rC >& localFunction,
const BaseFunctionSetInterface< T >& testBase,
const BaseFunctionSetInterface< A >& ansatzBase,
const Dune::FieldVector< D, d >& localPoint,
Dune::DynamicMatrix< R >& ret)
{
derived_type::evaluate(localFunction, testBase, ansatzBase, localPoint, ret);
}
}; // class BinaryEvaluationInterface
template< class Traits >
class UnaryEvaluationInterface
{
public:
typedef typename Traits::derived_type derived_type;
/**
* \brief Computes a unary evaluation.
* \tparam L Traits of the Dune::Stuff::LocalFunctionInterface implementation
* \tparam T Traits of the test BaseFunctionSetInterface implementation
*/
template< class L, class T, class D, int d, class R, int rR, int rC >
static void evaluate(const Dune::Stuff::LocalFunctionInterface< L, D, d, R, rR, rC >& localFunction,
const BaseFunctionSetInterface< T >& testBase,
const Dune::FieldVector< D, d >& localPoint,
Dune::DynamicVector< R >& ret)
{
derived_type::evaluate(localFunction, testBase, localPoint, ret);
}
}; // class UnaryEvaluationInterface
} // namespace Discretizations
} // namespace Detailed
} // namespace Dune
#endif // DUNE_DETAILED_DISCRETIZATIONS_EVALUATION_INTERFACE_HH
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2010 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2007-2008 The Florida State University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Stephen Hines
*/
#ifndef __ARCH_ARM_TYPES_HH__
#define __ARCH_ARM_TYPES_HH__
#include "base/bitunion.hh"
#include "base/types.hh"
namespace ArmISA
{
typedef uint32_t MachInst;
BitUnion64(ExtMachInst)
// Bitfields to select mode.
Bitfield<36> thumb;
Bitfield<35> bigThumb;
// Made up bitfields that make life easier.
Bitfield<33> sevenAndFour;
Bitfield<32> isMisc;
uint32_t instBits;
// All the different types of opcode fields.
Bitfield<27, 25> encoding;
Bitfield<25> useImm;
Bitfield<24, 21> opcode;
Bitfield<24, 20> mediaOpcode;
Bitfield<24> opcode24;
Bitfield<24, 23> opcode24_23;
Bitfield<23, 20> opcode23_20;
Bitfield<23, 21> opcode23_21;
Bitfield<20> opcode20;
Bitfield<22> opcode22;
Bitfield<19, 16> opcode19_16;
Bitfield<19> opcode19;
Bitfield<18> opcode18;
Bitfield<15, 12> opcode15_12;
Bitfield<15> opcode15;
Bitfield<7, 4> miscOpcode;
Bitfield<7,5> opc2;
Bitfield<7> opcode7;
Bitfield<6> opcode6;
Bitfield<4> opcode4;
Bitfield<31, 28> condCode;
Bitfield<20> sField;
Bitfield<19, 16> rn;
Bitfield<15, 12> rd;
Bitfield<15, 12> rt;
Bitfield<11, 7> shiftSize;
Bitfield<6, 5> shift;
Bitfield<3, 0> rm;
Bitfield<11, 8> rs;
SubBitUnion(puswl, 24, 20)
Bitfield<24> prepost;
Bitfield<23> up;
Bitfield<22> psruser;
Bitfield<21> writeback;
Bitfield<20> loadOp;
EndSubBitUnion(puswl)
Bitfield<24, 20> pubwl;
Bitfield<7, 0> imm;
Bitfield<11, 8> rotate;
Bitfield<11, 0> immed11_0;
Bitfield<7, 0> immed7_0;
Bitfield<11, 8> immedHi11_8;
Bitfield<3, 0> immedLo3_0;
Bitfield<15, 0> regList;
Bitfield<23, 0> offset;
Bitfield<23, 0> immed23_0;
Bitfield<11, 8> cpNum;
Bitfield<18, 16> fn;
Bitfield<14, 12> fd;
Bitfield<3> fpRegImm;
Bitfield<3, 0> fm;
Bitfield<2, 0> fpImm;
Bitfield<24, 20> punwl;
Bitfield<7, 0> m5Func;
// 16 bit thumb bitfields
Bitfield<15, 13> topcode15_13;
Bitfield<13, 11> topcode13_11;
Bitfield<12, 11> topcode12_11;
Bitfield<12, 10> topcode12_10;
Bitfield<11, 9> topcode11_9;
Bitfield<11, 8> topcode11_8;
Bitfield<10, 9> topcode10_9;
Bitfield<10, 8> topcode10_8;
Bitfield<9, 6> topcode9_6;
Bitfield<7> topcode7;
Bitfield<7, 6> topcode7_6;
Bitfield<7, 5> topcode7_5;
Bitfield<7, 4> topcode7_4;
Bitfield<3, 0> topcode3_0;
// 32 bit thumb bitfields
Bitfield<28, 27> htopcode12_11;
Bitfield<26, 25> htopcode10_9;
Bitfield<25> htopcode9;
Bitfield<25, 24> htopcode9_8;
Bitfield<25, 21> htopcode9_5;
Bitfield<25, 20> htopcode9_4;
Bitfield<24> htopcode8;
Bitfield<24, 23> htopcode8_7;
Bitfield<24, 22> htopcode8_6;
Bitfield<24, 21> htopcode8_5;
Bitfield<23> htopcode7;
Bitfield<23, 21> htopcode7_5;
Bitfield<22> htopcode6;
Bitfield<22, 21> htopcode6_5;
Bitfield<21, 20> htopcode5_4;
Bitfield<20> htopcode4;
Bitfield<19, 16> htrn;
Bitfield<20> hts;
Bitfield<15> ltopcode15;
Bitfield<11, 8> ltopcode11_8;
Bitfield<7, 6> ltopcode7_6;
Bitfield<7, 4> ltopcode7_4;
Bitfield<4> ltopcode4;
Bitfield<11, 8> ltrd;
Bitfield<11, 8> ltcoproc;
EndBitUnion(ExtMachInst)
// Shift types for ARM instructions
enum ArmShiftType {
LSL = 0,
LSR,
ASR,
ROR
};
typedef uint64_t LargestRead;
// Need to use 64 bits to make sure that read requests get handled properly
typedef int RegContextParam;
typedef int RegContextVal;
//used in FP convert & round function
enum ConvertType{
SINGLE_TO_DOUBLE,
SINGLE_TO_WORD,
SINGLE_TO_LONG,
DOUBLE_TO_SINGLE,
DOUBLE_TO_WORD,
DOUBLE_TO_LONG,
LONG_TO_SINGLE,
LONG_TO_DOUBLE,
LONG_TO_WORD,
LONG_TO_PS,
WORD_TO_SINGLE,
WORD_TO_DOUBLE,
WORD_TO_LONG,
WORD_TO_PS,
PL_TO_SINGLE,
PU_TO_SINGLE
};
//used in FP convert & round function
enum RoundMode{
RND_ZERO,
RND_DOWN,
RND_UP,
RND_NEAREST
};
enum OperatingMode {
MODE_USER = 16,
MODE_FIQ = 17,
MODE_IRQ = 18,
MODE_SVC = 19,
MODE_MON = 22,
MODE_ABORT = 23,
MODE_UNDEFINED = 27,
MODE_SYSTEM = 31
};
struct CoreSpecific {
// Empty for now on the ARM
};
} // namespace ArmISA
#endif
<commit_msg>ARM: Implement a badMode function that says whether a mode is legal.<commit_after>/*
* Copyright (c) 2010 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2007-2008 The Florida State University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Stephen Hines
*/
#ifndef __ARCH_ARM_TYPES_HH__
#define __ARCH_ARM_TYPES_HH__
#include "base/bitunion.hh"
#include "base/types.hh"
namespace ArmISA
{
typedef uint32_t MachInst;
BitUnion64(ExtMachInst)
// Bitfields to select mode.
Bitfield<36> thumb;
Bitfield<35> bigThumb;
// Made up bitfields that make life easier.
Bitfield<33> sevenAndFour;
Bitfield<32> isMisc;
uint32_t instBits;
// All the different types of opcode fields.
Bitfield<27, 25> encoding;
Bitfield<25> useImm;
Bitfield<24, 21> opcode;
Bitfield<24, 20> mediaOpcode;
Bitfield<24> opcode24;
Bitfield<24, 23> opcode24_23;
Bitfield<23, 20> opcode23_20;
Bitfield<23, 21> opcode23_21;
Bitfield<20> opcode20;
Bitfield<22> opcode22;
Bitfield<19, 16> opcode19_16;
Bitfield<19> opcode19;
Bitfield<18> opcode18;
Bitfield<15, 12> opcode15_12;
Bitfield<15> opcode15;
Bitfield<7, 4> miscOpcode;
Bitfield<7,5> opc2;
Bitfield<7> opcode7;
Bitfield<6> opcode6;
Bitfield<4> opcode4;
Bitfield<31, 28> condCode;
Bitfield<20> sField;
Bitfield<19, 16> rn;
Bitfield<15, 12> rd;
Bitfield<15, 12> rt;
Bitfield<11, 7> shiftSize;
Bitfield<6, 5> shift;
Bitfield<3, 0> rm;
Bitfield<11, 8> rs;
SubBitUnion(puswl, 24, 20)
Bitfield<24> prepost;
Bitfield<23> up;
Bitfield<22> psruser;
Bitfield<21> writeback;
Bitfield<20> loadOp;
EndSubBitUnion(puswl)
Bitfield<24, 20> pubwl;
Bitfield<7, 0> imm;
Bitfield<11, 8> rotate;
Bitfield<11, 0> immed11_0;
Bitfield<7, 0> immed7_0;
Bitfield<11, 8> immedHi11_8;
Bitfield<3, 0> immedLo3_0;
Bitfield<15, 0> regList;
Bitfield<23, 0> offset;
Bitfield<23, 0> immed23_0;
Bitfield<11, 8> cpNum;
Bitfield<18, 16> fn;
Bitfield<14, 12> fd;
Bitfield<3> fpRegImm;
Bitfield<3, 0> fm;
Bitfield<2, 0> fpImm;
Bitfield<24, 20> punwl;
Bitfield<7, 0> m5Func;
// 16 bit thumb bitfields
Bitfield<15, 13> topcode15_13;
Bitfield<13, 11> topcode13_11;
Bitfield<12, 11> topcode12_11;
Bitfield<12, 10> topcode12_10;
Bitfield<11, 9> topcode11_9;
Bitfield<11, 8> topcode11_8;
Bitfield<10, 9> topcode10_9;
Bitfield<10, 8> topcode10_8;
Bitfield<9, 6> topcode9_6;
Bitfield<7> topcode7;
Bitfield<7, 6> topcode7_6;
Bitfield<7, 5> topcode7_5;
Bitfield<7, 4> topcode7_4;
Bitfield<3, 0> topcode3_0;
// 32 bit thumb bitfields
Bitfield<28, 27> htopcode12_11;
Bitfield<26, 25> htopcode10_9;
Bitfield<25> htopcode9;
Bitfield<25, 24> htopcode9_8;
Bitfield<25, 21> htopcode9_5;
Bitfield<25, 20> htopcode9_4;
Bitfield<24> htopcode8;
Bitfield<24, 23> htopcode8_7;
Bitfield<24, 22> htopcode8_6;
Bitfield<24, 21> htopcode8_5;
Bitfield<23> htopcode7;
Bitfield<23, 21> htopcode7_5;
Bitfield<22> htopcode6;
Bitfield<22, 21> htopcode6_5;
Bitfield<21, 20> htopcode5_4;
Bitfield<20> htopcode4;
Bitfield<19, 16> htrn;
Bitfield<20> hts;
Bitfield<15> ltopcode15;
Bitfield<11, 8> ltopcode11_8;
Bitfield<7, 6> ltopcode7_6;
Bitfield<7, 4> ltopcode7_4;
Bitfield<4> ltopcode4;
Bitfield<11, 8> ltrd;
Bitfield<11, 8> ltcoproc;
EndBitUnion(ExtMachInst)
// Shift types for ARM instructions
enum ArmShiftType {
LSL = 0,
LSR,
ASR,
ROR
};
typedef uint64_t LargestRead;
// Need to use 64 bits to make sure that read requests get handled properly
typedef int RegContextParam;
typedef int RegContextVal;
//used in FP convert & round function
enum ConvertType{
SINGLE_TO_DOUBLE,
SINGLE_TO_WORD,
SINGLE_TO_LONG,
DOUBLE_TO_SINGLE,
DOUBLE_TO_WORD,
DOUBLE_TO_LONG,
LONG_TO_SINGLE,
LONG_TO_DOUBLE,
LONG_TO_WORD,
LONG_TO_PS,
WORD_TO_SINGLE,
WORD_TO_DOUBLE,
WORD_TO_LONG,
WORD_TO_PS,
PL_TO_SINGLE,
PU_TO_SINGLE
};
//used in FP convert & round function
enum RoundMode{
RND_ZERO,
RND_DOWN,
RND_UP,
RND_NEAREST
};
enum OperatingMode {
MODE_USER = 16,
MODE_FIQ = 17,
MODE_IRQ = 18,
MODE_SVC = 19,
MODE_MON = 22,
MODE_ABORT = 23,
MODE_UNDEFINED = 27,
MODE_SYSTEM = 31
};
static inline bool
badMode(OperatingMode mode)
{
switch (mode) {
case MODE_USER:
case MODE_FIQ:
case MODE_IRQ:
case MODE_SVC:
case MODE_MON:
case MODE_ABORT:
case MODE_UNDEFINED:
case MODE_SYSTEM:
return false;
default:
return true;
}
}
struct CoreSpecific {
// Empty for now on the ARM
};
} // namespace ArmISA
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/message_loop.h"
#include "chrome/browser/chrome_plugin_service_filter.h"
#include "chrome/browser/chromeos/gview_request_interceptor.h"
#include "chrome/browser/plugin_prefs.h"
#include "chrome/browser/plugin_prefs_factory.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/testing_pref_service.h"
#include "content/browser/mock_resource_context.h"
#include "content/browser/plugin_service.h"
#include "content/browser/renderer_host/dummy_resource_handler.h"
#include "content/browser/renderer_host/resource_dispatcher_host_request_info.h"
#include "content/test/test_browser_thread.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_job.h"
#include "net/url_request/url_request_job_factory.h"
#include "net/url_request/url_request_test_job.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/plugins/npapi/plugin_list.h"
using content::BrowserThread;
namespace chromeos {
namespace {
const char kPdfUrl[] = "http://foo.com/file.pdf";
const char kPptUrl[] = "http://foo.com/file.ppt";
const char kHtmlUrl[] = "http://foo.com/index.html";
const char kPdfBlob[] = "blob:blobinternal:///d17c4eef-28e7-42bd-bafa-78d5cb8";
const char kPdfUrlIntercepted[] =
"http://docs.google.com/gview?url=http%3A//foo.com/file.pdf";
const char kPptUrlIntercepted[] =
"http://docs.google.com/gview?url=http%3A//foo.com/file.ppt";
class GViewURLRequestTestJob : public net::URLRequestTestJob {
public:
explicit GViewURLRequestTestJob(net::URLRequest* request)
: net::URLRequestTestJob(request, true) {
}
virtual bool GetMimeType(std::string* mime_type) const {
// During the course of a single test, two URLRequestJobs are
// created -- the first is for the viewable document URL, and the
// second is for the rediected URL. In order to test the
// interceptor, the mime type of the first request must be one of
// the supported viewable mime types. So when the net::URLRequestJob
// is a request for one of the test URLs that point to viewable
// content, return an appropraite mime type. Otherwise, return
// "text/html".
const GURL& request_url = request_->url();
if (request_url == GURL(kPdfUrl) || request_url == GURL(kPdfBlob)) {
*mime_type = "application/pdf";
} else if (request_url == GURL(kPptUrl)) {
*mime_type = "application/vnd.ms-powerpoint";
} else {
*mime_type = "text/html";
}
return true;
}
private:
~GViewURLRequestTestJob() {}
};
class GViewRequestProtocolFactory
: public net::URLRequestJobFactory::ProtocolHandler {
public:
GViewRequestProtocolFactory() {}
virtual ~GViewRequestProtocolFactory() {}
virtual net::URLRequestJob* MaybeCreateJob(net::URLRequest* request) const {
return new GViewURLRequestTestJob(request);
}
};
void QuitMessageLoop(const std::vector<webkit::WebPluginInfo>&) {
MessageLoop::current()->Quit();
}
class GViewRequestInterceptorTest : public testing::Test {
public:
GViewRequestInterceptorTest()
: ui_thread_(BrowserThread::UI, &message_loop_),
file_thread_(BrowserThread::FILE, &message_loop_),
io_thread_(BrowserThread::IO, &message_loop_) {}
virtual void SetUp() {
content::ResourceContext* resource_context =
content::MockResourceContext::GetInstance();
net::URLRequestContext* request_context =
resource_context->request_context();
old_factory_ = request_context->job_factory();
job_factory_.SetProtocolHandler("http", new GViewRequestProtocolFactory);
job_factory_.AddInterceptor(new GViewRequestInterceptor);
request_context->set_job_factory(&job_factory_);
PluginPrefsFactory::GetInstance()->ForceRegisterPrefsForTest(&prefs_);
plugin_prefs_ = new PluginPrefs();
plugin_prefs_->SetPrefs(&prefs_);
ChromePluginServiceFilter* filter =
ChromePluginServiceFilter::GetInstance();
filter->RegisterResourceContext(plugin_prefs_, resource_context);
PluginService::GetInstance()->set_filter(filter);
ASSERT_TRUE(PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf_path_));
handler_ = new content::DummyResourceHandler();
PluginService::GetInstance()->RefreshPluginList();
PluginService::GetInstance()->GetPlugins(base::Bind(&QuitMessageLoop));
MessageLoop::current()->Run();
}
virtual void TearDown() {
plugin_prefs_->ShutdownOnUIThread();
content::ResourceContext* resource_context =
content::MockResourceContext::GetInstance();
net::URLRequestContext* request_context =
resource_context->request_context();
request_context->set_job_factory(old_factory_);
ChromePluginServiceFilter* filter =
ChromePluginServiceFilter::GetInstance();
filter->UnregisterResourceContext(resource_context);
PluginService::GetInstance()->set_filter(NULL);
}
// GetPluginInfoByPath() will only use stale information. Because plugin
// refresh is asynchronous, spin a MessageLoop until the callback is run,
// after which, the test will continue.
void RegisterPDFPlugin() {
webkit::WebPluginInfo info;
info.path = pdf_path_;
webkit::npapi::PluginList::Singleton()->RegisterInternalPlugin(info);
PluginService::GetInstance()->RefreshPluginList();
PluginService::GetInstance()->GetPlugins(base::Bind(&QuitMessageLoop));
MessageLoop::current()->Run();
}
void UnregisterPDFPlugin() {
webkit::npapi::PluginList::Singleton()->UnregisterInternalPlugin(pdf_path_);
PluginService::GetInstance()->RefreshPluginList();
PluginService::GetInstance()->GetPlugins(base::Bind(&QuitMessageLoop));
MessageLoop::current()->Run();
}
void SetPDFPluginLoadedState(bool want_loaded) {
webkit::WebPluginInfo info;
bool is_loaded = PluginService::GetInstance()->GetPluginInfoByPath(
pdf_path_, &info);
if (is_loaded && !want_loaded) {
UnregisterPDFPlugin();
is_loaded = PluginService::GetInstance()->GetPluginInfoByPath(
pdf_path_, &info);
} else if (!is_loaded && want_loaded) {
// This "loads" the plug-in even if it's not present on the
// system - which is OK since we don't actually use it, just
// need it to be "enabled" for the test.
RegisterPDFPlugin();
is_loaded = PluginService::GetInstance()->GetPluginInfoByPath(
pdf_path_, &info);
}
EXPECT_EQ(want_loaded, is_loaded);
}
void SetupRequest(net::URLRequest* request) {
content::ResourceContext* context =
content::MockResourceContext::GetInstance();
ResourceDispatcherHostRequestInfo* info =
new ResourceDispatcherHostRequestInfo(handler_,
ChildProcessInfo::RENDER_PROCESS,
-1, // child_id
MSG_ROUTING_NONE,
0, // origin_pid
request->identifier(),
false, // is_main_frame
-1, // frame_id
ResourceType::MAIN_FRAME,
content::PAGE_TRANSITION_LINK,
0, // upload_size
false, // is_download
true, // allow_download
false, // has_user_gesture
context);
request->SetUserData(NULL, info);
request->set_context(context->request_context());
}
protected:
MessageLoopForIO message_loop_;
content::TestBrowserThread ui_thread_;
content::TestBrowserThread file_thread_;
content::TestBrowserThread io_thread_;
TestingPrefService prefs_;
scoped_refptr<PluginPrefs> plugin_prefs_;
net::URLRequestJobFactory job_factory_;
const net::URLRequestJobFactory* old_factory_;
scoped_refptr<ResourceHandler> handler_;
TestDelegate test_delegate_;
FilePath pdf_path_;
};
TEST_F(GViewRequestInterceptorTest, DoNotInterceptHtml) {
net::URLRequest request(GURL(kHtmlUrl), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(0, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kHtmlUrl), request.url());
}
TEST_F(GViewRequestInterceptorTest, DoNotInterceptDownload) {
net::URLRequest request(GURL(kPdfUrl), &test_delegate_);
SetupRequest(&request);
request.set_load_flags(net::LOAD_IS_DOWNLOAD);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(0, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfUrl), request.url());
}
TEST_F(GViewRequestInterceptorTest, DoNotInterceptPdfWhenEnabled) {
SetPDFPluginLoadedState(true);
plugin_prefs_->EnablePlugin(true, pdf_path_);
net::URLRequest request(GURL(kPdfUrl), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(0, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfUrl), request.url());
}
TEST_F(GViewRequestInterceptorTest, InterceptPdfWhenDisabled) {
SetPDFPluginLoadedState(true);
plugin_prefs_->EnablePlugin(false, pdf_path_);
net::URLRequest request(GURL(kPdfUrl), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(1, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfUrlIntercepted), request.url());
}
TEST_F(GViewRequestInterceptorTest, InterceptPdfWithNoPlugin) {
SetPDFPluginLoadedState(false);
net::URLRequest request(GURL(kPdfUrl), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(1, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfUrlIntercepted), request.url());
}
TEST_F(GViewRequestInterceptorTest, InterceptPowerpoint) {
net::URLRequest request(GURL(kPptUrl), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(1, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPptUrlIntercepted), request.url());
}
TEST_F(GViewRequestInterceptorTest, DoNotInterceptPost) {
SetPDFPluginLoadedState(false);
net::URLRequest request(GURL(kPdfUrl), &test_delegate_);
SetupRequest(&request);
request.set_method("POST");
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(0, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfUrl), request.url());
}
TEST_F(GViewRequestInterceptorTest, DoNotInterceptBlob) {
SetPDFPluginLoadedState(false);
net::URLRequest request(GURL(kPdfBlob), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(0, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfBlob), request.url());
}
} // namespace
} // namespace chromeos
<commit_msg>Fix GViewRequestInterceptorTest.* that has been failing on Linux ChromeOS bots<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/message_loop.h"
#include "chrome/browser/chrome_plugin_service_filter.h"
#include "chrome/browser/chromeos/gview_request_interceptor.h"
#include "chrome/browser/plugin_prefs.h"
#include "chrome/browser/plugin_prefs_factory.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/testing_pref_service.h"
#include "content/browser/mock_resource_context.h"
#include "content/browser/plugin_service.h"
#include "content/browser/renderer_host/dummy_resource_handler.h"
#include "content/browser/renderer_host/resource_dispatcher_host_request_info.h"
#include "content/test/test_browser_thread.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_job.h"
#include "net/url_request/url_request_job_factory.h"
#include "net/url_request/url_request_test_job.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/plugins/npapi/plugin_list.h"
using content::BrowserThread;
namespace chromeos {
namespace {
const char kPdfUrl[] = "http://foo.com/file.pdf";
const char kPptUrl[] = "http://foo.com/file.ppt";
const char kHtmlUrl[] = "http://foo.com/index.html";
const char kPdfBlob[] = "blob:blobinternal:///d17c4eef-28e7-42bd-bafa-78d5cb8";
const char kPdfUrlIntercepted[] =
"http://docs.google.com/gview?url=http%3A//foo.com/file.pdf";
const char kPptUrlIntercepted[] =
"http://docs.google.com/gview?url=http%3A//foo.com/file.ppt";
class GViewURLRequestTestJob : public net::URLRequestTestJob {
public:
explicit GViewURLRequestTestJob(net::URLRequest* request)
: net::URLRequestTestJob(request, true) {
}
virtual bool GetMimeType(std::string* mime_type) const {
// During the course of a single test, two URLRequestJobs are
// created -- the first is for the viewable document URL, and the
// second is for the rediected URL. In order to test the
// interceptor, the mime type of the first request must be one of
// the supported viewable mime types. So when the net::URLRequestJob
// is a request for one of the test URLs that point to viewable
// content, return an appropraite mime type. Otherwise, return
// "text/html".
const GURL& request_url = request_->url();
if (request_url == GURL(kPdfUrl) || request_url == GURL(kPdfBlob)) {
*mime_type = "application/pdf";
} else if (request_url == GURL(kPptUrl)) {
*mime_type = "application/vnd.ms-powerpoint";
} else {
*mime_type = "text/html";
}
return true;
}
private:
~GViewURLRequestTestJob() {}
};
class GViewRequestProtocolFactory
: public net::URLRequestJobFactory::ProtocolHandler {
public:
GViewRequestProtocolFactory() {}
virtual ~GViewRequestProtocolFactory() {}
virtual net::URLRequestJob* MaybeCreateJob(net::URLRequest* request) const {
return new GViewURLRequestTestJob(request);
}
};
void QuitMessageLoop(const std::vector<webkit::WebPluginInfo>&) {
MessageLoop::current()->Quit();
}
class GViewRequestInterceptorTest : public testing::Test {
public:
GViewRequestInterceptorTest()
: ui_thread_(BrowserThread::UI, &message_loop_),
file_thread_(BrowserThread::FILE, &message_loop_),
io_thread_(BrowserThread::IO, &message_loop_) {}
virtual void SetUp() {
content::ResourceContext* resource_context =
content::MockResourceContext::GetInstance();
net::URLRequestContext* request_context =
resource_context->request_context();
old_factory_ = request_context->job_factory();
job_factory_.SetProtocolHandler("http", new GViewRequestProtocolFactory);
job_factory_.AddInterceptor(new GViewRequestInterceptor);
request_context->set_job_factory(&job_factory_);
PluginPrefsFactory::GetInstance()->ForceRegisterPrefsForTest(&prefs_);
plugin_prefs_ = new PluginPrefs();
plugin_prefs_->SetPrefs(&prefs_);
ChromePluginServiceFilter* filter =
ChromePluginServiceFilter::GetInstance();
filter->RegisterResourceContext(plugin_prefs_, resource_context);
PluginService::GetInstance()->set_filter(filter);
ASSERT_TRUE(PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf_path_));
handler_ = new content::DummyResourceHandler();
PluginService::GetInstance()->RefreshPluginList();
PluginService::GetInstance()->GetPlugins(base::Bind(&QuitMessageLoop));
MessageLoop::current()->RunAllPending();
}
virtual void TearDown() {
plugin_prefs_->ShutdownOnUIThread();
content::ResourceContext* resource_context =
content::MockResourceContext::GetInstance();
net::URLRequestContext* request_context =
resource_context->request_context();
request_context->set_job_factory(old_factory_);
ChromePluginServiceFilter* filter =
ChromePluginServiceFilter::GetInstance();
filter->UnregisterResourceContext(resource_context);
PluginService::GetInstance()->set_filter(NULL);
}
// GetPluginInfoByPath() will only use stale information. Because plugin
// refresh is asynchronous, spin a MessageLoop until the callback is run,
// after which, the test will continue.
void RegisterPDFPlugin() {
webkit::WebPluginInfo info;
info.path = pdf_path_;
webkit::npapi::PluginList::Singleton()->RegisterInternalPlugin(info);
PluginService::GetInstance()->RefreshPluginList();
PluginService::GetInstance()->GetPlugins(base::Bind(&QuitMessageLoop));
MessageLoop::current()->RunAllPending();
}
void UnregisterPDFPlugin() {
webkit::npapi::PluginList::Singleton()->UnregisterInternalPlugin(pdf_path_);
PluginService::GetInstance()->RefreshPluginList();
PluginService::GetInstance()->GetPlugins(base::Bind(&QuitMessageLoop));
MessageLoop::current()->RunAllPending();
}
void SetPDFPluginLoadedState(bool want_loaded) {
webkit::WebPluginInfo info;
bool is_loaded = PluginService::GetInstance()->GetPluginInfoByPath(
pdf_path_, &info);
if (is_loaded && !want_loaded) {
UnregisterPDFPlugin();
is_loaded = PluginService::GetInstance()->GetPluginInfoByPath(
pdf_path_, &info);
} else if (!is_loaded && want_loaded) {
// This "loads" the plug-in even if it's not present on the
// system - which is OK since we don't actually use it, just
// need it to be "enabled" for the test.
RegisterPDFPlugin();
is_loaded = PluginService::GetInstance()->GetPluginInfoByPath(
pdf_path_, &info);
}
EXPECT_EQ(want_loaded, is_loaded);
}
void SetupRequest(net::URLRequest* request) {
content::ResourceContext* context =
content::MockResourceContext::GetInstance();
ResourceDispatcherHostRequestInfo* info =
new ResourceDispatcherHostRequestInfo(handler_,
ChildProcessInfo::RENDER_PROCESS,
-1, // child_id
MSG_ROUTING_NONE,
0, // origin_pid
request->identifier(),
false, // is_main_frame
-1, // frame_id
ResourceType::MAIN_FRAME,
content::PAGE_TRANSITION_LINK,
0, // upload_size
false, // is_download
true, // allow_download
false, // has_user_gesture
context);
request->SetUserData(NULL, info);
request->set_context(context->request_context());
}
protected:
MessageLoopForIO message_loop_;
content::TestBrowserThread ui_thread_;
content::TestBrowserThread file_thread_;
content::TestBrowserThread io_thread_;
TestingPrefService prefs_;
scoped_refptr<PluginPrefs> plugin_prefs_;
net::URLRequestJobFactory job_factory_;
const net::URLRequestJobFactory* old_factory_;
scoped_refptr<ResourceHandler> handler_;
TestDelegate test_delegate_;
FilePath pdf_path_;
};
TEST_F(GViewRequestInterceptorTest, DoNotInterceptHtml) {
net::URLRequest request(GURL(kHtmlUrl), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(0, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kHtmlUrl), request.url());
}
TEST_F(GViewRequestInterceptorTest, DoNotInterceptDownload) {
net::URLRequest request(GURL(kPdfUrl), &test_delegate_);
SetupRequest(&request);
request.set_load_flags(net::LOAD_IS_DOWNLOAD);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(0, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfUrl), request.url());
}
TEST_F(GViewRequestInterceptorTest, DISABLED_DoNotInterceptPdfWhenEnabled) {
SetPDFPluginLoadedState(true);
plugin_prefs_->EnablePlugin(true, pdf_path_);
net::URLRequest request(GURL(kPdfUrl), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(0, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfUrl), request.url());
}
TEST_F(GViewRequestInterceptorTest, DISABLED_InterceptPdfWhenDisabled) {
SetPDFPluginLoadedState(true);
plugin_prefs_->EnablePlugin(false, pdf_path_);
net::URLRequest request(GURL(kPdfUrl), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(1, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfUrlIntercepted), request.url());
}
TEST_F(GViewRequestInterceptorTest, InterceptPdfWithNoPlugin) {
SetPDFPluginLoadedState(false);
net::URLRequest request(GURL(kPdfUrl), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(1, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfUrlIntercepted), request.url());
}
TEST_F(GViewRequestInterceptorTest, InterceptPowerpoint) {
net::URLRequest request(GURL(kPptUrl), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(1, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPptUrlIntercepted), request.url());
}
TEST_F(GViewRequestInterceptorTest, DoNotInterceptPost) {
SetPDFPluginLoadedState(false);
net::URLRequest request(GURL(kPdfUrl), &test_delegate_);
SetupRequest(&request);
request.set_method("POST");
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(0, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfUrl), request.url());
}
TEST_F(GViewRequestInterceptorTest, DoNotInterceptBlob) {
SetPDFPluginLoadedState(false);
net::URLRequest request(GURL(kPdfBlob), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(0, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfBlob), request.url());
}
} // namespace
} // namespace chromeos
<|endoftext|> |
<commit_before>#ifndef V_SMC_CORE_MONITOR_HPP
#define V_SMC_CORE_MONITOR_HPP
#include <vSMC/internal/common.hpp>
namespace vSMC {
/// \brief Monitor for Monte Carlo integration
///
/// \tparam T State state type. Requiment:
/// \li Consturctor: T (IntType N)
/// \li Method: copy (IntType from, IntType to)
template <typename T>
class Monitor
{
public :
/// The type of monitor integral functor
typedef internal::function<void (std::size_t, Particle<T> &, double *)>
integral_type;
/// The type of the index vector
typedef std::vector<std::size_t> index_type;
/// The type of the record vector
typedef std::vector<Eigen::VectorXd> record_type;
/// \brief Construct a Monitor with an integral function
///
/// \param dim The dimension of the monitor, i.e., the number of variables
/// \param integral The functor used to compute the integrands
explicit Monitor (unsigned dim = 1, const integral_type &integral = NULL) :
dim_(dim), integral_(integral) {}
/// \brief Copy constructor
///
/// \param monitor The Monitor to by copied
Monitor (const Monitor<T> &monitor) :
dim_(monitor.dim_), integral_(monitor.integral_),
index_(monitor.index_), record_(monitor.record_) {}
/// \brief Assignment operator
///
/// \param monitor The Monitor to be assigned
///
/// \return The Monitor after assignemnt
Monitor<T> & operator= (const Monitor<T> &monitor)
{
if (&monitor != this) {
dim_ = monitor.dim_;
integral_ = monitor.integral_;
index_ = monitor.index_;
record_ = monitor.record_;
}
return *this;
}
/// \brief Dimension of the monitor
///
/// \return The number of parameters
unsigned dim () const
{
return dim_;
}
/// \brief Size of records
///
/// \return The number of iterations recorded
index_type::size_type iter_size () const
{
return index_.size();
}
/// \brief Set the integral functor
///
/// \param dim The dimension of the monitor
/// \param integral The functor used to compute the integrands
void integral (unsigned dim, const integral_type &integral)
{
dim_ = dim;
integral_ = integral;
}
/// \brief Test if the monitor is empty
///
/// \return \b true if the monitor is empty
bool empty () const
{
return !bool(integral_);
}
/// \brief Iteration index
///
/// \return A const reference to the index
const index_type &index () const
{
return index_;
}
/// \brief Record of Monte Carlo integration
///
/// \return A const reference to the record
const record_type &record () const
{
return record_;
}
/// \brief Evaluate the integration
///
/// \param iter The iteration number
/// \param particle The particle set to be operated on by eval()
///
/// \note The integral function has to be set through either the
/// constructor or integral() to a non-NULL value before calling eval().
/// Otherwise exception will be raised when calling eval().
void eval (std::size_t iter, Particle<T> &particle)
{
#ifdef EIGEN_DEFAULT_TO_ROW_MAJOR
buffer_.resize(particle.size(), dim_);
#else
buffer_.resize(dim_, particle.size());
#endif
integral_(iter, particle, buffer_.data());
#ifdef EIGEN_DEFAULT_TO_ROW_MAJOR
result_.noalias() = buffer_.transpose() * particle.weight();
#else
result_.noalias() = buffer_ * particle.weight();
#endif
index_.push_back(iter);
record_.push_back(result_);
}
/// \brief Clear all recorded data
///
/// \note The integral function is not reset
void clear ()
{
index_.clear();
record_.clear();
}
private :
Eigen::MatrixXd buffer_;
Eigen::VectorXd result_;
unsigned dim_;
integral_type integral_;
index_type index_;
record_type record_;
}; // class Monitor
} // namespace vSMC
#endif // V_SMC_CORE_MONITOR_HPP
<commit_msg>remove support for EIGEN_DEFAULT_TO_ROW_MAJOR<commit_after>#ifndef V_SMC_CORE_MONITOR_HPP
#define V_SMC_CORE_MONITOR_HPP
#include <vSMC/internal/common.hpp>
namespace vSMC {
/// \brief Monitor for Monte Carlo integration
///
/// \tparam T State state type. Requiment:
/// \li Consturctor: T (IntType N)
/// \li Method: copy (IntType from, IntType to)
template <typename T>
class Monitor
{
public :
/// The type of monitor integral functor
typedef internal::function<void (std::size_t, Particle<T> &, double *)>
integral_type;
/// The type of the index vector
typedef std::vector<std::size_t> index_type;
/// The type of the record vector
typedef std::vector<Eigen::VectorXd> record_type;
/// \brief Construct a Monitor with an integral function
///
/// \param dim The dimension of the monitor, i.e., the number of variables
/// \param integral The functor used to compute the integrands
explicit Monitor (unsigned dim = 1, const integral_type &integral = NULL) :
dim_(dim), integral_(integral) {}
/// \brief Copy constructor
///
/// \param monitor The Monitor to by copied
Monitor (const Monitor<T> &monitor) :
dim_(monitor.dim_), integral_(monitor.integral_),
index_(monitor.index_), record_(monitor.record_) {}
/// \brief Assignment operator
///
/// \param monitor The Monitor to be assigned
///
/// \return The Monitor after assignemnt
Monitor<T> & operator= (const Monitor<T> &monitor)
{
if (&monitor != this) {
dim_ = monitor.dim_;
integral_ = monitor.integral_;
index_ = monitor.index_;
record_ = monitor.record_;
}
return *this;
}
/// \brief Dimension of the monitor
///
/// \return The number of parameters
unsigned dim () const
{
return dim_;
}
/// \brief Size of records
///
/// \return The number of iterations recorded
index_type::size_type iter_size () const
{
return index_.size();
}
/// \brief Set the integral functor
///
/// \param dim The dimension of the monitor
/// \param integral The functor used to compute the integrands
void integral (unsigned dim, const integral_type &integral)
{
dim_ = dim;
integral_ = integral;
}
/// \brief Test if the monitor is empty
///
/// \return \b true if the monitor is empty
bool empty () const
{
return !bool(integral_);
}
/// \brief Iteration index
///
/// \return A const reference to the index
const index_type &index () const
{
return index_;
}
/// \brief Record of Monte Carlo integration
///
/// \return A const reference to the record
const record_type &record () const
{
return record_;
}
/// \brief Evaluate the integration
///
/// \param iter The iteration number
/// \param particle The particle set to be operated on by eval()
///
/// \note The integral function has to be set through either the
/// constructor or integral() to a non-NULL value before calling eval().
/// Otherwise exception will be raised when calling eval().
void eval (std::size_t iter, Particle<T> &particle)
{
buffer_.resize(dim_, particle.size());
integral_(iter, particle, buffer_.data());
result_.noalias() = buffer_ * particle.weight();
index_.push_back(iter);
record_.push_back(result_);
}
/// \brief Clear all recorded data
///
/// \note The integral function is not reset
void clear ()
{
index_.clear();
record_.clear();
}
private :
Eigen::MatrixXd buffer_;
Eigen::VectorXd result_;
unsigned dim_;
integral_type integral_;
index_type index_;
record_type record_;
}; // class Monitor
} // namespace vSMC
#endif // V_SMC_CORE_MONITOR_HPP
<|endoftext|> |
<commit_before>#ifndef BULL_CORE_PREREQUISITES_HPP
#define BULL_CORE_PREREQUISITES_HPP
#include <cstdint>
#define BULL_COMPILER_MSC 1
#define BULL_COMPILER_GCC 2
#define BULL_COMPILER_INTEL 3
#define BULL_COMPILER_CLANG 4
#define BULL_COMPILER_MINGW_32 5
#define BULL_COMPILER_MINGW_64 6
#if defined _MSC_VER
#define BULL_COMPILER BULL_COMPILER_MSC
#elif defined __GNUC__
#define BULL_COMPILER BULL_COMPILER_GCC
#define BULL_COMPILER_VERSION __GNUC__
#elif defined __MINGW32__
#define BULL_COMPILER BULL_COMPILER_MINGW_32
#elif defined __MINGW64__
#define BULL_COMPILER BULL_COMPILER_MINGW_64
#else
#error Unsupported compiler
#endif
#if defined _WIN32
#define BULL_OS_WINDOWS
#define BULL_WINDOWS_8 0x0602
#define BULL_WINDOWS_7 0x0601
#define BULL_WINDOWS_VISTA 0x0600
#define BULL_WINDOWS_XP 0x0501 // Defined but not planed to be used
#if defined BULL_BUILD_WINDOWS_8
#define BULL_WINDOWS_VERSION BULL_WINDOWS_8
#elif defined BULL_BUILD_WINDOWS_7
#define BULL_WINDOWS_VERSION BULL_WINDOWS_7
#elif defined BULL_BUILD_WINDOWS_VISTA
#define BULL_WINDOWS_VERSION BULL_WINDOWS_VISTA
#else
#error Windows XP is not supported
#endif
#elif defined __FreeBSD__
#define BULL_OS_FREEBSD
#define BULL_OS_UNIX
#elif defined __gnu_linux__
#define BULL_OS_UNIX
#define BULL_OS_GNU_LINUX
#elif defined __APPLE__ && __MACH__
#define BULL_OS_OSX
#define BULL_OS_UNIX
#else
#error Your system is not supported by Bull
#endif
#if defined BULL_DYNAMIC
#if defined BULL_OS_WINDOWS
#define BULL_API_EXPORT __declspec(dllexport)
#define BULL_API_IMPORT __declspec(dllimport)
#else
#if BULL_COMPLER == BULL_COMPILER_GCC
#if BULL_COMPILER_VERSION >= 4
#define BULL_API_EXPORT __attribute__ ((__visibility__ ("default")))
#define BULL_API_IMPORT __attribute__ ((__visibility__ ("default")))
#else
#define BULL_API_EXPORT
#define BULL_API_IMPORT
#endif
#endif
#endif
#else
#define BULL_API_EXPORT
#define BULL_API_IMPORT
#endif
#ifndef BULL_ZERO_MEMORY
#ifndef BULL_HAS_CSTRING
#include <cstring>
#define BULL_HAS_CSTRING
#endif
#define BULL_ZERO_MEMORY(Object) std::memset(&(Object), 0, sizeof(decltype(Object)))
#endif
#ifndef BULL_ZERO_MEMORY_PTR
#ifndef BULL_HAS_CSTRING
#include <cstring>
#define BULL_HAS_CSTRING
#endif
#define BULL_ZERO_MEMORY_PTR(Pointer, Length) std::memset(Pointer, 0, Length)
#endif
#ifndef BULL_UNUSED
#define BULL_UNUSED(Variable) (void)Variable
#endif
namespace Bull
{
typedef int8_t Int8;
typedef int16_t Int16;
typedef int32_t Int32;
typedef int64_t Int64;
typedef uint8_t Uint8;
typedef uint16_t Uint16;
typedef uint32_t Uint32;
typedef uint64_t Uint64;
}
#endif // BULL_CORE_PREREQUISITES_HPP
<commit_msg>[Core/Prerequisites] Improve Mingw support<commit_after>#ifndef BULL_CORE_PREREQUISITES_HPP
#define BULL_CORE_PREREQUISITES_HPP
#include <cstdint>
#include <cstring>
#define BULL_COMPILER_MSC 1
#define BULL_COMPILER_GCC 2
#define BULL_COMPILER_MINGW_32 5
#define BULL_COMPILER_MINGW_64 6
#if defined _MSC_VER
#define BULL_COMPILER BULL_COMPILER_MSC
#elif defined __GNUC__
#if defined __MINGW32__ && defined __MINGW64__
#define BULL_COMPILER BULL_COMPILER_MINGW_64
#define BULL_COMPILER_VERSION_MAJOR __MINGW64_VERSION_MAJOR
#define BULL_COMPILER_VERSION_MINOR __MINGW64_VERSION_MINOR
#define BULL_COMPILER_VERSION_BUGFIX __MINGW64_VERSION_BUGFIX
#define BULL_COMPILER_VERSION_STRING __MINGW64_VERSION_STR
#elif defined __MINGW32__
#define BULL_COMPILER BULL_COMPILER_MINGW_32
#define BULL_COMPILER_VERSION_MAJOR __MINGW32_VERSION_MAJOR
#define BULL_COMPILER_VERSION_MINOR __MINGW32_VERSION_MINOR
#define BULL_COMPILER_VERSION_BUGFIX __MINGW32_VERSION_BUGFIX
#define BULL_COMPILER_VERSION_STRING __MINGW32_VERSION_STR
#else
#define BULL_COMPILER BULL_COMPILER_GCC
#endif
#else
#warning Unsupported compiler
#endif
#if defined _WIN32
#define BULL_OS_WINDOWS
#define BULL_WINDOWS_8 0x0602
#define BULL_WINDOWS_7 0x0601
#define BULL_WINDOWS_VISTA 0x0600
#define BULL_WINDOWS_XP 0x0501 // Defined but not planed to be used
#if defined BULL_BUILD_WINDOWS_8
#define BULL_WINDOWS_VERSION BULL_WINDOWS_8
#elif defined BULL_BUILD_WINDOWS_7
#define BULL_WINDOWS_VERSION BULL_WINDOWS_7
#elif defined BULL_BUILD_WINDOWS_VISTA
#define BULL_WINDOWS_VERSION BULL_WINDOWS_VISTA
#else
#error Windows XP is not supported
#endif
#elif defined __FreeBSD__
#define BULL_OS_FREEBSD
#define BULL_OS_UNIX
#elif defined __gnu_linux__
#define BULL_OS_UNIX
#define BULL_OS_GNU_LINUX
#elif defined __APPLE__ && __MACH__
#define BULL_OS_OSX
#define BULL_OS_UNIX
#else
#error Your system is not supported by Bull
#endif
#if defined BULL_DYNAMIC
#if defined BULL_OS_WINDOWS
#define BULL_API_EXPORT __declspec(dllexport)
#define BULL_API_IMPORT __declspec(dllimport)
#else
#if BULL_COMPLER == BULL_COMPILER_GCC
#if BULL_COMPILER_VERSION >= 4
#define BULL_API_EXPORT __attribute__ ((__visibility__ ("default")))
#define BULL_API_IMPORT __attribute__ ((__visibility__ ("default")))
#else
#define BULL_API_EXPORT
#define BULL_API_IMPORT
#endif
#endif
#endif
#else
#define BULL_API_EXPORT
#define BULL_API_IMPORT
#endif
#ifndef BULL_ZERO_MEMORY
#define BULL_ZERO_MEMORY(Object) std::memset(&(Object), 0, sizeof(decltype(Object)))
#endif
#ifndef BULL_ZERO_MEMORY_PTR
#define BULL_ZERO_MEMORY_PTR(Pointer, Length) std::memset(Pointer, 0, Length)
#endif
#ifndef BULL_UNUSED
#define BULL_UNUSED(Variable) (void)Variable
#endif
namespace Bull
{
typedef int8_t Int8;
typedef int16_t Int16;
typedef int32_t Int32;
typedef int64_t Int64;
typedef uint8_t Uint8;
typedef uint16_t Uint16;
typedef uint32_t Uint32;
typedef uint64_t Uint64;
}
#endif // BULL_CORE_PREREQUISITES_HPP
<|endoftext|> |
<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGColumnVector3.cpp
Author: Originally by Tony Peden [formatted here by JSB]
Date started: 1998
Purpose: FGColumnVector3 class
Called by: Various
------------- Copyright (C) 1998 Tony Peden and Jon S. Berndt ([email protected]) -
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU Lesser General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
HISTORY
--------------------------------------------------------------------------------
??/??/?? TP Created
03/16/2000 JSB Added exception throwing
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGColumnVector3.h"
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cmath>
using namespace std;
namespace JSBSim {
static const char *IdSrc = "$Id: FGColumnVector3.cpp,v 1.14 2010/12/07 12:57:14 jberndt Exp $";
static const char *IdHdr = ID_COLUMNVECTOR3;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGColumnVector3::FGColumnVector3(void)
{
data[0] = data[1] = data[2] = 0.0;
// Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
string FGColumnVector3::Dump(const string& delimiter) const
{
ostringstream buffer;
buffer << std::setw(18) << std::setprecision(16) << data[0] << delimiter;
buffer << std::setw(18) << std::setprecision(16) << data[1] << delimiter;
buffer << std::setw(18) << std::setprecision(16) << data[2];
return buffer.str();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ostream& operator<<(ostream& os, const FGColumnVector3& col)
{
os << col(1) << " , " << col(2) << " , " << col(3);
return os;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGColumnVector3 FGColumnVector3::operator/(const double scalar) const
{
if (scalar != 0.0)
return operator*( 1.0/scalar );
cerr << "Attempt to divide by zero in method \
FGColumnVector3::operator/(const double scalar), \
object " << data[0] << " , " << data[1] << " , " << data[2] << endl;
return FGColumnVector3();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGColumnVector3& FGColumnVector3::operator/=(const double scalar)
{
if (scalar != 0.0)
operator*=( 1.0/scalar );
else
cerr << "Attempt to divide by zero in method \
FGColumnVector3::operator/=(const double scalar), \
object " << data[0] << " , " << data[1] << " , " << data[2] << endl;
return *this;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double FGColumnVector3::Magnitude(void) const
{
return sqrt( data[0]*data[0] + data[1]*data[1] + data[2]*data[2] );
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGColumnVector3& FGColumnVector3::Normalize(void)
{
double Mag = Magnitude();
if (Mag != 0.0)
operator*=( 1.0/Mag );
return *this;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double FGColumnVector3::Magnitude(const int idx1, const int idx2) const {
return sqrt( data[idx1-1]*data[idx1-1] + data[idx2-1]*data[idx2-1] );
}
} // namespace JSBSim
<commit_msg>Remove superfluous field widths from Dump method. They were originally added for sprintf buffer handling.<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGColumnVector3.cpp
Author: Originally by Tony Peden [formatted here by JSB]
Date started: 1998
Purpose: FGColumnVector3 class
Called by: Various
------------- Copyright (C) 1998 Tony Peden and Jon S. Berndt ([email protected]) -
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU Lesser General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
HISTORY
--------------------------------------------------------------------------------
??/??/?? TP Created
03/16/2000 JSB Added exception throwing
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGColumnVector3.h"
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cmath>
using namespace std;
namespace JSBSim {
static const char *IdSrc = "$Id: FGColumnVector3.cpp,v 1.15 2012/02/07 00:27:51 jentron Exp $";
static const char *IdHdr = ID_COLUMNVECTOR3;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGColumnVector3::FGColumnVector3(void)
{
data[0] = data[1] = data[2] = 0.0;
// Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
string FGColumnVector3::Dump(const string& delimiter) const
{
ostringstream buffer;
buffer << std::setprecision(16) << data[0] << delimiter;
buffer << std::setprecision(16) << data[1] << delimiter;
buffer << std::setprecision(16) << data[2];
return buffer.str();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ostream& operator<<(ostream& os, const FGColumnVector3& col)
{
os << col(1) << " , " << col(2) << " , " << col(3);
return os;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGColumnVector3 FGColumnVector3::operator/(const double scalar) const
{
if (scalar != 0.0)
return operator*( 1.0/scalar );
cerr << "Attempt to divide by zero in method \
FGColumnVector3::operator/(const double scalar), \
object " << data[0] << " , " << data[1] << " , " << data[2] << endl;
return FGColumnVector3();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGColumnVector3& FGColumnVector3::operator/=(const double scalar)
{
if (scalar != 0.0)
operator*=( 1.0/scalar );
else
cerr << "Attempt to divide by zero in method \
FGColumnVector3::operator/=(const double scalar), \
object " << data[0] << " , " << data[1] << " , " << data[2] << endl;
return *this;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double FGColumnVector3::Magnitude(void) const
{
return sqrt( data[0]*data[0] + data[1]*data[1] + data[2]*data[2] );
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGColumnVector3& FGColumnVector3::Normalize(void)
{
double Mag = Magnitude();
if (Mag != 0.0)
operator*=( 1.0/Mag );
return *this;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double FGColumnVector3::Magnitude(const int idx1, const int idx2) const {
return sqrt( data[idx1-1]*data[idx1-1] + data[idx2-1]*data[idx2-1] );
}
} // namespace JSBSim
<|endoftext|> |
<commit_before>#ifndef V_SMC_CORE_SAMPLER_HPP
#define V_SMC_CORE_SAMPLER_HPP
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vSMC/internal/common.hpp>
namespace vSMC {
/// \brief SMC Sampler
template <typename T>
class Sampler
{
public :
/// The type of initialization functor
typedef internal::function<std::size_t (Particle<T> &, void *)>
initialize_type;
/// The type of move functor
typedef internal::function<std::size_t (std::size_t, Particle<T> &)>
move_type;
/// The type ESS history vector
typedef std::vector<double> ess_type;
/// The type resampling history vector
typedef std::vector<bool> resampled_type;
/// The type accept count history vector
typedef std::vector<std::size_t> accept_type;
/// \brief Construct a sampler with given number of particles
///
/// \param N The number of particles
/// \param init The functor used to initialize the particles
/// \param move The functor used to move the particles and weights
/// \param mcmc The functor used to perform MCMC move
/// \param scheme The resampling scheme. See ResampleScheme
/// \param threshold The threshold for performing resampling
/// \param seed The seed to the parallel RNG system
explicit Sampler (
std::size_t N,
const initialize_type &init = NULL,
const move_type &move = NULL,
const move_type &mcmc = NULL,
ResampleScheme scheme = STRATIFIED,
double threshold = 0.5,
typename Particle<T>::seed_type seed = V_SMC_CRNG_SEED) :
initialized_(false), init_(init), move_(move), mcmc_(mcmc),
scheme_(scheme), threshold_(threshold * N),
particle_(N, seed), iter_num_(0)
{
particle_.sampler(this);
}
/// \brief Size of the particle set
///
/// \return The number of particles
std::size_t size () const
{
return particle_.size();
}
/// \brief Size of records
///
/// \return The number of iterations recorded (including the
/// initialization step)
std::size_t iter_size () const
{
return ess_.size();
}
/// \brief Get the current resampling scheme
///
/// \return The current resampling scheme
ResampleScheme resample_scheme () const
{
return scheme_;
}
/// \brief Set new resampling scheme
///
/// \param scheme The new scheme for resampling
void resample_scheme (ResampleScheme scheme)
{
scheme_ = scheme;
}
/// \brief Get the current threshold
///
/// \return The current threshold for resmapling
double resample_threshold () const
{
return threshold_;
}
/// \brief Set new resampling threshold
///
/// \param threshold The new threshold for resampling
void resample_threshold (double threshold)
{
threshold_ = threshold * particle_.size();
}
/// \brief ESS
///
/// \return The ESS value of the latest iteration
ess_type::value_type ess () const
{
return ess_.back();
}
/// \brief ESS history
///
/// \return A const reference to the history of ESS
const ess_type &ess_history () const
{
return ess_;
}
/// \brief Indicator of resampling
///
/// \return A bool value, \b true if the latest iteration was resampled
resampled_type::value_type resampled () const
{
return resampled_.back();
}
/// \brief Resampling history
///
/// \return A const reference to the history of resampling
const resampled_type &resampled_history () const
{
return resampled_;
}
/// \brief Accept count
///
/// \return The accept count of the latest iteration
accept_type::value_type accept () const
{
return accept_.back();
}
/// \brief Accept count history
///
/// \return A const reference to the history of accept count
const accept_type &accept_history () const
{
return accept_;
}
/// \brief Read and write access to the particle set
///
/// \return A reference to the latest particle set
///
/// \note When the system changes, this reference may be invalidated
Particle<T> &particle ()
{
return particle_;
}
/// \brief Read only access to the particle set
///
/// \return A const reference to the latest particle set.
///
/// \note When the system changes, this reference may be invalidated
const Particle<T> &particle () const
{
return particle_;
}
/// \brief Replace initialization functor
///
/// \param init New Initialization functor
void initialize (initialize_type &init)
{
init_ = init;
}
/// \brief Initialize the particle set
///
/// \param param Additional parameters passed to the initialization
/// functor
void initialize (void *param = NULL)
{
ess_.clear();
resampled_.clear();
accept_.clear();
path_.clear();
for (typename std::map<std::string, Monitor<T> >::iterator
imap = monitor_.begin(); imap != monitor_.end(); ++imap)
imap->second.clear();
iter_num_ = 0;
accept_.push_back(init_(particle_, param));
post_move();
particle_.reset_zconst();
initialized_ = true;
}
/// \brief Replace iteration functor
///
/// \param move New Move functor
/// \param mcmc New MCMC functor
void iterate (const move_type &move, const move_type &mcmc = NULL)
{
move_ = move;
mcmc_ = mcmc;
}
/// \brief Perform iteration
void iterate ()
{
assert(initialized_);
++iter_num_;
accept_.push_back(move_(iter_num_, particle_));
if (bool(mcmc_))
accept_.back() = mcmc_(iter_num_, particle_);
post_move();
}
/// \brief Perform iteration
///
/// \param n The number of iterations to be performed
void iterate (std::size_t n)
{
for (std::size_t i = 0; i != n; ++i)
iterate();
}
/// \brief Perform importance sampling integration
///
/// \param integral The functor used to compute the integrands
/// \param res The result, an array of length dim
template<typename MonitorType>
void integrate (const MonitorType &integral, double *res)
{
Monitor<T> m(integral.dim(), integral);
m.eval(iter_num_, particle_);
Eigen::Map<Eigen::VectorXd> r(res, m.dim());
r = m.record().back();
}
/// \brief Perform importance sampling integration
///
/// \param dim The dimension of the parameter
/// \param integral The functor used to compute the integrands
/// \param res The result, an array of length dim
void integrate (unsigned dim,
const typename Monitor<T>::integral_type &integral, double *res)
{
Monitor<T> m(dim, integral);
m.eval(iter_num_, particle_);
Eigen::Map<Eigen::VectorXd> r(res, m.dim());
r = m.record().back();
}
/// \brief Add a monitor, similar to \b monitor in \b BUGS
///
/// \param name The name of the monitor
/// \param integral The functor used to compute the integrands
template<typename MonitorType>
void monitor (const std::string &name, const MonitorType &integral)
{
monitor_.insert(std::make_pair(
name, Monitor<T>(integral.dim(), integral)));
monitor_name_.insert(name);
}
/// \brief Add a monitor, similar to \b monitor in \b BUGS
///
/// \param name The name of the monitor
/// \param dim The dimension of the monitor
/// \param integral The functor used to compute the integrands
void monitor (const std::string &name, unsigned dim,
const typename Monitor<T>::integral_type &integral)
{
monitor_.insert(std::make_pair(name, Monitor<T>(dim, integral)));
monitor_name_.insert(name);
}
/// \brief Read only access to a named monitor through iterator
///
/// \param name The name of the monitor
///
/// \return An const_iterator point to the monitor for the given name
///
/// \note When the system changes, this reference may be invalidated
typename std::map<std::string, Monitor<T> >::const_iterator
monitor (const std::string &name) const
{
return monitor_.find(name);
}
/// \brief Read only access to all monitors
///
/// \return A const reference to monitors
///
/// \note When the system changes, this reference may be invalidated
const std::map<std::string, Monitor<T> > &monitor () const
{
return monitor_;
}
/// \brief Erase a named monitor
///
/// \param name The name of the monitor
void clear_monitor (const std::string &name)
{
monitor_.erase(name);
monitor_name_.erase(name);
}
/// \brief Erase all monitors
void clear_monitor ()
{
monitor_.clear();
monitor_name_.clear();
}
/// \brief Read only access to the Path sampling monitor
///
/// \return A const reference to the Path sampling monitor
///
/// \note When the system changes, this reference may be invalidated
const Path<T> &path () const
{
return path_;
}
/// \brief Set the path sampling integral
///
/// \param integral The functor used to compute the integrands
///
/// \note Set integral = NULL will stop path sampling recording
void path_sampling (const typename Path<T>::integral_type &integral)
{
path_.integral(integral);
}
/// \brief Path sampling estimate of normalizing constant
///
/// \return The log ratio of normalizing constants
double path_sampling () const
{
return path_.zconst();
}
/// \brief SMC estimate of normalizing constant
///
/// \return The log of SMC normalizng constant estimate
double zconst () const
{
return particle_.zconst();
}
/// \brief Print the history of the sampler
///
/// \param os The ostream to which the contents are printed
/// \param print_header Print header if \b true
void print (std::ostream &os = std::cout, bool print_header = true) const
{
print(os, print_header, !path_.index().empty(), monitor_name_);
}
/// \brief Print the history of the sampler
///
/// \param os The ostream to which the contents are printed
/// \param print_path Print path sampling history if \b true
/// \param print_monitor A set of monitor names to be printed
/// \param print_header Print header if \b true
void print (std::ostream &os, bool print_header, bool print_path,
const std::set<std::string> &print_monitor) const
{
if (print_header) {
os << "iter\tESS\tresample\taccept\t";
if (print_path)
os << "path.integrand\tpath.width\tpath.grid\t";
}
typename Path<T>::index_type::const_iterator iter_path_index
= path_.index().begin();
typename Path<T>::integrand_type::const_iterator iter_path_integrand
= path_.integrand().begin();
typename Path<T>::width_type::const_iterator iter_path_width
= path_.width().begin();
typename Path<T>::grid_type::const_iterator iter_path_grid
= path_.grid().begin();
std::vector<bool> monitor_index_empty;
std::vector<unsigned> monitor_dim;
std::vector<typename Monitor<T>::index_type::const_iterator>
iter_monitor_index;
std::vector<typename Monitor<T>::record_type::const_iterator>
iter_monitor_record;
for (typename std::map<std::string, Monitor<T> >::const_iterator
imap = monitor_.begin(); imap != monitor_.end(); ++imap) {
if (print_monitor.count(imap->first)) {
monitor_index_empty.push_back(imap->second.index().empty());
monitor_dim.push_back(imap->second.dim());
iter_monitor_index.push_back(imap->second.index().begin());
iter_monitor_record.push_back(imap->second.record().begin());
if (print_header) {
if (monitor_dim.back() > 1) {
for (unsigned d = 0; d != monitor_dim.back(); ++d)
os << imap->first << d + 1 << '\t';
} else {
os << imap->first << '\t';
}
}
}
}
if (print_header)
os << '\n';
for (std::size_t i = 0; i != iter_size(); ++i) {
os
<< i << '\t' << ess_[i] / size()
<< '\t' << resampled_[i]
<< '\t' << static_cast<double>(accept_[i]) / size();
if (print_path) {
if (!path_.index().empty() && *iter_path_index == i) {
os
<< '\t' << *iter_path_integrand++
<< '\t' << *iter_path_width++
<< '\t' << *iter_path_grid++;
++iter_path_index;
} else {
os << '\t' << '.' << '\t' << '.' << '\t' << '.';
}
}
for (std::size_t m = 0; m != monitor_index_empty.size(); ++m) {
if (!monitor_index_empty[m] && *iter_monitor_index[m] == i) {
for (unsigned d = 0; d != monitor_dim[m]; ++d)
os << '\t' << (*iter_monitor_record[m])[d];
++iter_monitor_index[m];
++iter_monitor_record[m];
} else {
for (unsigned d = 0; d != monitor_dim[m]; ++d)
os << '\t' << '.';
}
}
if (i != iter_size() - 1)
os << '\n';
}
}
private :
/// Initialization indicator
bool initialized_;
/// Initialization and movement
initialize_type init_;
move_type move_;
move_type mcmc_;
/// Resampling
ResampleScheme scheme_;
double threshold_;
/// Particle sets
Particle<T> particle_;
std::size_t iter_num_;
ess_type ess_;
resampled_type resampled_;
accept_type accept_;
/// Monte Carlo estimation by integration
std::map<std::string, Monitor<T> > monitor_;
std::set<std::string> monitor_name_;
/// Path sampling
Path<T> path_;
void post_move ()
{
ess_.push_back(particle_.ess());
particle_.resampled(ess_.back() < threshold_);
resampled_.push_back(particle_.resampled());
if (particle_.resampled()) {
particle_.resample(scheme_);
ess_.back() = particle_.size();
}
if (!path_.empty())
path_.eval(iter_num_, particle_);
for (typename std::map<std::string, Monitor<T> >::iterator
imap = monitor_.begin(); imap != monitor_.end(); ++imap) {
if (!imap->second.empty())
imap->second.eval(iter_num_, particle_);
}
}
}; // class Sampler
} // namespace vSMC
namespace std {
/// \brief Print the sampler
///
/// \param os The ostream to which the contents are printed
/// \param sampler The sampler to be printed
///
/// \note This is the same as <tt>sampler.print(os)</tt>
template<typename T>
std::ostream & operator<< (std::ostream &os, const vSMC::Sampler<T> &sampler)
{
sampler.print(os);
return os;
}
} // namespace std
#endif // V_SMC_CORE_SAMPLER_HPP
<commit_msg>use Particle<T>::size_type for Sampler constructor;<commit_after>#ifndef V_SMC_CORE_SAMPLER_HPP
#define V_SMC_CORE_SAMPLER_HPP
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vSMC/internal/common.hpp>
namespace vSMC {
/// \brief SMC Sampler
template <typename T>
class Sampler
{
public :
/// The type of initialization functor
typedef internal::function<std::size_t (Particle<T> &, void *)>
initialize_type;
/// The type of move functor
typedef internal::function<std::size_t (std::size_t, Particle<T> &)>
move_type;
/// The type ESS history vector
typedef std::vector<double> ess_type;
/// The type resampling history vector
typedef std::vector<bool> resampled_type;
/// The type accept count history vector
typedef std::vector<std::size_t> accept_type;
/// \brief Construct a sampler with given number of particles
///
/// \param N The number of particles
/// \param init The functor used to initialize the particles
/// \param move The functor used to move the particles and weights
/// \param mcmc The functor used to perform MCMC move
/// \param scheme The resampling scheme. See ResampleScheme
/// \param threshold The threshold for performing resampling
/// \param seed The seed to the parallel RNG system
explicit Sampler (
typename Particle<T>::size_type N,
const initialize_type &init = NULL,
const move_type &move = NULL,
const move_type &mcmc = NULL,
ResampleScheme scheme = STRATIFIED,
double threshold = 0.5,
typename Particle<T>::seed_type seed = V_SMC_CRNG_SEED) :
initialized_(false), init_(init), move_(move), mcmc_(mcmc),
scheme_(scheme), threshold_(threshold * N),
particle_(N, seed), iter_num_(0)
{
particle_.sampler(this);
}
/// \brief Size of the particle set
///
/// \return The number of particles
typename Particle<T>::size_type size () const
{
return particle_.size();
}
/// \brief Size of records
///
/// \return The number of iterations recorded (including the
/// initialization step)
std::size_t iter_size () const
{
return ess_.size();
}
/// \brief Get the current resampling scheme
///
/// \return The current resampling scheme
ResampleScheme resample_scheme () const
{
return scheme_;
}
/// \brief Set new resampling scheme
///
/// \param scheme The new scheme for resampling
void resample_scheme (ResampleScheme scheme)
{
scheme_ = scheme;
}
/// \brief Get the current threshold
///
/// \return The current threshold for resmapling
double resample_threshold () const
{
return threshold_;
}
/// \brief Set new resampling threshold
///
/// \param threshold The new threshold for resampling
void resample_threshold (double threshold)
{
threshold_ = threshold * particle_.size();
}
/// \brief ESS
///
/// \return The ESS value of the latest iteration
ess_type::value_type ess () const
{
return ess_.back();
}
/// \brief ESS history
///
/// \return A const reference to the history of ESS
const ess_type &ess_history () const
{
return ess_;
}
/// \brief Indicator of resampling
///
/// \return A bool value, \b true if the latest iteration was resampled
resampled_type::value_type resampled () const
{
return resampled_.back();
}
/// \brief Resampling history
///
/// \return A const reference to the history of resampling
const resampled_type &resampled_history () const
{
return resampled_;
}
/// \brief Accept count
///
/// \return The accept count of the latest iteration
accept_type::value_type accept () const
{
return accept_.back();
}
/// \brief Accept count history
///
/// \return A const reference to the history of accept count
const accept_type &accept_history () const
{
return accept_;
}
/// \brief Read and write access to the particle set
///
/// \return A reference to the latest particle set
///
/// \note When the system changes, this reference may be invalidated
Particle<T> &particle ()
{
return particle_;
}
/// \brief Read only access to the particle set
///
/// \return A const reference to the latest particle set.
///
/// \note When the system changes, this reference may be invalidated
const Particle<T> &particle () const
{
return particle_;
}
/// \brief Replace initialization functor
///
/// \param init New Initialization functor
void initialize (initialize_type &init)
{
init_ = init;
}
/// \brief Initialize the particle set
///
/// \param param Additional parameters passed to the initialization
/// functor
void initialize (void *param = NULL)
{
ess_.clear();
resampled_.clear();
accept_.clear();
path_.clear();
for (typename std::map<std::string, Monitor<T> >::iterator
imap = monitor_.begin(); imap != monitor_.end(); ++imap)
imap->second.clear();
iter_num_ = 0;
accept_.push_back(init_(particle_, param));
post_move();
particle_.reset_zconst();
initialized_ = true;
}
/// \brief Replace iteration functor
///
/// \param move New Move functor
/// \param mcmc New MCMC functor
void iterate (const move_type &move, const move_type &mcmc = NULL)
{
move_ = move;
mcmc_ = mcmc;
}
/// \brief Perform iteration
void iterate ()
{
assert(initialized_);
++iter_num_;
accept_.push_back(move_(iter_num_, particle_));
if (bool(mcmc_))
accept_.back() = mcmc_(iter_num_, particle_);
post_move();
}
/// \brief Perform iteration
///
/// \param n The number of iterations to be performed
void iterate (std::size_t n)
{
for (std::size_t i = 0; i != n; ++i)
iterate();
}
/// \brief Perform importance sampling integration
///
/// \param integral The functor used to compute the integrands
/// \param res The result, an array of length dim
template<typename MonitorType>
void integrate (const MonitorType &integral, double *res)
{
Monitor<T> m(integral.dim(), integral);
m.eval(iter_num_, particle_);
Eigen::Map<Eigen::VectorXd> r(res, m.dim());
r = m.record().back();
}
/// \brief Perform importance sampling integration
///
/// \param dim The dimension of the parameter
/// \param integral The functor used to compute the integrands
/// \param res The result, an array of length dim
void integrate (unsigned dim,
const typename Monitor<T>::integral_type &integral, double *res)
{
Monitor<T> m(dim, integral);
m.eval(iter_num_, particle_);
Eigen::Map<Eigen::VectorXd> r(res, m.dim());
r = m.record().back();
}
/// \brief Add a monitor, similar to \b monitor in \b BUGS
///
/// \param name The name of the monitor
/// \param integral The functor used to compute the integrands
template<typename MonitorType>
void monitor (const std::string &name, const MonitorType &integral)
{
monitor_.insert(std::make_pair(
name, Monitor<T>(integral.dim(), integral)));
monitor_name_.insert(name);
}
/// \brief Add a monitor, similar to \b monitor in \b BUGS
///
/// \param name The name of the monitor
/// \param dim The dimension of the monitor
/// \param integral The functor used to compute the integrands
void monitor (const std::string &name, unsigned dim,
const typename Monitor<T>::integral_type &integral)
{
monitor_.insert(std::make_pair(name, Monitor<T>(dim, integral)));
monitor_name_.insert(name);
}
/// \brief Read only access to a named monitor through iterator
///
/// \param name The name of the monitor
///
/// \return An const_iterator point to the monitor for the given name
///
/// \note When the system changes, this reference may be invalidated
typename std::map<std::string, Monitor<T> >::const_iterator
monitor (const std::string &name) const
{
return monitor_.find(name);
}
/// \brief Read only access to all monitors
///
/// \return A const reference to monitors
///
/// \note When the system changes, this reference may be invalidated
const std::map<std::string, Monitor<T> > &monitor () const
{
return monitor_;
}
/// \brief Erase a named monitor
///
/// \param name The name of the monitor
void clear_monitor (const std::string &name)
{
monitor_.erase(name);
monitor_name_.erase(name);
}
/// \brief Erase all monitors
void clear_monitor ()
{
monitor_.clear();
monitor_name_.clear();
}
/// \brief Read only access to the Path sampling monitor
///
/// \return A const reference to the Path sampling monitor
///
/// \note When the system changes, this reference may be invalidated
const Path<T> &path () const
{
return path_;
}
/// \brief Set the path sampling integral
///
/// \param integral The functor used to compute the integrands
///
/// \note Set integral = NULL will stop path sampling recording
void path_sampling (const typename Path<T>::integral_type &integral)
{
path_.integral(integral);
}
/// \brief Path sampling estimate of normalizing constant
///
/// \return The log ratio of normalizing constants
double path_sampling () const
{
return path_.zconst();
}
/// \brief SMC estimate of normalizing constant
///
/// \return The log of SMC normalizng constant estimate
double zconst () const
{
return particle_.zconst();
}
/// \brief Print the history of the sampler
///
/// \param os The ostream to which the contents are printed
/// \param print_header Print header if \b true
void print (std::ostream &os = std::cout, bool print_header = true) const
{
print(os, print_header, !path_.index().empty(), monitor_name_);
}
/// \brief Print the history of the sampler
///
/// \param os The ostream to which the contents are printed
/// \param print_path Print path sampling history if \b true
/// \param print_monitor A set of monitor names to be printed
/// \param print_header Print header if \b true
void print (std::ostream &os, bool print_header, bool print_path,
const std::set<std::string> &print_monitor) const
{
if (print_header) {
os << "iter\tESS\tresample\taccept\t";
if (print_path)
os << "path.integrand\tpath.width\tpath.grid\t";
}
typename Path<T>::index_type::const_iterator iter_path_index
= path_.index().begin();
typename Path<T>::integrand_type::const_iterator iter_path_integrand
= path_.integrand().begin();
typename Path<T>::width_type::const_iterator iter_path_width
= path_.width().begin();
typename Path<T>::grid_type::const_iterator iter_path_grid
= path_.grid().begin();
std::vector<bool> monitor_index_empty;
std::vector<unsigned> monitor_dim;
std::vector<typename Monitor<T>::index_type::const_iterator>
iter_monitor_index;
std::vector<typename Monitor<T>::record_type::const_iterator>
iter_monitor_record;
for (typename std::map<std::string, Monitor<T> >::const_iterator
imap = monitor_.begin(); imap != monitor_.end(); ++imap) {
if (print_monitor.count(imap->first)) {
monitor_index_empty.push_back(imap->second.index().empty());
monitor_dim.push_back(imap->second.dim());
iter_monitor_index.push_back(imap->second.index().begin());
iter_monitor_record.push_back(imap->second.record().begin());
if (print_header) {
if (monitor_dim.back() > 1) {
for (unsigned d = 0; d != monitor_dim.back(); ++d)
os << imap->first << d + 1 << '\t';
} else {
os << imap->first << '\t';
}
}
}
}
if (print_header)
os << '\n';
for (std::size_t i = 0; i != iter_size(); ++i) {
os
<< i << '\t' << ess_[i] / size()
<< '\t' << resampled_[i]
<< '\t' << static_cast<double>(accept_[i]) / size();
if (print_path) {
if (!path_.index().empty() && *iter_path_index == i) {
os
<< '\t' << *iter_path_integrand++
<< '\t' << *iter_path_width++
<< '\t' << *iter_path_grid++;
++iter_path_index;
} else {
os << '\t' << '.' << '\t' << '.' << '\t' << '.';
}
}
for (std::size_t m = 0; m != monitor_index_empty.size(); ++m) {
if (!monitor_index_empty[m] && *iter_monitor_index[m] == i) {
for (unsigned d = 0; d != monitor_dim[m]; ++d)
os << '\t' << (*iter_monitor_record[m])[d];
++iter_monitor_index[m];
++iter_monitor_record[m];
} else {
for (unsigned d = 0; d != monitor_dim[m]; ++d)
os << '\t' << '.';
}
}
if (i != iter_size() - 1)
os << '\n';
}
}
private :
/// Initialization indicator
bool initialized_;
/// Initialization and movement
initialize_type init_;
move_type move_;
move_type mcmc_;
/// Resampling
ResampleScheme scheme_;
double threshold_;
/// Particle sets
Particle<T> particle_;
std::size_t iter_num_;
ess_type ess_;
resampled_type resampled_;
accept_type accept_;
/// Monte Carlo estimation by integration
std::map<std::string, Monitor<T> > monitor_;
std::set<std::string> monitor_name_;
/// Path sampling
Path<T> path_;
void post_move ()
{
ess_.push_back(particle_.ess());
particle_.resampled(ess_.back() < threshold_);
resampled_.push_back(particle_.resampled());
if (particle_.resampled()) {
particle_.resample(scheme_);
ess_.back() = particle_.size();
}
if (!path_.empty())
path_.eval(iter_num_, particle_);
for (typename std::map<std::string, Monitor<T> >::iterator
imap = monitor_.begin(); imap != monitor_.end(); ++imap) {
if (!imap->second.empty())
imap->second.eval(iter_num_, particle_);
}
}
}; // class Sampler
} // namespace vSMC
namespace std {
/// \brief Print the sampler
///
/// \param os The ostream to which the contents are printed
/// \param sampler The sampler to be printed
///
/// \note This is the same as <tt>sampler.print(os)</tt>
template<typename T>
std::ostream & operator<< (std::ostream &os, const vSMC::Sampler<T> &sampler)
{
sampler.print(os);
return os;
}
} // namespace std
#endif // V_SMC_CORE_SAMPLER_HPP
<|endoftext|> |
<commit_before>/*
*
* MIT License
*
* Copyright (c) 2016-2018 The Cats Project
*
* 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.
*
*/
#ifndef CATS_CORECAT_DATA_ARRAY_HPP
#define CATS_CORECAT_DATA_ARRAY_HPP
#include <cstddef>
#include <iterator>
#include <memory>
#include <utility>
#include "Allocator/DefaultAllocator.hpp"
#include "../Util/Iterator.hpp"
namespace Cats {
namespace Corecat {
inline namespace Data {
template <typename T>
class ArrayView;
template <typename T, typename A = DefaultAllocator>
class Array {
public:
using Type = T;
using AllocatorType = A;
using Iterator = Type*;
using ConstIterator = const Type*;
using ReverseIterator = Corecat::ReverseIterator<Iterator>;
using ConstReverseIterator = Corecat::ReverseIterator<ConstIterator>;
using ArrayViewType = ArrayView<T>;
using ConstArrayViewType = ArrayView<const T>;
private:
A allocator;
Type* data = nullptr;
std::size_t size = 0;
std::size_t capacity = 0;
public:
Array() = default;
Array(std::size_t size_) { resize(size_); }
Array(const Array& src) {
data = static_cast<T*>(allocator.allocate(src.size * sizeof(T)));
size = src.size;
capacity = size;
std::size_t i = 0;
try {
for(; i < size; ++i) new(data + i) T(src.data[i]);
} catch(...) {
for(--i; i != std::size_t(-1); --i) data[i].~T();
allocator.deallocate(data, capacity * sizeof(T));
std::rethrow_exception(std::current_exception());
}
}
Array(Array&& src) noexcept { swap(src); }
~Array() {
clear();
if(data) allocator.deallocate(data, capacity * sizeof(T));
}
Array& operator =(const Array& src) = delete;
Array& operator =(Array&& src) noexcept { swap(*this, src); return *this; }
operator ConstArrayViewType() const noexcept { return getView(); }
operator ArrayViewType() noexcept { return getView(); }
const Type& operator [](std::size_t index) const noexcept { return data[index]; }
Type& operator [](std::size_t index) noexcept { return data[index]; }
const Type* getData() const noexcept { return data; }
Type* getData() noexcept { return data; }
std::size_t getSize() const noexcept { return size; }
std::size_t getCapacity() const noexcept { return capacity; }
ConstArrayViewType getView() const noexcept { return {data, size}; }
ArrayViewType getView() noexcept { return {data, size}; }
bool isEmpty() const noexcept { return !size; }
void clear() noexcept { resize(0); }
void reserve(std::size_t capacity_) {
if(capacity >= capacity_) return;
T* data_ = static_cast<T*>(allocator.allocate(capacity_ * sizeof(T)));
std::size_t i = 0;
try {
for(; i < size; ++i) new(data_ + i) T(data[i]);
} catch(...) {
for(--i; i != std::size_t(-1); --i) data_[i].~T();
allocator.deallocate(data_, capacity_ * sizeof(T));
std::rethrow_exception(std::current_exception());
}
if(data) {
for(std::size_t i = size - 1; i != std::size_t(-1); --i) data[i].~T();
allocator.deallocate(data, capacity * sizeof(T));
}
data = data_;
capacity = capacity_;
}
void resize(std::size_t size_) {
if(size_ < size) {
for(std::size_t i = size_ - 1; i != size_ - 1; --i)
data[i].~T();
} else if(size_ > size) {
if(size_ <= capacity) {
std::size_t i = size;
try {
for(; i < size_; ++i) new(data + i) T();
} catch(...) {
for(--i; i != size - 1; --i) data[i].~T();
std::rethrow_exception(std::current_exception());
}
} else {
T* data_ = static_cast<T*>(allocator.allocate(size_ * sizeof(T)));
std::size_t i = 0;
try {
for(; i < size; ++i) new(data_ + i) T(data[i]);
for(; i < size_; ++i) new(data_ + i) T();
} catch(...) {
for(--i; i != std::size_t(-1); --i) data_[i].~T();
allocator.deallocate(data_, size_ * sizeof(T));
std::rethrow_exception(std::current_exception());
}
if(data) {
for(std::size_t i = size - 1; i != std::size_t(-1); --i) data[i].~T();
allocator.deallocate(data, capacity * sizeof(T));
}
data = data_;
capacity = size_;
}
}
size = size_;
}
template <typename... Arg>
void append(Arg&&... arg) {
if(size < capacity) {
new(data + size) T(std::forward<Arg>(arg)...);
} else {
std::size_t newSize = size + 1;
T* newData = static_cast<T*>(allocator.allocate(newSize * sizeof(T)));
std::size_t i = 0;
try {
for(; i < size; ++i) new(newData + i) T(data[i]);
new(newData + size) T(std::forward<Arg>(arg)...);
} catch(...) {
for(--i; i != std::size_t(-1); --i) newData[i].~T();
allocator.deallocate(newData, newSize * sizeof(T));
std::rethrow_exception(std::current_exception());
}
if(data) {
for(std::size_t i = size - 1; i != std::size_t(-1); --i) data[i].~T();
allocator.deallocate(data, capacity * sizeof(T));
}
data = newData;
capacity = newSize;
}
++size;
}
void swap(Array& src) noexcept {
std::swap(allocator, src.allocator);
std::swap(data, src.data);
std::swap(size, src.size);
std::swap(capacity, src.capacity);
}
Iterator begin() const noexcept { return data; }
Iterator end() const noexcept { return data + size; }
ConstIterator cbegin() const noexcept { return begin(); }
ConstIterator cend() const noexcept { return end(); }
ReverseIterator rbegin() const noexcept { return ReverseIterator(end()); }
ReverseIterator rend() const noexcept { return ReverseIterator(begin()); }
ConstReverseIterator crbegin() const noexcept { return ConstReverseIterator(cend()); }
ConstReverseIterator crend() const noexcept { return ConstReverseIterator(cbegin()); }
};
template <typename T>
class ArrayView {
public:
using Type = T;
using Iterator = Type*;
using ConstIterator = const Type*;
using ReverseIterator = Corecat::ReverseIterator<Iterator>;
using ConstReverseIterator = Corecat::ReverseIterator<ConstIterator>;
private:
Type* data = nullptr;
std::size_t size = 0;
public:
ArrayView() = default;
ArrayView(std::nullptr_t) noexcept {}
ArrayView(Type* data_, std::size_t size_) noexcept : data(data_), size(size_) {}
template <std::size_t S>
ArrayView(Type (&array)[S]) noexcept : data(array), size(S) {}
ArrayView(const ArrayView& src) = default;
ArrayView& operator =(const ArrayView& src) = default;
operator ArrayView<const Type>() noexcept { return {data, size}; }
Type& operator [](std::size_t index) const noexcept { return data[index]; }
Type* getData() const noexcept { return data; }
std::size_t getSize() const noexcept { return size; }
bool isEmpty() const noexcept { return !size; }
Iterator begin() const noexcept { return data; }
Iterator end() const noexcept { return data + size; }
ConstIterator cbegin() const noexcept { return begin(); }
ConstIterator cend() const noexcept { return end(); }
ReverseIterator rbegin() const noexcept { return ReverseIterator(end()); }
ReverseIterator rend() const noexcept { return ReverseIterator(begin()); }
ConstReverseIterator crbegin() const noexcept { return ConstReverseIterator(cend()); }
ConstReverseIterator crend() const noexcept { return ConstReverseIterator(cbegin()); }
};
}
}
}
#endif
<commit_msg>Update Array<commit_after>/*
*
* MIT License
*
* Copyright (c) 2016-2018 The Cats Project
*
* 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.
*
*/
#ifndef CATS_CORECAT_DATA_ARRAY_HPP
#define CATS_CORECAT_DATA_ARRAY_HPP
#include <cstddef>
#include <iterator>
#include <memory>
#include <utility>
#include "Allocator/DefaultAllocator.hpp"
#include "../Util/Iterator.hpp"
namespace Cats {
namespace Corecat {
inline namespace Data {
template <typename T>
class ArrayView;
template <typename T, typename A = DefaultAllocator>
class Array {
public:
using Type = T;
using AllocatorType = A;
using Iterator = Type*;
using ConstIterator = const Type*;
using ReverseIterator = Corecat::ReverseIterator<Iterator>;
using ConstReverseIterator = Corecat::ReverseIterator<ConstIterator>;
using ArrayViewType = ArrayView<T>;
using ConstArrayViewType = ArrayView<const T>;
private:
A allocator;
Type* data = nullptr;
std::size_t size = 0;
std::size_t capacity = 0;
public:
Array() = default;
Array(std::size_t size_) { resize(size_); }
Array(const Array& src) {
data = static_cast<T*>(allocator.allocate(src.size * sizeof(T)));
size = src.size;
capacity = size;
std::size_t i = 0;
try {
for(; i < size; ++i) new(data + i) T(src.data[i]);
} catch(...) {
for(std::size_t j = 0; j < i; ++j) data[j].~T();
allocator.deallocate(data, capacity * sizeof(T));
throw;
}
}
Array(Array&& src) noexcept { swap(src); }
~Array() {
clear();
if(data) allocator.deallocate(data, capacity * sizeof(T));
}
Array& operator =(const Array& src) {
if(src.size > capacity) {
T* newData = static_cast<T*>(allocator.allocate(src.size * sizeof(T)));
std::size_t i = 0;
try {
for(; i < src.size; ++i) new(newData + i) T(src.data[i]);
} catch(...) {
for(std::size_t j = 0; j < i; ++j) newData[j].~T();
allocator.deallocate(newData, src.size * sizeof(T));
throw;
}
if(data) {
for(std::size_t i = 0; i < size; ++i) data[i].~T();
allocator.deallocate(data, capacity * sizeof(T));
}
data = newData;
size = src.size;
capacity = size;
} else if(src.size > size) {
std::size_t i = 0;
for(; i < size; ++i) data[i] = src.data[i];
try {
for(; i < src.size; ++i) new(data + i) T(src.data[i]);
} catch(...) {
for(std::size_t j = size; j < i; ++j) data[j].~T();
throw;
}
size = src.size;
} else {
std::size_t i = 0;
for(; i < src.size; ++i) data[i] = src.data[i];
for(; i < size; ++i) data[i].~T();
size = src.size;
}
return *this;
}
Array& operator =(Array&& src) noexcept { swap(src); return *this; }
operator ConstArrayViewType() const noexcept { return getView(); }
operator ArrayViewType() noexcept { return getView(); }
const Type& operator [](std::size_t index) const noexcept { return data[index]; }
Type& operator [](std::size_t index) noexcept { return data[index]; }
const Type* getData() const noexcept { return data; }
Type* getData() noexcept { return data; }
std::size_t getSize() const noexcept { return size; }
std::size_t getCapacity() const noexcept { return capacity; }
ConstArrayViewType getView() const noexcept { return {data, size}; }
ArrayViewType getView() noexcept { return {data, size}; }
bool isEmpty() const noexcept { return !size; }
void clear() noexcept { resize(0); }
void reserve(std::size_t capacity_) {
if(capacity >= capacity_) return;
T* data_ = static_cast<T*>(allocator.allocate(capacity_ * sizeof(T)));
std::size_t i = 0;
try {
for(; i < size; ++i) new(data_ + i) T(data[i]);
} catch(...) {
for(std::size_t j = 0; j < i; ++j) data[j].~T();
allocator.deallocate(data_, capacity_ * sizeof(T));
throw;
}
if(data) {
for(std::size_t i = 0; i < size; ++i) data[i].~T();
allocator.deallocate(data, capacity * sizeof(T));
}
data = data_;
capacity = capacity_;
}
void resize(std::size_t size_) {
if(size_ < size) {
for(std::size_t i = size_ - 1; i != size_ - 1; --i)
data[i].~T();
} else if(size_ > size) {
if(size_ <= capacity) {
std::size_t i = size;
try {
for(; i < size_; ++i) new(data + i) T();
} catch(...) {
for(std::size_t j = 0; j < i; ++j) data[j].~T();
throw;
}
} else {
T* data_ = static_cast<T*>(allocator.allocate(size_ * sizeof(T)));
std::size_t i = 0;
try {
for(; i < size; ++i) new(data_ + i) T(data[i]);
for(; i < size_; ++i) new(data_ + i) T();
} catch(...) {
for(std::size_t j = 0; j < i; ++j) data_[j].~T();
allocator.deallocate(data_, size_ * sizeof(T));
throw;
}
if(data) {
for(std::size_t i = 0; i < size; ++i) data[i].~T();
allocator.deallocate(data, capacity * sizeof(T));
}
data = data_;
capacity = size_;
}
}
size = size_;
}
template <typename... Arg>
void append(Arg&&... arg) {
if(size < capacity) {
new(data + size) T(std::forward<Arg>(arg)...);
} else {
std::size_t newSize = size + 1;
T* newData = static_cast<T*>(allocator.allocate(newSize * sizeof(T)));
std::size_t i = 0;
try {
for(; i < size; ++i) new(newData + i) T(data[i]);
new(newData + size) T(std::forward<Arg>(arg)...);
} catch(...) {
for(std::size_t j = 0; j < i; ++j) newData[j].~T();
allocator.deallocate(newData, newSize * sizeof(T));
throw;
}
if(data) {
for(std::size_t i = 0; i < size; ++i) data[i].~T();
allocator.deallocate(data, capacity * sizeof(T));
}
data = newData;
capacity = newSize;
}
++size;
}
void swap(Array& src) noexcept {
std::swap(allocator, src.allocator);
std::swap(data, src.data);
std::swap(size, src.size);
std::swap(capacity, src.capacity);
}
Iterator begin() const noexcept { return data; }
Iterator end() const noexcept { return data + size; }
ConstIterator cbegin() const noexcept { return begin(); }
ConstIterator cend() const noexcept { return end(); }
ReverseIterator rbegin() const noexcept { return ReverseIterator(end()); }
ReverseIterator rend() const noexcept { return ReverseIterator(begin()); }
ConstReverseIterator crbegin() const noexcept { return ConstReverseIterator(cend()); }
ConstReverseIterator crend() const noexcept { return ConstReverseIterator(cbegin()); }
};
template <typename T>
class ArrayView {
public:
using Type = T;
using Iterator = Type*;
using ConstIterator = const Type*;
using ReverseIterator = Corecat::ReverseIterator<Iterator>;
using ConstReverseIterator = Corecat::ReverseIterator<ConstIterator>;
private:
Type* data = nullptr;
std::size_t size = 0;
public:
ArrayView() = default;
ArrayView(std::nullptr_t) noexcept {}
ArrayView(Type* data_, std::size_t size_) noexcept : data(data_), size(size_) {}
template <std::size_t S>
ArrayView(Type (&array)[S]) noexcept : data(array), size(S) {}
ArrayView(const ArrayView& src) = default;
ArrayView& operator =(const ArrayView& src) = default;
operator ArrayView<const Type>() noexcept { return {data, size}; }
Type& operator [](std::size_t index) const noexcept { return data[index]; }
Type* getData() const noexcept { return data; }
std::size_t getSize() const noexcept { return size; }
bool isEmpty() const noexcept { return !size; }
Iterator begin() const noexcept { return data; }
Iterator end() const noexcept { return data + size; }
ConstIterator cbegin() const noexcept { return begin(); }
ConstIterator cend() const noexcept { return end(); }
ReverseIterator rbegin() const noexcept { return ReverseIterator(end()); }
ReverseIterator rend() const noexcept { return ReverseIterator(begin()); }
ConstReverseIterator crbegin() const noexcept { return ConstReverseIterator(cend()); }
ConstReverseIterator crend() const noexcept { return ConstReverseIterator(cbegin()); }
};
}
}
}
#endif
<|endoftext|> |
<commit_before>#include "common.h"
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <ctime>
#include <cstddef>
#include <cstdio>
#include <mutex>
#include <memory>
#ifdef PROJECT_NAMESPACE
namespace PROJECT_NAMESPACE {
#endif // PROJECT_NAMESPACE
namespace common {
namespace {
const bool use_color = isatty(fileno(stderr));
thread_local const int pid = getpid();
} // unnamed namespace
char const* LogLevelSymbol(LogLevel l) {
switch (l) {
case LogLevel::kInfo:
return "I";
case LogLevel::kWarn:
return "W";
case LogLevel::kDebug:
return "D";
case LogLevel::kFatal:
return "F";
}
return "";
}
char const* LogLevelColorMaybe(LogLevel l) {
if (use_color) {
switch (l) {
case LogLevel::kInfo:
return "\x1b[32m";
case LogLevel::kWarn:
return "\x1b[31m";
case LogLevel::kDebug:
return "\x1b[34m";
case LogLevel::kFatal:
return "\x1b[31m";
}
}
return "";
}
char const* LogLevelClearMaybe() {
if (use_color) {
return "\x1b[0m";
} else {
return "";
}
}
void Log(LogLevel level, char const* file, int line, char const* func,
char const* fmt, ...) {
static std::mutex m;
char const* format_string = "%s%s%s.%06d %d %s:%d: %s]%s ";
std::time_t time_now;
std::time(&time_now);
char time_str[64];
timeval tv;
gettimeofday(&tv, nullptr);
{
std::lock_guard<std::mutex> lock{m};
std::strftime(time_str, sizeof(time_str), "%m%d %H:%M:%S",
std::localtime(&time_now));
std::fprintf(stderr, format_string, LogLevelColorMaybe(level),
LogLevelSymbol(level), time_str, tv.tv_usec, pid, file, line,
func, LogLevelClearMaybe());
std::va_list ap;
va_start(ap, fmt);
std::vfprintf(stderr, fmt, ap);
va_end(ap);
std::fputc('\n', stderr);
}
if (level == LogLevel::kFatal) {
throw FatalError{"Fatal error"};
}
}
void AssertFail(char const* file, int line, char const* func, char const* expr,
char const* fmt, ...) {
std::string msg = FormatString("Assertion `%s' failed at %s:%d: %s", expr,
file, line, func);
if (fmt) {
msg.append("\nextra message: ");
std::va_list ap;
va_start(ap, fmt);
msg.append(FormatString(fmt, ap));
va_end(ap);
}
throw AssertionError{msg};
}
std::string FormatString(char const* fmt, ...) {
std::va_list ap;
va_start(ap, fmt);
auto&& rst = FormatStringVariadic(fmt, ap);
va_end(ap);
return rst;
}
std::string FormatStringVariadic(char const* fmt, std::va_list ap_orig) {
constexpr std::size_t stack_size = 128;
auto size = stack_size;
char stack_ptr[stack_size];
std::unique_ptr<char[]> heap_ptr{};
char* ptr = stack_ptr;
while (true) {
std::va_list ap;
va_copy(ap, ap_orig);
auto n = std::vsnprintf(ptr, size, fmt, ap);
va_end(ap);
if (n < 0) {
throw std::runtime_error("Encoding error");
} else if (static_cast<std::size_t>(n) < size) {
return std::string(ptr);
} else {
size = n + 1;
heap_ptr.reset(new char[size]);
ptr = heap_ptr.get();
}
}
}
Exception::Exception(std::string const& s) : msg_{s} {}
Exception::~Exception() = default;
char const* Exception::what() const noexcept { return msg_.c_str(); }
} // namespace common
#ifdef PROJECT_NAMESPACE
} // namespace PROJECT_NAMESPACE
#endif // PROJECT_NAMESPACE
<commit_msg>[master] use curly braces<commit_after>#include "common.h"
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <ctime>
#include <cstddef>
#include <cstdio>
#include <mutex>
#include <memory>
#ifdef PROJECT_NAMESPACE
namespace PROJECT_NAMESPACE {
#endif // PROJECT_NAMESPACE
namespace common {
namespace {
const bool use_color = isatty(fileno(stderr));
thread_local const int pid = getpid();
} // unnamed namespace
char const* LogLevelSymbol(LogLevel l) {
switch (l) {
case LogLevel::kInfo:
return "I";
case LogLevel::kWarn:
return "W";
case LogLevel::kDebug:
return "D";
case LogLevel::kFatal:
return "F";
}
return "";
}
char const* LogLevelColorMaybe(LogLevel l) {
if (use_color) {
switch (l) {
case LogLevel::kInfo:
return "\x1b[32m";
case LogLevel::kWarn:
return "\x1b[31m";
case LogLevel::kDebug:
return "\x1b[34m";
case LogLevel::kFatal:
return "\x1b[31m";
}
}
return "";
}
char const* LogLevelClearMaybe() {
if (use_color) {
return "\x1b[0m";
} else {
return "";
}
}
void Log(LogLevel level, char const* file, int line, char const* func,
char const* fmt, ...) {
static std::mutex m;
char const* format_string = "%s%s%s.%06d %d %s:%d: %s]%s ";
std::time_t time_now;
std::time(&time_now);
char time_str[64];
timeval tv;
gettimeofday(&tv, nullptr);
{
std::lock_guard<std::mutex> lock{m};
std::strftime(time_str, sizeof(time_str), "%m%d %H:%M:%S",
std::localtime(&time_now));
std::fprintf(stderr, format_string, LogLevelColorMaybe(level),
LogLevelSymbol(level), time_str, tv.tv_usec, pid, file, line,
func, LogLevelClearMaybe());
std::va_list ap;
va_start(ap, fmt);
std::vfprintf(stderr, fmt, ap);
va_end(ap);
std::fputc('\n', stderr);
}
if (level == LogLevel::kFatal) {
throw FatalError{"Fatal error"};
}
}
void AssertFail(char const* file, int line, char const* func, char const* expr,
char const* fmt, ...) {
std::string msg = FormatString("Assertion `%s' failed at %s:%d: %s", expr,
file, line, func);
if (fmt) {
msg.append("\nextra message: ");
std::va_list ap;
va_start(ap, fmt);
msg.append(FormatString(fmt, ap));
va_end(ap);
}
throw AssertionError{msg};
}
std::string FormatString(char const* fmt, ...) {
std::va_list ap;
va_start(ap, fmt);
auto&& rst = FormatStringVariadic(fmt, ap);
va_end(ap);
return rst;
}
std::string FormatStringVariadic(char const* fmt, std::va_list ap_orig) {
constexpr std::size_t stack_size = 128;
auto size = stack_size;
char stack_ptr[stack_size];
std::unique_ptr<char[]> heap_ptr{};
char* ptr = stack_ptr;
while (true) {
std::va_list ap;
va_copy(ap, ap_orig);
auto n = std::vsnprintf(ptr, size, fmt, ap);
va_end(ap);
if (n < 0) {
throw std::runtime_error{"Encoding error"};
} else if (static_cast<std::size_t>(n) < size) {
return std::string(ptr);
} else {
size = n + 1;
heap_ptr.reset(new char[size]);
ptr = heap_ptr.get();
}
}
}
Exception::Exception(std::string const& s) : msg_{s} {}
Exception::~Exception() = default;
char const* Exception::what() const noexcept { return msg_.c_str(); }
} // namespace common
#ifdef PROJECT_NAMESPACE
} // namespace PROJECT_NAMESPACE
#endif // PROJECT_NAMESPACE
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include <string>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/themes/browser_theme_provider.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_service.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
ThemeInstalledInfoBarDelegate::ThemeInstalledInfoBarDelegate(
TabContents* tab_contents,
const Extension* new_theme,
const std::string& previous_theme_id)
: ConfirmInfoBarDelegate(tab_contents),
profile_(tab_contents->profile()),
name_(new_theme->name()),
theme_id_(new_theme->id()),
previous_theme_id_(previous_theme_id),
tab_contents_(tab_contents) {
profile_->GetThemeProvider()->OnInfobarDisplayed();
registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
NotificationService::AllSources());
}
ThemeInstalledInfoBarDelegate::~ThemeInstalledInfoBarDelegate() {
// We don't want any notifications while we're running our destructor.
registrar_.RemoveAll();
profile_->GetThemeProvider()->OnInfobarDestroyed();
}
void ThemeInstalledInfoBarDelegate::InfoBarClosed() {
delete this;
}
string16 ThemeInstalledInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringFUTF16(IDS_THEME_INSTALL_INFOBAR_LABEL,
UTF8ToUTF16(name_));
}
SkBitmap* ThemeInstalledInfoBarDelegate::GetIcon() const {
// TODO(aa): Reply with the theme's icon, but this requires reading it
// asynchronously from disk.
return ResourceBundle::GetSharedInstance().GetBitmapNamed(IDR_INFOBAR_THEME);
}
ThemeInstalledInfoBarDelegate*
ThemeInstalledInfoBarDelegate::AsThemePreviewInfobarDelegate() {
return this;
}
int ThemeInstalledInfoBarDelegate::GetButtons() const {
return BUTTON_CANCEL;
}
string16 ThemeInstalledInfoBarDelegate::GetButtonLabel(
ConfirmInfoBarDelegate::InfoBarButton button) const {
// The InfoBar will create a default OK button and make it invisible.
// TODO(mirandac): remove the default OK button from ConfirmInfoBar.
return (button == BUTTON_CANCEL) ?
l10n_util::GetStringUTF16(IDS_THEME_INSTALL_INFOBAR_UNDO_BUTTON) :
string16();
}
bool ThemeInstalledInfoBarDelegate::Cancel() {
if (!previous_theme_id_.empty()) {
ExtensionsService* service = profile_->GetExtensionsService();
if (service) {
const Extension* previous_theme =
service->GetExtensionById(previous_theme_id_, true);
if (previous_theme) {
profile_->SetTheme(previous_theme);
return true;
}
}
}
profile_->ClearTheme();
return true;
}
void ThemeInstalledInfoBarDelegate::Observe(
NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK_EQ(NotificationType::BROWSER_THEME_CHANGED, type.value);
// If the new theme is different from what this info bar is associated
// with, close this info bar since it is no longer relevant.
const Extension* extension = Details<const Extension>(details).ptr();
if (!extension || theme_id_ != extension->id())
tab_contents_->RemoveInfoBar(this);
}
bool ThemeInstalledInfoBarDelegate::MatchesTheme(const Extension* theme) {
return (theme && theme->id() == theme_id_);
}
<commit_msg>Check that TabContents is valid (not null) before removing theme change InfoBar.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include <string>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/themes/browser_theme_provider.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_service.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
ThemeInstalledInfoBarDelegate::ThemeInstalledInfoBarDelegate(
TabContents* tab_contents,
const Extension* new_theme,
const std::string& previous_theme_id)
: ConfirmInfoBarDelegate(tab_contents),
profile_(tab_contents->profile()),
name_(new_theme->name()),
theme_id_(new_theme->id()),
previous_theme_id_(previous_theme_id),
tab_contents_(tab_contents) {
profile_->GetThemeProvider()->OnInfobarDisplayed();
registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
NotificationService::AllSources());
}
ThemeInstalledInfoBarDelegate::~ThemeInstalledInfoBarDelegate() {
// We don't want any notifications while we're running our destructor.
registrar_.RemoveAll();
profile_->GetThemeProvider()->OnInfobarDestroyed();
}
void ThemeInstalledInfoBarDelegate::InfoBarClosed() {
delete this;
}
string16 ThemeInstalledInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringFUTF16(IDS_THEME_INSTALL_INFOBAR_LABEL,
UTF8ToUTF16(name_));
}
SkBitmap* ThemeInstalledInfoBarDelegate::GetIcon() const {
// TODO(aa): Reply with the theme's icon, but this requires reading it
// asynchronously from disk.
return ResourceBundle::GetSharedInstance().GetBitmapNamed(IDR_INFOBAR_THEME);
}
ThemeInstalledInfoBarDelegate*
ThemeInstalledInfoBarDelegate::AsThemePreviewInfobarDelegate() {
return this;
}
int ThemeInstalledInfoBarDelegate::GetButtons() const {
return BUTTON_CANCEL;
}
string16 ThemeInstalledInfoBarDelegate::GetButtonLabel(
ConfirmInfoBarDelegate::InfoBarButton button) const {
// The InfoBar will create a default OK button and make it invisible.
// TODO(mirandac): remove the default OK button from ConfirmInfoBar.
return (button == BUTTON_CANCEL) ?
l10n_util::GetStringUTF16(IDS_THEME_INSTALL_INFOBAR_UNDO_BUTTON) :
string16();
}
bool ThemeInstalledInfoBarDelegate::Cancel() {
if (!previous_theme_id_.empty()) {
ExtensionsService* service = profile_->GetExtensionsService();
if (service) {
const Extension* previous_theme =
service->GetExtensionById(previous_theme_id_, true);
if (previous_theme) {
profile_->SetTheme(previous_theme);
return true;
}
}
}
profile_->ClearTheme();
return true;
}
void ThemeInstalledInfoBarDelegate::Observe(
NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK_EQ(NotificationType::BROWSER_THEME_CHANGED, type.value);
// If the new theme is different from what this info bar is associated
// with, close this info bar since it is no longer relevant.
const Extension* extension = Details<const Extension>(details).ptr();
if (!extension || theme_id_ != extension->id()) {
if (tab_contents_ && !tab_contents_->is_being_destroyed()) {
tab_contents_->RemoveInfoBar(this);
// The infobar is gone so there is no reason for this delegate to keep
// a pointer to the TabContents (the TabContents has deleted its
// reference to this delegate and a new delegate will be created if
// a new infobar is created).
tab_contents_ = NULL;
// Although it's not being used anymore, this delegate is never deleted.
// It can not be deleted now because it is still needed if we
// "undo" the theme change that triggered this notification
// (when InfoBar::OnBackgroundExpose() is called). This will likely
// be fixed when infobar delegate deletion is cleaned up for
// http://crbug.com/62154.
}
}
}
bool ThemeInstalledInfoBarDelegate::MatchesTheme(const Extension* theme) {
return (theme && theme->id() == theme_id_);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include "consts.h"
#include "circuits/circuit.h"
#include "matrix/newtonraphson.h"
using namespace std;
static const int MAX_ATTEMPTS = 500;
static const int MAX_LOOPS = 1000;
static const double TOLERANCE = 1e-4;
void randomize(int numVariables, double (&solution)[MAX_NODES+1]){
solution[0] = 0; // gnd
for(int i=1; i<=numVariables; i++){
solution[i] = ((double(rand()) / double(RAND_MAX)) - 0.5)*100;
}
}
double calcDistance(int numVariables, double x[MAX_NODES+1], double y[MAX_NODES+1]){
double sum=0;
double distance=0;
for(int i=1; i<=numVariables ;i++) {
sum += pow((x[i]-y[i]),2);
}
distance = sqrt(sum);
return distance;
}
void printSolution(int numVariables, double solution[MAX_NODES+1]){
for(int i=1; i<=numVariables; i++){
cout << solution[i] << endl;
}
cout << endl;
}
int runNewtonRaphson(Circuit circuit,
double (&finalSolution)[MAX_NODES+1],
double t,
double (&lastSolution)[MAX_NODES+1]){
int rc=0;
int numAttempts=0;
int numLoops=0;
bool converged=false;
double solution[MAX_NODES+1];
double distance=0;
double previousSolution[MAX_NODES+1];
double Yn[MAX_NODES+1][MAX_NODES+2];
copySolution(circuit.getNumVariables(), ZERO_SOLUTION, previousSolution);
while(!converged && numAttempts <= MAX_ATTEMPTS ){
numAttempts++;
numLoops=0;
while(!converged && numLoops <= MAX_LOOPS){
numLoops++;
init(circuit.getNumVariables(), Yn);
circuit.applyStamps(Yn,
previousSolution,
t,
lastSolution);
rc = solve(circuit.getNumVariables(), Yn);
if (rc)
// Let's try a new randomized initial solution!
break;
getSolution(circuit.getNumVariables(),
Yn,
solution);
distance = calcDistance(circuit.getNumVariables(),
solution,
previousSolution);
if (distance < TOLERANCE){
converged = true;
solution[0] = 0; // Ground!
copySolution(circuit.getNumVariables(),
solution,
finalSolution);
} else {
copySolution(circuit.getNumVariables(),
solution,
previousSolution);
}
}
randomize(circuit.getNumVariables(), previousSolution);
}
if (!converged){
cout << "Newton Raphson did not converge.";
#if defined (WIN32) || defined(_WIN32)
cout << endl << "Press any key to exit...";
cin.get();
cin.get();
#endif
exit(EXIT_FAILURE);
}
return 0;
}
<commit_msg>Revert "Raises range for Newton Raphson initialization"<commit_after>#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include "consts.h"
#include "circuits/circuit.h"
#include "matrix/newtonraphson.h"
using namespace std;
static const int MAX_ATTEMPTS = 500;
static const int MAX_LOOPS = 1000;
static const double TOLERANCE = 1e-4;
void randomize(int numVariables, double (&solution)[MAX_NODES+1]){
solution[0] = 0; // gnd
for(int i=1; i<=numVariables; i++){
solution[i] = (double(rand()) / double(RAND_MAX)) - 0.5;
}
}
double calcDistance(int numVariables, double x[MAX_NODES+1], double y[MAX_NODES+1]){
double sum=0;
double distance=0;
for(int i=1; i<=numVariables ;i++) {
sum += pow((x[i]-y[i]),2);
}
distance = sqrt(sum);
return distance;
}
void printSolution(int numVariables, double solution[MAX_NODES+1]){
for(int i=1; i<=numVariables; i++){
cout << solution[i] << endl;
}
cout << endl;
}
int runNewtonRaphson(Circuit circuit,
double (&finalSolution)[MAX_NODES+1],
double t,
double (&lastSolution)[MAX_NODES+1]){
int rc=0;
int numAttempts=0;
int numLoops=0;
bool converged=false;
double solution[MAX_NODES+1];
double distance=0;
double previousSolution[MAX_NODES+1];
double Yn[MAX_NODES+1][MAX_NODES+2];
copySolution(circuit.getNumVariables(), ZERO_SOLUTION, previousSolution);
while(!converged && numAttempts <= MAX_ATTEMPTS ){
numAttempts++;
numLoops=0;
while(!converged && numLoops <= MAX_LOOPS){
numLoops++;
init(circuit.getNumVariables(), Yn);
circuit.applyStamps(Yn,
previousSolution,
t,
lastSolution);
rc = solve(circuit.getNumVariables(), Yn);
if (rc)
// Let's try a new randomized initial solution!
break;
getSolution(circuit.getNumVariables(),
Yn,
solution);
distance = calcDistance(circuit.getNumVariables(),
solution,
previousSolution);
if (distance < TOLERANCE){
converged = true;
solution[0] = 0; // Ground!
copySolution(circuit.getNumVariables(),
solution,
finalSolution);
} else {
copySolution(circuit.getNumVariables(),
solution,
previousSolution);
}
}
randomize(circuit.getNumVariables(), previousSolution);
}
if (!converged){
cout << "Newton Raphson did not converge.";
#if defined (WIN32) || defined(_WIN32)
cout << endl << "Press any key to exit...";
cin.get();
cin.get();
#endif
exit(EXIT_FAILURE);
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 Tmplt <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <map> // std::map
#include <string> // std::string
#include <vector> // std::vector
#include <memory> // std:unique_ptr
#include <utility> // std::forward
#include <experimental/string_view> // std::experimental::string_view
#include "errors.hpp"
using std::string;
using std::vector;
using std::experimental::string_view;
using std::forward;
namespace command_line {
/* Something more specific than "runtime_error". */
DEFINE_ERROR(argument_error);
DEFINE_ERROR(value_error);
class option;
class option_group;
using options = vector<option>;
using groups = vector<option_group>;
using choices = vector<string>;
/*
* Holds all properties for an option.
* (A possible flag to pass to the program.)
*/
struct option {
const string flag, flag_long, desc;
/*
* e.g. seen as --log LEVEL in usage(),
* where LEVEL is the token.
*/
const string token;
/*
* For options where a set of values are allowed,
* e.g. --log LEVEL, where LEVEL is one of:
* error, warning, info, trace.
*/
const choices values;
explicit option(string &&flag, string &&flag_long, string &&desc, string &&token = "",
const choices c = {})
: flag(forward<string>(flag)), flag_long(forward<string>(flag_long)),
desc(forward<string>(desc)), token(forward<string>(token)), values(c) {}
};
/* A named group with it's related options. */
struct option_group {
public:
const string name;
const string synopsis;
vector<option> options;
explicit option_group(string &&name, string &&synopsis)
: name(forward<string>(name)), synopsis(forward<string>(synopsis)) {}
template <typename... Args>
option_group& operator()(Args&&... args)
{
options.emplace_back(option(forward<Args>(args)...));
return *this;
}
};
class parser {
public:
using cli_type = std::unique_ptr<parser>;
static cli_type make(const string &&scriptname, const groups &&groups);
/* Construct the parser. */
explicit parser(string &&synopsis, const groups &&groups)
: synopsis_(std::forward<decltype(synopsis)>(synopsis)),
valid_groups_(std::forward<decltype(groups)>(groups)) {}
/* Print which flags you can pass and how to use the program. */
void usage() const;
/* Process command line arguments. */
void process_arguments(const vector<string> &args);
/*
* Program specific; adhere to the options' synopsises seen in main(),
* e.g. pass at least one main argument if -d isn't passed.
*/
void validate_arguments() const;
/* Check if an option has been passed. */
bool has(const string &option) const;
/* Get the value for a given option. */
string get(string opt) const;
protected:
/*
* Construct a string of all valid token values,
* e.g. "VAL1, VAL2, VAL3".
*/
auto values_to_str(const choices &values) const;
/*
* Is the flag passed in it's long or its short form?
* Does it match any of the two?
*/
auto is_short(const string_view &option, const string_view &opt_short) const;
auto is_long(const string_view &option, const string_view &opt_long) const;
auto is(const string_view &option, string opt_short, string opt_long) const;
/* Check if the passed value matches an element in the group of valid values. */
auto check_value(const string_view &flag, const string_view &value, const choices &values) const;
/* Parse a single argument with the next argument, which may be its value (or another flag). */
void parse(const string_view &input, const string_view &input_next);
/*
* Used to check if a passed option is valid
* between the group of valid options and the group
* of passed options.
*/
bool compare(string opt, const string_view &val) const;
private:
/* Program synopsis. */
const string synopsis_;
const options valid_opts_;
const groups valid_groups_;
std::map<string, string> passed_opts_;
/*
* Is the next argument associated with the previous one,
* or should the current argument be treated as another flag?
*/
bool skipnext_ = false;
};
/* ns command_line */
}
using cliparser = command_line::parser;
using cligroup = command_line::option_group;
using clioption = command_line::option;
<commit_msg>option_group::operator(): let emplace_back handle option construction<commit_after>/*
* Copyright (C) 2017 Tmplt <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <map> // std::map
#include <string> // std::string
#include <vector> // std::vector
#include <memory> // std:unique_ptr
#include <utility> // std::forward
#include <experimental/string_view> // std::experimental::string_view
#include "errors.hpp"
using std::string;
using std::vector;
using std::experimental::string_view;
using std::forward;
namespace command_line {
/* Something more specific than "runtime_error". */
DEFINE_ERROR(argument_error);
DEFINE_ERROR(value_error);
class option;
class option_group;
using options = vector<option>;
using groups = vector<option_group>;
using choices = vector<string>;
/*
* Holds all properties for an option.
* (A possible flag to pass to the program.)
*/
struct option {
const string flag, flag_long, desc;
/*
* e.g. seen as --log LEVEL in usage(),
* where LEVEL is the token.
*/
const string token;
/*
* For options where a set of values are allowed,
* e.g. --log LEVEL, where LEVEL is one of:
* error, warning, info, trace.
*/
const choices values;
explicit option(string &&flag, string &&flag_long, string &&desc, string &&token = "",
const choices c = {})
: flag(forward<string>(flag)), flag_long(forward<string>(flag_long)),
desc(forward<string>(desc)), token(forward<string>(token)), values(c) {}
};
/* A named group with it's related options. */
struct option_group {
public:
const string name;
const string synopsis;
vector<option> options;
explicit option_group(string &&name, string &&synopsis)
: name(forward<string>(name)), synopsis(forward<string>(synopsis)) {}
template <typename... Args>
option_group& operator()(Args&&... args)
{
options.emplace_back(forward<Args>(args)...);
return *this;
}
};
class parser {
public:
using cli_type = std::unique_ptr<parser>;
static cli_type make(const string &&scriptname, const groups &&groups);
/* Construct the parser. */
explicit parser(string &&synopsis, const groups &&groups)
: synopsis_(std::forward<decltype(synopsis)>(synopsis)),
valid_groups_(std::forward<decltype(groups)>(groups)) {}
/* Print which flags you can pass and how to use the program. */
void usage() const;
/* Process command line arguments. */
void process_arguments(const vector<string> &args);
/*
* Program specific; adhere to the options' synopsises seen in main(),
* e.g. pass at least one main argument if -d isn't passed.
*/
void validate_arguments() const;
/* Check if an option has been passed. */
bool has(const string &option) const;
/* Get the value for a given option. */
string get(string opt) const;
protected:
/*
* Construct a string of all valid token values,
* e.g. "VAL1, VAL2, VAL3".
*/
auto values_to_str(const choices &values) const;
/*
* Is the flag passed in it's long or its short form?
* Does it match any of the two?
*/
auto is_short(const string_view &option, const string_view &opt_short) const;
auto is_long(const string_view &option, const string_view &opt_long) const;
auto is(const string_view &option, string opt_short, string opt_long) const;
/* Check if the passed value matches an element in the group of valid values. */
auto check_value(const string_view &flag, const string_view &value, const choices &values) const;
/* Parse a single argument with the next argument, which may be its value (or another flag). */
void parse(const string_view &input, const string_view &input_next);
/*
* Used to check if a passed option is valid
* between the group of valid options and the group
* of passed options.
*/
bool compare(string opt, const string_view &val) const;
private:
/* Program synopsis. */
const string synopsis_;
const options valid_opts_;
const groups valid_groups_;
std::map<string, string> passed_opts_;
/*
* Is the next argument associated with the previous one,
* or should the current argument be treated as another flag?
*/
bool skipnext_ = false;
};
/* ns command_line */
}
using cliparser = command_line::parser;
using cligroup = command_line::option_group;
using clioption = command_line::option;
<|endoftext|> |
<commit_before>#pragma once
#include <string>
#ifndef _MSC_VER
#include <cxxabi.h>
#endif
namespace wiertlo
{
namespace detail
{
void replaceAll(std::string& source, const std::string& from, const std::string& to)
{
std::string newString;
newString.reserve(source.length()); // avoids a few memory allocations
std::string::size_type lastPos = 0;
std::string::size_type findPos;
while(std::string::npos != (findPos = source.find(from, lastPos)))
{
newString.append(source, lastPos, findPos - lastPos);
newString += to;
lastPos = findPos + from.length();
}
// Care for the rest after last occurrence
newString += source.substr(lastPos);
source.swap(newString);
}
struct free_deleter
{
template<typename T>
void operator()(T* ptr)
{
free(ptr);
}
};
}
inline std::string demangled(const std::type_info& ti)
{
#ifndef _MSC_VER
int status;
std::size_t length;
std::unique_ptr<char, detail::free_deleter> demangled(abi::__cxa_demangle(ti.name(), nullptr, &length, &status));
if(status != 0)
throw "FUCK";
std::string s = demangled.get();
#else
std::string s = ti.name();
#endif
return s;
}
// for use with <wiertlo/pretty_print.hpp>
struct RTTINamePolicy
{
template<typename T>
static std::string get_name()
{
std::string s = demangled(typeid(T));
// TODO: don't break on identifiers like `lolenum`
detail::replaceAll(s, "enum ", "");
detail::replaceAll(s, "struct ", "");
detail::replaceAll(s, "class ", "");
detail::replaceAll(s, "union ", "");
return s;
}
};
}<commit_msg>Add missing `inline`<commit_after>#pragma once
#include <string>
#ifndef _MSC_VER
#include <cxxabi.h>
#endif
namespace wiertlo
{
namespace detail
{
inline void replaceAll(std::string& source, const std::string& from, const std::string& to)
{
std::string newString;
newString.reserve(source.length()); // avoids a few memory allocations
std::string::size_type lastPos = 0;
std::string::size_type findPos;
while(std::string::npos != (findPos = source.find(from, lastPos)))
{
newString.append(source, lastPos, findPos - lastPos);
newString += to;
lastPos = findPos + from.length();
}
// Care for the rest after last occurrence
newString += source.substr(lastPos);
source.swap(newString);
}
struct free_deleter
{
template<typename T>
void operator()(T* ptr)
{
free(ptr);
}
};
}
inline std::string demangled(const std::type_info& ti)
{
#ifndef _MSC_VER
int status;
std::size_t length;
std::unique_ptr<char, detail::free_deleter> demangled(abi::__cxa_demangle(ti.name(), nullptr, &length, &status));
if(status != 0)
throw "FUCK";
std::string s = demangled.get();
#else
std::string s = ti.name();
#endif
return s;
}
// for use with <wiertlo/pretty_print.hpp>
struct RTTINamePolicy
{
template<typename T>
static std::string get_name()
{
std::string s = demangled(typeid(T));
// TODO: don't break on identifiers like `lolenum`
detail::replaceAll(s, "enum ", "");
detail::replaceAll(s, "struct ", "");
detail::replaceAll(s, "class ", "");
detail::replaceAll(s, "union ", "");
return s;
}
};
}<|endoftext|> |
<commit_before>#pragma once
#include <tuple>
#include <type_traits>
#include <cmath>
#include <limits>
namespace spn {
//! 累積カウンタの比較用
template <class T>
bool CompareAndSet(T& num, const T& target) {
if(num != target) {
num = target;
return true;
}
return false;
}
//! コンパイル時数値計算 & 比較
template <int M, int N>
struct TValue {
enum { add = M+N,
sub = M-N,
less = (M>N) ? N : M,
great = (M>N) ? M : N,
less_eq = (M<=N) ? 1 : 0,
great_eq = (M>=N) ? 1 : 0,
lesser = (M<N) ? 1 : 0,
greater = (M>N) ? 1 : 0,
equal = M==N ? 1 : 0
};
};
//! bool -> std::true_type or std::false_type
template <int V>
using TFCond = typename std::conditional<V!=0, std::true_type, std::false_type>::type;
//! 2つの定数の演算結果をstd::true_type か std::false_typeで返す
template <int N, int M>
struct NType {
using t_and = TFCond<(N&M)>;
using t_or = TFCond<(N|M)>;
using t_xor = TFCond<(N^M)>;
using t_nand = TFCond<((N&M) ^ 0x01)>;
using less = TFCond<(N<M)>;
using great = TFCond<(N>M)>;
using equal = TFCond<N==M>;
using not_equal = TFCond<N!=M>;
using less_eq = TFCond<(N<=M)>;
using great_eq = TFCond<(N>=M)>;
};
//! 2つのintegral_constant<bool>を論理演算
template <class T0, class T1>
struct TType {
constexpr static int I0 = std::is_same<T0, std::true_type>::value,
I1 = std::is_same<T1, std::true_type>::value;
using t_and = TFCond<I0&I1>;
using t_or = TFCond<I0|I1>;
using t_xor = TFCond<I0^I1>;
using t_nand = TFCond<(I0&I1) ^ 0x01>;
};
//! 条件式の評価結果がfalseの場合、マクロ定義した箇所には到達しないことを保証
#define __assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0);
//! 最大値を取得
template <int... N>
struct TMax {
constexpr static int result = 0; };
template <int N0, int... N>
struct TMax<N0, N...> {
constexpr static int result = N0; };
template <int N0, int N1, int... N>
struct TMax<N0, N1, N...> {
constexpr static int result = TValue<N0, TMax<N1, N...>::result>::great; };
//! SFINAEで関数を無効化する際に使うダミー変数
static void* Enabler;
//! コンパイル時定数で数値のN*10乗を計算
template <class T, int N, typename std::enable_if<N==0>::type*& = Enabler>
constexpr T ConstantPow10(T value=1, std::integral_constant<int,N>* =nullptr) {
return value;
}
template <class T, int N, typename std::enable_if<(N<0)>::type*& = Enabler>
constexpr T ConstantPow10(T value=1, std::integral_constant<int,N>* =nullptr) {
return ConstantPow10(value/10, (std::integral_constant<int,N+1>*)nullptr);
}
template <class T, int N, typename std::enable_if<(N>0)>::type*& = Enabler>
constexpr T ConstantPow10(T value=1.f, std::integral_constant<int,N>* =nullptr) {
return ConstantPow10(value*10, (std::integral_constant<int,N-1>*)nullptr);
}
//! std::tupleのハッシュを計算
struct TupleHash {
template <class Tup>
static size_t get(size_t value, const Tup& /*tup*/, std::integral_constant<int,-1>) { return value; }
template <class Tup, int N>
static size_t get(size_t value, const Tup& tup, std::integral_constant<int,N>) {
const auto& t = std::get<N>(tup);
size_t h = std::hash<typename std::decay<decltype(t)>::type>()(t);
value = (value ^ (h<<(h&0x07))) ^ (h>>3);
return get(value, tup, std::integral_constant<int,N-1>());
}
template <class... Ts>
size_t operator()(const std::tuple<Ts...>& tup) const {
return get(0xdeadbeef * 0xdeadbeef, tup, std::integral_constant<int,sizeof...(Ts)-1>());
}
};
//! クラスがwidthフィールドを持っていればintegral_constantでそれを返す
template <class T>
std::integral_constant<int,T::width> _GetWidthT(decltype(T::width)*);
template <class T>
std::integral_constant<int,0> _GetWidthT(...);
template <class T>
decltype(_GetWidthT<T>(nullptr)) GetWidthT();
//! クラスがheightフィールドを持っていればintegral_constantでそれを返す
template <class T>
std::integral_constant<int,T::height> _GetHeightT(decltype(T::height)*);
template <class T>
std::integral_constant<int,0> _GetHeightT(...);
template <class T>
decltype(_GetHeightT<T>(nullptr)) GetHeightT();
//! クラスがwidthとheightフィールドを持っていればintegral_pairでそれを返す
template <class T, T val0, T val1>
using integral_pair = std::pair<std::integral_constant<T, val0>,
std::integral_constant<T, val1>>;
template <class T>
integral_pair<int,T::height, T::width> _GetWidthHeightT(decltype(T::width)*, decltype(T::height)*);
template <class T>
integral_pair<int,0, T::width> _GetWidthHeightT(decltype(T::width)*, ...);
template <class T>
integral_pair<int,0,0> _GetWidthHeightT(...);
template <class T>
decltype(_GetWidthHeightT<T>(nullptr,nullptr)) GetWidthHeightT();
// 値比較(widthメンバ有り)
template <class T, class CMP, int N>
bool _EqFunc(const T& v0, const T& v1, CMP&& cmp, integral_pair<int,0,N>) {
for(int i=0 ; i<N ; i++) {
if(!cmp(v0.m[i], v1.m[i]))
return false;
}
return true;
}
// 値比較(width & heightメンバ有り)
template <class T, class CMP, int M, int N>
bool _EqFunc(const T& v0, const T& v1, CMP&& cmp, integral_pair<int,M,N>) {
for(int i=0 ; i<M ; i++) {
for(int j=0 ; j<N ; j++) {
if(!cmp(v0.ma[i][j], v1.ma[i][j]))
return false;
}
}
return true;
}
// 値比較(単一値)
template <class T, class CMP>
bool _EqFunc(const T& v0, const T& v1, CMP&& cmp, integral_pair<int,0,0>) {
return cmp(v0, v1);
}
//! 絶対値の誤差による等値判定
/*! \param[in] val value to check
\param[in] vExcept target value
\param[in] vEps value threshold */
template <class T, class T2>
bool EqAbs(const T& val, const T& vExcept, T2 vEps = std::numeric_limits<T>::epsilon()) {
auto fnCmp = [vEps](const auto& val, const auto& except){ return std::fabs(except-val) <= vEps; };
return _EqFunc(val, vExcept, fnCmp, decltype(GetWidthHeightT<T>())());
}
template <class T, class... Ts>
bool EqAbsT(const std::tuple<Ts...>& /*tup0*/, const std::tuple<Ts...>& /*tup1*/, const T& /*epsilon*/, std::integral_constant<int,-1>*) {
return true;
}
//! std::tuple全部の要素に対してEqAbsを呼ぶ
template <class T, int N, class... Ts, typename std::enable_if<(N>=0)>::type*& = Enabler>
bool EqAbsT(const std::tuple<Ts...>& tup0, const std::tuple<Ts...>& tup1, const T& epsilon, std::integral_constant<int,N>*) {
return EqAbs(std::get<N>(tup0), std::get<N>(tup1), epsilon)
&& EqAbsT(tup0, tup1, epsilon, (std::integral_constant<int,N-1>*)nullptr);
}
template <class... Ts, class T>
bool EqAbs(const std::tuple<Ts...>& tup0, const std::tuple<Ts...>& tup1, const T& epsilon) {
return EqAbsT<T>(tup0, tup1, epsilon, (std::integral_constant<int,sizeof...(Ts)-1>*)nullptr);
}
//! 浮動少数点数の値がNaNになっているか
template <class T, class = typename std::enable_if<std::is_floating_point<T>::value>::type>
bool IsNaN(const T& val) {
return !(val>=T(0)) && !(val<T(0)); }
//! 浮動少数点数の値がNaN又は無限大になっているか
template <class T, class = typename std::enable_if<std::is_floating_point<T>::value>::type>
bool IsOutstanding(const T& val) {
auto valA = std::fabs(val);
return valA==std::numeric_limits<float>::infinity() || IsNaN(valA); }
//! 値飽和
template <class T>
T Saturate(const T& val, const T& minV, const T& maxV) {
if(val > maxV)
return maxV;
if(val < minV)
return minV;
return val;
}
template <class T>
T Saturate(const T& val, const T& range) {
return Saturate(val, -range, range);
}
//! 値の範囲判定
template <class T>
bool IsInRange(const T& val, const T& vMin, const T& vMax) {
return val>=vMin && val<=vMax;
}
template <class T>
bool IsInRange(const T& val, const T& vMin, const T& vMax, const T& vEps) {
return IsInRange(val, vMin-vEps, vMax+vEps);
}
//! std::tupleの要素ごとの距離(EqAbs)比較
template <class T, int NPow>
struct TupleNear {
template <class P>
bool operator()(const P& t0, const P& t1) const {
return EqAbs(t0, t1, spn::ConstantPow10<T,NPow>());
}
};
template <size_t N>
struct GetCountOf_helper {
using type = char [N];
};
template <class T, size_t N>
typename GetCountOf_helper<N>::type& GetCountOf(T (&)[N]);
//! 配列の要素数を取得する (配列でない場合はエラー)
#define countof(e) sizeof(::spn::GetCountOf(e))
template <class T>
char GetCountOfNA(T);
template <class T, size_t N>
typename GetCountOf_helper<N>::type& GetCountOfNA(T (&)[N]);
//! 配列の要素数を取得する (配列でない場合は1が返る)
#define countof_na(e) sizeof(::spn::GetCountOfNA(e))
}
<commit_msg>IsCallableを追加 指定の型と引数で呼び出し可能かを調べる<commit_after>#pragma once
#include <tuple>
#include <type_traits>
#include <cmath>
#include <limits>
namespace spn {
//! 累積カウンタの比較用
template <class T>
bool CompareAndSet(T& num, const T& target) {
if(num != target) {
num = target;
return true;
}
return false;
}
//! コンパイル時数値計算 & 比較
template <int M, int N>
struct TValue {
enum { add = M+N,
sub = M-N,
less = (M>N) ? N : M,
great = (M>N) ? M : N,
less_eq = (M<=N) ? 1 : 0,
great_eq = (M>=N) ? 1 : 0,
lesser = (M<N) ? 1 : 0,
greater = (M>N) ? 1 : 0,
equal = M==N ? 1 : 0
};
};
//! bool -> std::true_type or std::false_type
template <int V>
using TFCond = typename std::conditional<V!=0, std::true_type, std::false_type>::type;
//! 2つの定数の演算結果をstd::true_type か std::false_typeで返す
template <int N, int M>
struct NType {
using t_and = TFCond<(N&M)>;
using t_or = TFCond<(N|M)>;
using t_xor = TFCond<(N^M)>;
using t_nand = TFCond<((N&M) ^ 0x01)>;
using less = TFCond<(N<M)>;
using great = TFCond<(N>M)>;
using equal = TFCond<N==M>;
using not_equal = TFCond<N!=M>;
using less_eq = TFCond<(N<=M)>;
using great_eq = TFCond<(N>=M)>;
};
//! 2つのintegral_constant<bool>を論理演算
template <class T0, class T1>
struct TType {
constexpr static int I0 = std::is_same<T0, std::true_type>::value,
I1 = std::is_same<T1, std::true_type>::value;
using t_and = TFCond<I0&I1>;
using t_or = TFCond<I0|I1>;
using t_xor = TFCond<I0^I1>;
using t_nand = TFCond<(I0&I1) ^ 0x01>;
};
//! 条件式の評価結果がfalseの場合、マクロ定義した箇所には到達しないことを保証
#define __assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0);
//! 最大値を取得
template <int... N>
struct TMax {
constexpr static int result = 0; };
template <int N0, int... N>
struct TMax<N0, N...> {
constexpr static int result = N0; };
template <int N0, int N1, int... N>
struct TMax<N0, N1, N...> {
constexpr static int result = TValue<N0, TMax<N1, N...>::result>::great; };
//! SFINAEで関数を無効化する際に使うダミー変数
static void* Enabler;
//! コンパイル時定数で数値のN*10乗を計算
template <class T, int N, typename std::enable_if<N==0>::type*& = Enabler>
constexpr T ConstantPow10(T value=1, std::integral_constant<int,N>* =nullptr) {
return value;
}
template <class T, int N, typename std::enable_if<(N<0)>::type*& = Enabler>
constexpr T ConstantPow10(T value=1, std::integral_constant<int,N>* =nullptr) {
return ConstantPow10(value/10, (std::integral_constant<int,N+1>*)nullptr);
}
template <class T, int N, typename std::enable_if<(N>0)>::type*& = Enabler>
constexpr T ConstantPow10(T value=1.f, std::integral_constant<int,N>* =nullptr) {
return ConstantPow10(value*10, (std::integral_constant<int,N-1>*)nullptr);
}
//! std::tupleのハッシュを計算
struct TupleHash {
template <class Tup>
static size_t get(size_t value, const Tup& /*tup*/, std::integral_constant<int,-1>) { return value; }
template <class Tup, int N>
static size_t get(size_t value, const Tup& tup, std::integral_constant<int,N>) {
const auto& t = std::get<N>(tup);
size_t h = std::hash<typename std::decay<decltype(t)>::type>()(t);
value = (value ^ (h<<(h&0x07))) ^ (h>>3);
return get(value, tup, std::integral_constant<int,N-1>());
}
template <class... Ts>
size_t operator()(const std::tuple<Ts...>& tup) const {
return get(0xdeadbeef * 0xdeadbeef, tup, std::integral_constant<int,sizeof...(Ts)-1>());
}
};
//! クラスがwidthフィールドを持っていればintegral_constantでそれを返す
template <class T>
std::integral_constant<int,T::width> _GetWidthT(decltype(T::width)*);
template <class T>
std::integral_constant<int,0> _GetWidthT(...);
template <class T>
decltype(_GetWidthT<T>(nullptr)) GetWidthT();
//! クラスがheightフィールドを持っていればintegral_constantでそれを返す
template <class T>
std::integral_constant<int,T::height> _GetHeightT(decltype(T::height)*);
template <class T>
std::integral_constant<int,0> _GetHeightT(...);
template <class T>
decltype(_GetHeightT<T>(nullptr)) GetHeightT();
//! クラスがwidthとheightフィールドを持っていればintegral_pairでそれを返す
template <class T, T val0, T val1>
using integral_pair = std::pair<std::integral_constant<T, val0>,
std::integral_constant<T, val1>>;
template <class T>
integral_pair<int,T::height, T::width> _GetWidthHeightT(decltype(T::width)*, decltype(T::height)*);
template <class T>
integral_pair<int,0, T::width> _GetWidthHeightT(decltype(T::width)*, ...);
template <class T>
integral_pair<int,0,0> _GetWidthHeightT(...);
template <class T>
decltype(_GetWidthHeightT<T>(nullptr,nullptr)) GetWidthHeightT();
// 値比較(widthメンバ有り)
template <class T, class CMP, int N>
bool _EqFunc(const T& v0, const T& v1, CMP&& cmp, integral_pair<int,0,N>) {
for(int i=0 ; i<N ; i++) {
if(!cmp(v0.m[i], v1.m[i]))
return false;
}
return true;
}
// 値比較(width & heightメンバ有り)
template <class T, class CMP, int M, int N>
bool _EqFunc(const T& v0, const T& v1, CMP&& cmp, integral_pair<int,M,N>) {
for(int i=0 ; i<M ; i++) {
for(int j=0 ; j<N ; j++) {
if(!cmp(v0.ma[i][j], v1.ma[i][j]))
return false;
}
}
return true;
}
// 値比較(単一値)
template <class T, class CMP>
bool _EqFunc(const T& v0, const T& v1, CMP&& cmp, integral_pair<int,0,0>) {
return cmp(v0, v1);
}
//! 絶対値の誤差による等値判定
/*! \param[in] val value to check
\param[in] vExcept target value
\param[in] vEps value threshold */
template <class T, class T2>
bool EqAbs(const T& val, const T& vExcept, T2 vEps = std::numeric_limits<T>::epsilon()) {
auto fnCmp = [vEps](const auto& val, const auto& except){ return std::fabs(except-val) <= vEps; };
return _EqFunc(val, vExcept, fnCmp, decltype(GetWidthHeightT<T>())());
}
template <class T, class... Ts>
bool EqAbsT(const std::tuple<Ts...>& /*tup0*/, const std::tuple<Ts...>& /*tup1*/, const T& /*epsilon*/, std::integral_constant<int,-1>*) {
return true;
}
//! std::tuple全部の要素に対してEqAbsを呼ぶ
template <class T, int N, class... Ts, typename std::enable_if<(N>=0)>::type*& = Enabler>
bool EqAbsT(const std::tuple<Ts...>& tup0, const std::tuple<Ts...>& tup1, const T& epsilon, std::integral_constant<int,N>*) {
return EqAbs(std::get<N>(tup0), std::get<N>(tup1), epsilon)
&& EqAbsT(tup0, tup1, epsilon, (std::integral_constant<int,N-1>*)nullptr);
}
template <class... Ts, class T>
bool EqAbs(const std::tuple<Ts...>& tup0, const std::tuple<Ts...>& tup1, const T& epsilon) {
return EqAbsT<T>(tup0, tup1, epsilon, (std::integral_constant<int,sizeof...(Ts)-1>*)nullptr);
}
//! 浮動少数点数の値がNaNになっているか
template <class T, class = typename std::enable_if<std::is_floating_point<T>::value>::type>
bool IsNaN(const T& val) {
return !(val>=T(0)) && !(val<T(0)); }
//! 浮動少数点数の値がNaN又は無限大になっているか
template <class T, class = typename std::enable_if<std::is_floating_point<T>::value>::type>
bool IsOutstanding(const T& val) {
auto valA = std::fabs(val);
return valA==std::numeric_limits<float>::infinity() || IsNaN(valA); }
//! 値飽和
template <class T>
T Saturate(const T& val, const T& minV, const T& maxV) {
if(val > maxV)
return maxV;
if(val < minV)
return minV;
return val;
}
template <class T>
T Saturate(const T& val, const T& range) {
return Saturate(val, -range, range);
}
//! 値の範囲判定
template <class T>
bool IsInRange(const T& val, const T& vMin, const T& vMax) {
return val>=vMin && val<=vMax;
}
template <class T>
bool IsInRange(const T& val, const T& vMin, const T& vMax, const T& vEps) {
return IsInRange(val, vMin-vEps, vMax+vEps);
}
//! std::tupleの要素ごとの距離(EqAbs)比較
template <class T, int NPow>
struct TupleNear {
template <class P>
bool operator()(const P& t0, const P& t1) const {
return EqAbs(t0, t1, spn::ConstantPow10<T,NPow>());
}
};
template <size_t N>
struct GetCountOf_helper {
using type = char [N];
};
template <class T, size_t N>
typename GetCountOf_helper<N>::type& GetCountOf(T (&)[N]);
//! 配列の要素数を取得する (配列でない場合はエラー)
#define countof(e) sizeof(::spn::GetCountOf(e))
template <class T>
char GetCountOfNA(T);
template <class T, size_t N>
typename GetCountOf_helper<N>::type& GetCountOfNA(T (&)[N]);
//! 配列の要素数を取得する (配列でない場合は1が返る)
#define countof_na(e) sizeof(::spn::GetCountOfNA(e))
template <class T, class... Args>
class IsCallable {
private:
template <class F>
static std::true_type _check(decltype(std::declval<F>()(std::declval<Args>()...), (void)0)*);
template <class F>
static std::false_type _check(...);
public:
using type = decltype(_check<T>(nullptr));
constexpr static bool value = type::value;
};
}
<|endoftext|> |
<commit_before>/**@file Logical Channel. */
/*
* Copyright 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
* Copyright 2010 Kestrel Signal Processing, Inc.
* Copyright 2011 Range Networks, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "GSML3RRElements.h"
#include "GSML3Message.h"
#include "GSML3RRMessages.h"
#include "GSMLogicalChannel.h"
#include "GSMConfig.h"
#include <TransactionTable.h>
#include <SMSControl.h>
#include <ControlCommon.h>
#include <Logger.h>
#undef WARNING
using namespace std;
using namespace GSM;
void LogicalChannel::open()
{
LOG(INFO);
if (mSACCH) mSACCH->open();
if (mL1) mL1->open();
for (int s=0; s<4; s++) {
if (mL2[s]) mL2[s]->open();
}
// Empty any stray transactions in the FIFO from the SIP layer.
while (true) {
Control::TransactionEntry *trans = mTransactionFIFO.readNoBlock();
if (!trans) break;
LOG(WARNING) << "flushing stray transaction " << *trans;
// FIXME -- Shouldn't we be deleting these?
}
}
void LogicalChannel::connect()
{
mMux.downstream(mL1);
if (mL1) mL1->upstream(&mMux);
for (int s=0; s<4; s++) {
mMux.upstream(mL2[s],s);
if (mL2[s]) mL2[s]->downstream(&mMux);
}
}
void LogicalChannel::downstream(ARFCNManager* radio)
{
assert(mL1);
mL1->downstream(radio);
if (mSACCH) mSACCH->downstream(radio);
}
// Serialize and send an L3Message with a given primitive.
void LogicalChannel::send(const L3Message& msg,
const GSM::Primitive& prim,
unsigned SAPI)
{
LOG(INFO) << "L3 SAP" << SAPI << " sending " << msg;
send(L3Frame(msg,prim), SAPI);
}
CCCHLogicalChannel::CCCHLogicalChannel(const TDMAMapping& wMapping)
:mRunning(false)
{
mL1 = new CCCHL1FEC(wMapping);
mL2[0] = new CCCHL2;
connect();
}
void CCCHLogicalChannel::open()
{
LogicalChannel::open();
if (!mRunning) {
mRunning=true;
mServiceThread.start((void*(*)(void*))CCCHLogicalChannelServiceLoopAdapter,this);
}
}
void CCCHLogicalChannel::serviceLoop()
{
// build the idle frame
static const L3PagingRequestType1 filler;
static const L3Frame idleFrame(filler,UNIT_DATA);
// prime the first idle frame
LogicalChannel::send(idleFrame);
// run the loop
while (true) {
L3Frame* frame = mQ.read();
if (frame) {
LogicalChannel::send(*frame);
OBJLOG(DEBUG) << "CCCHLogicalChannel::serviceLoop sending " << *frame;
delete frame;
}
if (mQ.size()==0) {
LogicalChannel::send(idleFrame);
OBJLOG(DEBUG) << "CCCHLogicalChannel::serviceLoop sending idle frame";
}
}
}
void *GSM::CCCHLogicalChannelServiceLoopAdapter(CCCHLogicalChannel* chan)
{
chan->serviceLoop();
return NULL;
}
L3ChannelDescription LogicalChannel::channelDescription() const
{
// In some debug cases, L1 may not exist, so we fake this information.
if (mL1==NULL) return L3ChannelDescription(TDMA_MISC,0,0,0);
// In normal cases, we get this information from L1.
return L3ChannelDescription(
mL1->typeAndOffset(),
mL1->TN(),
mL1->TSC(),
mL1->ARFCN()
);
}
SDCCHLogicalChannel::SDCCHLogicalChannel(
unsigned wCN,
unsigned wTN,
const CompleteMapping& wMapping)
{
mL1 = new SDCCHL1FEC(wCN,wTN,wMapping.LCH());
// SAP0 is RR/MM/CC, SAP3 is SMS
// SAP1 and SAP2 are not used.
L2LAPDm *SAP0L2 = new SDCCHL2(1,0);
L2LAPDm *SAP3L2 = new SDCCHL2(1,3);
LOG(DEBUG) << "LAPDm pairs SAP0=" << SAP0L2 << " SAP3=" << SAP3L2;
SAP3L2->master(SAP0L2);
mL2[0] = SAP0L2;
mL2[3] = SAP3L2;
mSACCH = new SACCHLogicalChannel(wCN,wTN,wMapping.SACCH());
connect();
}
SACCHLogicalChannel::SACCHLogicalChannel(
unsigned wCN,
unsigned wTN,
const MappingPair& wMapping)
: mRunning(false)
{
mSACCHL1 = new SACCHL1FEC(wCN,wTN,wMapping);
mL1 = mSACCHL1;
// SAP0 is RR, SAP3 is SMS
// SAP1 and SAP2 are not used.
mL2[0] = new SACCHL2(1,0);
mL2[3] = new SACCHL2(1,3);
connect();
assert(mSACCH==NULL);
}
void SACCHLogicalChannel::open()
{
LogicalChannel::open();
if (!mRunning) {
mRunning=true;
mServiceThread.start((void*(*)(void*))SACCHLogicalChannelServiceLoopAdapter,this);
}
}
L3Message* processSACCHMessage(L3Frame *l3frame)
{
if (!l3frame) return NULL;
LOG(DEBUG) << *l3frame;
Primitive prim = l3frame->primitive();
if ((prim!=DATA) && (prim!=UNIT_DATA)) {
LOG(INFO) << "non-data primitive " << prim;
return NULL;
}
// FIXME -- Why, again, do we need to do this?
// L3Frame realFrame = l3frame->segment(24, l3frame->size()-24);
L3Message* message = parseL3(*l3frame);
if (!message) {
LOG(WARNING) << "SACCH recevied unparsable L3 frame " << *l3frame;
}
return message;
}
void SACCHLogicalChannel::serviceLoop()
{
// run the loop
unsigned count = 0;
while (true) {
// Throttle back if not active.
if (!active()) {
OBJLOG(DEBUG) << "SACCH sleeping";
sleepFrames(51);
continue;
}
// TODO SMS -- Check to see if the tx queues are empty. If so, send SI5/6,
// otherwise sleep and continue;
// Send alternating SI5/SI6.
OBJLOG(DEBUG) << "sending SI5/6 on SACCH";
if (count%2) LogicalChannel::send(gBTS.SI5Frame());
else LogicalChannel::send(gBTS.SI6Frame());
count++;
// Receive inbound messages.
// This read loop flushes stray reports quickly.
while (true) {
OBJLOG(DEBUG) << "polling SACCH for inbound messages";
bool nothing = true;
// Process SAP0 -- RR Measurement reports
L3Frame *rrFrame = LogicalChannel::recv(0,0);
if (rrFrame) nothing=false;
L3Message* rrMessage = processSACCHMessage(rrFrame);
delete rrFrame;
if (rrMessage) {
L3MeasurementReport* measurement = dynamic_cast<L3MeasurementReport*>(rrMessage);
if (measurement) {
mMeasurementResults = measurement->results();
OBJLOG(DEBUG) << "SACCH measurement report " << mMeasurementResults;
// Add the measurement results to the table
// Note that the typeAndOffset of a SACCH match the host channel.
gPhysStatus.setPhysical(this, mMeasurementResults);
} else {
OBJLOG(NOTICE) << "SACCH SAP0 sent unaticipated message " << rrMessage;
}
delete rrMessage;
}
// Process SAP3 -- SMS
L3Frame *smsFrame = LogicalChannel::recv(0,3);
if (smsFrame) nothing=false;
L3Message* smsMessage = processSACCHMessage(smsFrame);
delete smsFrame;
if (smsMessage) {
const SMS::CPData* cpData = dynamic_cast<const SMS::CPData*>(smsMessage);
if (cpData) {
OBJLOG(INFO) << "SMS CPDU " << *cpData;
Control::TransactionEntry *transaction = gTransactionTable.find(this);
try {
if (transaction) {
Control::InCallMOSMSController(cpData,transaction,this);
} else {
OBJLOG(WARNING) << "in-call MOSMS CP-DATA with no corresponding transaction";
}
} catch (Control::ControlLayerException e) {
//LogicalChannel::send(RELEASE,3);
gTransactionTable.remove(e.transactionID());
}
} else {
OBJLOG(NOTICE) << "SACCH SAP3 sent unaticipated message " << rrMessage;
}
delete smsMessage;
}
// Anything from the SIP side?
// MTSMS (delivery from SIP to the MS)
Control::TransactionEntry *sipTransaction = mTransactionFIFO.readNoBlock();
if (sipTransaction) {
OBJLOG(INFO) << "SIP-side transaction: " << sipTransaction;
assert(sipTransaction->service() == L3CMServiceType::MobileTerminatedShortMessage);
try {
Control::MTSMSController(sipTransaction,this);
} catch (Control::ControlLayerException e) {
//LogicalChannel::send(RELEASE,3);
gTransactionTable.remove(e.transactionID());
}
}
// Nothing happened?
if (nothing) break;
}
}
}
void *GSM::SACCHLogicalChannelServiceLoopAdapter(SACCHLogicalChannel* chan)
{
chan->serviceLoop();
return NULL;
}
// These have to go into the .cpp file to prevent an illegal forward reference.
void LogicalChannel::setPhy(float wRSSI, float wTimingError)
{ assert(mSACCH); mSACCH->setPhy(wRSSI,wTimingError); }
void LogicalChannel::setPhy(const LogicalChannel& other)
{ assert(mSACCH); mSACCH->setPhy(*other.SACCH()); }
float LogicalChannel::RSSI() const
{ assert(mSACCH); return mSACCH->RSSI(); }
float LogicalChannel::timingError() const
{ assert(mSACCH); return mSACCH->timingError(); }
int LogicalChannel::actualMSPower() const
{ assert(mSACCH); return mSACCH->actualMSPower(); }
int LogicalChannel::actualMSTiming() const
{ assert(mSACCH); return mSACCH->actualMSTiming(); }
TCHFACCHLogicalChannel::TCHFACCHLogicalChannel(
unsigned wCN,
unsigned wTN,
const CompleteMapping& wMapping)
{
mTCHL1 = new TCHFACCHL1FEC(wCN,wTN,wMapping.LCH());
mL1 = mTCHL1;
// SAP0 is RR/MM/CC, SAP3 is SMS
// SAP1 and SAP2 are not used.
mL2[0] = new FACCHL2(1,0);
mL2[3] = new FACCHL2(1,3);
mSACCH = new SACCHLogicalChannel(wCN,wTN,wMapping.SACCH());
connect();
}
bool LogicalChannel::waitForPrimitive(Primitive primitive, unsigned timeout_ms)
{
bool waiting = true;
while (waiting) {
L3Frame *req = recv(timeout_ms);
if (req==NULL) {
LOG(NOTICE) << "timeout at uptime " << gBTS.uptime() << " frame " << gBTS.time();
return false;
}
waiting = (req->primitive()!=primitive);
delete req;
}
return true;
}
void LogicalChannel::waitForPrimitive(Primitive primitive)
{
bool waiting = true;
while (waiting) {
L3Frame *req = recv();
if (req==NULL) continue;
waiting = (req->primitive()!=primitive);
delete req;
}
}
ostream& GSM::operator<<(ostream& os, const LogicalChannel& chan)
{
os << chan.descriptiveString();
return os;
}
void LogicalChannel::addTransaction(Control::TransactionEntry *transaction)
{
assert(transaction->channel()==this);
mTransactionFIFO.write(transaction);
}
// vim: ts=4 sw=4
<commit_msg>Fixed CCCH serviceLoop().<commit_after>/**@file Logical Channel. */
/*
* Copyright 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
* Copyright 2010 Kestrel Signal Processing, Inc.
* Copyright 2011 Range Networks, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "GSML3RRElements.h"
#include "GSML3Message.h"
#include "GSML3RRMessages.h"
#include "GSMLogicalChannel.h"
#include "GSMConfig.h"
#include <TransactionTable.h>
#include <SMSControl.h>
#include <ControlCommon.h>
#include <Logger.h>
#undef WARNING
using namespace std;
using namespace GSM;
void LogicalChannel::open()
{
LOG(INFO);
if (mSACCH) mSACCH->open();
if (mL1) mL1->open();
for (int s=0; s<4; s++) {
if (mL2[s]) mL2[s]->open();
}
// Empty any stray transactions in the FIFO from the SIP layer.
while (true) {
Control::TransactionEntry *trans = mTransactionFIFO.readNoBlock();
if (!trans) break;
LOG(WARNING) << "flushing stray transaction " << *trans;
// FIXME -- Shouldn't we be deleting these?
}
}
void LogicalChannel::connect()
{
mMux.downstream(mL1);
if (mL1) mL1->upstream(&mMux);
for (int s=0; s<4; s++) {
mMux.upstream(mL2[s],s);
if (mL2[s]) mL2[s]->downstream(&mMux);
}
}
void LogicalChannel::downstream(ARFCNManager* radio)
{
assert(mL1);
mL1->downstream(radio);
if (mSACCH) mSACCH->downstream(radio);
}
// Serialize and send an L3Message with a given primitive.
void LogicalChannel::send(const L3Message& msg,
const GSM::Primitive& prim,
unsigned SAPI)
{
LOG(INFO) << "L3 SAP" << SAPI << " sending " << msg;
send(L3Frame(msg,prim), SAPI);
}
CCCHLogicalChannel::CCCHLogicalChannel(const TDMAMapping& wMapping)
:mRunning(false)
{
mL1 = new CCCHL1FEC(wMapping);
mL2[0] = new CCCHL2;
connect();
}
void CCCHLogicalChannel::open()
{
LogicalChannel::open();
if (!mRunning) {
mRunning=true;
mServiceThread.start((void*(*)(void*))CCCHLogicalChannelServiceLoopAdapter,this);
}
}
void CCCHLogicalChannel::serviceLoop()
{
// build the idle frame
static const L3PagingRequestType1 filler;
static const L3Frame idleFrame(filler,UNIT_DATA);
// prime the first idle frame
LogicalChannel::send(idleFrame);
// run the loop
while (true) {
L3Frame* frame = mQ.readNoBlock();
if (frame) {
LogicalChannel::send(*frame);
OBJLOG(DEBUG) << "CCCHLogicalChannel::serviceLoop sending " << *frame;
delete frame;
}
else {
LogicalChannel::send(idleFrame);
OBJLOG(DEBUG) << "CCCHLogicalChannel::serviceLoop sending idle frame";
}
}
}
void *GSM::CCCHLogicalChannelServiceLoopAdapter(CCCHLogicalChannel* chan)
{
chan->serviceLoop();
return NULL;
}
L3ChannelDescription LogicalChannel::channelDescription() const
{
// In some debug cases, L1 may not exist, so we fake this information.
if (mL1==NULL) return L3ChannelDescription(TDMA_MISC,0,0,0);
// In normal cases, we get this information from L1.
return L3ChannelDescription(
mL1->typeAndOffset(),
mL1->TN(),
mL1->TSC(),
mL1->ARFCN()
);
}
SDCCHLogicalChannel::SDCCHLogicalChannel(
unsigned wCN,
unsigned wTN,
const CompleteMapping& wMapping)
{
mL1 = new SDCCHL1FEC(wCN,wTN,wMapping.LCH());
// SAP0 is RR/MM/CC, SAP3 is SMS
// SAP1 and SAP2 are not used.
L2LAPDm *SAP0L2 = new SDCCHL2(1,0);
L2LAPDm *SAP3L2 = new SDCCHL2(1,3);
LOG(DEBUG) << "LAPDm pairs SAP0=" << SAP0L2 << " SAP3=" << SAP3L2;
SAP3L2->master(SAP0L2);
mL2[0] = SAP0L2;
mL2[3] = SAP3L2;
mSACCH = new SACCHLogicalChannel(wCN,wTN,wMapping.SACCH());
connect();
}
SACCHLogicalChannel::SACCHLogicalChannel(
unsigned wCN,
unsigned wTN,
const MappingPair& wMapping)
: mRunning(false)
{
mSACCHL1 = new SACCHL1FEC(wCN,wTN,wMapping);
mL1 = mSACCHL1;
// SAP0 is RR, SAP3 is SMS
// SAP1 and SAP2 are not used.
mL2[0] = new SACCHL2(1,0);
mL2[3] = new SACCHL2(1,3);
connect();
assert(mSACCH==NULL);
}
void SACCHLogicalChannel::open()
{
LogicalChannel::open();
if (!mRunning) {
mRunning=true;
mServiceThread.start((void*(*)(void*))SACCHLogicalChannelServiceLoopAdapter,this);
}
}
L3Message* processSACCHMessage(L3Frame *l3frame)
{
if (!l3frame) return NULL;
LOG(DEBUG) << *l3frame;
Primitive prim = l3frame->primitive();
if ((prim!=DATA) && (prim!=UNIT_DATA)) {
LOG(INFO) << "non-data primitive " << prim;
return NULL;
}
// FIXME -- Why, again, do we need to do this?
// L3Frame realFrame = l3frame->segment(24, l3frame->size()-24);
L3Message* message = parseL3(*l3frame);
if (!message) {
LOG(WARNING) << "SACCH recevied unparsable L3 frame " << *l3frame;
}
return message;
}
void SACCHLogicalChannel::serviceLoop()
{
// run the loop
unsigned count = 0;
while (true) {
// Throttle back if not active.
if (!active()) {
OBJLOG(DEBUG) << "SACCH sleeping";
sleepFrames(51);
continue;
}
// TODO SMS -- Check to see if the tx queues are empty. If so, send SI5/6,
// otherwise sleep and continue;
// Send alternating SI5/SI6.
OBJLOG(DEBUG) << "sending SI5/6 on SACCH";
if (count%2) LogicalChannel::send(gBTS.SI5Frame());
else LogicalChannel::send(gBTS.SI6Frame());
count++;
// Receive inbound messages.
// This read loop flushes stray reports quickly.
while (true) {
OBJLOG(DEBUG) << "polling SACCH for inbound messages";
bool nothing = true;
// Process SAP0 -- RR Measurement reports
L3Frame *rrFrame = LogicalChannel::recv(0,0);
if (rrFrame) nothing=false;
L3Message* rrMessage = processSACCHMessage(rrFrame);
delete rrFrame;
if (rrMessage) {
L3MeasurementReport* measurement = dynamic_cast<L3MeasurementReport*>(rrMessage);
if (measurement) {
mMeasurementResults = measurement->results();
OBJLOG(DEBUG) << "SACCH measurement report " << mMeasurementResults;
// Add the measurement results to the table
// Note that the typeAndOffset of a SACCH match the host channel.
gPhysStatus.setPhysical(this, mMeasurementResults);
} else {
OBJLOG(NOTICE) << "SACCH SAP0 sent unaticipated message " << rrMessage;
}
delete rrMessage;
}
// Process SAP3 -- SMS
L3Frame *smsFrame = LogicalChannel::recv(0,3);
if (smsFrame) nothing=false;
L3Message* smsMessage = processSACCHMessage(smsFrame);
delete smsFrame;
if (smsMessage) {
const SMS::CPData* cpData = dynamic_cast<const SMS::CPData*>(smsMessage);
if (cpData) {
OBJLOG(INFO) << "SMS CPDU " << *cpData;
Control::TransactionEntry *transaction = gTransactionTable.find(this);
try {
if (transaction) {
Control::InCallMOSMSController(cpData,transaction,this);
} else {
OBJLOG(WARNING) << "in-call MOSMS CP-DATA with no corresponding transaction";
}
} catch (Control::ControlLayerException e) {
//LogicalChannel::send(RELEASE,3);
gTransactionTable.remove(e.transactionID());
}
} else {
OBJLOG(NOTICE) << "SACCH SAP3 sent unaticipated message " << rrMessage;
}
delete smsMessage;
}
// Anything from the SIP side?
// MTSMS (delivery from SIP to the MS)
Control::TransactionEntry *sipTransaction = mTransactionFIFO.readNoBlock();
if (sipTransaction) {
OBJLOG(INFO) << "SIP-side transaction: " << sipTransaction;
assert(sipTransaction->service() == L3CMServiceType::MobileTerminatedShortMessage);
try {
Control::MTSMSController(sipTransaction,this);
} catch (Control::ControlLayerException e) {
//LogicalChannel::send(RELEASE,3);
gTransactionTable.remove(e.transactionID());
}
}
// Nothing happened?
if (nothing) break;
}
}
}
void *GSM::SACCHLogicalChannelServiceLoopAdapter(SACCHLogicalChannel* chan)
{
chan->serviceLoop();
return NULL;
}
// These have to go into the .cpp file to prevent an illegal forward reference.
void LogicalChannel::setPhy(float wRSSI, float wTimingError)
{ assert(mSACCH); mSACCH->setPhy(wRSSI,wTimingError); }
void LogicalChannel::setPhy(const LogicalChannel& other)
{ assert(mSACCH); mSACCH->setPhy(*other.SACCH()); }
float LogicalChannel::RSSI() const
{ assert(mSACCH); return mSACCH->RSSI(); }
float LogicalChannel::timingError() const
{ assert(mSACCH); return mSACCH->timingError(); }
int LogicalChannel::actualMSPower() const
{ assert(mSACCH); return mSACCH->actualMSPower(); }
int LogicalChannel::actualMSTiming() const
{ assert(mSACCH); return mSACCH->actualMSTiming(); }
TCHFACCHLogicalChannel::TCHFACCHLogicalChannel(
unsigned wCN,
unsigned wTN,
const CompleteMapping& wMapping)
{
mTCHL1 = new TCHFACCHL1FEC(wCN,wTN,wMapping.LCH());
mL1 = mTCHL1;
// SAP0 is RR/MM/CC, SAP3 is SMS
// SAP1 and SAP2 are not used.
mL2[0] = new FACCHL2(1,0);
mL2[3] = new FACCHL2(1,3);
mSACCH = new SACCHLogicalChannel(wCN,wTN,wMapping.SACCH());
connect();
}
bool LogicalChannel::waitForPrimitive(Primitive primitive, unsigned timeout_ms)
{
bool waiting = true;
while (waiting) {
L3Frame *req = recv(timeout_ms);
if (req==NULL) {
LOG(NOTICE) << "timeout at uptime " << gBTS.uptime() << " frame " << gBTS.time();
return false;
}
waiting = (req->primitive()!=primitive);
delete req;
}
return true;
}
void LogicalChannel::waitForPrimitive(Primitive primitive)
{
bool waiting = true;
while (waiting) {
L3Frame *req = recv();
if (req==NULL) continue;
waiting = (req->primitive()!=primitive);
delete req;
}
}
ostream& GSM::operator<<(ostream& os, const LogicalChannel& chan)
{
os << chan.descriptiveString();
return os;
}
void LogicalChannel::addTransaction(Control::TransactionEntry *transaction)
{
assert(transaction->channel()==this);
mTransactionFIFO.write(transaction);
}
// vim: ts=4 sw=4
<|endoftext|> |
<commit_before>#include "RPIBeerPongController.h"
#include <signal.h>
#include <unistd.h>
#include "OCPlatform.h"
#include "OCApi.h"
using namespace OIC;
using namespace Service;
RPIBeerPongController::Ptr controller;
#define FREQUENCY_MILLISECONDS 500000 // 500 MS
/*
* This is a signal handling function for SIGINT(CTRL+C).
* A Resource Coordinator handle the SIGINT signal for safe exit.
*
* @param[in] signal
* signal number of caught signal.
*/
int g_quitFlag = 0;
void handleSigInt(int signum)
{
if (signum == SIGINT)
{
g_quitFlag = 1;
}
}
int main()
{
std::cout << "Starting test program" << std::endl;
controller = RPIBeerPongController::Ptr(RPIBeerPongController::getInstance());
static char buffer[50] = {};
while (!g_quitFlag)
{
if(OCProcess() != OC_STACK_OK)
{
return 0;
}
uint8_t data[4] = {};
int len, val;
printf("Input 4 new data values. \n");
acquireMutex();
for(size_t i = 0; i < 4; i++)
{
fgets(buffer, 50, stdin);
len = strlen(buffer) - 1;
for(size_t i = 0; i < len; ++i)
{
if(!isdigit(buffer[i]))
{
printf("Invalid input");
return 1;
}
}
val = atoi(buffer);
data[i] = val;
}
setTestData(data);
releaseMutex();
usleep(FREQUENCY_MILLISECONDS);
}
return 0;
}
<commit_msg>ADded individual runthread<commit_after>#include "RPIBeerPongController.h"
#include <signal.h>
#include <unistd.h>
#include <thread>
#include "OCPlatform.h"
#include "OCApi.h"
using namespace OIC;
using namespace Service;
RPIBeerPongController::Ptr controller;
#define FREQUENCY_MILLISECONDS 500000 // 500 MS
/*
* This is a signal handling function for SIGINT(CTRL+C).
* A Resource Coordinator handle the SIGINT signal for safe exit.
*
* @param[in] signal
* signal number of caught signal.
*/
int g_quitFlag = 0;
void handleSigInt(int signum)
{
if (signum == SIGINT)
{
g_quitFlag = 1;
}
}
void runOCThread()
{
while(!g_quitFlag)
{
if(OCProcess() != OC_STACK_OK)
{
break;
}
usleep(10);
}
}
int main()
{
std::cout << "Starting test program" << std::endl;
controller = RPIBeerPongController::Ptr(RPIBeerPongController::getInstance());
std::thread runThread(runOCThread);
runThread.detach();
static char buffer[50] = {};
while (!g_quitFlag)
{
uint8_t data[4] = {};
int len, val;
printf("Input 4 new data values. \n");
acquireMutex();
for(size_t i = 0; i < 4; i++)
{
fgets(buffer, 50, stdin);
len = strlen(buffer) - 1;
for(size_t i = 0; i < len; ++i)
{
if(!isdigit(buffer[i]))
{
printf("Invalid input");
return 1;
}
}
val = atoi(buffer);
data[i] = val;
}
setTestData(data);
releaseMutex();
printf("After released mutex\n");
usleep(FREQUENCY_MILLISECONDS);
printf("after usleep\n");
}
return 0;
}
<|endoftext|> |
<commit_before>#include "../include/semver/semver.hpp"
#include <sstream>
#include <exception>
#include <boost/regex.hpp>
using std::stringstream;
namespace semver {
static unsigned
string_to_int(const string value) {
stringstream ss(value);
unsigned result;
ss >> result;
return result;
}
/*
* Methods names 'major' and 'minor' conflicts with sys/sysmacros.h, but POSIX
* says they must be available, so with the next lines, those macros are
* undefined. See more information at:
* http://stackoverflow.com/questions/22240973/major-and-minor-macros-defined-in-sys-sysmacros-h-pulled-in-by-iterator
*/
#undef major
#undef minor
static const string NUMBER_SEPARATOR = ".";
static const string LABEL_SEPARATOR = "-";
static const string BUILD_SEPARATOR = "+";
SemVer::SemVer()
: fMajor(0),
fMinor(0),
fPatch(0),
fLabel(),
fBuild()
{
}
SemVer::SemVer(const SemVer& s)
: fMajor(s.fMajor),
fMinor(s.fMinor),
fPatch(s.fPatch),
fLabel(s.fLabel),
fBuild(s.fBuild)
{
}
SemVer::SemVer(unsigned major, unsigned minor, unsigned patch, const string label, const string build)
: fMajor(major),
fMinor(minor),
fPatch(patch),
fLabel(label),
fBuild(build)
{
}
SemVer::SemVer(const string version)
: fMajor(0),
fMinor(0),
fPatch(0),
fLabel(),
fBuild()
{
assign(version);
}
SemVer::~SemVer() {
}
void
SemVer::check(const string version) const {
if (version != toString()) {
throw std::invalid_argument("Invalid semantic version string: " + version);
}
}
int
SemVer::intCompare(unsigned a, unsigned b) const {
return (a < b) ? -1 : (a > b);
}
int
SemVer::stringCompare(string a, string b) const {
// TODO: Implement this with element precedence rules.
return a.compare(b);
}
void
SemVer::assign(const string version) {
// Examples: 1.2.3, 1.2.3-beta, 1.2.3-beta+build, 1.2.3+build
// RegEx: ([0-9]+)\.([0-9]+)\.([0-9]+)(?:-(\w+)(\+(.*))?|\+(.*))?
// Matches: 1, 2 and 3: version parts. 4 is always de label part (alpha,
// beta, etc.); 6 or 7 are the build metainformation part.
static const boost::regex expression("([0-9]+)\\.([0-9]+)\\.([0-9]+)(?:-(\\w+(\\.\\w*)?)(\\+(.*))?|\\+(.*))?");
boost::match_results<string::const_iterator> results;
if (boost::regex_search(version, results, expression)) {
fMajor = string_to_int(results[1]);
fMinor = string_to_int(results[2]);
fPatch = string_to_int(results[3]);
fLabel = results[4];
fBuild = results[6] != "" ? results[6] : results[7];
check(version);
} else {
throw std::invalid_argument("Invalid semantic version string: " + version);
}
}
unsigned
SemVer::major() const {
return fMajor;
}
unsigned
SemVer::minor() const {
return fMinor;
}
unsigned
SemVer::patch() const {
return fPatch;
}
const string
SemVer::label() const {
return fLabel;
}
const string
SemVer::build() const {
return fBuild;
}
int
SemVer::compare(const SemVer& semver) const {
if (fMajor == semver.fMajor) {
if (fMinor == semver.fMinor) {
if (fPatch == semver.fPatch) {
if (fLabel == semver.fLabel) {
return stringCompare(fBuild, semver.fBuild);
} else {
return stringCompare(fLabel, semver.fLabel);
}
} else {
return intCompare(fPatch, semver.fPatch);
}
} else {
return intCompare(fMinor, semver.fMinor);
}
} else {
return intCompare(fMajor, semver.fMajor);
}
return 0;
}
int
SemVer::compare(const SemVer* semver) const {
return compare(*semver);
}
bool
SemVer::operator == (const SemVer& semver) const {
return compare(semver) == 0;
}
bool
SemVer::operator != (const SemVer& semver) const {
return !operator==(semver);
}
bool
SemVer::operator < (const SemVer& semver) const {
return compare(semver) < 0;
}
bool
SemVer::operator > (const SemVer& semver) const {
return compare(semver) > 0;
}
bool
SemVer::operator <= (const SemVer& semver) const {
return compare(semver) <= 0;
}
bool
SemVer::operator >= (const SemVer& semver) const {
return compare(semver) >= 0;
}
const string
SemVer::toString() const {
stringstream out;
out << fMajor << NUMBER_SEPARATOR << fMinor << NUMBER_SEPARATOR << fPatch << (fLabel != "" ? LABEL_SEPARATOR + fLabel : "") << (fBuild != "" ? BUILD_SEPARATOR + fBuild : "");
return out.str();
}
std::ostream&
operator << (std::ostream& out, const SemVer& semver) {
out << semver.toString();
return out;
}
} // namespace semver
<commit_msg>Fix problem getting build information.<commit_after>#include "../include/semver/semver.hpp"
#include <sstream>
#include <exception>
#include <boost/regex.hpp>
using std::stringstream;
namespace semver {
static unsigned
string_to_int(const string value) {
stringstream ss(value);
unsigned result;
ss >> result;
return result;
}
/*
* Methods names 'major' and 'minor' conflicts with sys/sysmacros.h, but POSIX
* says they must be available, so with the next lines, those macros are
* undefined. See more information at:
* http://stackoverflow.com/questions/22240973/major-and-minor-macros-defined-in-sys-sysmacros-h-pulled-in-by-iterator
*/
#undef major
#undef minor
static const string NUMBER_SEPARATOR = ".";
static const string LABEL_SEPARATOR = "-";
static const string BUILD_SEPARATOR = "+";
SemVer::SemVer()
: fMajor(0),
fMinor(0),
fPatch(0),
fLabel(),
fBuild()
{
}
SemVer::SemVer(const SemVer& s)
: fMajor(s.fMajor),
fMinor(s.fMinor),
fPatch(s.fPatch),
fLabel(s.fLabel),
fBuild(s.fBuild)
{
}
SemVer::SemVer(unsigned major, unsigned minor, unsigned patch, const string label, const string build)
: fMajor(major),
fMinor(minor),
fPatch(patch),
fLabel(label),
fBuild(build)
{
}
SemVer::SemVer(const string version)
: fMajor(0),
fMinor(0),
fPatch(0),
fLabel(),
fBuild()
{
assign(version);
}
SemVer::~SemVer() {
}
void
SemVer::check(const string version) const {
if (version != toString()) {
throw std::invalid_argument("Invalid semantic version string: " + version);
}
}
int
SemVer::intCompare(unsigned a, unsigned b) const {
return (a < b) ? -1 : (a > b);
}
int
SemVer::stringCompare(string a, string b) const {
// TODO: Implement this with element precedence rules.
return a.compare(b);
}
void
SemVer::assign(const string version) {
// Examples: 1.2.3, 1.2.3-beta, 1.2.3-beta+build, 1.2.3+build
// RegEx: ([0-9]+)\.([0-9]+)\.([0-9]+)(?:-(\w+)(\+(.*))?|\+(.*))?
// Matches: 1, 2 and 3: version parts. 4 is always de label part (alpha,
// beta, etc.); 6 or 7 are the build metainformation part.
static const boost::regex expression("([0-9]+)\\.([0-9]+)\\.([0-9]+)(?:-(\\w+(\\.\\w*)?)(\\+(.*))?|\\+(.*))?");
boost::match_results<string::const_iterator> results;
if (boost::regex_search(version, results, expression)) {
fMajor = string_to_int(results[1]);
fMinor = string_to_int(results[2]);
fPatch = string_to_int(results[3]);
fLabel = results[4];
fBuild = results[7] != "" ? results[7] : results[8];
check(version);
} else {
throw std::invalid_argument("Invalid semantic version string: " + version);
}
}
unsigned
SemVer::major() const {
return fMajor;
}
unsigned
SemVer::minor() const {
return fMinor;
}
unsigned
SemVer::patch() const {
return fPatch;
}
const string
SemVer::label() const {
return fLabel;
}
const string
SemVer::build() const {
return fBuild;
}
int
SemVer::compare(const SemVer& semver) const {
if (fMajor == semver.fMajor) {
if (fMinor == semver.fMinor) {
if (fPatch == semver.fPatch) {
if (fLabel == semver.fLabel) {
return stringCompare(fBuild, semver.fBuild);
} else {
return stringCompare(fLabel, semver.fLabel);
}
} else {
return intCompare(fPatch, semver.fPatch);
}
} else {
return intCompare(fMinor, semver.fMinor);
}
} else {
return intCompare(fMajor, semver.fMajor);
}
return 0;
}
int
SemVer::compare(const SemVer* semver) const {
return compare(*semver);
}
bool
SemVer::operator == (const SemVer& semver) const {
return compare(semver) == 0;
}
bool
SemVer::operator != (const SemVer& semver) const {
return !operator==(semver);
}
bool
SemVer::operator < (const SemVer& semver) const {
return compare(semver) < 0;
}
bool
SemVer::operator > (const SemVer& semver) const {
return compare(semver) > 0;
}
bool
SemVer::operator <= (const SemVer& semver) const {
return compare(semver) <= 0;
}
bool
SemVer::operator >= (const SemVer& semver) const {
return compare(semver) >= 0;
}
const string
SemVer::toString() const {
stringstream out;
out << fMajor << NUMBER_SEPARATOR << fMinor << NUMBER_SEPARATOR << fPatch << (fLabel != "" ? LABEL_SEPARATOR + fLabel : "") << (fBuild != "" ? BUILD_SEPARATOR + fBuild : "");
return out.str();
}
std::ostream&
operator << (std::ostream& out, const SemVer& semver) {
out << semver.toString();
return out;
}
} // namespace semver
<|endoftext|> |
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005 darkbits Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ^
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef GCN_LISTBOX_HPP
#define GCN_LISTBOX_HPP
#include "guichan/keylistener.hpp"
#include "guichan/listmodel.hpp"
#include "guichan/mouselistener.hpp"
#include "guichan/platform.hpp"
#include "guichan/widget.hpp"
namespace gcn
{
/**
* A ListBox displaying a list in which elemets can be selected. Only one
* element can be selected at time. ListBox uses a ListModel to handle the
* list. To be able to use ListBox you must give ListBox an implemented
* ListModel which represents your list.
*/
class GCN_CORE_DECLSPEC ListBox :
public Widget,
public MouseListener,
public KeyListener
{
public:
/**
* Constructor.
*/
ListBox();
/**
* Constructor.
*
* @param listModel the ListModel to use.
*/
ListBox(ListModel *listModel);
/**
* Destructor.
*/
virtual ~ListBox() { }
/**
* Gets the ListModel index of the selected element.
*
* @return the ListModel index of the selected element.
*/
virtual int getSelected();
/**
* Sets the ListModel index of the selected element.
*
* @param selected the ListModel index of the selected element.
*/
virtual void setSelected(int selected);
/**
* Sets the ListModel to use.
*
* @param listModel the ListModel to use.
*/
virtual void setListModel(ListModel *listModel);
/**
* Gets the ListModel used.
*
* @return the ListModel used.
*/
virtual ListModel *getListModel();
/**
* Adjusts the size of the ListBox to fit the font used.
*/
virtual void adjustSize();
// Inherited from Widget
virtual void draw(Graphics* graphics);
virtual void drawBorder(Graphics* graphics);
virtual void logic();
// Inherited from KeyListener
virtual void keyPress(const Key& key);
// Inherited from MouseListener
virtual void mousePress(int x, int y, int button);
protected:
ListModel *mListModel;
int mSelected;
};
}
#endif // end GCN_LISTBOX_HPP
<commit_msg>Ability for wrapping keyboard selection has been added.<commit_after>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005 darkbits Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ^
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef GCN_LISTBOX_HPP
#define GCN_LISTBOX_HPP
#include "guichan/keylistener.hpp"
#include "guichan/listmodel.hpp"
#include "guichan/mouselistener.hpp"
#include "guichan/platform.hpp"
#include "guichan/widget.hpp"
namespace gcn
{
/**
* A ListBox displaying a list in which elemets can be selected. Only one
* element can be selected at time. ListBox uses a ListModel to handle the
* list. To be able to use ListBox you must give ListBox an implemented
* ListModel which represents your list.
*/
class GCN_CORE_DECLSPEC ListBox :
public Widget,
public MouseListener,
public KeyListener
{
public:
/**
* Constructor.
*/
ListBox();
/**
* Constructor.
*
* @param listModel the ListModel to use.
*/
ListBox(ListModel *listModel);
/**
* Destructor.
*/
virtual ~ListBox() { }
/**
* Gets the ListModel index of the selected element.
*
* @return the ListModel index of the selected element.
*/
virtual int getSelected();
/**
* Sets the ListModel index of the selected element.
*
* @param selected the ListModel index of the selected element.
*/
virtual void setSelected(int selected);
/**
* Sets the ListModel to use.
*
* @param listModel the ListModel to use.
*/
virtual void setListModel(ListModel *listModel);
/**
* Gets the ListModel used.
*
* @return the ListModel used.
*/
virtual ListModel *getListModel();
/**
* Adjusts the size of the ListBox to fit the font used.
*/
virtual void adjustSize();
/**
* Checks whether the ListBox wraps when selecting items with keyboard.
*
* Wrapping means that if up is pressed and the first item is selected, the last
* item will get selected. If down is pressed and the last item is selected, the
* first item will get selected.
*
* @return true if wrapping, fasle otherwise.
*/
virtual bool isWrappingKeyboardSelection();
/**
* Sets the ListBox to wrap or not when selecting items with keyboard.
*
* Wrapping means that if up is pressed and the first item is selected, the last
* item will get selected. If down is pressed and the last item is selected, the
* first item will get selected.
*
*/
virtual void setWrappingKeyboardSelection(bool wrapping);
// Inherited from Widget
virtual void draw(Graphics* graphics);
virtual void drawBorder(Graphics* graphics);
virtual void logic();
// Inherited from KeyListener
virtual void keyPress(const Key& key);
// Inherited from MouseListener
virtual void mousePress(int x, int y, int button);
protected:
ListModel *mListModel;
int mSelected;
bool mWrappingKeyboardSelection;
};
}
#endif // end GCN_LISTBOX_HPP
<|endoftext|> |
<commit_before>#ifndef COFFEE_MILL_BEST_FIT
#define COFFEE_MILL_BEST_FIT
#include <vector>
namespace mill
{
template<typename sclT, template<typename sclT, std::size_t D> class vectorT,
template<typename sclT, std::size_t R, std::size_t C> class matrixT>
class BestFit
{
public:
using scalar_type = sclT;
using vector3_type = vectorT<sclT, 3>;
using vector4_type = vectorT<sclT, 4>;
using matrix33_type = matrixT<sclT, 3, 3>;
using matrix44_type = matrixT<sclT, 4, 4>;
using structure_type = std::vector<vector_3_type>;
public:
BestFit() = default;
~BestFit() = default;
structure_type
fit(const structure_type& snapshot, const structure_type& reference) const;
structure_type // with reference cash
fit(const structure_type& snapshot) const;
matrix33_type
rotational_matrix(const structure_type& snapshot,
const structure_type& reference) const;
matrix33_type // with cash
rotational_matrix(const structure_type& snapshot) const;
structure_type const& reference() const {return reference_;}
structure_type & reference() {return reference_;}
private:
Matrix33_type make_rotation_matrix(const structure_type& snapshot,
const structure_type& reference) const;
Matrix33_type make_rotation_matrix(const Vector4d& quaternion) const;
Matrix44_type score_matrix(const std::vector<Vector3d>& a,
const std::vector<Vector3d>& b) const;
private:
structure_type reference_; //!< optional;
};
template<typename sclT, template<typename sT1, std::size_t D> class vectorT,
template<typename sT2, std::size_t R, std::size_t C> class matrixT>
typename BestFit<sclT, vectorT, matrixT>::Structure
BestFit<sclT, vectorT, matrixT>::fit(
const structure_type& str, const structure_type& ref) const
{
if(str.size() != ref.size())
throw std::invalid_argument("different structure in argument");
vector3_type sum_str(0., 0., 0.);
for(auto iter = str.cbegin(); iter != str.cend(); ++iter)
sum_str += *iter;
const vector3_type centroid_str =
sum_str / static_cast<scalar_type>(str.size());
structure_type rotated_str;
rotated.reserve(str.size());
for(auto iter = str.begin(); iter != str.end(); ++iter)
rotated_str.push_back(*iter - centroid_str);
vector3_type sum_ref(0., 0., 0.);
for(auto iter = ref.cbegin(); iter != ref.cend(); ++iter)
sum_ref += *iter;
vector3_type centroid_ref =
sum_ref / static_cast<scalar_type>(ref.size());
structure_type zeroed_ref;
zeroed_ref.reserve(ref.size());
for(auto iter = ref.begin(); iter != ref.end(); ++iter)
zeroed_ref.push_back(*iter - centroid_ref);
auto R = this->make_rotation_matrix(rotated_str, zeroed_ref);
for(auto iter = rotated_str.begin(); iter != rotated_str.end(); ++iter)
{
const vector3_type temp = R * (*iter);
*iter = temp;
}
return rotated_str;
}
BestFit::Matrix3d BestFit::RotationMatrix(const Structure& structure) const
{
assert(structure.size() == this->reference_.size());
Vector3d sum(0e0);
for(auto iter = structure.cbegin(); iter != structure.cend(); ++iter)
sum += *iter;
const Vector3d CoM = sum / static_cast<double>(structure.size());
Structure zeroed;
zeroed.reserve(structure.size());
for(auto iter = structure.cbegin(); iter != structure.cend(); ++iter)
zeroed.push_back(*iter - CoM);
return RotationMatrix(zeroed, true);
}
BestFit::Matrix3d BestFit::RotationMatrix(const Structure& structure, bool zeroed) const
{
assert(zeroed);
std::vector<Vector3d> rA(structure.size());
std::vector<Vector3d> rB(structure.size());
for(std::size_t i=0; i < structure.size(); ++i)
{
rA.at(i) = reference_[i] + structure[i];
rB.at(i) = reference_[i] - structure[i];
}
auto score = score_matrix(rA, rB);
ax::JacobiSolver<4> solver(score);
std::pair<double, Vector4d> min_pair = solver.get_mineigenpair();
const Vector4d q = min_pair.second;
return rotation_matrix(q);
}
template<typename vector3T, typename vector4T,
typename matrix33T, typename matrix44T>
BestFit::Matrix4d
BestFit::score_matrix(const std::vector<Vector3d>& a,
const std::vector<Vector3d>& b) const
{
assert(a.size() == b.size());
Matrix4d retval(0e0);
for(std::size_t i(0); i<a.size(); ++i)
{
retval(0,0) += (b[i][0]*b[i][0]) + (b[i][1]*b[i][1]) + (b[i][2]*b[i][2]);
retval(0,1) += (a[i][2]*b[i][1]) - (a[i][1]*b[i][2]);
retval(0,2) += (a[i][0]*b[i][2]) - (a[i][2]*b[i][0]);
retval(0,3) += (a[i][1]*b[i][0]) - (a[i][0]*b[i][1]);
retval(1,1) += (b[i][0]*b[i][0]) + (a[i][1]*a[i][1]) + (a[i][2]*a[i][2]);
retval(1,2) += (b[i][0]*b[i][1]) - (a[i][0]*a[i][1]);
retval(1,3) += (b[i][0]*b[i][2]) - (a[i][0]*a[i][2]);
retval(2,2) += (a[i][0]*a[i][0]) + (b[i][1]*b[i][1]) + (a[i][2]*a[i][2]);
retval(2,3) += (b[i][1]*b[i][2]) - (a[i][1]*a[i][2]);
retval(3,3) += (a[i][0]*a[i][0]) + (a[i][1]*a[i][1]) + (b[i][2]*b[i][2]);
}
const double N = static_cast<double>(a.size());
retval(0,0) = retval(0,0) / N;
retval(0,1) = retval(0,1) / N;
retval(0,2) = retval(0,2) / N;
retval(0,3) = retval(0,3) / N;
retval(1,1) = retval(1,1) / N;
retval(1,2) = retval(1,2) / N;
retval(1,3) = retval(1,3) / N;
retval(2,2) = retval(2,2) / N;
retval(2,3) = retval(2,3) / N;
retval(3,3) = retval(3,3) / N;
//symmetric matrix
retval(1,0) = retval(0,1);
retval(2,0) = retval(0,2);
retval(2,1) = retval(1,2);
retval(3,0) = retval(0,3);
retval(3,1) = retval(1,3);
retval(3,2) = retval(2,3);
return retval;
}
BestFit::Matrix3d BestFit::rotation_matrix(const Vector4d& q) const
{
Matrix3d R(0e0);
R(0,0) = 2e0*q[0]*q[0] + 2e0*q[1]*q[1] - 1e0;
R(0,1) = 2e0*q[1]*q[2] - 2e0*q[0]*q[3];
R(0,2) = 2e0*q[1]*q[3] + 2e0*q[0]*q[2];
R(1,0) = 2e0*q[1]*q[2] + 2e0*q[0]*q[3];
R(1,1) = 2e0*q[0]*q[0] + 2e0*q[2]*q[2] - 1e0;
R(1,2) = 2e0*q[2]*q[3] - 2e0*q[0]*q[1];
R(2,0) = 2e0*q[1]*q[3] - 2e0*q[0]*q[2];
R(2,1) = 2e0*q[2]*q[3] + 2e0*q[0]*q[1];
R(2,2) = 2e0*q[0]*q[0] + 2e0*q[3]*q[3] - 1e0;
return R;
}
}// mill
#endif /* COFFEE_MILL_BEST_FIT */
<commit_msg>change BestFit<commit_after>#ifndef COFFEE_MILL_BEST_FIT
#define COFFEE_MILL_BEST_FIT
#include <vector>
namespace mill
{
template<typename sclT, template<typename sclT1, std::size_t D> class vectorT,
template<typename sclT2, std::size_t R, std::size_t C> class matrixT>
class BestFit
{
public:
using scalar_type = sclT;
using vector3_type = vectorT<sclT, 3>;
using vector4_type = vectorT<sclT, 4>;
using matrix33_type = matrixT<sclT, 3, 3>;
using matrix44_type = matrixT<sclT, 4, 4>;
using structure_type = std::vector<vector3_type>;
public:
BestFit() = default;
~BestFit() = default;
structure_type
fit(const structure_type& snapshot, const structure_type& reference) const;
structure_type // with reference cash
fit(const structure_type& snapshot) const;
matrix33_type
rotational_matrix(const structure_type& snapshot,
const structure_type& reference) const;
matrix33_type // with cash
rotational_matrix(const structure_type& snapshot) const;
structure_type const& reference() const {return reference_;}
structure_type & reference() {return reference_;}
private:
structure_type move_to_center(const structure_type& str) const;
void move_to_center(structure_type& str) const;
matrix33_type make_rotation_matrix(const structure_type& snapshot,
const structure_type& reference) const;
matrix33_type make_rotation_matrix(const vector4_type& quaternion) const;
matrix44_type score_matrix(const std::vector<vector3_type>& a,
const std::vector<vector3_type>& b) const;
private:
structure_type reference_; //!< optional;
};
template<typename sclT, template<typename sT1, std::size_t D> class vectorT,
template<typename sT2, std::size_t R, std::size_t C> class matrixT>
typename BestFit<sclT, vectorT, matrixT>::structure_type
BestFit<sclT, vectorT, matrixT>::fit(
const structure_type& str, const structure_type& ref) const
{
if(str.size() != ref.size())
throw std::invalid_argument("different structure in argument");
vector3_type sum_str(0., 0., 0.);
for(auto iter = str.cbegin(); iter != str.cend(); ++iter)
sum_str += *iter;
const vector3_type centroid_str =
sum_str / static_cast<scalar_type>(str.size());
structure_type rotated_str;
rotated_str.reserve(str.size());
for(auto iter = str.begin(); iter != str.end(); ++iter)
rotated_str.push_back(*iter - centroid_str);
vector3_type sum_ref(0., 0., 0.);
for(auto iter = ref.cbegin(); iter != ref.cend(); ++iter)
sum_ref += *iter;
vector3_type centroid_ref =
sum_ref / static_cast<scalar_type>(ref.size());
structure_type zeroed_ref;
zeroed_ref.reserve(ref.size());
for(auto iter = ref.begin(); iter != ref.end(); ++iter)
zeroed_ref.push_back(*iter - centroid_ref);
auto R = this->make_rotation_matrix(rotated_str, zeroed_ref);
for(auto iter = rotated_str.begin(); iter != rotated_str.end(); ++iter)
{
const vector3_type temp = R * (*iter);
*iter = temp;
}
return rotated_str;
}
template<typename sclT, template<typename sT1, std::size_t D> class vectorT,
template<typename sT2, std::size_t R, std::size_t C> class matrixT>
typename BestFit<sclT, vectorT, matrixT>::matrix33_type
BestFit<sclT, vectorT, matrixT>::rotational_matrix(
const structure_type& structure) const
{
assert(structure.size() == this->reference_.size());
vector3_type sum(0e0);
for(auto iter = structure.cbegin(); iter != structure.cend(); ++iter)
sum += *iter;
const vector3_type centroid = sum / static_cast<sclT>(structure.size());
structure_type zeroed;
zeroed.reserve(structure.size());
for(auto iter = structure.cbegin(); iter != structure.cend(); ++iter)
zeroed.push_back(*iter - centroid);
return RotationMatrix(zeroed, true);
}
template<typename sclT, template<typename sT1, std::size_t D> class vectorT,
template<typename sT2, std::size_t R, std::size_t C> class matrixT>
typename BestFit<sclT, vectorT, matrixT>::matrix33_type
BestFit<sclT, vectorT, matrixT>::make_rotation_matrix(
const structure_type& structure, const structure_type& reference) const
{
if(structure.size() != reference.size())
throw std::invalid_argument("different size structures");
std::vector<vector3_type> rA(structure.size());
std::vector<vector3_type> rB(structure.size());
for(std::size_t i=0; i < structure.size(); ++i)
{
rA[i] = reference[i] + structure[i];
rB[i] = reference[i] - structure[i];
}
auto score = score_matrix(rA, rB);
// ax::JacobiSolver<4> solver(score);
// std::pair<double, Vector4d> min_pair = solver.get_mineigenpair();
// const Vector4d q = min_pair.second;
// return rotation_matrix(q);
}
template<typename sclT, template<typename sT1, std::size_t D> class vectorT,
template<typename sT2, std::size_t R, std::size_t C> class matrixT>
typename BestFit<sclT, vectorT, matrixT>::matrix44_type
BestFit<sclT, vectorT, matrixT>::score_matrix(
const std::vector<vector3_type>& a, const std::vector<vector3_type>& b) const
{
if(a.size() != b.size())
throw std::invalid_argument("different size structures");
matrix44_type retval;
for(std::size_t i(0); i<a.size(); ++i)
{
retval(0,0) += (b[i][0]*b[i][0]) + (b[i][1]*b[i][1]) + (b[i][2]*b[i][2]);
retval(0,1) += (a[i][2]*b[i][1]) - (a[i][1]*b[i][2]);
retval(0,2) += (a[i][0]*b[i][2]) - (a[i][2]*b[i][0]);
retval(0,3) += (a[i][1]*b[i][0]) - (a[i][0]*b[i][1]);
retval(1,1) += (b[i][0]*b[i][0]) + (a[i][1]*a[i][1]) + (a[i][2]*a[i][2]);
retval(1,2) += (b[i][0]*b[i][1]) - (a[i][0]*a[i][1]);
retval(1,3) += (b[i][0]*b[i][2]) - (a[i][0]*a[i][2]);
retval(2,2) += (a[i][0]*a[i][0]) + (b[i][1]*b[i][1]) + (a[i][2]*a[i][2]);
retval(2,3) += (b[i][1]*b[i][2]) - (a[i][1]*a[i][2]);
retval(3,3) += (a[i][0]*a[i][0]) + (a[i][1]*a[i][1]) + (b[i][2]*b[i][2]);
}
const sclT inv_N = 1. / static_cast<sclT>(a.size());
retval(0,0) = retval(0,0) * inv_N;
retval(0,1) = retval(0,1) * inv_N;
retval(0,2) = retval(0,2) * inv_N;
retval(0,3) = retval(0,3) * inv_N;
retval(1,1) = retval(1,1) * inv_N;
retval(1,2) = retval(1,2) * inv_N;
retval(1,3) = retval(1,3) * inv_N;
retval(2,2) = retval(2,2) * inv_N;
retval(2,3) = retval(2,3) * inv_N;
retval(3,3) = retval(3,3) * inv_N;
//symmetric matrix
retval(1,0) = retval(0,1);
retval(2,0) = retval(0,2);
retval(2,1) = retval(1,2);
retval(3,0) = retval(0,3);
retval(3,1) = retval(1,3);
retval(3,2) = retval(2,3);
return retval;
}
template<typename sclT, template<typename sT1, std::size_t D> class vectorT,
template<typename sT2, std::size_t R, std::size_t C> class matrixT>
typename BestFit<sclT, vectorT, matrixT>::matrix33_type
BestFit<sclT, vectorT, matrixT>::make_rotation_matrix(const vector4_type& q) const
{
matrix33_type R;
R(0,0) = 2e0*q[0]*q[0] + 2e0*q[1]*q[1] - 1e0;
R(0,1) = 2e0*q[1]*q[2] - 2e0*q[0]*q[3];
R(0,2) = 2e0*q[1]*q[3] + 2e0*q[0]*q[2];
R(1,0) = 2e0*q[1]*q[2] + 2e0*q[0]*q[3];
R(1,1) = 2e0*q[0]*q[0] + 2e0*q[2]*q[2] - 1e0;
R(1,2) = 2e0*q[2]*q[3] - 2e0*q[0]*q[1];
R(2,0) = 2e0*q[1]*q[3] - 2e0*q[0]*q[2];
R(2,1) = 2e0*q[2]*q[3] + 2e0*q[0]*q[1];
R(2,2) = 2e0*q[0]*q[0] + 2e0*q[3]*q[3] - 1e0;
return R;
}
template<typename sclT, template<typename sT1, std::size_t D> class vectorT,
template<typename sT2, std::size_t R, std::size_t C> class matrixT>
typename BestFit<sclT, vectorT, matrixT>::structure_type
BestFit<sclT, vectorT, matrixT>::move_to_center(const structure_type& str) const
{
vector3_type sum(0., 0., 0.);
for(auto iter = str.cbegin(); iter != str.cend(); ++iter)
sum += *iter;
const sclT invN = 1. / static_cast<double>(str.size());
const vector3_type centroid = sum * invN;
structure_type retval(str.size());
for(std::size_t i = 0; i<str.size(); ++i)
retval[i] = str[i] - centroid;
return retval;
}
template<typename sclT, template<typename sT1, std::size_t D> class vectorT,
template<typename sT2, std::size_t R, std::size_t C> class matrixT>
void BestFit<sclT, vectorT, matrixT>::move_to_center(structure_type& str) const
{
vector3_type sum(0., 0., 0.);
for(auto iter = str.cbegin(); iter != str.cend(); ++iter)
sum += *iter;
const sclT invN = 1. / static_cast<double>(str.size());
const vector3_type centroid = sum * invN;
for(auto iter = str.begin(); iter != str.end(); ++iter)
*iter -= centroid;
return ;
}
}// mill
#endif /* COFFEE_MILL_BEST_FIT */
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/process_util.h"
#include "base/test/test_timeouts.h"
#include "chrome/browser/service/service_process_control.h"
#include "chrome/browser/service/service_process_control_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/service_process_util.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
class ServiceProcessControlBrowserTest
: public InProcessBrowserTest {
public:
ServiceProcessControlBrowserTest()
: service_process_handle_(base::kNullProcessHandle) {
}
~ServiceProcessControlBrowserTest() {
base::CloseProcessHandle(service_process_handle_);
service_process_handle_ = base::kNullProcessHandle;
// Delete all instances of ServiceProcessControl.
ServiceProcessControlManager::GetInstance()->Shutdown();
}
#if defined(OS_MACOSX)
virtual void TearDown() {
// ForceServiceProcessShutdown removes the process from launchd on Mac.
ForceServiceProcessShutdown("", 0);
}
#endif // OS_MACOSX
protected:
void LaunchServiceProcessControl() {
ServiceProcessControl* process =
ServiceProcessControlManager::GetInstance()->GetProcessControl(
browser()->profile());
process_ = process;
// Launch the process asynchronously.
process->Launch(
NewRunnableMethod(
this,
&ServiceProcessControlBrowserTest::ProcessControlLaunched),
NewRunnableMethod(
this,
&ServiceProcessControlBrowserTest::ProcessControlLaunchFailed));
// Then run the message loop to keep things running.
ui_test_utils::RunMessageLoop();
}
// Send a remoting host status request and wait reply from the service.
void SendRequestAndWait() {
process()->GetCloudPrintProxyStatus(NewCallback(
this, &ServiceProcessControlBrowserTest::CloudPrintStatusCallback));
ui_test_utils::RunMessageLoop();
}
void CloudPrintStatusCallback(
bool enabled, std::string email) {
MessageLoop::current()->Quit();
}
void Disconnect() {
// This will delete all instances of ServiceProcessControl and close the IPC
// connections.
ServiceProcessControlManager::GetInstance()->Shutdown();
process_ = NULL;
}
void WaitForShutdown() {
EXPECT_TRUE(base::WaitForSingleProcess(
service_process_handle_,
TestTimeouts::wait_for_terminate_timeout_ms()));
}
void ProcessControlLaunched() {
base::ProcessId service_pid;
EXPECT_TRUE(GetServiceProcessData(NULL, &service_pid));
EXPECT_NE(static_cast<base::ProcessId>(0), service_pid);
EXPECT_TRUE(base::OpenProcessHandleWithAccess(
service_pid,
base::kProcessAccessWaitForTermination,
&service_process_handle_));
// Quit the current message. Post a QuitTask instead of just calling Quit()
// because this can get invoked in the context of a Launch() call and we
// may not be in Run() yet.
MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}
void ProcessControlLaunchFailed() {
ADD_FAILURE();
// Quit the current message.
MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}
ServiceProcessControl* process() { return process_; }
private:
ServiceProcessControl* process_;
base::ProcessHandle service_process_handle_;
};
// They way that the IPC is implemented only works on windows. This has to
// change when we implement a different scheme for IPC.
// Times out flakily, http://crbug.com/70076.
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest,
DISABLED_LaunchAndIPC) {
LaunchServiceProcessControl();
// Make sure we are connected to the service process.
EXPECT_TRUE(process()->is_connected());
SendRequestAndWait();
// And then shutdown the service process.
EXPECT_TRUE(process()->Shutdown());
}
// This tests the case when a service process is launched when browser
// starts but we try to launch it again in the remoting setup dialog.
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, LaunchTwice) {
// Launch the service process the first time.
LaunchServiceProcessControl();
// Make sure we are connected to the service process.
EXPECT_TRUE(process()->is_connected());
SendRequestAndWait();
// Launch the service process again.
LaunchServiceProcessControl();
EXPECT_TRUE(process()->is_connected());
SendRequestAndWait();
// And then shutdown the service process.
EXPECT_TRUE(process()->Shutdown());
}
static void DecrementUntilZero(int* count) {
(*count)--;
if (!(*count))
MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}
// Invoke multiple Launch calls in succession and ensure that all the tasks
// get invoked.
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, MultipleLaunchTasks) {
ServiceProcessControl* process =
ServiceProcessControlManager::GetInstance()->GetProcessControl(
browser()->profile());
int launch_count = 5;
for (int i = 0; i < launch_count; i++) {
// Launch the process asynchronously.
process->Launch(
NewRunnableFunction(&DecrementUntilZero, &launch_count),
new MessageLoop::QuitTask());
}
// Then run the message loop to keep things running.
ui_test_utils::RunMessageLoop();
EXPECT_EQ(0, launch_count);
// And then shutdown the service process.
EXPECT_TRUE(process->Shutdown());
}
// Make sure using the same task for success and failure tasks works.
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, SameLaunchTask) {
ServiceProcessControl* process =
ServiceProcessControlManager::GetInstance()->GetProcessControl(
browser()->profile());
int launch_count = 5;
for (int i = 0; i < launch_count; i++) {
// Launch the process asynchronously.
Task * task = NewRunnableFunction(&DecrementUntilZero, &launch_count);
process->Launch(task, task);
}
// Then run the message loop to keep things running.
ui_test_utils::RunMessageLoop();
EXPECT_EQ(0, launch_count);
// And then shutdown the service process.
EXPECT_TRUE(process->Shutdown());
}
// Tests whether disconnecting from the service IPC causes the service process
// to die.
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, DieOnDisconnect) {
// Launch the service process.
LaunchServiceProcessControl();
// Make sure we are connected to the service process.
EXPECT_TRUE(process()->is_connected());
Disconnect();
WaitForShutdown();
}
//http://code.google.com/p/chromium/issues/detail?id=70793
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest,
DISABLED_ForceShutdown) {
// Launch the service process.
LaunchServiceProcessControl();
// Make sure we are connected to the service process.
EXPECT_TRUE(process()->is_connected());
base::ProcessId service_pid;
EXPECT_TRUE(GetServiceProcessData(NULL, &service_pid));
EXPECT_NE(static_cast<base::ProcessId>(0), service_pid);
chrome::VersionInfo version_info;
ForceServiceProcessShutdown(version_info.Version(), service_pid);
WaitForShutdown();
}
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, CheckPid) {
base::ProcessId service_pid;
EXPECT_FALSE(GetServiceProcessData(NULL, &service_pid));
// Launch the service process.
LaunchServiceProcessControl();
EXPECT_TRUE(GetServiceProcessData(NULL, &service_pid));
EXPECT_NE(static_cast<base::ProcessId>(0), service_pid);
}
DISABLE_RUNNABLE_METHOD_REFCOUNT(ServiceProcessControlBrowserTest);
<commit_msg>Mark CheckPid,DieOnDisconnect,LaunchTwice,MultipleLaunchTasks,SameLaunchTask as FAILS on mac.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/process_util.h"
#include "base/test/test_timeouts.h"
#include "chrome/browser/service/service_process_control.h"
#include "chrome/browser/service/service_process_control_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/service_process_util.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
class ServiceProcessControlBrowserTest
: public InProcessBrowserTest {
public:
ServiceProcessControlBrowserTest()
: service_process_handle_(base::kNullProcessHandle) {
}
~ServiceProcessControlBrowserTest() {
base::CloseProcessHandle(service_process_handle_);
service_process_handle_ = base::kNullProcessHandle;
// Delete all instances of ServiceProcessControl.
ServiceProcessControlManager::GetInstance()->Shutdown();
}
#if defined(OS_MACOSX)
virtual void TearDown() {
// ForceServiceProcessShutdown removes the process from launchd on Mac.
ForceServiceProcessShutdown("", 0);
}
#endif // OS_MACOSX
protected:
void LaunchServiceProcessControl() {
ServiceProcessControl* process =
ServiceProcessControlManager::GetInstance()->GetProcessControl(
browser()->profile());
process_ = process;
// Launch the process asynchronously.
process->Launch(
NewRunnableMethod(
this,
&ServiceProcessControlBrowserTest::ProcessControlLaunched),
NewRunnableMethod(
this,
&ServiceProcessControlBrowserTest::ProcessControlLaunchFailed));
// Then run the message loop to keep things running.
ui_test_utils::RunMessageLoop();
}
// Send a remoting host status request and wait reply from the service.
void SendRequestAndWait() {
process()->GetCloudPrintProxyStatus(NewCallback(
this, &ServiceProcessControlBrowserTest::CloudPrintStatusCallback));
ui_test_utils::RunMessageLoop();
}
void CloudPrintStatusCallback(
bool enabled, std::string email) {
MessageLoop::current()->Quit();
}
void Disconnect() {
// This will delete all instances of ServiceProcessControl and close the IPC
// connections.
ServiceProcessControlManager::GetInstance()->Shutdown();
process_ = NULL;
}
void WaitForShutdown() {
EXPECT_TRUE(base::WaitForSingleProcess(
service_process_handle_,
TestTimeouts::wait_for_terminate_timeout_ms()));
}
void ProcessControlLaunched() {
base::ProcessId service_pid;
EXPECT_TRUE(GetServiceProcessData(NULL, &service_pid));
EXPECT_NE(static_cast<base::ProcessId>(0), service_pid);
EXPECT_TRUE(base::OpenProcessHandleWithAccess(
service_pid,
base::kProcessAccessWaitForTermination,
&service_process_handle_));
// Quit the current message. Post a QuitTask instead of just calling Quit()
// because this can get invoked in the context of a Launch() call and we
// may not be in Run() yet.
MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}
void ProcessControlLaunchFailed() {
ADD_FAILURE();
// Quit the current message.
MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}
ServiceProcessControl* process() { return process_; }
private:
ServiceProcessControl* process_;
base::ProcessHandle service_process_handle_;
};
// They way that the IPC is implemented only works on windows. This has to
// change when we implement a different scheme for IPC.
// Times out flakily, http://crbug.com/70076.
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest,
DISABLED_LaunchAndIPC) {
LaunchServiceProcessControl();
// Make sure we are connected to the service process.
EXPECT_TRUE(process()->is_connected());
SendRequestAndWait();
// And then shutdown the service process.
EXPECT_TRUE(process()->Shutdown());
}
// This tests the case when a service process is launched when browser
// starts but we try to launch it again in the remoting setup dialog.
// Fails on mac. http://crbug.com/75518
#if defined(OS_MACOSX)
#define MAYBE_LaunchTwice FAILS_LaunchTwice
#else
#define MAYBE_LaunchTwice LaunchTwice
#endif
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, MAYBE_LaunchTwice) {
// Launch the service process the first time.
LaunchServiceProcessControl();
// Make sure we are connected to the service process.
EXPECT_TRUE(process()->is_connected());
SendRequestAndWait();
// Launch the service process again.
LaunchServiceProcessControl();
EXPECT_TRUE(process()->is_connected());
SendRequestAndWait();
// And then shutdown the service process.
EXPECT_TRUE(process()->Shutdown());
}
static void DecrementUntilZero(int* count) {
(*count)--;
if (!(*count))
MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}
// Invoke multiple Launch calls in succession and ensure that all the tasks
// get invoked.
// Fails on mac. http://crbug.com/75518
#if defined(OS_MACOSX)
#define MAYBE_MultipleLaunchTasks FAILS_MultipleLaunchTasks
#else
#define MAYBE_MultipleLaunchTasks MultipleLaunchTasks
#endif
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest,
MAYBE_MultipleLaunchTasks) {
ServiceProcessControl* process =
ServiceProcessControlManager::GetInstance()->GetProcessControl(
browser()->profile());
int launch_count = 5;
for (int i = 0; i < launch_count; i++) {
// Launch the process asynchronously.
process->Launch(
NewRunnableFunction(&DecrementUntilZero, &launch_count),
new MessageLoop::QuitTask());
}
// Then run the message loop to keep things running.
ui_test_utils::RunMessageLoop();
EXPECT_EQ(0, launch_count);
// And then shutdown the service process.
EXPECT_TRUE(process->Shutdown());
}
// Make sure using the same task for success and failure tasks works.
// Fails on mac. http://crbug.com/75518
#if defined(OS_MACOSX)
#define MAYBE_SameLaunchTask FAILS_SameLaunchTask
#else
#define MAYBE_SameLaunchTask SameLaunchTask
#endif
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, MAYBE_SameLaunchTask) {
ServiceProcessControl* process =
ServiceProcessControlManager::GetInstance()->GetProcessControl(
browser()->profile());
int launch_count = 5;
for (int i = 0; i < launch_count; i++) {
// Launch the process asynchronously.
Task * task = NewRunnableFunction(&DecrementUntilZero, &launch_count);
process->Launch(task, task);
}
// Then run the message loop to keep things running.
ui_test_utils::RunMessageLoop();
EXPECT_EQ(0, launch_count);
// And then shutdown the service process.
EXPECT_TRUE(process->Shutdown());
}
// Tests whether disconnecting from the service IPC causes the service process
// to die.
// Fails on mac. http://crbug.com/75518
#if defined(OS_MACOSX)
#define MAYBE_DieOnDisconnect FAILS_DieOnDisconnect
#else
#define MAYBE_DieOnDisconnect DieOnDisconnect
#endif
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest,
MAYBE_DieOnDisconnect) {
// Launch the service process.
LaunchServiceProcessControl();
// Make sure we are connected to the service process.
EXPECT_TRUE(process()->is_connected());
Disconnect();
WaitForShutdown();
}
//http://code.google.com/p/chromium/issues/detail?id=70793
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest,
DISABLED_ForceShutdown) {
// Launch the service process.
LaunchServiceProcessControl();
// Make sure we are connected to the service process.
EXPECT_TRUE(process()->is_connected());
base::ProcessId service_pid;
EXPECT_TRUE(GetServiceProcessData(NULL, &service_pid));
EXPECT_NE(static_cast<base::ProcessId>(0), service_pid);
chrome::VersionInfo version_info;
ForceServiceProcessShutdown(version_info.Version(), service_pid);
WaitForShutdown();
}
// Fails on mac. http://crbug.com/75518
#if defined(OS_MACOSX)
#define MAYBE_CheckPid FAILS_CheckPid
#else
#define MAYBE_CheckPid CheckPid
#endif
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, MAYBE_CheckPid) {
base::ProcessId service_pid;
EXPECT_FALSE(GetServiceProcessData(NULL, &service_pid));
// Launch the service process.
LaunchServiceProcessControl();
EXPECT_TRUE(GetServiceProcessData(NULL, &service_pid));
EXPECT_NE(static_cast<base::ProcessId>(0), service_pid);
}
DISABLE_RUNNABLE_METHOD_REFCOUNT(ServiceProcessControlBrowserTest);
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "net/base/net_util.h"
#include "webkit/dom_storage/dom_storage_area.h"
namespace {
// The tests server is started separately for each test function (including PRE_
// functions). We need a test server which always uses the same port, so that
// the pages can be accessed with the same URLs after restoring the browser
// session.
class FixedPortTestServer : public net::LocalTestServer {
public:
explicit FixedPortTestServer(uint16 port)
: LocalTestServer(
net::TestServer::TYPE_HTTP,
net::TestServer::kLocalhost,
FilePath().AppendASCII("chrome/test/data")) {
BaseTestServer::SetPort(port);
}
private:
DISALLOW_COPY_AND_ASSIGN(FixedPortTestServer);
};
} // namespace
class BetterSessionRestoreTest : public InProcessBrowserTest {
public:
BetterSessionRestoreTest()
: test_server_(8001),
title_pass_(ASCIIToUTF16("PASS")),
title_storing_(ASCIIToUTF16("STORING")),
title_error_write_failed_(ASCIIToUTF16("ERROR_WRITE_FAILED")),
title_error_empty_(ASCIIToUTF16("ERROR_EMPTY")) {
CHECK(test_server_.Start());
}
protected:
void StoreDataWithPage(const std::string& filename) {
GURL url = test_server_.GetURL("files/session_restore/" + filename);
content::WebContents* web_contents =
chrome::GetActiveWebContents(browser());
content::TitleWatcher title_watcher(web_contents, title_storing_);
title_watcher.AlsoWaitForTitle(title_pass_);
title_watcher.AlsoWaitForTitle(title_error_write_failed_);
title_watcher.AlsoWaitForTitle(title_error_empty_);
ui_test_utils::NavigateToURL(browser(), url);
string16 final_title = title_watcher.WaitAndGetTitle();
EXPECT_EQ(title_storing_, final_title);
}
void CheckReloadedPage() {
content::WebContents* web_contents = chrome::GetWebContentsAt(browser(), 0);
content::TitleWatcher title_watcher(web_contents, title_pass_);
title_watcher.AlsoWaitForTitle(title_storing_);
title_watcher.AlsoWaitForTitle(title_error_write_failed_);
title_watcher.AlsoWaitForTitle(title_error_empty_);
// It's possible that the title was already the right one before
// title_watcher was created.
if (web_contents->GetTitle() != title_pass_) {
string16 final_title = title_watcher.WaitAndGetTitle();
EXPECT_EQ(title_pass_, final_title);
}
}
private:
FixedPortTestServer test_server_;
string16 title_pass_;
string16 title_storing_;
string16 title_error_write_failed_;
string16 title_error_empty_;
DISALLOW_COPY_AND_ASSIGN(BetterSessionRestoreTest);
};
// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, FLAKY_PRE_SessionCookies) {
// Set the startup preference to "continue where I left off" and visit a page
// which stores a session cookie.
SessionStartupPref::SetStartupPref(
browser()->profile(), SessionStartupPref(SessionStartupPref::LAST));
StoreDataWithPage("session_cookies.html");
}
// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, FLAKY_SessionCookies) {
// The browsing session will be continued; just wait for the page to reload
// and check the stored data.
CheckReloadedPage();
}
// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, FLAKY_PRE_SessionStorage) {
// Write the data on disk less lazily.
dom_storage::DomStorageArea::DisableCommitDelayForTesting();
SessionStartupPref::SetStartupPref(
browser()->profile(), SessionStartupPref(SessionStartupPref::LAST));
StoreDataWithPage("session_storage.html");
}
// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, FLAKY_SessionStorage) {
CheckReloadedPage();
}
<commit_msg>Disable BetterSessionRestoreTest.* under AddressSanitizer<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "net/base/net_util.h"
#include "webkit/dom_storage/dom_storage_area.h"
namespace {
// The tests server is started separately for each test function (including PRE_
// functions). We need a test server which always uses the same port, so that
// the pages can be accessed with the same URLs after restoring the browser
// session.
class FixedPortTestServer : public net::LocalTestServer {
public:
explicit FixedPortTestServer(uint16 port)
: LocalTestServer(
net::TestServer::TYPE_HTTP,
net::TestServer::kLocalhost,
FilePath().AppendASCII("chrome/test/data")) {
BaseTestServer::SetPort(port);
}
private:
DISALLOW_COPY_AND_ASSIGN(FixedPortTestServer);
};
} // namespace
class BetterSessionRestoreTest : public InProcessBrowserTest {
public:
BetterSessionRestoreTest()
: test_server_(8001),
title_pass_(ASCIIToUTF16("PASS")),
title_storing_(ASCIIToUTF16("STORING")),
title_error_write_failed_(ASCIIToUTF16("ERROR_WRITE_FAILED")),
title_error_empty_(ASCIIToUTF16("ERROR_EMPTY")) {
CHECK(test_server_.Start());
}
protected:
void StoreDataWithPage(const std::string& filename) {
GURL url = test_server_.GetURL("files/session_restore/" + filename);
content::WebContents* web_contents =
chrome::GetActiveWebContents(browser());
content::TitleWatcher title_watcher(web_contents, title_storing_);
title_watcher.AlsoWaitForTitle(title_pass_);
title_watcher.AlsoWaitForTitle(title_error_write_failed_);
title_watcher.AlsoWaitForTitle(title_error_empty_);
ui_test_utils::NavigateToURL(browser(), url);
string16 final_title = title_watcher.WaitAndGetTitle();
EXPECT_EQ(title_storing_, final_title);
}
void CheckReloadedPage() {
content::WebContents* web_contents = chrome::GetWebContentsAt(browser(), 0);
content::TitleWatcher title_watcher(web_contents, title_pass_);
title_watcher.AlsoWaitForTitle(title_storing_);
title_watcher.AlsoWaitForTitle(title_error_write_failed_);
title_watcher.AlsoWaitForTitle(title_error_empty_);
// It's possible that the title was already the right one before
// title_watcher was created.
if (web_contents->GetTitle() != title_pass_) {
string16 final_title = title_watcher.WaitAndGetTitle();
EXPECT_EQ(title_pass_, final_title);
}
}
private:
FixedPortTestServer test_server_;
string16 title_pass_;
string16 title_storing_;
string16 title_error_write_failed_;
string16 title_error_empty_;
DISALLOW_COPY_AND_ASSIGN(BetterSessionRestoreTest);
};
// BetterSessionRestoreTest tests fail under AddressSanitizer, see
// http://crbug.com/156444.
#if defined(ADDRESS_SANITIZER)
# define MAYBE_PRE_SessionCookies DISABLED_PRE_SessionCookies
# define MAYBE_SessionCookies DISABLED_SessionCookies
# define MAYBE_PRE_SessionStorage DISABLED_PRE_SessionStorage
# define MAYBE_SessionStorage DISABLED_SessionStorage
#else
# define MAYBE_PRE_SessionCookies FLAKY_PRE_SessionCookies
# define MAYBE_SessionCookies FLAKY_SessionCookies
# define MAYBE_PRE_SessionStorage FLAKY_PRE_SessionStorage
# define MAYBE_SessionStorage FLAKY_SessionStorage
#endif
// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, MAYBE_PRE_SessionCookies) {
// Set the startup preference to "continue where I left off" and visit a page
// which stores a session cookie.
SessionStartupPref::SetStartupPref(
browser()->profile(), SessionStartupPref(SessionStartupPref::LAST));
StoreDataWithPage("session_cookies.html");
}
// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, MAYBE_SessionCookies) {
// The browsing session will be continued; just wait for the page to reload
// and check the stored data.
CheckReloadedPage();
}
// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, MAYBE_PRE_SessionStorage) {
// Write the data on disk less lazily.
dom_storage::DomStorageArea::DisableCommitDelayForTesting();
SessionStartupPref::SetStartupPref(
browser()->profile(), SessionStartupPref(SessionStartupPref::LAST));
StoreDataWithPage("session_storage.html");
}
// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, MAYBE_SessionStorage) {
CheckReloadedPage();
}
<|endoftext|> |
<commit_before>/**\file
* \ingroup example-programmes
* \brief "Hello World" HTTP Server
*
* An example HTTP server that serves a simple "Hello World!" on /, and a 404 on
* all other resources.
*
* Call it like this:
* \code
* $ ./hello http:localhost:8080
* \endcode
*
* With localhost and 8080 being a host name and port of your choosing. Then,
* while the programme is running, open a browser and go to
* http://localhost:8080/ and you should see the familiar greeting.
*
* \copyright
* Copyright (c) 2015, Magnus Achim Deininger <[email protected]>
* \copyright
* 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:
* \copyright
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* \copyright
* 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.
*
* \see Documentation: https://ef.gy/documentation/imperiald
* \see Source Code: https://github.com/jyujin/imperiald
* \see Licence Terms: https://github.com/jyujin/imperiald/COPYING
*/
#define ASIO_DISABLE_THREADS
#include <prometheus/http.h>
#include <imperiald/procfs-linux.h>
using namespace efgy;
using namespace prometheus;
using asio::ip::tcp;
using asio::local::stream_protocol;
static imperiald::linux::stat<> linux_procfs_stats(1);
/**\brief Hello World request handler
*
* This function serves the familiar "Hello World!" when called.
*
* \param[out] session The HTTP session to answer on.
*
* \returns true (always, as we always reply).
*/
template <class transport>
static bool hello(typename net::http::server<transport>::session &session,
std::smatch &) {
session.reply(200, "Hello World!");
return true;
}
/**\brief Hello World request handler for /quit
*
* When this handler is invoked, it stops the ASIO IO handler (after replying,
* maybe...).
*
* \note Having this on your production server in this exact way is PROBABLY a
* really bad idea, unless you gate it in an upstream forward proxy. Or
* you have some way of automatically respawning your server. Or both.
*
* \param[out] session The HTTP session to answer on.
*
* \returns true (always, as we always reply).
*/
template <class transport>
static bool quit(typename net::http::server<transport>::session &session,
std::smatch &) {
session.reply(200, "Good-Bye, Cruel World!");
session.server.io.get().stop();
return true;
}
template <class sock>
static std::size_t setup(net::endpoint<sock> lookup,
io::service &service = io::service::common()) {
return lookup.with([&service](typename sock::endpoint &endpoint) -> bool {
net::http::server<sock> *s = new net::http::server<sock>(endpoint, service);
s->processor.add("^/$", hello<sock>);
s->processor.add("^/quit$", quit<sock>);
s->processor.add(http::regex, http::common<sock>);
return true;
});
}
/**\brief Main function for the HTTP/IRC demo
*
* Main function for the network server hello world programme.
*
* Sets up server(s) as per the given command line arguments. Invalid arguments
* are ignored.
*
* \param[in] argc Process argument count.
* \param[in] argv Process argument vector
*
* \returns 0 when nothing bad happened, 1 otherwise.
*/
int main(int argc, char *argv[]) {
try {
int targets = 0;
if (argc < 2) {
std::cerr << "Usage: server [http:<host>:<port>|http:unix:<path>]...\n";
return 1;
}
for (unsigned int i = 1; i < argc; i++) {
static const std::regex http("http:(.+):([0-9]+)");
static const std::regex httpSocket("http:unix:(.+)");
std::smatch matches;
if (std::regex_match(std::string(argv[i]), matches, httpSocket)) {
targets += setup(net::endpoint<stream_protocol>(matches[1]));
} else if (std::regex_match(std::string(argv[i]), matches, http)) {
targets += setup(net::endpoint<tcp>(matches[1], matches[2]));
} else {
std::cerr << "Argument not recognised: " << argv[i] << "\n";
}
}
if (targets > 0) {
io::service::common().run();
}
return 0;
} catch (std::exception &e) {
std::cerr << "Exception: " << e.what() << "\n";
} catch (std::system_error &e) {
std::cerr << "System Error: " << e.what() << "\n";
}
return 1;
}
<commit_msg>upgrade to the latest command line parsing shiny<commit_after>/**\file
* \ingroup example-programmes
* \brief "Hello World" HTTP Server
*
* An example HTTP server that serves a simple "Hello World!" on /, and a 404 on
* all other resources.
*
* Call it like this:
* \code
* $ ./hello http:localhost:8080
* \endcode
*
* With localhost and 8080 being a host name and port of your choosing. Then,
* while the programme is running, open a browser and go to
* http://localhost:8080/ and you should see the familiar greeting.
*
* \copyright
* Copyright (c) 2015, Magnus Achim Deininger <[email protected]>
* \copyright
* 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:
* \copyright
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* \copyright
* 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.
*
* \see Documentation: https://ef.gy/documentation/imperiald
* \see Source Code: https://github.com/jyujin/imperiald
* \see Licence Terms: https://github.com/jyujin/imperiald/COPYING
*/
#define ASIO_DISABLE_THREADS
#include <prometheus/http.h>
#include <imperiald/procfs-linux.h>
#include <ef.gy/cli.h>
using namespace efgy;
using namespace prometheus;
using asio::ip::tcp;
using asio::local::stream_protocol;
static imperiald::linux::stat<> linux_procfs_stats(1);
/**\brief Hello World request handler
*
* This function serves the familiar "Hello World!" when called.
*
* \param[out] session The HTTP session to answer on.
*
* \returns true (always, as we always reply).
*/
template <class transport>
static bool hello(typename net::http::server<transport>::session &session,
std::smatch &) {
session.reply(200, "Hello World!");
return true;
}
/**\brief Hello World request handler for /quit
*
* When this handler is invoked, it stops the ASIO IO handler (after replying,
* maybe...).
*
* \note Having this on your production server in this exact way is PROBABLY a
* really bad idea, unless you gate it in an upstream forward proxy. Or
* you have some way of automatically respawning your server. Or both.
*
* \param[out] session The HTTP session to answer on.
*
* \returns true (always, as we always reply).
*/
template <class transport>
static bool quit(typename net::http::server<transport>::session &session,
std::smatch &) {
session.reply(200, "Good-Bye, Cruel World!");
session.server.io.get().stop();
return true;
}
template <class sock>
static std::size_t setup(net::endpoint<sock> lookup,
io::service &service = io::service::common()) {
return lookup.with([&service](typename sock::endpoint &endpoint) -> bool {
net::http::server<sock> *s = new net::http::server<sock>(endpoint, service);
s->processor.add("^/$", hello<sock>);
s->processor.add("^/quit$", quit<sock>);
s->processor.add(http::regex, http::common<sock>);
return true;
});
}
static cli::option oHTTPSocket(std::regex("http:unix:(.+)"), [](std::smatch &m)->bool {
return setup(net::endpoint<stream_protocol>(m[1])) > 0;
});
static cli::option oHTTP(std::regex("http:(.+):([0-9]+)"), [](std::smatch &m)->bool {
return setup(net::endpoint<tcp>(m[1], m[2])) > 0;
});
/**\brief Main function for the HTTP/IRC demo
*
* Main function for the network server hello world programme.
*
* Sets up server(s) as per the given command line arguments. Invalid arguments
* are ignored.
*
* \param[in] argc Process argument count.
* \param[in] argv Process argument vector
*
* \returns 0 when nothing bad happened, 1 otherwise.
*/
int main(int argc, char *argv[]) {
try {
int targets = 0;
if (cli::options<cli::option>::common().apply(argc, argv) > 0) {
io::service::common().run();
} else {
std::cerr << "Usage: server [http:<host>:<port>|http:unix:<path>]...\n";
return 1;
}
return 0;
} catch (std::exception &e) {
std::cerr << "Exception: " << e.what() << "\n";
} catch (std::system_error &e) {
std::cerr << "System Error: " << e.what() << "\n";
}
return 1;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/notifier/registration_manager.h"
#include <cstddef>
#include <deque>
#include <vector>
#include "base/basictypes.h"
#include "chrome/browser/sync/notifier/invalidation_util.h"
#include "chrome/browser/sync/syncable/model_type.h"
#include "google/cacheinvalidation/invalidation-client.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace sync_notifier {
namespace {
// Fake invalidation client that just stores the args of calls to
// Register().
class FakeInvalidationClient : public invalidation::InvalidationClient {
public:
FakeInvalidationClient() {}
virtual ~FakeInvalidationClient() {}
virtual void Register(const invalidation::ObjectId& oid) {
registered_oids.push_back(oid);
}
virtual void Unregister(const invalidation::ObjectId& oid) {
ADD_FAILURE();
}
virtual invalidation::NetworkEndpoint* network_endpoint() {
ADD_FAILURE();
return NULL;
}
std::deque<invalidation::ObjectId> registered_oids;
private:
DISALLOW_COPY_AND_ASSIGN(FakeInvalidationClient);
};
class RegistrationManagerTest : public testing::Test {
protected:
RegistrationManagerTest()
: registration_manager_(&fake_invalidation_client_) {}
virtual ~RegistrationManagerTest() {}
FakeInvalidationClient fake_invalidation_client_;
RegistrationManager registration_manager_;
private:
DISALLOW_COPY_AND_ASSIGN(RegistrationManagerTest);
};
invalidation::ObjectId ModelTypeToObjectId(
syncable::ModelType model_type) {
invalidation::ObjectId object_id;
EXPECT_TRUE(RealModelTypeToObjectId(model_type, &object_id));
return object_id;
}
syncable::ModelType ObjectIdToModelType(
const invalidation::ObjectId& object_id) {
syncable::ModelType model_type = syncable::UNSPECIFIED;
EXPECT_TRUE(ObjectIdToRealModelType(object_id, &model_type));
return model_type;
}
invalidation::RegistrationUpdateResult MakeRegistrationUpdateResult(
syncable::ModelType model_type) {
invalidation::RegistrationUpdateResult result;
result.mutable_operation()->
set_type(invalidation::RegistrationUpdate::REGISTER);
*result.mutable_operation()->mutable_object_id() =
ModelTypeToObjectId(model_type);
result.mutable_status()->set_code(invalidation::Status::SUCCESS);
return result;
}
TEST_F(RegistrationManagerTest, RegisterType) {
const syncable::ModelType kModelTypes[] = {
syncable::BOOKMARKS,
syncable::PREFERENCES,
syncable::THEMES,
syncable::AUTOFILL,
syncable::EXTENSIONS,
};
const size_t kModelTypeCount = arraysize(kModelTypes);
// Register types.
for (size_t i = 0; i < kModelTypeCount; ++i) {
// Register twice; it shouldn't matter.
registration_manager_.RegisterType(kModelTypes[i]);
registration_manager_.RegisterType(kModelTypes[i]);
}
ASSERT_EQ(kModelTypeCount,
fake_invalidation_client_.registered_oids.size());
// Everything should be registered.
for (size_t i = 0; i < kModelTypeCount; ++i) {
EXPECT_TRUE(registration_manager_.IsRegistered(kModelTypes[i]));
}
// Check object IDs.
for (size_t i = 0; i < kModelTypeCount; ++i) {
EXPECT_EQ(kModelTypes[i],
ObjectIdToModelType(
fake_invalidation_client_.registered_oids[i]));
}
}
TEST_F(RegistrationManagerTest, MarkRegistrationLost) {
const syncable::ModelType kModelTypes[] = {
syncable::BOOKMARKS,
syncable::PREFERENCES,
syncable::THEMES,
syncable::AUTOFILL,
syncable::EXTENSIONS,
};
const size_t kModelTypeCount = arraysize(kModelTypes);
// Register types.
for (size_t i = 0; i < kModelTypeCount; ++i) {
registration_manager_.RegisterType(kModelTypes[i]);
}
ASSERT_EQ(kModelTypeCount,
fake_invalidation_client_.registered_oids.size());
// All should be registered.
for (size_t i = 0; i < kModelTypeCount; ++i) {
EXPECT_TRUE(registration_manager_.IsRegistered(kModelTypes[i]));
}
// Mark the registrations of all but the first one lost.
for (size_t i = 1; i < kModelTypeCount; ++i) {
registration_manager_.MarkRegistrationLost(kModelTypes[i]);
}
ASSERT_EQ(2 * kModelTypeCount - 1,
fake_invalidation_client_.registered_oids.size());
// All should still be registered.
for (size_t i = 0; i < kModelTypeCount; ++i) {
EXPECT_TRUE(registration_manager_.IsRegistered(kModelTypes[i]));
}
}
TEST_F(RegistrationManagerTest, MarkAllRegistrationsLost) {
const syncable::ModelType kModelTypes[] = {
syncable::BOOKMARKS,
syncable::PREFERENCES,
syncable::THEMES,
syncable::AUTOFILL,
syncable::EXTENSIONS,
};
const size_t kModelTypeCount = arraysize(kModelTypes);
// Register types.
for (size_t i = 0; i < kModelTypeCount; ++i) {
registration_manager_.RegisterType(kModelTypes[i]);
}
ASSERT_EQ(kModelTypeCount,
fake_invalidation_client_.registered_oids.size());
// All should be registered.
for (size_t i = 0; i < kModelTypeCount; ++i) {
EXPECT_TRUE(registration_manager_.IsRegistered(kModelTypes[i]));
}
// Mark the registrations of all but the first one lost. Then mark
// everything lost.
for (size_t i = 1; i < kModelTypeCount; ++i) {
registration_manager_.MarkRegistrationLost(kModelTypes[i]);
}
registration_manager_.MarkAllRegistrationsLost();
ASSERT_EQ(3 * kModelTypeCount - 1,
fake_invalidation_client_.registered_oids.size());
// All should still be registered.
for (size_t i = 0; i < kModelTypeCount; ++i) {
EXPECT_TRUE(registration_manager_.IsRegistered(kModelTypes[i]));
}
}
} // namespace
} // namespace notifier
<commit_msg>[Sync] Removed unused function causing clang build to fail<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/notifier/registration_manager.h"
#include <cstddef>
#include <deque>
#include <vector>
#include "base/basictypes.h"
#include "chrome/browser/sync/notifier/invalidation_util.h"
#include "chrome/browser/sync/syncable/model_type.h"
#include "google/cacheinvalidation/invalidation-client.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace sync_notifier {
namespace {
// Fake invalidation client that just stores the args of calls to
// Register().
class FakeInvalidationClient : public invalidation::InvalidationClient {
public:
FakeInvalidationClient() {}
virtual ~FakeInvalidationClient() {}
virtual void Register(const invalidation::ObjectId& oid) {
registered_oids.push_back(oid);
}
virtual void Unregister(const invalidation::ObjectId& oid) {
ADD_FAILURE();
}
virtual invalidation::NetworkEndpoint* network_endpoint() {
ADD_FAILURE();
return NULL;
}
std::deque<invalidation::ObjectId> registered_oids;
private:
DISALLOW_COPY_AND_ASSIGN(FakeInvalidationClient);
};
class RegistrationManagerTest : public testing::Test {
protected:
RegistrationManagerTest()
: registration_manager_(&fake_invalidation_client_) {}
virtual ~RegistrationManagerTest() {}
FakeInvalidationClient fake_invalidation_client_;
RegistrationManager registration_manager_;
private:
DISALLOW_COPY_AND_ASSIGN(RegistrationManagerTest);
};
invalidation::ObjectId ModelTypeToObjectId(
syncable::ModelType model_type) {
invalidation::ObjectId object_id;
EXPECT_TRUE(RealModelTypeToObjectId(model_type, &object_id));
return object_id;
}
syncable::ModelType ObjectIdToModelType(
const invalidation::ObjectId& object_id) {
syncable::ModelType model_type = syncable::UNSPECIFIED;
EXPECT_TRUE(ObjectIdToRealModelType(object_id, &model_type));
return model_type;
}
TEST_F(RegistrationManagerTest, RegisterType) {
const syncable::ModelType kModelTypes[] = {
syncable::BOOKMARKS,
syncable::PREFERENCES,
syncable::THEMES,
syncable::AUTOFILL,
syncable::EXTENSIONS,
};
const size_t kModelTypeCount = arraysize(kModelTypes);
// Register types.
for (size_t i = 0; i < kModelTypeCount; ++i) {
// Register twice; it shouldn't matter.
registration_manager_.RegisterType(kModelTypes[i]);
registration_manager_.RegisterType(kModelTypes[i]);
}
ASSERT_EQ(kModelTypeCount,
fake_invalidation_client_.registered_oids.size());
// Everything should be registered.
for (size_t i = 0; i < kModelTypeCount; ++i) {
EXPECT_TRUE(registration_manager_.IsRegistered(kModelTypes[i]));
}
// Check object IDs.
for (size_t i = 0; i < kModelTypeCount; ++i) {
EXPECT_EQ(kModelTypes[i],
ObjectIdToModelType(
fake_invalidation_client_.registered_oids[i]));
}
}
TEST_F(RegistrationManagerTest, MarkRegistrationLost) {
const syncable::ModelType kModelTypes[] = {
syncable::BOOKMARKS,
syncable::PREFERENCES,
syncable::THEMES,
syncable::AUTOFILL,
syncable::EXTENSIONS,
};
const size_t kModelTypeCount = arraysize(kModelTypes);
// Register types.
for (size_t i = 0; i < kModelTypeCount; ++i) {
registration_manager_.RegisterType(kModelTypes[i]);
}
ASSERT_EQ(kModelTypeCount,
fake_invalidation_client_.registered_oids.size());
// All should be registered.
for (size_t i = 0; i < kModelTypeCount; ++i) {
EXPECT_TRUE(registration_manager_.IsRegistered(kModelTypes[i]));
}
// Mark the registrations of all but the first one lost.
for (size_t i = 1; i < kModelTypeCount; ++i) {
registration_manager_.MarkRegistrationLost(kModelTypes[i]);
}
ASSERT_EQ(2 * kModelTypeCount - 1,
fake_invalidation_client_.registered_oids.size());
// All should still be registered.
for (size_t i = 0; i < kModelTypeCount; ++i) {
EXPECT_TRUE(registration_manager_.IsRegistered(kModelTypes[i]));
}
}
TEST_F(RegistrationManagerTest, MarkAllRegistrationsLost) {
const syncable::ModelType kModelTypes[] = {
syncable::BOOKMARKS,
syncable::PREFERENCES,
syncable::THEMES,
syncable::AUTOFILL,
syncable::EXTENSIONS,
};
const size_t kModelTypeCount = arraysize(kModelTypes);
// Register types.
for (size_t i = 0; i < kModelTypeCount; ++i) {
registration_manager_.RegisterType(kModelTypes[i]);
}
ASSERT_EQ(kModelTypeCount,
fake_invalidation_client_.registered_oids.size());
// All should be registered.
for (size_t i = 0; i < kModelTypeCount; ++i) {
EXPECT_TRUE(registration_manager_.IsRegistered(kModelTypes[i]));
}
// Mark the registrations of all but the first one lost. Then mark
// everything lost.
for (size_t i = 1; i < kModelTypeCount; ++i) {
registration_manager_.MarkRegistrationLost(kModelTypes[i]);
}
registration_manager_.MarkAllRegistrationsLost();
ASSERT_EQ(3 * kModelTypeCount - 1,
fake_invalidation_client_.registered_oids.size());
// All should still be registered.
for (size_t i = 0; i < kModelTypeCount; ++i) {
EXPECT_TRUE(registration_manager_.IsRegistered(kModelTypes[i]));
}
}
} // namespace
} // namespace notifier
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2013-2018 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <set>
#include <thread>
#include "cpp_utils/assert.hpp"
#include "server.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "accounts.hpp"
#include "incomes.hpp"
#include "assets.hpp"
#include "config.hpp"
#include "objectives.hpp"
#include "wishes.hpp"
#include "fortune.hpp"
#include "recurring.hpp"
#include "debts.hpp"
#include "currency.hpp"
#include "share.hpp"
#include "http.hpp"
#include "api/server_api.hpp"
#include "pages/server_pages.hpp"
using namespace budget;
namespace {
bool server_running = false;
httplib::Server * server_ptr = nullptr;
volatile bool cron = true;
void server_signal_handler(int signum) {
std::cout << "INFO: Received signal (" << signum << ")" << std::endl;
cron = false;
if (server_ptr) {
server_ptr->stop();
}
}
void install_signal_handler() {
struct sigaction action;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
action.sa_handler = server_signal_handler;
sigaction(SIGTERM, &action, NULL);
sigaction(SIGINT, &action, NULL);
std::cout << "INFO: Installed the signal handler" << std::endl;
}
void start_server(){
std::cout << "INFO: Started the server thread" << std::endl;
httplib::Server server;
load_pages(server);
load_api(server);
install_signal_handler();
auto port = get_server_port();
auto listen = get_server_listen();
server_ptr = &server;
// Listen
std::cout << "INFO: Server is starting to listen on " << listen << ':' << port << std::endl;
server.listen(listen.c_str(), port);
std::cout << "INFO: Server has exited" << std::endl;
}
void start_cron_loop(){
std::cout << "INFO: Started the cron thread" << std::endl;
size_t hours = 0;
while(cron){
using namespace std::chrono_literals;
std::this_thread::sleep_for(1h);
++hours;
check_for_recurrings();
// We save the cache once per day
if (hours % 24 == 0) {
save_currency_cache();
save_share_price_cache();
}
// Every four hours, we refresh the currency cache
// Only current day rates are refreshed
if (hours % 4 == 0) {
std::cout << "Refresh the currency cache" << std::endl;
budget::refresh_currency_cache();
}
// Every hour, we try to prefetch value for new days
std::cout << "Prefetch the share cache" << std::endl;
budget::prefetch_share_price_cache();
}
std::cout << "INFO: Cron Thread has exited" << std::endl;
}
} //end of anonymous namespace
void budget::set_server_running(){
// Indicates to the system that it's running in server mode
server_running = true;
}
void budget::server_module::load(){
load_accounts();
load_incomes();
load_expenses();
load_earnings();
load_assets();
load_objectives();
load_wishes();
load_fortunes();
load_recurrings();
load_debts();
load_wishes();
}
void budget::server_module::handle(const std::vector<std::string>& args){
cpp_unused(args);
std::cout << "Starting the threads" << std::endl;
std::thread server_thread([](){ start_server(); });
std::thread cron_thread([](){ start_cron_loop(); });
server_thread.join();
cron_thread.join();
}
bool budget::is_server_running(){
return server_running;
}
<commit_msg>Cleanup server starting<commit_after>//=======================================================================
// Copyright (c) 2013-2018 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <set>
#include <thread>
#include "cpp_utils/assert.hpp"
#include "server.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "accounts.hpp"
#include "incomes.hpp"
#include "assets.hpp"
#include "config.hpp"
#include "objectives.hpp"
#include "wishes.hpp"
#include "fortune.hpp"
#include "recurring.hpp"
#include "debts.hpp"
#include "currency.hpp"
#include "share.hpp"
#include "http.hpp"
#include "api/server_api.hpp"
#include "pages/server_pages.hpp"
using namespace budget;
namespace {
bool server_running = false;
httplib::Server * server_ptr = nullptr;
volatile bool cron = true;
void server_signal_handler(int signum) {
std::cout << "INFO: Received signal (" << signum << ")" << std::endl;
cron = false;
if (server_ptr) {
server_ptr->stop();
}
}
void install_signal_handler() {
struct sigaction action;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
action.sa_handler = server_signal_handler;
sigaction(SIGTERM, &action, NULL);
sigaction(SIGINT, &action, NULL);
std::cout << "INFO: Installed the signal handler" << std::endl;
}
bool start_server(){
std::cout << "INFO: Started the server thread" << std::endl;
httplib::Server server;
load_pages(server);
load_api(server);
install_signal_handler();
auto port = get_server_port();
auto listen = get_server_listen();
server_ptr = &server;
// Listen
std::cout << "INFO: Server is starting to listen on " << listen << ':' << port << std::endl;
if (!server.listen(listen.c_str(), port)) {
std::cerr << "INFO: Server failed to start" << std::endl;
return false;
}
std::cout << "INFO: Server has exited normally" << std::endl;
return true;
}
void start_cron_loop(){
std::cout << "INFO: Started the cron thread" << std::endl;
size_t hours = 0;
while(cron){
using namespace std::chrono_literals;
std::this_thread::sleep_for(1h);
++hours;
check_for_recurrings();
// We save the cache once per day
if (hours % 24 == 0) {
save_currency_cache();
save_share_price_cache();
}
// Every four hours, we refresh the currency cache
// Only current day rates are refreshed
if (hours % 4 == 0) {
std::cout << "Refresh the currency cache" << std::endl;
budget::refresh_currency_cache();
}
// Every hour, we try to prefetch value for new days
std::cout << "Prefetch the share cache" << std::endl;
budget::prefetch_share_price_cache();
}
std::cout << "INFO: Cron Thread has exited" << std::endl;
}
} //end of anonymous namespace
void budget::set_server_running(){
// Indicates to the system that it's running in server mode
server_running = true;
}
void budget::server_module::load(){
load_accounts();
load_incomes();
load_expenses();
load_earnings();
load_assets();
load_objectives();
load_wishes();
load_fortunes();
load_recurrings();
load_debts();
load_wishes();
}
void budget::server_module::handle(const std::vector<std::string>& args){
cpp_unused(args);
std::cout << "Starting the threads" << std::endl;
volatile bool success = false;
std::thread server_thread([&success](){ success = start_server(); });
std::thread cron_thread([](){ start_cron_loop(); });
server_thread.join();
if (!success) {
cron = false;
}
cron_thread.join();
}
bool budget::is_server_running(){
return server_running;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/crypto_module_password_dialog_view.h"
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/views/window.h"
#include "googleurl/src/gurl.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/controls/button/text_button.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/widget/widget.h"
int kInputPasswordMinWidth = 8;
namespace browser {
// CryptoModulePasswordDialogView
////////////////////////////////////////////////////////////////////////////////
CryptoModulePasswordDialogView::CryptoModulePasswordDialogView(
const std::string& slot_name,
browser::CryptoModulePasswordReason reason,
const std::string& server,
const base::Callback<void(const char*)>& callback)
: callback_(callback) {
Init(server, slot_name, reason);
}
CryptoModulePasswordDialogView::~CryptoModulePasswordDialogView() {
}
void CryptoModulePasswordDialogView::Init(
const std::string& server,
const std::string& slot_name,
browser::CryptoModulePasswordReason reason) {
// Select an appropriate text for the reason.
std::string text;
const string16& server16 = UTF8ToUTF16(server);
const string16& slot16 = UTF8ToUTF16(slot_name);
switch (reason) {
case browser::kCryptoModulePasswordKeygen:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_KEYGEN, slot16, server16);
break;
case browser::kCryptoModulePasswordCertEnrollment:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_ENROLLMENT, slot16, server16);
break;
case browser::kCryptoModulePasswordClientAuth:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CLIENT_AUTH, slot16, server16);
break;
case browser::kCryptoModulePasswordListCerts:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_LIST_CERTS, slot16);
break;
case browser::kCryptoModulePasswordCertImport:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_IMPORT, slot16);
break;
case browser::kCryptoModulePasswordCertExport:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_EXPORT, slot16);
break;
default:
NOTREACHED();
}
reason_label_ = new views::Label(UTF8ToUTF16(text));
reason_label_->SetMultiLine(true);
password_label_ = new views::Label(l10n_util::GetStringUTF16(
IDS_CRYPTO_MODULE_AUTH_DIALOG_PASSWORD_FIELD));
password_entry_ = new views::Textfield(views::Textfield::STYLE_OBSCURED);
password_entry_->SetController(this);
views::GridLayout* layout = views::GridLayout::CreatePanel(this);
SetLayoutManager(layout);
views::ColumnSet* reason_column_set = layout->AddColumnSet(0);
reason_column_set->AddColumn(
views::GridLayout::LEADING, views::GridLayout::LEADING, 1,
views::GridLayout::USE_PREF, 0, 0);
views::ColumnSet* column_set = layout->AddColumnSet(1);
column_set->AddColumn(views::GridLayout::LEADING,
views::GridLayout::LEADING, 0,
views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(
0, views::kUnrelatedControlLargeHorizontalSpacing);
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
layout->StartRow(0, 0);
layout->AddView(reason_label_);
layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing);
layout->StartRow(0, 1);
layout->AddView(password_label_);
layout->AddView(password_entry_);
}
views::View* CryptoModulePasswordDialogView::GetInitiallyFocusedView() {
return password_entry_;
}
ui::ModalType CryptoModulePasswordDialogView::GetModalType() const {
return ui::MODAL_TYPE_WINDOW;
}
views::View* CryptoModulePasswordDialogView::GetContentsView() {
return this;
}
string16 CryptoModulePasswordDialogView::GetDialogButtonLabel(
ui::DialogButton button) const {
return l10n_util::GetStringUTF16(button == ui::DIALOG_BUTTON_OK ?
IDS_CRYPTO_MODULE_AUTH_DIALOG_OK_BUTTON_LABEL : IDS_CANCEL);
}
bool CryptoModulePasswordDialogView::Accept() {
callback_.Run(UTF16ToUTF8(password_entry_->text()).c_str());
const string16 empty;
password_entry_->SetText(empty);
return true;
}
bool CryptoModulePasswordDialogView::Cancel() {
callback_.Run(static_cast<const char*>(NULL));
const string16 empty;
password_entry_->SetText(empty);
return true;
}
bool CryptoModulePasswordDialogView::HandleKeyEvent(
views::Textfield* sender,
const views::KeyEvent& keystroke) {
return false;
}
void CryptoModulePasswordDialogView::ContentsChanged(
views::Textfield* sender,
const string16& new_contents) {
}
string16 CryptoModulePasswordDialogView::GetWindowTitle() const {
return l10n_util::GetStringUTF16(IDS_CRYPTO_MODULE_AUTH_DIALOG_TITLE);
}
void ShowCryptoModulePasswordDialog(
const std::string& slot_name,
bool retry,
CryptoModulePasswordReason reason,
const std::string& server,
const CryptoModulePasswordCallback& callback) {
CryptoModulePasswordDialogView* dialog =
new CryptoModulePasswordDialogView(slot_name, reason, server, callback);
views::Widget::CreateWindow(dialog)->Show();
}
} // namespace browser
<commit_msg>views: Remove unused const from crypto module password dialog.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/crypto_module_password_dialog_view.h"
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/views/window.h"
#include "googleurl/src/gurl.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/controls/button/text_button.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/widget/widget.h"
namespace browser {
// CryptoModulePasswordDialogView
////////////////////////////////////////////////////////////////////////////////
CryptoModulePasswordDialogView::CryptoModulePasswordDialogView(
const std::string& slot_name,
browser::CryptoModulePasswordReason reason,
const std::string& server,
const base::Callback<void(const char*)>& callback)
: callback_(callback) {
Init(server, slot_name, reason);
}
CryptoModulePasswordDialogView::~CryptoModulePasswordDialogView() {
}
void CryptoModulePasswordDialogView::Init(
const std::string& server,
const std::string& slot_name,
browser::CryptoModulePasswordReason reason) {
// Select an appropriate text for the reason.
std::string text;
const string16& server16 = UTF8ToUTF16(server);
const string16& slot16 = UTF8ToUTF16(slot_name);
switch (reason) {
case browser::kCryptoModulePasswordKeygen:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_KEYGEN, slot16, server16);
break;
case browser::kCryptoModulePasswordCertEnrollment:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_ENROLLMENT, slot16, server16);
break;
case browser::kCryptoModulePasswordClientAuth:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CLIENT_AUTH, slot16, server16);
break;
case browser::kCryptoModulePasswordListCerts:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_LIST_CERTS, slot16);
break;
case browser::kCryptoModulePasswordCertImport:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_IMPORT, slot16);
break;
case browser::kCryptoModulePasswordCertExport:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_EXPORT, slot16);
break;
default:
NOTREACHED();
}
reason_label_ = new views::Label(UTF8ToUTF16(text));
reason_label_->SetMultiLine(true);
password_label_ = new views::Label(l10n_util::GetStringUTF16(
IDS_CRYPTO_MODULE_AUTH_DIALOG_PASSWORD_FIELD));
password_entry_ = new views::Textfield(views::Textfield::STYLE_OBSCURED);
password_entry_->SetController(this);
views::GridLayout* layout = views::GridLayout::CreatePanel(this);
SetLayoutManager(layout);
views::ColumnSet* reason_column_set = layout->AddColumnSet(0);
reason_column_set->AddColumn(
views::GridLayout::LEADING, views::GridLayout::LEADING, 1,
views::GridLayout::USE_PREF, 0, 0);
views::ColumnSet* column_set = layout->AddColumnSet(1);
column_set->AddColumn(views::GridLayout::LEADING,
views::GridLayout::LEADING, 0,
views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(
0, views::kUnrelatedControlLargeHorizontalSpacing);
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
layout->StartRow(0, 0);
layout->AddView(reason_label_);
layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing);
layout->StartRow(0, 1);
layout->AddView(password_label_);
layout->AddView(password_entry_);
}
views::View* CryptoModulePasswordDialogView::GetInitiallyFocusedView() {
return password_entry_;
}
ui::ModalType CryptoModulePasswordDialogView::GetModalType() const {
return ui::MODAL_TYPE_WINDOW;
}
views::View* CryptoModulePasswordDialogView::GetContentsView() {
return this;
}
string16 CryptoModulePasswordDialogView::GetDialogButtonLabel(
ui::DialogButton button) const {
return l10n_util::GetStringUTF16(button == ui::DIALOG_BUTTON_OK ?
IDS_CRYPTO_MODULE_AUTH_DIALOG_OK_BUTTON_LABEL : IDS_CANCEL);
}
bool CryptoModulePasswordDialogView::Accept() {
callback_.Run(UTF16ToUTF8(password_entry_->text()).c_str());
const string16 empty;
password_entry_->SetText(empty);
return true;
}
bool CryptoModulePasswordDialogView::Cancel() {
callback_.Run(static_cast<const char*>(NULL));
const string16 empty;
password_entry_->SetText(empty);
return true;
}
bool CryptoModulePasswordDialogView::HandleKeyEvent(
views::Textfield* sender,
const views::KeyEvent& keystroke) {
return false;
}
void CryptoModulePasswordDialogView::ContentsChanged(
views::Textfield* sender,
const string16& new_contents) {
}
string16 CryptoModulePasswordDialogView::GetWindowTitle() const {
return l10n_util::GetStringUTF16(IDS_CRYPTO_MODULE_AUTH_DIALOG_TITLE);
}
void ShowCryptoModulePasswordDialog(
const std::string& slot_name,
bool retry,
CryptoModulePasswordReason reason,
const std::string& server,
const CryptoModulePasswordCallback& callback) {
CryptoModulePasswordDialogView* dialog =
new CryptoModulePasswordDialogView(slot_name, reason, server, callback);
views::Widget::CreateWindow(dialog)->Show();
}
} // namespace browser
<|endoftext|> |
<commit_before>#include <Game/ECS/GameWorld.h>
#include <Game/ECS/Components/ActionQueueComponent.h>
#include <Game/ECS/Components/SceneComponent.h>
#include <AI/Navigation/NavAgentComponent.h>
#include <AI/Movement/SteerAction.h>
#include <Game/Objects/SmartObjectComponent.h>
#include <Game/Objects/SmartObject.h>
#include <DetourCommon.h>
namespace DEM::Game
{
static inline float SqDistanceToInteractionZone(const vector3& Pos, const CInteractionZone& Zone, UPTR& OutSegment, float& OutT)
{
const auto VertexCount = Zone.Vertices.size();
if (VertexCount == 0) return std::numeric_limits<float>().max();
else if (VertexCount == 1) return vector3::SqDistance(Pos, Zone.Vertices[0]);
else if (VertexCount == 2) return dtDistancePtSegSqr2D(Pos.v, Zone.Vertices[0].v, Zone.Vertices[1].v, OutT);
else
{
float MinSqDistance = std::numeric_limits<float>().max();
if (Zone.ClosedPolygon)
{
// NB: only convex polys are supported for now!
if (dtPointInPolygon(Pos.v, Zone.Vertices[0].v, VertexCount))
{
OutSegment = VertexCount;
return 0.f;
}
// Process implicit closing edge
MinSqDistance = dtDistancePtSegSqr2D(Pos.v, Zone.Vertices[VertexCount - 1].v, Zone.Vertices[0].v, OutT);
OutSegment = VertexCount - 1;
}
for (UPTR i = 0; i < VertexCount - 1; ++i)
{
float t;
const float SqDistance = dtDistancePtSegSqr2D(Pos.v, Zone.Vertices[i].v, Zone.Vertices[i + 1].v, t);
if (SqDistance < MinSqDistance)
{
MinSqDistance = SqDistance;
OutSegment = i;
OutT = t;
}
}
return MinSqDistance;
}
}
//---------------------------------------------------------------------
static inline vector3 PointInInteractionZone(const vector3& Pos, const CInteractionZone& Zone, UPTR Segment, float t)
{
const auto VertexCount = Zone.Vertices.size();
if (VertexCount == 0) return vector3::Zero;
else if (VertexCount == 1) return Zone.Vertices[0];
else if (VertexCount == 2) return vector3::lerp(Zone.Vertices[0], Zone.Vertices[1], t);
else if (Segment == VertexCount) return Pos;
else return vector3::lerp(Zone.Vertices[Segment], Zone.Vertices[(Segment + 1) % VertexCount], t);
}
//---------------------------------------------------------------------
// NB: non-zero _AllowedZones implied
static vector3 FindLocalInteractionPoint(SwitchSmartObjectState& Action, const CSmartObject& SO, const vector3& ActorLocalPos, U8 ZoneIndex = CSmartObject::MAX_ZONES)
{
float MinSqDistance = std::numeric_limits<float>().max();
UPTR SegmentIdx = 0;
float t = 0.f;
if (ZoneIndex >= CSmartObject::MAX_ZONES)
{
// Find closest suitable zone
const auto ZoneCount = SO.GetInteractionZoneCount();
for (U8 i = 0; i < ZoneCount; ++i)
{
if (!((1 << i) & Action._AllowedZones)) continue;
const float SqDistance = SqDistanceToInteractionZone(ActorLocalPos, SO.GetInteractionZone(i), SegmentIdx, t);
if (SqDistance < MinSqDistance)
{
MinSqDistance = SqDistance;
Action._ZoneIndex = i;
}
}
}
else
{
MinSqDistance = SqDistanceToInteractionZone(ActorLocalPos, SO.GetInteractionZone(ZoneIndex), SegmentIdx, t);
Action._ZoneIndex = ZoneIndex;
}
// For static smart objects try each zone only once
if (SO.IsStatic()) Action._AllowedZones &= ~(1 << Action._ZoneIndex);
return PointInInteractionZone(ActorLocalPos, SO.GetInteractionZone(Action._ZoneIndex), SegmentIdx, t);
}
//---------------------------------------------------------------------
void InteractWithSmartObjects(CGameWorld& World)
{
World.ForEachEntityWith<CActionQueueComponent, const CSceneComponent, const AI::CNavAgentComponent*>(
[&World](auto EntityID, auto& Entity,
CActionQueueComponent& Queue,
const CSceneComponent& ActorSceneComponent,
const AI::CNavAgentComponent* pNavAgent)
{
if (!ActorSceneComponent.RootNode) return;
auto Action = Queue.FindCurrent<SwitchSmartObjectState>();
if (!Action) return;
const auto ActionStatus = Queue.GetStatus(Action);
if (ActionStatus != EActionStatus::Active) return;
const auto ChildAction = Queue.GetChild(Action);
const auto ChildActionStatus = Queue.GetStatus(ChildAction);
if (ChildActionStatus == EActionStatus::Cancelled)
{
Queue.SetStatus(Action, EActionStatus::Cancelled);
return;
}
auto pAction = Action.As<SwitchSmartObjectState>();
auto pSOComponent = World.FindComponent<CSmartObjectComponent>(pAction->_Object);
if (!pSOComponent || !pSOComponent->Asset)
{
Queue.SetStatus(Action, EActionStatus::Failed);
return;
}
const CSmartObject* pSOAsset = pSOComponent->Asset->GetObject<CSmartObject>();
if (!pSOAsset)
{
Queue.SetStatus(Action, EActionStatus::Failed);
return;
}
auto pSOSceneComponent = World.FindComponent<CSceneComponent>(pAction->_Object);
if (!pSOSceneComponent || !pSOSceneComponent->RootNode)
{
Queue.SetStatus(Action, EActionStatus::Failed);
return;
}
// Cache allowed zones once
if (!pAction->_AllowedZones)
{
const auto ZoneCount = pSOAsset->GetInteractionZoneCount();
for (U8 i = 0; i < ZoneCount; ++i)
{
const auto& Zone = pSOAsset->GetInteractionZone(i);
for (const auto& Interaction : Zone.Interactions)
{
if (Interaction.ID == pAction->_Interaction)
{
pAction->_AllowedZones |= (1 << i);
break;
}
}
}
if (!pAction->_AllowedZones)
{
Queue.SetStatus(Action, EActionStatus::Failed);
return;
}
}
const auto& ActorPos = ActorSceneComponent.RootNode->GetWorldPosition();
const auto& ObjectPos = pSOSceneComponent->RootNode->GetWorldPosition();
const auto& ObjectWorldTfm = pSOSceneComponent->RootNode->GetWorldMatrix();
// Move to the interaction point
if (auto pSteerAction = ChildAction.As<AI::Steer>())
{
if (ChildActionStatus == EActionStatus::Active)
{
//if (pSOAsset->IsStatic()) return;
// if Steer optimization will be used for dynamic objects, must update target here
// and generate Steer or Navigate. But most probably Steer will be used for Static only.
// NB: Steer can also be used for dynamic if actor can't navigate. So can check this
// and if nav agent is null then update Steer target without trying to generate Navigate.
return;
}
else if (ChildActionStatus == EActionStatus::Failed)
{
Queue.SetStatus(Action, EActionStatus::Failed);
return;
}
}
else if (auto pNavAction = ChildAction.As<AI::Navigate>())
{
if (ChildActionStatus == EActionStatus::Active)
{
if (pSOAsset->IsStatic())
{
// If the path intersects with another interaction zone, can optimize by navigating to it
//!!!TODO: instead of _PathScanned could increment path version on replan and recheck, to handle partial path and corridor optimizations!
if (!pAction->_PathScanned && pAction->_AllowedZones && pNavAgent && pNavAgent->State == AI::ENavigationState::Following)
{
pAction->_PathScanned = true;
const auto ZoneCount = pSOAsset->GetInteractionZoneCount();
for (int PolyIdx = 0; PolyIdx < pNavAgent->Corridor.getPathCount(); ++PolyIdx)
{
const auto PolyRef = pNavAgent->Corridor.getPath()[PolyIdx];
for (U8 ZoneIdx = 0; ZoneIdx < ZoneCount; ++ZoneIdx)
{
if (!((1 << ZoneIdx) & pAction->_AllowedZones)) continue;
const auto& Zone = pSOAsset->GetInteractionZone(ZoneIdx);
//!!!calc distance from PolyRef to Zone!
const float SqDistance = 0.f;
const float Radius = Zone.Radius; //???apply actor radius too?
const float SqRadius = std::max(Radius * Radius, AI::Steer::SqLinearTolerance);
if (SqDistance <= SqRadius)
{
pAction->_ZoneIndex = ZoneIdx;
pAction->_AllowedZones &= ~(1 << ZoneIdx);
//!!!set new point as a target, no replanning will happen!
}
}
}
}
}
else
{
const auto& Zone = pSOAsset->GetInteractionZone(pAction->_ZoneIndex);
//const float SqDistance = SqDistanceToInteractionZone(SOSpaceActorPos, Zone, SegmentIdx, t);
// get target position from SO asset (for the curr region) and update it in the action
}
return;
}
else if (ChildActionStatus == EActionStatus::Failed)
{
// try to navigate to the point in the next closest region (static) or any region (dynamic)
// if all are tried and failed, Queue.SetStatus(Action, EActionStatus::Failed);
//???when dynamic fails?
return;
}
}
else if (!pSOAsset->IsStatic() || !ChildAction)
{
if (!pAction->_AllowedZones)
{
Queue.SetStatus(Action, EActionStatus::Failed);
return;
}
matrix44 WorldToSmartObject;
ObjectWorldTfm.invert_simple(WorldToSmartObject);
const vector3 SOSpaceActorPos = WorldToSmartObject.transform_coord(ActorPos);
vector3 ActionPos = FindLocalInteractionPoint(*pAction, *pSOAsset, SOSpaceActorPos);
const auto& Zone = pSOAsset->GetInteractionZone(pAction->_ZoneIndex);
const float Radius = Zone.Radius; //???apply actor radius too?
const float SqRadius = std::max(Radius * Radius, AI::Steer::SqLinearTolerance);
// FIXME: find closest navigable point, use radius as arrival distance, apply to the last path segment
//if (SqRadius < MinSqDistance)
// ActionPos = vector3::lerp(ActionPos, SOSpaceActorPos, Radius / n_sqrt(MinSqDistance));
ActionPos = ObjectWorldTfm.transform_coord(ActionPos);
if (vector3::SqDistance2D(ActionPos, ActorPos) > SqRadius)
{
if (pNavAgent)
{
float NearestPos[3];
const float Extents[3] = { Radius, pNavAgent->Height, Radius };
dtPolyRef ObjPolyRef = 0;
pNavAgent->pNavQuery->findNearestPoly(ActionPos.v, Extents, pNavAgent->Settings->GetQueryFilter(), &ObjPolyRef, NearestPos);
const float SqDiff = dtVdist2DSqr(ActionPos.v, NearestPos);
if (!ObjPolyRef || SqDiff > SqRadius)
{
// No navigable point found
// FIXME: try the next zone right now!
// TODO: could explore all the interaction zone for intersecion with valid navigation polys, but it is slow
//???what if dynamic? discard this zone or fail immediately?
return;
}
else if (SqDiff > 0.f) ActionPos = NearestPos;
// FIXME: use pNavAgent->Corridor.getFirstPoly() instead! Offmesh can break this now!
const float AgentExtents[3] = { pNavAgent->Radius, pNavAgent->Height, pNavAgent->Radius };
dtPolyRef AgentPolyRef = 0;
pNavAgent->pNavQuery->findNearestPoly(ActorPos.v, AgentExtents, pNavAgent->Settings->GetQueryFilter(), &AgentPolyRef, NearestPos);
//n_assert_dbg(pNavAgent->Corridor.getFirstPoly() == AgentPolyRef);
if (ObjPolyRef != AgentPolyRef)
{
// To avoid possible parent path invalidation, could try to optimize with:
//Agent.pNavQuery->findLocalNeighbourhood
//Agent.pNavQuery->moveAlongSurface
//Agent.pNavQuery->raycast
// but it would require additional logic and complicate navigation.
Queue.PushOrUpdateChild<AI::Navigate>(Action, ActionPos, 0.f);
return;
}
}
Queue.PushOrUpdateChild<AI::Steer>(Action, ActionPos, ObjectPos, 0.f);
return;
}
}
// Face interaction direction
if (auto pTurnAction = ChildAction.As<AI::Turn>())
{
if (ChildActionStatus == EActionStatus::Active)
{
if (pSOAsset->IsStatic()) return;
// get facing from SO asset for the current region
// if facing is still required by SO, update it in Turn action and return
}
else if (ChildActionStatus == EActionStatus::Failed)
{
Queue.SetStatus(Action, EActionStatus::Failed);
return;
}
}
else if (!pSOAsset->IsStatic() || !ChildAction)
{
// get facing from SO asset for the current region
// if facing is required by SO and not already looking at that dir, generate Turn action and return
}
// Interact with object
// ... anim, state transition etc ...
// FIXME: fill! Get facing (only if necessary) from interaction params
vector3 TargetDir = ObjectPos - ActorPos;
TargetDir.norm();
//???update only if there is no Turn already active?
vector3 LookatDir = -ActorSceneComponent.RootNode->GetWorldMatrix().AxisZ();
LookatDir.norm();
const float Angle = vector3::Angle2DNorm(LookatDir, TargetDir);
if (std::fabsf(Angle) >= DEM::AI::Turn::AngularTolerance)
{
Queue.PushOrUpdateChild<AI::Turn>(Action, TargetDir);
return;
}
pSOComponent->RequestedState = pAction->_State;
pSOComponent->Force = pAction->_Force;
// TODO: start actor animation and/or state switching, wait for its end before setting Succeeded status!
Queue.SetStatus(Action, EActionStatus::Succeeded);
});
}
//---------------------------------------------------------------------
}
<commit_msg>SO iact movement progress 2<commit_after>#include <Game/ECS/GameWorld.h>
#include <Game/ECS/Components/ActionQueueComponent.h>
#include <Game/ECS/Components/SceneComponent.h>
#include <AI/Navigation/NavAgentComponent.h>
#include <AI/Movement/SteerAction.h>
#include <Game/Objects/SmartObjectComponent.h>
#include <Game/Objects/SmartObject.h>
#include <DetourCommon.h>
namespace DEM::Game
{
static inline float SqDistanceToInteractionZone(const vector3& Pos, const CInteractionZone& Zone, UPTR& OutSegment, float& OutT)
{
const auto VertexCount = Zone.Vertices.size();
if (VertexCount == 0) return std::numeric_limits<float>().max();
else if (VertexCount == 1) return vector3::SqDistance(Pos, Zone.Vertices[0]);
else if (VertexCount == 2) return dtDistancePtSegSqr2D(Pos.v, Zone.Vertices[0].v, Zone.Vertices[1].v, OutT);
else
{
float MinSqDistance = std::numeric_limits<float>().max();
if (Zone.ClosedPolygon)
{
// NB: only convex polys are supported for now!
if (dtPointInPolygon(Pos.v, Zone.Vertices[0].v, VertexCount))
{
OutSegment = VertexCount;
return 0.f;
}
// Process implicit closing edge
MinSqDistance = dtDistancePtSegSqr2D(Pos.v, Zone.Vertices[VertexCount - 1].v, Zone.Vertices[0].v, OutT);
OutSegment = VertexCount - 1;
}
for (UPTR i = 0; i < VertexCount - 1; ++i)
{
float t;
const float SqDistance = dtDistancePtSegSqr2D(Pos.v, Zone.Vertices[i].v, Zone.Vertices[i + 1].v, t);
if (SqDistance < MinSqDistance)
{
MinSqDistance = SqDistance;
OutSegment = i;
OutT = t;
}
}
return MinSqDistance;
}
}
//---------------------------------------------------------------------
static inline vector3 PointInInteractionZone(const vector3& Pos, const CInteractionZone& Zone, UPTR Segment, float t)
{
const auto VertexCount = Zone.Vertices.size();
if (VertexCount == 0) return vector3::Zero;
else if (VertexCount == 1) return Zone.Vertices[0];
else if (VertexCount == 2) return vector3::lerp(Zone.Vertices[0], Zone.Vertices[1], t);
else if (Segment == VertexCount) return Pos;
else return vector3::lerp(Zone.Vertices[Segment], Zone.Vertices[(Segment + 1) % VertexCount], t);
}
//---------------------------------------------------------------------
// NB: non-zero _AllowedZones implied
static vector3 FindLocalInteractionPoint(SwitchSmartObjectState& Action, const CSmartObject& SO, const vector3& ActorLocalPos, bool OnlyCurrZone)
{
float MinSqDistance = std::numeric_limits<float>().max();
UPTR SegmentIdx = 0;
float t = 0.f;
if (OnlyCurrZone)
{
MinSqDistance = SqDistanceToInteractionZone(ActorLocalPos, SO.GetInteractionZone(Action._ZoneIndex), SegmentIdx, t);
}
else
{
// Find closest suitable zone
const auto ZoneCount = SO.GetInteractionZoneCount();
for (U8 i = 0; i < ZoneCount; ++i)
{
if (!((1 << i) & Action._AllowedZones)) continue;
const float SqDistance = SqDistanceToInteractionZone(ActorLocalPos, SO.GetInteractionZone(i), SegmentIdx, t);
if (SqDistance < MinSqDistance)
{
MinSqDistance = SqDistance;
Action._ZoneIndex = i;
}
}
}
// For static smart objects try each zone only once
if (SO.IsStatic()) Action._AllowedZones &= ~(1 << Action._ZoneIndex);
return PointInInteractionZone(ActorLocalPos, SO.GetInteractionZone(Action._ZoneIndex), SegmentIdx, t);
}
//---------------------------------------------------------------------
//???when dynamic fails? zones aren't marked as failed!
static bool UpdateMovementSubAction(CActionQueueComponent& Queue, HAction Action, const CSmartObject& SO,
const AI::CNavAgentComponent* pNavAgent, const matrix44& ObjectWorldTfm, const vector3& ActorPos, bool OnlyCurrZone)
{
auto pAction = Action.As<SwitchSmartObjectState>();
if (!pAction->_AllowedZones)
{
Queue.SetStatus(Action, EActionStatus::Failed);
return true;
}
matrix44 WorldToSmartObject;
ObjectWorldTfm.invert_simple(WorldToSmartObject);
const vector3 SOSpaceActorPos = WorldToSmartObject.transform_coord(ActorPos);
vector3 ActionPos = FindLocalInteractionPoint(*pAction, SO, SOSpaceActorPos, OnlyCurrZone);
const auto& Zone = SO.GetInteractionZone(pAction->_ZoneIndex);
const float Radius = Zone.Radius; //???apply actor radius too?
const float SqRadius = std::max(Radius * Radius, AI::Steer::SqLinearTolerance);
// FIXME: find closest navigable point, use radius as arrival distance, apply to the last path segment
//if (SqRadius < MinSqDistance)
// ActionPos = vector3::lerp(ActionPos, SOSpaceActorPos, Radius / n_sqrt(MinSqDistance));
ActionPos = ObjectWorldTfm.transform_coord(ActionPos);
if (vector3::SqDistance2D(ActionPos, ActorPos) <= SqRadius) return false;
if (pNavAgent)
{
float NearestPos[3];
const float Extents[3] = { Radius, pNavAgent->Height, Radius };
dtPolyRef ObjPolyRef = 0;
pNavAgent->pNavQuery->findNearestPoly(ActionPos.v, Extents, pNavAgent->Settings->GetQueryFilter(), &ObjPolyRef, NearestPos);
const float SqDiff = dtVdist2DSqr(ActionPos.v, NearestPos);
if (!ObjPolyRef || SqDiff > SqRadius)
{
// No navigable point found
// FIXME: try the next zone right now!
// TODO: could explore all the interaction zone for intersecion with valid navigation polys, but it is slow
//???what if dynamic? discard this zone or fail immediately?
return true;
}
else if (SqDiff > 0.f) ActionPos = NearestPos;
// FIXME: use pNavAgent->Corridor.getFirstPoly() instead! Offmesh can break this now!
const float AgentExtents[3] = { pNavAgent->Radius, pNavAgent->Height, pNavAgent->Radius };
dtPolyRef AgentPolyRef = 0;
pNavAgent->pNavQuery->findNearestPoly(ActorPos.v, AgentExtents, pNavAgent->Settings->GetQueryFilter(), &AgentPolyRef, NearestPos);
//n_assert_dbg(pNavAgent->Corridor.getFirstPoly() == AgentPolyRef);
if (ObjPolyRef != AgentPolyRef)
{
// To avoid possible parent path invalidation, could try to optimize with:
//Agent.pNavQuery->findLocalNeighbourhood
//Agent.pNavQuery->moveAlongSurface
//Agent.pNavQuery->raycast
// but it would require additional logic and complicate navigation.
Queue.PushOrUpdateChild<AI::Navigate>(Action, ActionPos, 0.f);
return true;
}
}
Queue.PushOrUpdateChild<AI::Steer>(Action, ActionPos, ObjectWorldTfm.Translation(), 0.f);
return true;
}
//---------------------------------------------------------------------
// NB: OutPos is not changed if function returns false
static bool IsNavPolyInInteractionZone(const CInteractionZone& Zone, dtPolyRef PolyRef, dtNavMeshQuery& Query, vector3& OutPos)
{
////!!!calc distance from PolyRef to Zone skeleton!
//const float SqDistance = 0.f;
//const float Radius = Zone.Radius; //???apply actor radius too?
//const float SqRadius = std::max(Radius * Radius, AI::Steer::SqLinearTolerance);
//return SqDistance <= SqRadius;
//!!!return closest pos!
//NOT_IMPLEMENTED;
return false;
}
//---------------------------------------------------------------------
// If new path intersects with another interaction zone, can optimize by navigating to it instead of the original target
static void OptimizeStaticPath(SwitchSmartObjectState& Action, AI::Navigate& NavAction, const CSmartObject& SO, const AI::CNavAgentComponent* pNavAgent)
{
//!!!TODO: instead of _PathScanned could increment path version on replan and recheck,
//to handle partial path and corridor optimizations!
if (Action._PathScanned || !Action._AllowedZones || !pNavAgent || pNavAgent->State != AI::ENavigationState::Following) return;
Action._PathScanned = true;
const auto ZoneCount = SO.GetInteractionZoneCount();
// Don't test the last poly, we already navigate to it
const int PolysToTest = pNavAgent->Corridor.getPathCount() - 1;
for (int PolyIdx = 0; PolyIdx < PolysToTest; ++PolyIdx)
{
const auto PolyRef = pNavAgent->Corridor.getPath()[PolyIdx];
for (U8 ZoneIdx = 0; ZoneIdx < ZoneCount; ++ZoneIdx)
{
if (!((1 << ZoneIdx) & Action._AllowedZones)) continue;
if (IsNavPolyInInteractionZone(SO.GetInteractionZone(ZoneIdx), PolyRef, *pNavAgent->pNavQuery, NavAction._Destination))
{
Action._ZoneIndex = ZoneIdx;
Action._AllowedZones &= ~(1 << ZoneIdx);
return;
}
}
}
}
//---------------------------------------------------------------------
void InteractWithSmartObjects(CGameWorld& World)
{
World.ForEachEntityWith<CActionQueueComponent, const CSceneComponent, const AI::CNavAgentComponent*>(
[&World](auto EntityID, auto& Entity,
CActionQueueComponent& Queue,
const CSceneComponent& ActorSceneComponent,
const AI::CNavAgentComponent* pNavAgent)
{
if (!ActorSceneComponent.RootNode) return;
auto Action = Queue.FindCurrent<SwitchSmartObjectState>();
if (!Action) return;
const auto ActionStatus = Queue.GetStatus(Action);
if (ActionStatus != EActionStatus::Active) return;
const auto ChildAction = Queue.GetChild(Action);
const auto ChildActionStatus = Queue.GetStatus(ChildAction);
if (ChildActionStatus == EActionStatus::Cancelled)
{
Queue.SetStatus(Action, EActionStatus::Cancelled);
return;
}
auto pAction = Action.As<SwitchSmartObjectState>();
auto pSOComponent = World.FindComponent<CSmartObjectComponent>(pAction->_Object);
if (!pSOComponent || !pSOComponent->Asset)
{
Queue.SetStatus(Action, EActionStatus::Failed);
return;
}
const CSmartObject* pSOAsset = pSOComponent->Asset->GetObject<CSmartObject>();
if (!pSOAsset)
{
Queue.SetStatus(Action, EActionStatus::Failed);
return;
}
auto pSOSceneComponent = World.FindComponent<CSceneComponent>(pAction->_Object);
if (!pSOSceneComponent || !pSOSceneComponent->RootNode)
{
Queue.SetStatus(Action, EActionStatus::Failed);
return;
}
// Cache allowed zones once
if (!pAction->_AllowedZones)
{
const auto ZoneCount = pSOAsset->GetInteractionZoneCount();
for (U8 i = 0; i < ZoneCount; ++i)
{
const auto& Zone = pSOAsset->GetInteractionZone(i);
for (const auto& Interaction : Zone.Interactions)
{
if (Interaction.ID == pAction->_Interaction)
{
pAction->_AllowedZones |= (1 << i);
break;
}
}
}
if (!pAction->_AllowedZones)
{
Queue.SetStatus(Action, EActionStatus::Failed);
return;
}
}
const auto& ActorPos = ActorSceneComponent.RootNode->GetWorldPosition();
const auto& ObjectWorldTfm = pSOSceneComponent->RootNode->GetWorldMatrix();
// Move to the interaction point
if (auto pSteerAction = ChildAction.As<AI::Steer>())
{
if (ChildActionStatus == EActionStatus::Active)
{
if (pSOAsset->IsStatic()) return;
else if (UpdateMovementSubAction(Queue, Action, *pSOAsset, pNavAgent, ObjectWorldTfm, ActorPos, true)) return;
}
else if (ChildActionStatus == EActionStatus::Failed)
{
Queue.SetStatus(Action, EActionStatus::Failed);
return;
}
}
else if (auto pNavAction = ChildAction.As<AI::Navigate>())
{
if (ChildActionStatus == EActionStatus::Active)
{
if (pSOAsset->IsStatic())
{
OptimizeStaticPath(*pAction, *pNavAction, *pSOAsset, pNavAgent);
return;
}
else
{
// Update movement target from the current zone
if (UpdateMovementSubAction(Queue, Action, *pSOAsset, pNavAgent, ObjectWorldTfm, ActorPos, true)) return;
}
}
else if (ChildActionStatus == EActionStatus::Failed)
{
// Try another remaining zones with navigable points one by one, fail if none left
if (UpdateMovementSubAction(Queue, Action, *pSOAsset, pNavAgent, ObjectWorldTfm, ActorPos, false)) return;
}
}
else if (!pSOAsset->IsStatic() || !ChildAction)
{
// Move to the closest zone with navigable point inside, fail if none left
if (UpdateMovementSubAction(Queue, Action, *pSOAsset, pNavAgent, ObjectWorldTfm, ActorPos, false)) return;
}
// Face interaction direction
if (auto pTurnAction = ChildAction.As<AI::Turn>())
{
if (ChildActionStatus == EActionStatus::Active)
{
if (pSOAsset->IsStatic()) return;
// get facing from SO asset for the current region
// if facing is still required by SO, update it in Turn action and return
}
else if (ChildActionStatus == EActionStatus::Failed)
{
Queue.SetStatus(Action, EActionStatus::Failed);
return;
}
}
else
{
// get facing from SO asset for the current region
// if facing is required by SO and not already looking at that dir, generate Turn action and return
//!!!DBG TMP!
vector3 TargetDir = ObjectWorldTfm.Translation() - ActorPos;
TargetDir.norm();
//???update only if there is no Turn already active?
vector3 LookatDir = -ActorSceneComponent.RootNode->GetWorldMatrix().AxisZ();
LookatDir.norm();
const float Angle = vector3::Angle2DNorm(LookatDir, TargetDir);
if (std::fabsf(Angle) >= DEM::AI::Turn::AngularTolerance)
{
Queue.PushOrUpdateChild<AI::Turn>(Action, TargetDir);
return;
}
}
// Interact with object
pSOComponent->RequestedState = pAction->_State;
pSOComponent->Force = pAction->_Force;
// TODO: start actor animation and/or state switching, wait for its end before setting Succeeded status!
Queue.SetStatus(Action, EActionStatus::Succeeded);
});
}
//---------------------------------------------------------------------
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2012 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_OFFSET_CONVERTER_HPP
#define MAPNIK_OFFSET_CONVERTER_HPP
#ifdef MAPNIK_LOG
#include <mapnik/debug.hpp>
#endif
#include <mapnik/config.hpp>
#include <mapnik/box2d.hpp>
#include <mapnik/vertex.hpp>
#include <mapnik/proj_transform.hpp>
// boost
#include <boost/math/constants/constants.hpp>
// stl
#include <cmath>
namespace mapnik
{
const double pi = boost::math::constants::pi<double>();
template <typename Geometry>
struct MAPNIK_DECL offset_converter
{
using size_type = std::size_t;
offset_converter(Geometry & geom)
: geom_(geom)
, offset_(0.0)
, threshold_(8.0)
, half_turn_segments_(16)
, status_(initial)
, pre_first_(vertex2d::no_init)
, pre_(vertex2d::no_init)
, cur_(vertex2d::no_init)
{}
enum status
{
initial,
process
};
unsigned type() const
{
return static_cast<unsigned>(geom_.type());
}
double get_offset() const
{
return offset_;
}
double get_threshold() const
{
return threshold_;
}
void set_offset(double value)
{
if (offset_ != value)
{
offset_ = value;
reset();
}
}
void set_threshold(double value)
{
threshold_ = value;
// no need to reset(), since threshold doesn't affect
// offset vertices' computation, it only controls how
// far will we be looking for self-intersections
}
unsigned vertex(double * x, double * y)
{
if (offset_ == 0.0)
{
return geom_.vertex(x, y);
}
if (status_ == initial)
{
init_vertices();
}
if (pos_ >= vertices_.size())
{
return SEG_END;
}
pre_ = (pos_ ? cur_ : pre_first_);
cur_ = vertices_.at(pos_++);
if (pos_ == vertices_.size())
{
return output_vertex(x, y);
}
double const check_dist = offset_ * threshold_;
double const check_dist2 = check_dist * check_dist;
double t = 1.0;
double vt, ut;
for (size_t i = pos_; i+1 < vertices_.size(); ++i)
{
//break; // uncomment this to see all the curls
vertex2d const& u0 = vertices_[i];
vertex2d const& u1 = vertices_[i+1];
double const dx = u0.x - cur_.x;
double const dy = u0.y - cur_.y;
if (dx*dx + dy*dy > check_dist2)
{
break;
}
if (!intersection(pre_, cur_, &vt, u0, u1, &ut))
{
continue;
}
if (vt < 0.0 || vt > t || ut < 0.0 || ut > 1.0)
{
continue;
}
t = vt;
pos_ = i+1;
}
cur_.x = pre_.x + t * (cur_.x - pre_.x);
cur_.y = pre_.y + t * (cur_.y - pre_.y);
return output_vertex(x, y);
}
void reset()
{
geom_.rewind(0);
vertices_.clear();
status_ = initial;
pos_ = 0;
}
void rewind(unsigned)
{
pos_ = 0;
}
private:
static double explement_reflex_angle(double angle)
{
if (angle > pi)
{
return angle - 2 * pi;
}
else if (angle < -pi)
{
return angle + 2 * pi;
}
else
{
return angle;
}
}
static bool intersection(vertex2d const& u1, vertex2d const& u2, double* ut,
vertex2d const& v1, vertex2d const& v2, double* vt)
{
double const dx = v1.x - u1.x;
double const dy = v1.y - u1.y;
double const ux = u2.x - u1.x;
double const uy = u2.y - u1.y;
double const vx = v2.x - v1.x;
double const vy = v2.y - v1.y;
// the first line is not vertical
if (ux < -1e-6 || ux > 1e-6)
{
double const up = ux * dy - dx * uy;
double const dn = vx * uy - ux * vy;
if (dn > -1e-6 && dn < 1e-6)
{
return false; // they are parallel
}
*vt = up / dn;
*ut = (*vt * vx + dx) / ux;
return true;
}
// the first line is not horizontal
if (uy < -1e-6 || uy > 1e-6)
{
double const up = uy * dx - dy * ux;
double const dn = vy * ux - uy * vx;
if (dn > -1e-6 && dn < 1e-6)
{
return false; // they are parallel
}
*vt = up / dn;
*ut = (*vt * vy + dy) / uy;
return true;
}
// the first line is too short
return false;
}
/**
* @brief Translate (vx, vy) by rotated (dx, dy).
*/
static void displace(vertex2d & v, double dx, double dy, double a)
{
v.x += dx * std::cos(a) - dy * std::sin(a);
v.y += dx * std::sin(a) + dy * std::cos(a);
}
/**
* @brief Translate (vx, vy) by rotated (0, -offset).
*/
void displace(vertex2d & v, double a) const
{
v.x += offset_ * std::sin(a);
v.y -= offset_ * std::cos(a);
}
/**
* @brief (vx, vy) := (ux, uy) + rotated (0, -offset)
*/
void displace(vertex2d & v, vertex2d const& u, double a) const
{
v.x = u.x + offset_ * std::sin(a);
v.y = u.y - offset_ * std::cos(a);
v.cmd = u.cmd;
}
void displace2(vertex2d & v, double a, double b) const
{
double sa = offset_ * std::sin(a);
double ca = offset_ * std::cos(a);
double h = std::tan(0.5 * (b - a));
v.x = v.x + sa + h * ca;
v.y = v.y - ca + h * sa;
}
status init_vertices()
{
if (status_ != initial) // already initialized
{
return status_;
}
vertex2d v1(vertex2d::no_init);
vertex2d v2(vertex2d::no_init);
vertex2d w(vertex2d::no_init);
v1.cmd = geom_.vertex(&v1.x, &v1.y);
v2.cmd = geom_.vertex(&v2.x, &v2.y);
if (v2.cmd == SEG_END) // not enough vertices in source
{
return status_ = process;
}
double angle_a = 0;
double angle_b = std::atan2((v2.y - v1.y), (v2.x - v1.x));
double joint_angle;
// first vertex
displace(v1, angle_b);
push_vertex(v1);
// Sometimes when the first segment is too short, it causes ugly
// curls at the beginning of the line. To avoid this, we make up
// a fake vertex two offset-lengths before the first, and expect
// intersection detection smoothes it out.
pre_first_ = v1;
displace(pre_first_, -2 * std::fabs(offset_), 0, angle_b);
while ((v1 = v2, v2.cmd = geom_.vertex(&v2.x, &v2.y)) != SEG_END)
{
angle_a = angle_b;
angle_b = std::atan2((v2.y - v1.y), (v2.x - v1.x));
joint_angle = explement_reflex_angle(angle_b - angle_a);
double half_turns = half_turn_segments_ * std::fabs(joint_angle);
int bulge_steps = 0;
if (offset_ < 0.0)
{
if (joint_angle > 0.0)
{
joint_angle = joint_angle - 2 * pi;
}
else
{
bulge_steps = 1 + static_cast<int>(std::floor(half_turns / pi));
}
}
else
{
if (joint_angle < 0.0)
{
joint_angle = joint_angle + 2 * pi;
}
else
{
bulge_steps = 1 + static_cast<int>(std::floor(half_turns / pi));
}
}
#ifdef MAPNIK_LOG
if (bulge_steps == 0)
{
// inside turn (sharp/obtuse angle)
MAPNIK_LOG_DEBUG(ctrans) << "offset_converter:"
<< " Sharp joint [<< inside turn " << int(joint_angle*180/pi)
<< " degrees >>]";
}
else
{
// outside turn (reflex angle)
MAPNIK_LOG_DEBUG(ctrans) << "offset_converter:"
<< " Bulge joint >)) outside turn " << int(joint_angle*180/pi)
<< " degrees ((< with " << bulge_steps << " segments";
}
#endif
displace(w, v1, angle_a);
push_vertex(w);
for (int s = 0; ++s < bulge_steps;)
{
displace(w, v1, angle_a + (joint_angle * s) / bulge_steps);
push_vertex(w);
}
displace(v1, angle_b);
push_vertex(v1);
}
// last vertex
displace(v1, angle_b);
push_vertex(v1);
// initialization finished
return status_ = process;
}
unsigned output_vertex(double* px, double* py)
{
*px = cur_.x;
*py = cur_.y;
return cur_.cmd;
}
unsigned output_vertex(double* px, double* py, status st)
{
status_ = st;
return output_vertex(px, py);
}
void push_vertex(vertex2d const& v)
{
vertices_.push_back(v);
}
Geometry & geom_;
double offset_;
double threshold_;
unsigned half_turn_segments_;
status status_;
size_t pos_;
std::vector<vertex2d> vertices_;
vertex2d pre_first_;
vertex2d pre_;
vertex2d cur_;
};
}
#endif // MAPNIK_OFFSET_CONVERTER_HPP
<commit_msg>speed up compile / avoid boost/math - refs #2439<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2012 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_OFFSET_CONVERTER_HPP
#define MAPNIK_OFFSET_CONVERTER_HPP
#ifdef MAPNIK_LOG
#include <mapnik/debug.hpp>
#endif
#include <mapnik/global.hpp>
#include <mapnik/config.hpp>
#include <mapnik/vertex.hpp>
// stl
#include <cmath>
#include <vector>
#include <cstddef>
namespace mapnik
{
template <typename Geometry>
struct MAPNIK_DECL offset_converter
{
using size_type = std::size_t;
offset_converter(Geometry & geom)
: geom_(geom)
, offset_(0.0)
, threshold_(8.0)
, half_turn_segments_(16)
, status_(initial)
, pre_first_(vertex2d::no_init)
, pre_(vertex2d::no_init)
, cur_(vertex2d::no_init)
{}
enum status
{
initial,
process
};
unsigned type() const
{
return static_cast<unsigned>(geom_.type());
}
double get_offset() const
{
return offset_;
}
double get_threshold() const
{
return threshold_;
}
void set_offset(double value)
{
if (offset_ != value)
{
offset_ = value;
reset();
}
}
void set_threshold(double value)
{
threshold_ = value;
// no need to reset(), since threshold doesn't affect
// offset vertices' computation, it only controls how
// far will we be looking for self-intersections
}
unsigned vertex(double * x, double * y)
{
if (offset_ == 0.0)
{
return geom_.vertex(x, y);
}
if (status_ == initial)
{
init_vertices();
}
if (pos_ >= vertices_.size())
{
return SEG_END;
}
pre_ = (pos_ ? cur_ : pre_first_);
cur_ = vertices_.at(pos_++);
if (pos_ == vertices_.size())
{
return output_vertex(x, y);
}
double const check_dist = offset_ * threshold_;
double const check_dist2 = check_dist * check_dist;
double t = 1.0;
double vt, ut;
for (size_t i = pos_; i+1 < vertices_.size(); ++i)
{
//break; // uncomment this to see all the curls
vertex2d const& u0 = vertices_[i];
vertex2d const& u1 = vertices_[i+1];
double const dx = u0.x - cur_.x;
double const dy = u0.y - cur_.y;
if (dx*dx + dy*dy > check_dist2)
{
break;
}
if (!intersection(pre_, cur_, &vt, u0, u1, &ut))
{
continue;
}
if (vt < 0.0 || vt > t || ut < 0.0 || ut > 1.0)
{
continue;
}
t = vt;
pos_ = i+1;
}
cur_.x = pre_.x + t * (cur_.x - pre_.x);
cur_.y = pre_.y + t * (cur_.y - pre_.y);
return output_vertex(x, y);
}
void reset()
{
geom_.rewind(0);
vertices_.clear();
status_ = initial;
pos_ = 0;
}
void rewind(unsigned)
{
pos_ = 0;
}
private:
static double explement_reflex_angle(double angle)
{
if (angle > M_PI)
{
return angle - 2 * M_PI;
}
else if (angle < -M_PI)
{
return angle + 2 * M_PI;
}
else
{
return angle;
}
}
static bool intersection(vertex2d const& u1, vertex2d const& u2, double* ut,
vertex2d const& v1, vertex2d const& v2, double* vt)
{
double const dx = v1.x - u1.x;
double const dy = v1.y - u1.y;
double const ux = u2.x - u1.x;
double const uy = u2.y - u1.y;
double const vx = v2.x - v1.x;
double const vy = v2.y - v1.y;
// the first line is not vertical
if (ux < -1e-6 || ux > 1e-6)
{
double const up = ux * dy - dx * uy;
double const dn = vx * uy - ux * vy;
if (dn > -1e-6 && dn < 1e-6)
{
return false; // they are parallel
}
*vt = up / dn;
*ut = (*vt * vx + dx) / ux;
return true;
}
// the first line is not horizontal
if (uy < -1e-6 || uy > 1e-6)
{
double const up = uy * dx - dy * ux;
double const dn = vy * ux - uy * vx;
if (dn > -1e-6 && dn < 1e-6)
{
return false; // they are parallel
}
*vt = up / dn;
*ut = (*vt * vy + dy) / uy;
return true;
}
// the first line is too short
return false;
}
/**
* @brief Translate (vx, vy) by rotated (dx, dy).
*/
static void displace(vertex2d & v, double dx, double dy, double a)
{
v.x += dx * std::cos(a) - dy * std::sin(a);
v.y += dx * std::sin(a) + dy * std::cos(a);
}
/**
* @brief Translate (vx, vy) by rotated (0, -offset).
*/
void displace(vertex2d & v, double a) const
{
v.x += offset_ * std::sin(a);
v.y -= offset_ * std::cos(a);
}
/**
* @brief (vx, vy) := (ux, uy) + rotated (0, -offset)
*/
void displace(vertex2d & v, vertex2d const& u, double a) const
{
v.x = u.x + offset_ * std::sin(a);
v.y = u.y - offset_ * std::cos(a);
v.cmd = u.cmd;
}
void displace2(vertex2d & v, double a, double b) const
{
double sa = offset_ * std::sin(a);
double ca = offset_ * std::cos(a);
double h = std::tan(0.5 * (b - a));
v.x = v.x + sa + h * ca;
v.y = v.y - ca + h * sa;
}
status init_vertices()
{
if (status_ != initial) // already initialized
{
return status_;
}
vertex2d v1(vertex2d::no_init);
vertex2d v2(vertex2d::no_init);
vertex2d w(vertex2d::no_init);
v1.cmd = geom_.vertex(&v1.x, &v1.y);
v2.cmd = geom_.vertex(&v2.x, &v2.y);
if (v2.cmd == SEG_END) // not enough vertices in source
{
return status_ = process;
}
double angle_a = 0;
double angle_b = std::atan2((v2.y - v1.y), (v2.x - v1.x));
double joint_angle;
// first vertex
displace(v1, angle_b);
push_vertex(v1);
// Sometimes when the first segment is too short, it causes ugly
// curls at the beginning of the line. To avoid this, we make up
// a fake vertex two offset-lengths before the first, and expect
// intersection detection smoothes it out.
pre_first_ = v1;
displace(pre_first_, -2 * std::fabs(offset_), 0, angle_b);
while ((v1 = v2, v2.cmd = geom_.vertex(&v2.x, &v2.y)) != SEG_END)
{
angle_a = angle_b;
angle_b = std::atan2((v2.y - v1.y), (v2.x - v1.x));
joint_angle = explement_reflex_angle(angle_b - angle_a);
double half_turns = half_turn_segments_ * std::fabs(joint_angle);
int bulge_steps = 0;
if (offset_ < 0.0)
{
if (joint_angle > 0.0)
{
joint_angle = joint_angle - 2 * M_PI;
}
else
{
bulge_steps = 1 + static_cast<int>(std::floor(half_turns / M_PI));
}
}
else
{
if (joint_angle < 0.0)
{
joint_angle = joint_angle + 2 * M_PI;
}
else
{
bulge_steps = 1 + static_cast<int>(std::floor(half_turns / M_PI));
}
}
#ifdef MAPNIK_LOG
if (bulge_steps == 0)
{
// inside turn (sharp/obtuse angle)
MAPNIK_LOG_DEBUG(ctrans) << "offset_converter:"
<< " Sharp joint [<< inside turn " << int(joint_angle*180/M_PI)
<< " degrees >>]";
}
else
{
// outside turn (reflex angle)
MAPNIK_LOG_DEBUG(ctrans) << "offset_converter:"
<< " Bulge joint >)) outside turn " << int(joint_angle*180/M_PI)
<< " degrees ((< with " << bulge_steps << " segments";
}
#endif
displace(w, v1, angle_a);
push_vertex(w);
for (int s = 0; ++s < bulge_steps;)
{
displace(w, v1, angle_a + (joint_angle * s) / bulge_steps);
push_vertex(w);
}
displace(v1, angle_b);
push_vertex(v1);
}
// last vertex
displace(v1, angle_b);
push_vertex(v1);
// initialization finished
return status_ = process;
}
unsigned output_vertex(double* px, double* py)
{
*px = cur_.x;
*py = cur_.y;
return cur_.cmd;
}
unsigned output_vertex(double* px, double* py, status st)
{
status_ = st;
return output_vertex(px, py);
}
void push_vertex(vertex2d const& v)
{
vertices_.push_back(v);
}
Geometry & geom_;
double offset_;
double threshold_;
unsigned half_turn_segments_;
status status_;
size_t pos_;
std::vector<vertex2d> vertices_;
vertex2d pre_first_;
vertex2d pre_;
vertex2d cur_;
};
}
#endif // MAPNIK_OFFSET_CONVERTER_HPP
<|endoftext|> |
<commit_before>#include "DataLikelihood.h"
#include "multichoose.h"
#include "multipermute.h"
// log probability of a given matching of true and observed alleles
// true alleles are the 'real' alleles
// observed alleles are whet we observe
// a mismatch between these two sets implies an error, which is scored accordingly here
long double likelihoodGivenTrueAlleles(vector<Allele*>& observedAlleles, vector<Allele*>& trueAlleles) {
long double prob = 0;
vector<Allele*>::iterator o = observedAlleles.begin();
vector<Allele*>::iterator t = trueAlleles.begin();
for ( ; o != observedAlleles.end() && t != trueAlleles.end(); ++o, ++t)
{
Allele& observedAllele = **o;
Allele& trueAllele = **t;
if (observedAllele == trueAllele) {
prob += log(1 - exp(observedAllele.lnquality));
} else {
prob += observedAllele.lnquality;
}
}
return prob;
}
/*
'Exact' data likelihood, sum of sampling probability * joint Q score for the
observed alleles over all possible underlying 'true allele' combinations."""
*/
long double
probObservedAllelesGivenGenotype(
vector<Allele*>& observedAlleles,
Genotype& genotype) {
//cout << endl << endl << "genotype: " << genotype << endl;
int observationCount = observedAlleles.size();
vector<long double> alleleProbs = genotype.alleleProbabilities();
vector<long double> probs;
vector<Allele> uniqueAlleles = genotype.uniqueAlleles();
vector<vector<Allele*> > combos = multichoose_ptr(observationCount, uniqueAlleles);
for (vector<vector<Allele*> >::iterator combo = combos.begin(); combo != combos.end(); ++combo) {
//cout << endl << "combo: " << *combo << endl;
vector<vector<Allele*> > trueAllelePermutations = multipermute(*combo);
for (vector<vector<Allele*> >::iterator perm = trueAllelePermutations.begin(); perm != trueAllelePermutations.end(); ++perm) {
vector<Allele*>& trueAlleles = *perm;
//cout << "permu: " << *perm << endl;
map<string, int> trueAlleleCounts = countAllelesString(trueAlleles);
long double lnTrueAllelePermutationsCount = log(trueAllelePermutations.size());
vector<int> observationCounts; // counts of 'observations' of true alleles, ordered according to the genotype's internal ordering
for (Genotype::const_iterator g = genotype.begin(); g != genotype.end(); ++g) {
map<string, int>::const_iterator count = trueAlleleCounts.find(g->first.currentBase);
if (count != trueAlleleCounts.end()) {
observationCounts.push_back(count->second);
} else {
observationCounts.push_back(0);
}
}
//cout << "multinomial: " << exp(multinomialln(alleleProbs, observationCounts)) << endl;
//cout << "likelihood: " << exp(likelihoodGivenTrueAlleles(observedAlleles, trueAlleles)) << endl;
probs.push_back(multinomialln(alleleProbs, observationCounts)
+ likelihoodGivenTrueAlleles(observedAlleles, trueAlleles)
- lnTrueAllelePermutationsCount);
}
}
//cout << "l = " << logsumexp(probs) << endl;
return logsumexp(probs);
}
/*
long double
badApproxProbObservedAllelesGivenGenotype(
vector<Allele*>& observedAlleles,
Genotype& genotype
) {
int observationCount = observedAlleles.size();
vector<long double> alleleProbs = genotype.alleleProbabilities();
vector<int> observationCounts = genotype.alleleCountsInObservations(observedAlleles);
long double probInAllWrong = 0; //
long double probOutAreAllErrors = 0; //
for (vector<Allele*>::iterator obs = observedAlleles.begin(); obs != observedAlleles.end(); ++obs) {
Allele& observation = **obs;
if (genotype.containsAllele(observation)) {
probInAllWrong += observation.lnquality;
} else {
probOutAreAllErrors += observation.lnquality;
}
}
if (sum(observationCounts) == 0) {
return probOutAreAllErrors;
} else {
long double someInCorrect = log(1 - exp(probInAllWrong));
return someInCorrect + (probOutAreAllErrors != 0 ? log(1 - exp(probOutAreAllErrors)) : 0) + log(dirichletMaximumLikelihoodRatio(alleleProbs, observationCounts));
}
}
*/
// p(out are wrong) * p(in are correct) * (multinomial(in | genotype))
// sum(Q) * sum(1 - Q) * ...
long double
approxProbObservedAllelesGivenGenotype(
vector<Allele*>& observedAlleles,
Genotype& genotype
) {
int observationCount = observedAlleles.size();
vector<long double> alleleProbs = genotype.alleleProbabilities();
vector<int> observationCounts = genotype.alleleCountsInObservations(observedAlleles);
long double probInAllCorrect = 0; //
long double probOutAllWrong = 0; //
for (vector<Allele*>::iterator obs = observedAlleles.begin(); obs != observedAlleles.end(); ++obs) {
Allele& observation = **obs;
if (genotype.containsAllele(observation)) {
probInAllCorrect += log(1 - exp(observation.lnquality));
} else {
probOutAllWrong += observation.lnquality;
}
}
if (sum(observationCounts) == 0) {
return probOutAllWrong;
} else {
return probInAllCorrect + probOutAllWrong + multinomialln(alleleProbs, observationCounts);
}
}
long double
bamBayesApproxProbObservedAllelesGivenGenotype(
vector<Allele*>& observedAlleles,
Genotype& genotype,
long double dependenceFactor
) {
int observationCount = observedAlleles.size();
long double sumQout = 0;
int countOut = 0;
for (vector<Allele*>::iterator obs = observedAlleles.begin(); obs != observedAlleles.end(); ++obs) {
Allele& observation = **obs;
if (!genotype.containsAllele(observation)) {
sumQout += observation.lnquality;
++countOut;
}
}
if (countOut > 1) {
sumQout *= (1 + (countOut - 1) * dependenceFactor) / countOut;
//cerr << "dependencefactor," << observedAlleles.front()->sampleID << "," << IUPAC2GenotypeStr(IUPAC(genotype)) << "," << (1 + (countOut - 1) * dependenceFactor) / countOut << endl;
}
long double lnprob = sumQout - countOut * log(3);
if (!genotype.homozygous()) {
long double lnBinomialfactor = observationCount * log(0.5);
//cerr << "lnprob," << observedAlleles.front()->sampleID << "," << IUPAC2GenotypeStr(IUPAC(genotype)) << "," << lnprob + lnBinomialfactor << endl;
return lnprob + lnBinomialfactor;
} else {
//cerr << "lnprob," << observedAlleles.front()->sampleID << "," << IUPAC2GenotypeStr(IUPAC(genotype)) << "," << lnprob << endl;
return lnprob;
}
}
vector<pair<Genotype*, long double> >
exactProbObservedAllelesGivenGenotypes(
vector<Allele*>& observedAlleles,
vector<Genotype>& genotypes) {
vector<pair<Genotype*, long double> > results;
for (vector<Genotype>::iterator g = genotypes.begin(); g != genotypes.end(); ++g) {
results.push_back(make_pair(&*g, probObservedAllelesGivenGenotype(observedAlleles, *g)));
}
return results;
}
vector<pair<Genotype*, long double> >
approxProbObservedAllelesGivenGenotypes(
vector<Allele*>& observedAlleles,
vector<Genotype>& genotypes) {
vector<pair<Genotype*, long double> > results;
for (vector<Genotype>::iterator g = genotypes.begin(); g != genotypes.end(); ++g) {
results.push_back(make_pair(&*g, approxProbObservedAllelesGivenGenotype(observedAlleles, *g)));
}
return results;
}
// uses caching to reduce computation while generating the exact correct result
vector<pair<Genotype*, long double> >
probObservedAllelesGivenGenotypes(
vector<Allele*>& observedAlleles,
vector<Genotype>& genotypes) {
vector<pair<Genotype*, long double> > results;
// cache the results on the basis of number of alleles in the genotype as a fraction of the genotype
map<pair<int, int>, long double> cachedProbsGivenAllelesInGenotype;
bool allSame = (countAlleles(observedAlleles).size() == 1);
for (vector<Genotype>::iterator g = genotypes.begin(); g != genotypes.end(); ++g) {
long double prob;
Genotype& genotype = *g;
if (allSame) {
pair<int, int> alleleRatio = make_pair(0, genotype.uniqueAlleles().size());
//alleleRatio(observedAlleles, genotype);
for (Genotype::iterator a = genotype.begin(); a != genotype.end(); ++a) {
if (a->first == *(observedAlleles.front()))
alleleRatio.first += 1;
}
map<pair<int, int>, long double>::iterator c = cachedProbsGivenAllelesInGenotype.find(alleleRatio);
if (c != cachedProbsGivenAllelesInGenotype.end()) {
prob = c->second;
} else {
prob = approxProbObservedAllelesGivenGenotype(observedAlleles, genotype);
cachedProbsGivenAllelesInGenotype[alleleRatio] = prob;
}
results.push_back(make_pair(&genotype, prob));
} else {
results.push_back(make_pair(&genotype, approxProbObservedAllelesGivenGenotype(observedAlleles, genotype)));
}
}
return results;
}
// bambayes style data likelihoods
vector<pair<Genotype*, long double> >
bamBayesProbObservedAllelesGivenGenotypes(
vector<Allele*>& observedAlleles,
vector<Genotype>& genotypes,
long double dependenceFactor) {
vector<pair<Genotype*, long double> > results;
// cache the results on the basis of number of alleles in the genotype as a fraction of the genotype
map<pair<int, int>, long double> cachedProbsGivenAllelesInGenotype;
bool allSame = (countAlleles(observedAlleles).size() == 1);
for (vector<Genotype>::iterator g = genotypes.begin(); g != genotypes.end(); ++g) {
long double prob;
Genotype& genotype = *g;
if (allSame) {
pair<int, int> alleleRatio = make_pair(0, genotype.uniqueAlleles().size());
//alleleRatio(observedAlleles, genotype);
for (Genotype::iterator a = genotype.begin(); a != genotype.end(); ++a) {
if (a->first == *(observedAlleles.front()))
alleleRatio.first += 1;
}
map<pair<int, int>, long double>::iterator c = cachedProbsGivenAllelesInGenotype.find(alleleRatio);
if (c != cachedProbsGivenAllelesInGenotype.end()) {
prob = c->second;
} else {
prob = bamBayesApproxProbObservedAllelesGivenGenotype(observedAlleles, genotype, dependenceFactor);
cachedProbsGivenAllelesInGenotype[alleleRatio] = prob;
}
results.push_back(make_pair(&genotype, prob));
} else {
results.push_back(make_pair(&genotype, bamBayesApproxProbObservedAllelesGivenGenotype(observedAlleles, genotype, dependenceFactor)));
}
}
return results;
}
<commit_msg>changed default data likelihood calculations<commit_after>#include "DataLikelihood.h"
#include "multichoose.h"
#include "multipermute.h"
// log probability of a given matching of true and observed alleles
// true alleles are the 'real' alleles
// observed alleles are whet we observe
// a mismatch between these two sets implies an error, which is scored accordingly here
long double likelihoodGivenTrueAlleles(vector<Allele*>& observedAlleles, vector<Allele*>& trueAlleles) {
long double prob = 0;
vector<Allele*>::iterator o = observedAlleles.begin();
vector<Allele*>::iterator t = trueAlleles.begin();
for ( ; o != observedAlleles.end() && t != trueAlleles.end(); ++o, ++t)
{
Allele& observedAllele = **o;
Allele& trueAllele = **t;
if (observedAllele == trueAllele) {
prob += log(1 - exp(observedAllele.lnquality));
} else {
prob += observedAllele.lnquality;
}
}
return prob;
}
/*
'Exact' data likelihood, sum of sampling probability * joint Q score for the
observed alleles over all possible underlying 'true allele' combinations."""
*/
long double
probObservedAllelesGivenGenotype(
vector<Allele*>& observedAlleles,
Genotype& genotype) {
//cout << endl << endl << "genotype: " << genotype << endl;
int observationCount = observedAlleles.size();
vector<long double> alleleProbs = genotype.alleleProbabilities();
vector<long double> probs;
vector<Allele> uniqueAlleles = genotype.uniqueAlleles();
vector<vector<Allele*> > combos = multichoose_ptr(observationCount, uniqueAlleles);
for (vector<vector<Allele*> >::iterator combo = combos.begin(); combo != combos.end(); ++combo) {
//cout << endl << "combo: " << *combo << endl;
vector<vector<Allele*> > trueAllelePermutations = multipermute(*combo);
for (vector<vector<Allele*> >::iterator perm = trueAllelePermutations.begin(); perm != trueAllelePermutations.end(); ++perm) {
vector<Allele*>& trueAlleles = *perm;
//cout << "permu: " << *perm << endl;
map<string, int> trueAlleleCounts = countAllelesString(trueAlleles);
long double lnTrueAllelePermutationsCount = log(trueAllelePermutations.size());
vector<int> observationCounts; // counts of 'observations' of true alleles, ordered according to the genotype's internal ordering
for (Genotype::const_iterator g = genotype.begin(); g != genotype.end(); ++g) {
map<string, int>::const_iterator count = trueAlleleCounts.find(g->first.currentBase);
if (count != trueAlleleCounts.end()) {
observationCounts.push_back(count->second);
} else {
observationCounts.push_back(0);
}
}
//cout << "multinomial: " << exp(multinomialln(alleleProbs, observationCounts)) << endl;
//cout << "likelihood: " << exp(likelihoodGivenTrueAlleles(observedAlleles, trueAlleles)) << endl;
probs.push_back(multinomialln(alleleProbs, observationCounts)
+ likelihoodGivenTrueAlleles(observedAlleles, trueAlleles)
- lnTrueAllelePermutationsCount);
}
}
//cout << "l = " << logsumexp(probs) << endl;
return logsumexp(probs);
}
// p(out are wrong) * p(in are correct) * (multinomial(in | genotype))
// sum(Q) * sum(1 - Q) * ...
/*
long double
approxProbObservedAllelesGivenGenotype(
vector<Allele*>& observedAlleles,
Genotype& genotype
) {
int observationCount = observedAlleles.size();
vector<long double> alleleProbs = genotype.alleleProbabilities();
vector<int> observationCounts = genotype.alleleCountsInObservations(observedAlleles);
long double probInAllCorrect = 0; //
long double probOutAllWrong = 0; //
for (vector<Allele*>::iterator obs = observedAlleles.begin(); obs != observedAlleles.end(); ++obs) {
Allele& observation = **obs;
if (genotype.containsAllele(observation)) {
probInAllCorrect += log(1 - exp(observation.lnquality));
} else {
probOutAllWrong += observation.lnquality;
}
}
if (sum(observationCounts) == 0) {
return probOutAllWrong;
} else {
return probInAllCorrect + probOutAllWrong + multinomialln(alleleProbs, observationCounts);
}
}
*/
long double
approxProbObservedAllelesGivenGenotype(
vector<Allele*>& observedAlleles,
Genotype& genotype
) {
int observationCount = observedAlleles.size();
vector<long double> alleleProbs = genotype.alleleProbabilities();
vector<int> observationCounts = genotype.alleleCountsInObservations(observedAlleles);
long double probInAllCorrect = 0; //
long double probOutAllWrong = 0; //
for (vector<Allele*>::iterator obs = observedAlleles.begin(); obs != observedAlleles.end(); ++obs) {
Allele& observation = **obs;
if (!genotype.containsAllele(observation)) {
probOutAllWrong += observation.lnquality;
}
}
if (sum(observationCounts) == 0) {
return probOutAllWrong;
} else {
return probOutAllWrong + multinomialln(alleleProbs, observationCounts);
}
}
long double
bamBayesApproxProbObservedAllelesGivenGenotype(
vector<Allele*>& observedAlleles,
Genotype& genotype,
long double dependenceFactor
) {
int observationCount = observedAlleles.size();
long double sumQout = 0;
int countOut = 0;
for (vector<Allele*>::iterator obs = observedAlleles.begin(); obs != observedAlleles.end(); ++obs) {
Allele& observation = **obs;
if (!genotype.containsAllele(observation)) {
sumQout += observation.lnquality;
++countOut;
}
}
if (countOut > 1) {
sumQout *= (1 + (countOut - 1) * dependenceFactor) / countOut;
//cerr << "dependencefactor," << observedAlleles.front()->sampleID << "," << IUPAC2GenotypeStr(IUPAC(genotype)) << "," << (1 + (countOut - 1) * dependenceFactor) / countOut << endl;
}
long double lnprob = sumQout - countOut * log(3);
if (!genotype.homozygous()) {
long double lnBinomialfactor = observationCount * log(0.5);
//cerr << "lnprob," << observedAlleles.front()->sampleID << "," << IUPAC2GenotypeStr(IUPAC(genotype)) << "," << lnprob + lnBinomialfactor << endl;
return lnprob + lnBinomialfactor;
} else {
//cerr << "lnprob," << observedAlleles.front()->sampleID << "," << IUPAC2GenotypeStr(IUPAC(genotype)) << "," << lnprob << endl;
return lnprob;
}
}
vector<pair<Genotype*, long double> >
exactProbObservedAllelesGivenGenotypes(
vector<Allele*>& observedAlleles,
vector<Genotype>& genotypes) {
vector<pair<Genotype*, long double> > results;
for (vector<Genotype>::iterator g = genotypes.begin(); g != genotypes.end(); ++g) {
results.push_back(make_pair(&*g, probObservedAllelesGivenGenotype(observedAlleles, *g)));
}
return results;
}
vector<pair<Genotype*, long double> >
approxProbObservedAllelesGivenGenotypes(
vector<Allele*>& observedAlleles,
vector<Genotype>& genotypes) {
vector<pair<Genotype*, long double> > results;
for (vector<Genotype>::iterator g = genotypes.begin(); g != genotypes.end(); ++g) {
results.push_back(make_pair(&*g, approxProbObservedAllelesGivenGenotype(observedAlleles, *g)));
}
return results;
}
// uses caching to reduce computation while generating the exact correct result
vector<pair<Genotype*, long double> >
probObservedAllelesGivenGenotypes(
vector<Allele*>& observedAlleles,
vector<Genotype>& genotypes) {
vector<pair<Genotype*, long double> > results;
// cache the results on the basis of number of alleles in the genotype as a fraction of the genotype
map<pair<int, int>, long double> cachedProbsGivenAllelesInGenotype;
bool allSame = (countAlleles(observedAlleles).size() == 1);
for (vector<Genotype>::iterator g = genotypes.begin(); g != genotypes.end(); ++g) {
long double prob;
Genotype& genotype = *g;
if (allSame) {
pair<int, int> alleleRatio = make_pair(0, genotype.uniqueAlleles().size());
//alleleRatio(observedAlleles, genotype);
for (Genotype::iterator a = genotype.begin(); a != genotype.end(); ++a) {
if (a->first == *(observedAlleles.front()))
alleleRatio.first += 1;
}
map<pair<int, int>, long double>::iterator c = cachedProbsGivenAllelesInGenotype.find(alleleRatio);
if (c != cachedProbsGivenAllelesInGenotype.end()) {
prob = c->second;
} else {
prob = approxProbObservedAllelesGivenGenotype(observedAlleles, genotype);
cachedProbsGivenAllelesInGenotype[alleleRatio] = prob;
}
results.push_back(make_pair(&genotype, prob));
} else {
results.push_back(make_pair(&genotype, approxProbObservedAllelesGivenGenotype(observedAlleles, genotype)));
}
}
return results;
}
// bambayes style data likelihoods
vector<pair<Genotype*, long double> >
bamBayesProbObservedAllelesGivenGenotypes(
vector<Allele*>& observedAlleles,
vector<Genotype>& genotypes,
long double dependenceFactor) {
vector<pair<Genotype*, long double> > results;
// cache the results on the basis of number of alleles in the genotype as a fraction of the genotype
map<pair<int, int>, long double> cachedProbsGivenAllelesInGenotype;
bool allSame = (countAlleles(observedAlleles).size() == 1);
for (vector<Genotype>::iterator g = genotypes.begin(); g != genotypes.end(); ++g) {
long double prob;
Genotype& genotype = *g;
if (allSame) {
pair<int, int> alleleRatio = make_pair(0, genotype.uniqueAlleles().size());
//alleleRatio(observedAlleles, genotype);
for (Genotype::iterator a = genotype.begin(); a != genotype.end(); ++a) {
if (a->first == *(observedAlleles.front()))
alleleRatio.first += 1;
}
map<pair<int, int>, long double>::iterator c = cachedProbsGivenAllelesInGenotype.find(alleleRatio);
if (c != cachedProbsGivenAllelesInGenotype.end()) {
prob = c->second;
} else {
prob = bamBayesApproxProbObservedAllelesGivenGenotype(observedAlleles, genotype, dependenceFactor);
cachedProbsGivenAllelesInGenotype[alleleRatio] = prob;
}
results.push_back(make_pair(&genotype, prob));
} else {
results.push_back(make_pair(&genotype, bamBayesApproxProbObservedAllelesGivenGenotype(observedAlleles, genotype, dependenceFactor)));
}
}
return results;
}
<|endoftext|> |
<commit_before>#include "codeConverterBase.h"
#include <qrkernel/settingsManager.h>
using namespace generatorBase::converters;
using namespace qReal;
CodeConverterBase::CodeConverterBase(QString const &pathToTemplates
, interpreterBase::robotModel::RobotModelInterface const &robotModel
, QMap<interpreterBase::robotModel::PortInfo, interpreterBase::robotModel::DeviceInfo> const &devices
, simple::Binding::ConverterInterface const *inputPortConverter
, simple::Binding::ConverterInterface const *functionInvocationsConverter)
: TemplateParametrizedConverter(pathToTemplates)
, mRobotModel(robotModel)
, mDevices(devices)
, mInputConverter(inputPortConverter)
, mFunctionInvocationsConverter(functionInvocationsConverter)
{
}
CodeConverterBase::~CodeConverterBase()
{
delete mInputConverter;
delete mFunctionInvocationsConverter;
}
QString CodeConverterBase::convert(QString const &data) const
{
return replaceFunctionInvocations(replaceSystemVariables(data)).trimmed();
}
QString CodeConverterBase::replaceSystemVariables(QString const &expression) const
{
QString result = expression;
for (interpreterBase::robotModel::PortInfo const &port : mRobotModel.availablePorts()) {
QString const variable = port.reservedVariable();
if (!variable.isEmpty()) {
result.replace(variable, deviceExpression(port));
}
}
result.replace("Time", timelineExpression());
return result;
}
QString CodeConverterBase::replaceFunctionInvocations(QString const &expression) const
{
QString result = expression;
QString const randomTemplate = mFunctionInvocationsConverter->convert("random");
QRegExp const randomFunctionInvocationRegEx("random\\((.*)\\)");
int pos = randomFunctionInvocationRegEx.indexIn(result, 0);
while (pos != -1) {
QString const param = randomFunctionInvocationRegEx.cap(1);
QString randomInvocation = randomTemplate;
randomInvocation.replace("@@UPPER_BOUND@@", param);
result.replace(randomFunctionInvocationRegEx, randomInvocation);
pos += randomFunctionInvocationRegEx.matchedLength();
pos = randomFunctionInvocationRegEx.indexIn(result, pos);
}
return result;
}
QString CodeConverterBase::deviceExpression(interpreterBase::robotModel::PortInfo const &port) const
{
if (mDevices[port].isNull()) {
return QString();
}
QString const templatePath = QString("sensors/%1.t").arg(mDevices[port].name());
// Converter must take a string like "1" or "2" (and etc) and return correct value
return readTemplate(templatePath).replace("@@PORT@@", mInputConverter->convert(port.name()));
}
QString CodeConverterBase::timelineExpression() const
{
/// @todo: generate timestamps code in nxt c when required
return readTemplate("whatTime.t");
}
<commit_msg>Fixed timer variable generation<commit_after>#include "codeConverterBase.h"
#include <qrkernel/settingsManager.h>
using namespace generatorBase::converters;
using namespace qReal;
CodeConverterBase::CodeConverterBase(QString const &pathToTemplates
, interpreterBase::robotModel::RobotModelInterface const &robotModel
, QMap<interpreterBase::robotModel::PortInfo, interpreterBase::robotModel::DeviceInfo> const &devices
, simple::Binding::ConverterInterface const *inputPortConverter
, simple::Binding::ConverterInterface const *functionInvocationsConverter)
: TemplateParametrizedConverter(pathToTemplates)
, mRobotModel(robotModel)
, mDevices(devices)
, mInputConverter(inputPortConverter)
, mFunctionInvocationsConverter(functionInvocationsConverter)
{
}
CodeConverterBase::~CodeConverterBase()
{
delete mInputConverter;
delete mFunctionInvocationsConverter;
}
QString CodeConverterBase::convert(QString const &data) const
{
return replaceFunctionInvocations(replaceSystemVariables(data)).trimmed();
}
QString CodeConverterBase::replaceSystemVariables(QString const &expression) const
{
QString result = expression;
for (interpreterBase::robotModel::PortInfo const &port : mRobotModel.availablePorts()) {
QString const variable = port.reservedVariable();
if (!variable.isEmpty()) {
result.replace(variable, deviceExpression(port));
}
}
result.replace("time", timelineExpression());
return result;
}
QString CodeConverterBase::replaceFunctionInvocations(QString const &expression) const
{
QString result = expression;
QString const randomTemplate = mFunctionInvocationsConverter->convert("random");
QRegExp const randomFunctionInvocationRegEx("random\\((.*)\\)");
int pos = randomFunctionInvocationRegEx.indexIn(result, 0);
while (pos != -1) {
QString const param = randomFunctionInvocationRegEx.cap(1);
QString randomInvocation = randomTemplate;
randomInvocation.replace("@@UPPER_BOUND@@", param);
result.replace(randomFunctionInvocationRegEx, randomInvocation);
pos += randomFunctionInvocationRegEx.matchedLength();
pos = randomFunctionInvocationRegEx.indexIn(result, pos);
}
return result;
}
QString CodeConverterBase::deviceExpression(interpreterBase::robotModel::PortInfo const &port) const
{
if (mDevices[port].isNull()) {
return QString();
}
QString const templatePath = QString("sensors/%1.t").arg(mDevices[port].name());
// Converter must take a string like "1" or "2" (and etc) and return correct value
return readTemplate(templatePath).replace("@@PORT@@", mInputConverter->convert(port.name()));
}
QString CodeConverterBase::timelineExpression() const
{
/// @todo: generate timestamps code in nxt c when required
return readTemplate("whatTime.t");
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2013 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_SYMBOLIZER_UTILS_HPP
#define MAPNIK_SYMBOLIZER_UTILS_HPP
// mapnik
#include <mapnik/symbolizer_keys.hpp>
#include <mapnik/raster_colorizer.hpp>
#include <mapnik/path_expression.hpp>
#include <mapnik/parse_path.hpp>
#include <mapnik/color.hpp>
#include <mapnik/expression.hpp>
#include <mapnik/transform_processor.hpp>
#include <mapnik/color_factory.hpp>
#include <mapnik/symbolizer.hpp>
#include <mapnik/xml_tree.hpp>
#include <mapnik/config_error.hpp>
#include <mapnik/evaluate_global_attributes.hpp>
#include <mapnik/parse_transform.hpp>
#include <mapnik/util/variant.hpp>
namespace mapnik {
template <typename Symbolizer>
struct symbolizer_traits
{
static char const* name() { return "Unknown";}
};
template<>
struct symbolizer_traits<point_symbolizer>
{
static char const* name() { return "PointSymbolizer";}
};
template<>
struct symbolizer_traits<line_symbolizer>
{
static char const* name() { return "LineSymbolizer";}
};
template<>
struct symbolizer_traits<polygon_symbolizer>
{
static char const* name() { return "PolygonSymbolizer";}
};
template<>
struct symbolizer_traits<text_symbolizer>
{
static char const* name() { return "TextSymbolizer";}
};
template<>
struct symbolizer_traits<line_pattern_symbolizer>
{
static char const* name() { return "LinePatternSymbolizer";}
};
template<>
struct symbolizer_traits<polygon_pattern_symbolizer>
{
static char const* name() { return "PolygonPatternSymbolizer";}
};
template<>
struct symbolizer_traits<markers_symbolizer>
{
static char const* name() { return "MarkersSymbolizer";}
};
template<>
struct symbolizer_traits<shield_symbolizer>
{
static char const* name() { return "ShieldSymbolizer";}
};
template<>
struct symbolizer_traits<raster_symbolizer>
{
static char const* name() { return "RasterSymbolizer";}
};
template<>
struct symbolizer_traits<building_symbolizer>
{
static char const* name() { return "BuildingSymbolizer";}
};
template<>
struct symbolizer_traits<group_symbolizer>
{
static char const* name() { return "GroupSymbolizer";}
};
template<>
struct symbolizer_traits<debug_symbolizer>
{
static char const* name() { return "DebugSymbolizer";}
};
// symbolizer name impl
namespace detail {
struct symbolizer_name_impl : public util::static_visitor<std::string>
{
public:
template <typename Symbolizer>
std::string operator () (Symbolizer const&) const
{
return symbolizer_traits<Symbolizer>::name();
}
};
}
inline std::string symbolizer_name(symbolizer const& sym)
{
std::string type = util::apply_visitor( detail::symbolizer_name_impl(), sym);
return type;
}
template <typename Meta>
class symbolizer_property_value_string : public util::static_visitor<std::string>
{
public:
symbolizer_property_value_string (Meta const& meta)
: meta_(meta) {}
std::string operator() ( mapnik::enumeration_wrapper const& e) const
{
std::stringstream ss;
auto const& convert_fun_ptr(std::get<2>(meta_));
if ( convert_fun_ptr )
{
ss << convert_fun_ptr(e);
}
return ss.str();
}
std::string operator () ( path_expression_ptr const& expr) const
{
std::ostringstream ss;
if (expr)
{
ss << '\"' << path_processor::to_string(*expr) << '\"';
}
return ss.str();
}
std::string operator () (text_placements_ptr const& expr) const
{
return std::string("\"<fixme-text-placement-ptr>\"");
}
std::string operator () (raster_colorizer_ptr const& expr) const
{
return std::string("\"<fixme-raster-colorizer-ptr>\"");
}
std::string operator () (transform_type const& expr) const
{
std::ostringstream ss;
if (expr)
{
ss << '\"' << transform_processor_type::to_string(*expr) << '\"';
}
return ss.str();
}
std::string operator () (expression_ptr const& expr) const
{
std::ostringstream ss;
if (expr)
{
ss << '\"' << "FIXME" /*mapnik::to_expression_string(*expr)*/ << '\"';
}
return ss.str();
}
std::string operator () (color const& c) const
{
std::ostringstream ss;
ss << '\"' << c << '\"';
return ss.str();
}
std::string operator () (dash_array const& dash) const
{
std::ostringstream ss;
for (std::size_t i = 0; i < dash.size(); ++i)
{
ss << dash[i].first << ", " << dash[i].second;
if ( i + 1 < dash.size() ) ss << ',';
}
return ss.str();
}
template <typename T>
std::string operator () ( T const& val ) const
{
std::ostringstream ss;
ss << val;
return ss.str();
}
private:
Meta const& meta_;
};
struct symbolizer_to_json : public util::static_visitor<std::string>
{
using result_type = std::string;
template <typename T>
auto operator() (T const& sym) const -> result_type
{
std::stringstream ss;
ss << "{\"type\":\"" << mapnik::symbolizer_traits<T>::name() << "\",";
ss << "\"properties\":{";
bool first = true;
for (auto const& prop : sym.properties)
{
auto const& meta = mapnik::get_meta(prop.first);
if (first) first = false;
else ss << ",";
ss << "\"" << std::get<0>(meta) << "\":";
ss << util::apply_visitor(symbolizer_property_value_string<property_meta_type>(meta),prop.second);
}
ss << "}}";
return ss.str();
}
};
namespace {
template <typename Symbolizer, typename T>
struct set_property_impl
{
static void apply(Symbolizer & sym, mapnik::keys key, std::string const& val)
{
std::cerr << "do nothing" << std::endl;
}
};
template <typename Symbolizer>
struct set_property_impl<Symbolizer, std::integral_constant<property_types, property_types::target_color> >
{
static void apply(Symbolizer & sym, mapnik::keys key, std::string const& val)
{
put(sym, key, mapnik::parse_color(val));
}
};
template <typename Symbolizer>
struct set_property_impl<Symbolizer, std::integral_constant<property_types, property_types::target_double> >
{
static void apply(Symbolizer & sym, mapnik::keys key, std::string const& val)
{
std::cerr << " expects double" << std::endl;
}
};
template <typename Symbolizer>
struct set_property_impl<Symbolizer, std::integral_constant<property_types, property_types::target_bool> >
{
static void apply(Symbolizer & sym, mapnik::keys key, std::string const& val)
{
std::cerr << " expects bool" << std::endl;
}
};
}
template <typename Symbolizer, typename T>
inline void set_property(Symbolizer & sym, mapnik::keys key, T const& val)
{
switch (std::get<3>(get_meta(key)))
{
case property_types::target_bool:
set_property_impl<Symbolizer, std::integral_constant<property_types, property_types::target_bool> >::apply(sym,key,val);
break;
case property_types::target_integer:
set_property_impl<Symbolizer, std::integral_constant<property_types, property_types::target_integer> >::apply(sym,key,val);
break;
case property_types::target_double:
set_property_impl<Symbolizer, std::integral_constant<property_types, property_types::target_double> >::apply(sym,key,val);
break;
case property_types::target_color:
set_property_impl<Symbolizer, std::integral_constant<property_types, property_types::target_color> >::apply(sym,key,val);
break;
default:
break;
}
}
template <typename Symbolizer, typename T>
inline void set_property_from_value(Symbolizer & sym, mapnik::keys key, T const& val)
{
switch (std::get<3>(get_meta(key)))
{
case property_types::target_bool:
put(sym, key, val.to_bool());
break;
case property_types::target_integer:
put(sym, key, val.to_int());
break;
case property_types::target_double:
put(sym, key, val.to_double());
break;
case property_types::target_color:
put(sym, key, mapnik::parse_color(val.to_string()));
break;
default:
break;
}
}
namespace detail {
// helpers
template <typename Symbolizer, typename T, bool is_enum = false>
struct set_symbolizer_property_impl
{
static void apply(Symbolizer & sym, keys key, std::string const& name, xml_node const& node)
{
using value_type = T;
try
{
boost::optional<value_type> val = node.get_opt_attr<value_type>(name);
if (val) put(sym, key, *val);
}
catch (config_error const& ex)
{
// try parsing as an expression
boost::optional<expression_ptr> val = node.get_opt_attr<expression_ptr>(name);
if (val)
{
// first try pre-evaluate expressions which don't have dynamic properties
auto result = pre_evaluate_expression<mapnik::value>(*val);
if (std::get<1>(result))
{
set_property_from_value(sym, key,std::get<0>(result));
}
else
{
// expression_ptr
put(sym, key, *val);
}
}
else
{
ex.append_context(std::string("set_symbolizer_property '") + name + "'", node);
throw;
}
}
}
};
template <typename Symbolizer>
struct set_symbolizer_property_impl<Symbolizer,transform_type,false>
{
static void apply(Symbolizer & sym, keys key, std::string const& name, xml_node const & node)
{
boost::optional<std::string> transform = node.get_opt_attr<std::string>(name);
if (transform) put(sym, key, mapnik::parse_transform(*transform));
}
};
template <typename Symbolizer>
struct set_symbolizer_property_impl<Symbolizer,dash_array,false>
{
static void apply(Symbolizer & sym, keys key, std::string const& name, xml_node const & node)
{
boost::optional<std::string> str = node.get_opt_attr<std::string>(name);
if (str)
{
std::vector<double> buf;
dash_array dash;
if (util::parse_dasharray((*str).begin(),(*str).end(),buf) && util::add_dashes(buf,dash))
{
put(sym,key,dash);
}
else
{
boost::optional<expression_ptr> val = node.get_opt_attr<expression_ptr>(name);
if (val)
{
// first try pre-evaluate expressions which don't have dynamic properties
auto result = pre_evaluate_expression<mapnik::value>(*val);
if (std::get<1>(result))
{
set_property_from_value(sym, key,std::get<0>(result));
}
else
{
// expression_ptr
put(sym, key, *val);
}
}
else
{
throw config_error(std::string("Failed to parse dasharray ") +
"'. Expected a " +
"list of floats or 'none' but got '" + (*str) + "'");
}
}
}
}
};
template <typename Symbolizer, typename T>
struct set_symbolizer_property_impl<Symbolizer, T, true>
{
static void apply(Symbolizer & sym, keys key, std::string const& name, xml_node const & node)
{
using value_type = T;
try
{
boost::optional<std::string> enum_str = node.get_opt_attr<std::string>(name);
if (enum_str)
{
boost::optional<T> enum_val = detail::enum_traits<T>::from_string(*enum_str);
if (enum_val)
{
put(sym, key, *enum_val);
}
else
{
boost::optional<expression_ptr> val = node.get_opt_attr<expression_ptr>(name);
if (val)
{
// first try pre-evaluating expression
auto result = pre_evaluate_expression<value>(*val);
if (std::get<1>(result))
{
boost::optional<T> enum_val = detail::enum_traits<T>::from_string(std::get<0>(result).to_string());
if (enum_val)
{
put(sym, key, *enum_val);
}
else
{
// can't evaluate
throw config_error("failed to parse symbolizer property: '" + name + "'");
}
}
else
{
// put expression_ptr
put(sym, key, *val);
}
}
else
{
throw config_error("failed to parse symbolizer property: '" + name + "'");
}
}
}
}
catch (config_error const& ex)
{
ex.append_context(std::string("set_symbolizer_property '") + name + "'", node);
throw;
}
}
};
} // namespace detail
template <typename Symbolizer, typename T>
bool set_symbolizer_property(Symbolizer & sym, keys key, xml_node const& node)
{
std::string const& name = std::get<0>(get_meta(key));
if (node.has_attribute(name)) {
detail::set_symbolizer_property_impl<Symbolizer,T, std::is_enum<T>::value>::apply(sym,key,name,node);
}
}
}
#endif // MAPNIK_SYMBOLIZER_UTILS_HPP
<commit_msg>fix return type<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2013 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_SYMBOLIZER_UTILS_HPP
#define MAPNIK_SYMBOLIZER_UTILS_HPP
// mapnik
#include <mapnik/symbolizer_keys.hpp>
#include <mapnik/raster_colorizer.hpp>
#include <mapnik/path_expression.hpp>
#include <mapnik/parse_path.hpp>
#include <mapnik/color.hpp>
#include <mapnik/expression.hpp>
#include <mapnik/transform_processor.hpp>
#include <mapnik/color_factory.hpp>
#include <mapnik/symbolizer.hpp>
#include <mapnik/xml_tree.hpp>
#include <mapnik/config_error.hpp>
#include <mapnik/evaluate_global_attributes.hpp>
#include <mapnik/parse_transform.hpp>
#include <mapnik/util/variant.hpp>
namespace mapnik {
template <typename Symbolizer>
struct symbolizer_traits
{
static char const* name() { return "Unknown";}
};
template<>
struct symbolizer_traits<point_symbolizer>
{
static char const* name() { return "PointSymbolizer";}
};
template<>
struct symbolizer_traits<line_symbolizer>
{
static char const* name() { return "LineSymbolizer";}
};
template<>
struct symbolizer_traits<polygon_symbolizer>
{
static char const* name() { return "PolygonSymbolizer";}
};
template<>
struct symbolizer_traits<text_symbolizer>
{
static char const* name() { return "TextSymbolizer";}
};
template<>
struct symbolizer_traits<line_pattern_symbolizer>
{
static char const* name() { return "LinePatternSymbolizer";}
};
template<>
struct symbolizer_traits<polygon_pattern_symbolizer>
{
static char const* name() { return "PolygonPatternSymbolizer";}
};
template<>
struct symbolizer_traits<markers_symbolizer>
{
static char const* name() { return "MarkersSymbolizer";}
};
template<>
struct symbolizer_traits<shield_symbolizer>
{
static char const* name() { return "ShieldSymbolizer";}
};
template<>
struct symbolizer_traits<raster_symbolizer>
{
static char const* name() { return "RasterSymbolizer";}
};
template<>
struct symbolizer_traits<building_symbolizer>
{
static char const* name() { return "BuildingSymbolizer";}
};
template<>
struct symbolizer_traits<group_symbolizer>
{
static char const* name() { return "GroupSymbolizer";}
};
template<>
struct symbolizer_traits<debug_symbolizer>
{
static char const* name() { return "DebugSymbolizer";}
};
// symbolizer name impl
namespace detail {
struct symbolizer_name_impl : public util::static_visitor<std::string>
{
public:
template <typename Symbolizer>
std::string operator () (Symbolizer const&) const
{
return symbolizer_traits<Symbolizer>::name();
}
};
}
inline std::string symbolizer_name(symbolizer const& sym)
{
std::string type = util::apply_visitor( detail::symbolizer_name_impl(), sym);
return type;
}
template <typename Meta>
class symbolizer_property_value_string : public util::static_visitor<std::string>
{
public:
symbolizer_property_value_string (Meta const& meta)
: meta_(meta) {}
std::string operator() ( mapnik::enumeration_wrapper const& e) const
{
std::stringstream ss;
auto const& convert_fun_ptr(std::get<2>(meta_));
if ( convert_fun_ptr )
{
ss << convert_fun_ptr(e);
}
return ss.str();
}
std::string operator () ( path_expression_ptr const& expr) const
{
std::ostringstream ss;
if (expr)
{
ss << '\"' << path_processor::to_string(*expr) << '\"';
}
return ss.str();
}
std::string operator () (text_placements_ptr const& expr) const
{
return std::string("\"<fixme-text-placement-ptr>\"");
}
std::string operator () (raster_colorizer_ptr const& expr) const
{
return std::string("\"<fixme-raster-colorizer-ptr>\"");
}
std::string operator () (transform_type const& expr) const
{
std::ostringstream ss;
if (expr)
{
ss << '\"' << transform_processor_type::to_string(*expr) << '\"';
}
return ss.str();
}
std::string operator () (expression_ptr const& expr) const
{
std::ostringstream ss;
if (expr)
{
ss << '\"' << "FIXME" /*mapnik::to_expression_string(*expr)*/ << '\"';
}
return ss.str();
}
std::string operator () (color const& c) const
{
std::ostringstream ss;
ss << '\"' << c << '\"';
return ss.str();
}
std::string operator () (dash_array const& dash) const
{
std::ostringstream ss;
for (std::size_t i = 0; i < dash.size(); ++i)
{
ss << dash[i].first << ", " << dash[i].second;
if ( i + 1 < dash.size() ) ss << ',';
}
return ss.str();
}
template <typename T>
std::string operator () ( T const& val ) const
{
std::ostringstream ss;
ss << val;
return ss.str();
}
private:
Meta const& meta_;
};
struct symbolizer_to_json : public util::static_visitor<std::string>
{
using result_type = std::string;
template <typename T>
auto operator() (T const& sym) const -> result_type
{
std::stringstream ss;
ss << "{\"type\":\"" << mapnik::symbolizer_traits<T>::name() << "\",";
ss << "\"properties\":{";
bool first = true;
for (auto const& prop : sym.properties)
{
auto const& meta = mapnik::get_meta(prop.first);
if (first) first = false;
else ss << ",";
ss << "\"" << std::get<0>(meta) << "\":";
ss << util::apply_visitor(symbolizer_property_value_string<property_meta_type>(meta),prop.second);
}
ss << "}}";
return ss.str();
}
};
namespace {
template <typename Symbolizer, typename T>
struct set_property_impl
{
static void apply(Symbolizer & sym, mapnik::keys key, std::string const& val)
{
std::cerr << "do nothing" << std::endl;
}
};
template <typename Symbolizer>
struct set_property_impl<Symbolizer, std::integral_constant<property_types, property_types::target_color> >
{
static void apply(Symbolizer & sym, mapnik::keys key, std::string const& val)
{
put(sym, key, mapnik::parse_color(val));
}
};
template <typename Symbolizer>
struct set_property_impl<Symbolizer, std::integral_constant<property_types, property_types::target_double> >
{
static void apply(Symbolizer & sym, mapnik::keys key, std::string const& val)
{
std::cerr << " expects double" << std::endl;
}
};
template <typename Symbolizer>
struct set_property_impl<Symbolizer, std::integral_constant<property_types, property_types::target_bool> >
{
static void apply(Symbolizer & sym, mapnik::keys key, std::string const& val)
{
std::cerr << " expects bool" << std::endl;
}
};
}
template <typename Symbolizer, typename T>
inline void set_property(Symbolizer & sym, mapnik::keys key, T const& val)
{
switch (std::get<3>(get_meta(key)))
{
case property_types::target_bool:
set_property_impl<Symbolizer, std::integral_constant<property_types, property_types::target_bool> >::apply(sym,key,val);
break;
case property_types::target_integer:
set_property_impl<Symbolizer, std::integral_constant<property_types, property_types::target_integer> >::apply(sym,key,val);
break;
case property_types::target_double:
set_property_impl<Symbolizer, std::integral_constant<property_types, property_types::target_double> >::apply(sym,key,val);
break;
case property_types::target_color:
set_property_impl<Symbolizer, std::integral_constant<property_types, property_types::target_color> >::apply(sym,key,val);
break;
default:
break;
}
}
template <typename Symbolizer, typename T>
inline void set_property_from_value(Symbolizer & sym, mapnik::keys key, T const& val)
{
switch (std::get<3>(get_meta(key)))
{
case property_types::target_bool:
put(sym, key, val.to_bool());
break;
case property_types::target_integer:
put(sym, key, val.to_int());
break;
case property_types::target_double:
put(sym, key, val.to_double());
break;
case property_types::target_color:
put(sym, key, mapnik::parse_color(val.to_string()));
break;
default:
break;
}
}
namespace detail {
// helpers
template <typename Symbolizer, typename T, bool is_enum = false>
struct set_symbolizer_property_impl
{
static void apply(Symbolizer & sym, keys key, std::string const& name, xml_node const& node)
{
using value_type = T;
try
{
boost::optional<value_type> val = node.get_opt_attr<value_type>(name);
if (val) put(sym, key, *val);
}
catch (config_error const& ex)
{
// try parsing as an expression
boost::optional<expression_ptr> val = node.get_opt_attr<expression_ptr>(name);
if (val)
{
// first try pre-evaluate expressions which don't have dynamic properties
auto result = pre_evaluate_expression<mapnik::value>(*val);
if (std::get<1>(result))
{
set_property_from_value(sym, key,std::get<0>(result));
}
else
{
// expression_ptr
put(sym, key, *val);
}
}
else
{
ex.append_context(std::string("set_symbolizer_property '") + name + "'", node);
throw;
}
}
}
};
template <typename Symbolizer>
struct set_symbolizer_property_impl<Symbolizer,transform_type,false>
{
static void apply(Symbolizer & sym, keys key, std::string const& name, xml_node const & node)
{
boost::optional<std::string> transform = node.get_opt_attr<std::string>(name);
if (transform) put(sym, key, mapnik::parse_transform(*transform));
}
};
template <typename Symbolizer>
struct set_symbolizer_property_impl<Symbolizer,dash_array,false>
{
static void apply(Symbolizer & sym, keys key, std::string const& name, xml_node const & node)
{
boost::optional<std::string> str = node.get_opt_attr<std::string>(name);
if (str)
{
std::vector<double> buf;
dash_array dash;
if (util::parse_dasharray((*str).begin(),(*str).end(),buf) && util::add_dashes(buf,dash))
{
put(sym,key,dash);
}
else
{
boost::optional<expression_ptr> val = node.get_opt_attr<expression_ptr>(name);
if (val)
{
// first try pre-evaluate expressions which don't have dynamic properties
auto result = pre_evaluate_expression<mapnik::value>(*val);
if (std::get<1>(result))
{
set_property_from_value(sym, key,std::get<0>(result));
}
else
{
// expression_ptr
put(sym, key, *val);
}
}
else
{
throw config_error(std::string("Failed to parse dasharray ") +
"'. Expected a " +
"list of floats or 'none' but got '" + (*str) + "'");
}
}
}
}
};
template <typename Symbolizer, typename T>
struct set_symbolizer_property_impl<Symbolizer, T, true>
{
static void apply(Symbolizer & sym, keys key, std::string const& name, xml_node const & node)
{
using value_type = T;
try
{
boost::optional<std::string> enum_str = node.get_opt_attr<std::string>(name);
if (enum_str)
{
boost::optional<T> enum_val = detail::enum_traits<T>::from_string(*enum_str);
if (enum_val)
{
put(sym, key, *enum_val);
}
else
{
boost::optional<expression_ptr> val = node.get_opt_attr<expression_ptr>(name);
if (val)
{
// first try pre-evaluating expression
auto result = pre_evaluate_expression<value>(*val);
if (std::get<1>(result))
{
boost::optional<T> enum_val = detail::enum_traits<T>::from_string(std::get<0>(result).to_string());
if (enum_val)
{
put(sym, key, *enum_val);
}
else
{
// can't evaluate
throw config_error("failed to parse symbolizer property: '" + name + "'");
}
}
else
{
// put expression_ptr
put(sym, key, *val);
}
}
else
{
throw config_error("failed to parse symbolizer property: '" + name + "'");
}
}
}
}
catch (config_error const& ex)
{
ex.append_context(std::string("set_symbolizer_property '") + name + "'", node);
throw;
}
}
};
} // namespace detail
template <typename Symbolizer, typename T>
void set_symbolizer_property(Symbolizer & sym, keys key, xml_node const& node)
{
std::string const& name = std::get<0>(get_meta(key));
if (node.has_attribute(name)) {
detail::set_symbolizer_property_impl<Symbolizer,T, std::is_enum<T>::value>::apply(sym,key,name,node);
}
}
}
#endif // MAPNIK_SYMBOLIZER_UTILS_HPP
<|endoftext|> |
<commit_before>/*
* PerfectSensorProcessor.hpp
*
* Created on: Sep 28, 2014
* Author: Péter Fankhauser
* Institute: ETH Zurich, ANYbotics
*/
#pragma once
#include <elevation_mapping/sensor_processors/SensorProcessorBase.hpp>
namespace elevation_mapping {
/*!
* Sensor processor for laser range sensors.
*/
class PerfectSensorProcessor : public SensorProcessorBase
{
public:
/*!
* Constructor.
* @param nodeHandle the ROS node handle.
* @param transformListener the ROS transform listener.
*/
PerfectSensorProcessor(ros::NodeHandle& nodeHandle, tf::TransformListener& transformListener);
/*!
* Destructor.
*/
virtual ~PerfectSensorProcessor();
private:
/*!
* Reads and verifies the parameters.
* @return true if successful.
*/
bool readParameters();
/*!
* Clean the point cloud. Points below the minimal and above the maximal sensor
* cutoff value are dropped.
* @param pointCloud the point cloud to clean.
* @return true if successful.
*/
virtual bool cleanPointCloud(const pcl::PointCloud<pcl::PointXYZRGB>::Ptr pointCloud);
/*!
* Computes the elevation map height variances for each point in a point cloud with the
* sensor model and the robot pose covariance.
* @param[in] pointCloud the point cloud for which the variances are computed.
* @param[in] robotPoseCovariance the robot pose covariance matrix.
* @param[out] variances the elevation map height variances.
* @return true if successful.
*/
virtual bool computeVariances(
const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr pointCloud,
const Eigen::Matrix<double, 6, 6>& robotPoseCovariance,
Eigen::VectorXf& variances);
};
} /* namespace elevation_mapping */
<commit_msg>Added missing white spaces<commit_after>/*
* PerfectSensorProcessor.hpp
*
* Created on: Sep 28, 2014
* Author: Péter Fankhauser
* Institute: ETH Zurich, ANYbotics
*/
#pragma once
#include <elevation_mapping/sensor_processors/SensorProcessorBase.hpp>
namespace elevation_mapping {
/*!
* Sensor processor for laser range sensors.
*/
class PerfectSensorProcessor : public SensorProcessorBase
{
public:
/*!
* Constructor.
* @param nodeHandle the ROS node handle.
* @param transformListener the ROS transform listener.
*/
PerfectSensorProcessor(ros::NodeHandle& nodeHandle, tf::TransformListener& transformListener);
/*!
* Destructor.
*/
virtual ~PerfectSensorProcessor();
private:
/*!
* Reads and verifies the parameters.
* @return true if successful.
*/
bool readParameters();
/*!
* Clean the point cloud. Points below the minimal and above the maximal sensor
* cutoff value are dropped.
* @param pointCloud the point cloud to clean.
* @return true if successful.
*/
virtual bool cleanPointCloud(const pcl::PointCloud<pcl::PointXYZRGB>::Ptr pointCloud);
/*!
* Computes the elevation map height variances for each point in a point cloud with the
* sensor model and the robot pose covariance.
* @param[in] pointCloud the point cloud for which the variances are computed.
* @param[in] robotPoseCovariance the robot pose covariance matrix.
* @param[out] variances the elevation map height variances.
* @return true if successful.
*/
virtual bool computeVariances(
const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr pointCloud,
const Eigen::Matrix<double, 6, 6>& robotPoseCovariance,
Eigen::VectorXf& variances);
};
} /* namespace elevation_mapping */
<|endoftext|> |
<commit_before>#ifndef PICOLIB_SOCKET_IMPL_H_
#define PICOLIB_SOCKET_IMPL_H_
#include <sys/un.h>
namespace Pico {
namespace Network {
FUNCTION
uint16_t _htons(uint16_t port)
{
return cpu_to_be16(port);
}
template <enum AddressType>
struct Sockaddr;
template <>
struct Sockaddr<IPV4>
{
static constexpr int family = AF_INET;
typedef struct sockaddr_in type;
FUNCTION
struct sockaddr_in pack(IpAddress const ip, uint16_t port)
{
struct sockaddr_in addr;
addr.sin_family = family;
addr.sin_port = _htons(port);
addr.sin_addr.s_addr = ip.value;
return addr;
}
};
template <>
struct Sockaddr<IPV6>
{
static constexpr int family = AF_INET6;
typedef struct sockaddr_in6 type;
FUNCTION
struct sockaddr_in6 pack(IpAddress6 const ip, uint16_t port)
{
struct sockaddr_in6 addr;
addr.sin6_flowinfo = 0;
addr.sin6_family = AF_INET6;
addr.sin6_port = _htons(port);
Memory::copy(&addr.sin6_addr.s6_addr, &ip, sizeof(ip));
return addr;
}
};
template <>
struct Sockaddr<UNIX>
{
static constexpr int family = AF_UNIX;
typedef struct sockaddr_un type;
FUNCTION
struct sockaddr_un pack(UnixAddress const unixaddr)
{
struct sockaddr_un addr;
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, unixaddr.path);
return addr;
}
};
template <>
struct Sockaddr<UNIX_ABSTRACT>
{
static constexpr int family = AF_UNIX;
typedef struct sockaddr_un type;
FUNCTION
struct sockaddr_un pack(UnixAbstractAddress const unixaddr)
{
struct sockaddr_un addr;
addr.sun_family = AF_UNIX;
addr.sun_path[0] = '\0';
strcpy(addr.sun_path + 1, unixaddr.path);
return addr;
}
};
METHOD
ssize_t SocketIO::in(void *buf, size_t count)
{
return Syscall::recv(fd, buf, count, MSG_WAITALL);
}
METHOD
ssize_t SocketIO::out(const void *buf, size_t count)
{
// Use write(2) instead of send(2) since it takes 3 arguments instead of 4.
// This produces slightly smaller code.
return Syscall::write(fd, buf, count);
}
METHOD
int SocketIO::close()
{
return Syscall::close(fd);
}
CONSTRUCTOR
Socket::Socket(int domain, int type, int protocol) : Socket( Syscall::socket(domain, type, protocol) ) {}
METHOD
int Socket::get(int level, int optname, void *val, unsigned *len)
{
return Syscall::getsockopt(this->file_desc(), level, optname, val, len);
}
METHOD
int Socket::set(int level, int optname, void *val, unsigned len)
{
return Syscall::setsockopt(this->file_desc(), level, optname, val, len);
}
template <enum AddressType T>
METHOD
int Socket::bind(Address<T> addr)
{
static_assert(T == UNIX || T == UNIX_ABSTRACT, "This method only supports UNIX address sockets.");
auto bind_addr = Sockaddr<T>::pack(addr);
return Syscall::bind(this->file_desc(), reinterpret_cast<struct sockaddr *>(&bind_addr), sizeof(bind_addr));
}
template <enum AddressType T>
METHOD
int Socket::bind(Address<T> addr, uint16_t port, bool reuse_addr)
{
if ( reuse_addr )
{
int option = 1;
set(SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
}
auto bind_addr = Sockaddr<T>::pack(addr, port);
return Syscall::bind(this->file_desc(), reinterpret_cast<struct sockaddr *>(&bind_addr), sizeof(bind_addr));
}
template <enum AddressType T>
METHOD
int StreamSocket::connect(Address<T> addr)
{
static_assert(T == UNIX || T == UNIX_ABSTRACT, "This method only supports UNIX address sockets.");
auto serv_addr = Sockaddr<T>::pack(addr);
return Syscall::connect(this->file_desc(), reinterpret_cast<struct sockaddr *>(&serv_addr), sizeof(serv_addr));
}
template <enum AddressType T>
METHOD
int StreamSocket::connect(Address<T> addr, uint16_t port)
{
auto serv_addr = Sockaddr<T>::pack(addr, port);
return Syscall::connect(this->file_desc(), reinterpret_cast<struct sockaddr *>(&serv_addr), sizeof(serv_addr));
}
METHOD
int StreamSocket::listen(int backlog)
{
return Syscall::listen(this->file_desc(), backlog);
}
template <bool Fork>
METHOD
StreamSocket StreamSocket::accept()
{
do {
int client_fd = Syscall::accept(this->file_desc(), nullptr, 0);
if ( fork )
{
if ( Syscall::fork() == 0 )
return StreamSocket(client_fd);
else
Syscall::close(client_fd);
}
else
return StreamSocket(client_fd);
} while ( fork );
}
}
}
#endif
<commit_msg>socket: fix fork bug in accept<commit_after>#ifndef PICOLIB_SOCKET_IMPL_H_
#define PICOLIB_SOCKET_IMPL_H_
#include <sys/un.h>
namespace Pico {
namespace Network {
FUNCTION
uint16_t _htons(uint16_t port)
{
return cpu_to_be16(port);
}
template <enum AddressType>
struct Sockaddr;
template <>
struct Sockaddr<IPV4>
{
static constexpr int family = AF_INET;
typedef struct sockaddr_in type;
FUNCTION
struct sockaddr_in pack(IpAddress const ip, uint16_t port)
{
struct sockaddr_in addr;
addr.sin_family = family;
addr.sin_port = _htons(port);
addr.sin_addr.s_addr = ip.value;
return addr;
}
};
template <>
struct Sockaddr<IPV6>
{
static constexpr int family = AF_INET6;
typedef struct sockaddr_in6 type;
FUNCTION
struct sockaddr_in6 pack(IpAddress6 const ip, uint16_t port)
{
struct sockaddr_in6 addr;
addr.sin6_flowinfo = 0;
addr.sin6_family = AF_INET6;
addr.sin6_port = _htons(port);
Memory::copy(&addr.sin6_addr.s6_addr, &ip, sizeof(ip));
return addr;
}
};
template <>
struct Sockaddr<UNIX>
{
static constexpr int family = AF_UNIX;
typedef struct sockaddr_un type;
FUNCTION
struct sockaddr_un pack(UnixAddress const unixaddr)
{
struct sockaddr_un addr;
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, unixaddr.path);
return addr;
}
};
template <>
struct Sockaddr<UNIX_ABSTRACT>
{
static constexpr int family = AF_UNIX;
typedef struct sockaddr_un type;
FUNCTION
struct sockaddr_un pack(UnixAbstractAddress const unixaddr)
{
struct sockaddr_un addr;
addr.sun_family = AF_UNIX;
addr.sun_path[0] = '\0';
strcpy(addr.sun_path + 1, unixaddr.path);
return addr;
}
};
METHOD
ssize_t SocketIO::in(void *buf, size_t count)
{
return Syscall::recv(fd, buf, count, MSG_WAITALL);
}
METHOD
ssize_t SocketIO::out(const void *buf, size_t count)
{
// Use write(2) instead of send(2) since it takes 3 arguments instead of 4.
// This produces slightly smaller code.
return Syscall::write(fd, buf, count);
}
METHOD
int SocketIO::close()
{
return Syscall::close(fd);
}
CONSTRUCTOR
Socket::Socket(int domain, int type, int protocol) : Socket( Syscall::socket(domain, type, protocol) ) {}
METHOD
int Socket::get(int level, int optname, void *val, unsigned *len)
{
return Syscall::getsockopt(this->file_desc(), level, optname, val, len);
}
METHOD
int Socket::set(int level, int optname, void *val, unsigned len)
{
return Syscall::setsockopt(this->file_desc(), level, optname, val, len);
}
template <enum AddressType T>
METHOD
int Socket::bind(Address<T> addr)
{
static_assert(T == UNIX || T == UNIX_ABSTRACT, "This method only supports UNIX address sockets.");
auto bind_addr = Sockaddr<T>::pack(addr);
return Syscall::bind(this->file_desc(), reinterpret_cast<struct sockaddr *>(&bind_addr), sizeof(bind_addr));
}
template <enum AddressType T>
METHOD
int Socket::bind(Address<T> addr, uint16_t port, bool reuse_addr)
{
if ( reuse_addr )
{
int option = 1;
set(SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
}
auto bind_addr = Sockaddr<T>::pack(addr, port);
return Syscall::bind(this->file_desc(), reinterpret_cast<struct sockaddr *>(&bind_addr), sizeof(bind_addr));
}
template <enum AddressType T>
METHOD
int StreamSocket::connect(Address<T> addr)
{
static_assert(T == UNIX || T == UNIX_ABSTRACT, "This method only supports UNIX address sockets.");
auto serv_addr = Sockaddr<T>::pack(addr);
return Syscall::connect(this->file_desc(), reinterpret_cast<struct sockaddr *>(&serv_addr), sizeof(serv_addr));
}
template <enum AddressType T>
METHOD
int StreamSocket::connect(Address<T> addr, uint16_t port)
{
auto serv_addr = Sockaddr<T>::pack(addr, port);
return Syscall::connect(this->file_desc(), reinterpret_cast<struct sockaddr *>(&serv_addr), sizeof(serv_addr));
}
METHOD
int StreamSocket::listen(int backlog)
{
return Syscall::listen(this->file_desc(), backlog);
}
template <bool Fork>
METHOD
StreamSocket StreamSocket::accept()
{
do {
int client_fd = Syscall::accept(this->file_desc(), nullptr, 0);
if ( Fork )
{
if ( Syscall::fork() == 0 )
return StreamSocket(client_fd);
else
Syscall::close(client_fd);
}
else
return StreamSocket(client_fd);
} while ( Fork );
}
}
}
#endif
<|endoftext|> |
<commit_before>#ifndef VSMC_UTILITY_CL_MANAGER_HPP
#define VSMC_UTILITY_CL_MANAGER_HPP
#include <vsmc/internal/config.hpp>
#include <vsmc/internal/assert.hpp>
#include <vsmc/internal/defines.hpp>
#include <vsmc/internal/forward.hpp>
#include <vsmc/internal/traits.hpp>
#include <vsmc/utility/cl_wrapper.hpp>
#include <cstddef>
#include <cstdlib>
#include <string>
#include <vector>
namespace vsmc {
struct CLDefault
{
typedef cxx11::integral_constant<cl_device_type, CL_DEVICE_TYPE_DEFAULT>
opencl_device_type;
};
/// \brief OpenCL Manager
/// \ingroup Utility
template <typename ID>
class CLManager
{
public :
static CLManager<ID> &instance ()
{
static CLManager<ID> manager;
return manager;
}
const cl::Platform &platform () const
{
return platform_;
}
const std::vector<cl::Platform> &platform_vec () const
{
return platform_vec_;
}
const cl::Context &context () const
{
return context_;
}
const cl::Device &device () const
{
return device_;
}
const std::vector<cl::Device> &device_vec () const
{
return device_vec_;
}
const cl::CommandQueue &command_queue () const
{
return command_queue_;
}
bool setup () const
{
return setup_;
}
void setup (cl_device_type dev)
{
setup_ = false;
setup_cl_manager(dev);
}
void setup (const cl::Platform &plat, const cl::Context &ctx,
const cl::Device &dev, const cl::CommandQueue &cmd)
{
setup_ = false;
platform_ = plat;
cl::Platform::get(&platform_vec_);
context_ = ctx;
device_ = dev;
device_vec_ = context_.getInfo<CL_CONTEXT_DEVICES>();
command_queue_ = cmd;
setup_ = true;
}
template<typename CLType>
cl::Buffer create_buffer (std::size_t num) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(create_buffer);
if (!num)
return cl::Buffer();
return cl::Buffer(context_, CL_MEM_READ_WRITE, sizeof(CLType) * num);
}
template<typename CLType, typename InputIter>
cl::Buffer create_buffer (InputIter first, InputIter last) const
{
using std::distance;
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(create_buffer);
std::size_t num = static_cast<std::size_t>(
std::abs(distance(first, last)));
if (!num)
return cl::Buffer();
cl::Buffer buf(create_buffer<CLType>(num));
write_buffer<CLType>(buf, num, first);
return buf;
}
template <typename CLType, typename OutputIter>
OutputIter read_buffer (const cl::Buffer &buf, std::size_t num,
OutputIter first) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(read_buffer);
CLType *temp = read_buffer_pool<CLType>(num);
command_queue_.finish();
command_queue_.enqueueReadBuffer(buf, CL_TRUE, 0,
sizeof(CLType) * num, (void *) temp);
for (std::size_t i = 0; i != num; ++i, ++first)
*first = temp[i];
return first;
}
template <typename CLType>
CLType *read_buffer (const cl::Buffer &buf, std::size_t num,
CLType *first) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(read_buffer);
command_queue_.finish();
command_queue_.enqueueReadBuffer(buf, CL_TRUE, 0,
sizeof(CLType) * num, (void *) first);
return first + num;
}
template <typename CLType, typename InputIter>
InputIter write_buffer (const cl::Buffer &buf, std::size_t num,
InputIter first) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(write_buffer);
CLType *temp = write_buffer_pool<CLType>(num);
for (std::size_t i = 0; i != num; ++i, ++first)
temp[i] = *first;
command_queue_.finish();
command_queue_.enqueueWriteBuffer(buf, CL_TRUE, 0,
sizeof(CLType) * num, (void *) temp);
return first;
}
template <typename CLType>
const CLType *write_buffer (const cl::Buffer &buf, std::size_t num,
const CLType *first) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(write_buffer);
command_queue_.finish();
command_queue_.enqueueWriteBuffer(buf, CL_TRUE, 0,
sizeof(CLType) * num, (void *) first);
return first + num;
}
template <typename CLType>
CLType *write_buffer (const cl::Buffer &buf, std::size_t num,
CLType *first) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(write_buffer);
command_queue_.finish();
command_queue_.enqueueWriteBuffer(buf, CL_TRUE, 0,
sizeof(CLType) * num, (void *) first);
return first + num;
}
template <typename CLType>
void copy_buffer (const cl::Buffer &src, std::size_t num,
const cl::Buffer &dst) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(copy_buffer);
command_queue_.finish();
command_queue_.enqueueCopyBuffer(src, dst, 0, 0, sizeof(CLType) * num);
command_queue_.finish();
}
cl::Program create_program (const std::string &source) const
{
return cl::Program(context_, source);
}
void run_kernel (const cl::Kernel &kern,
std::size_t global_size, std::size_t local_size) const
{
command_queue_.finish();
command_queue_.enqueueNDRangeKernel(kern, cl::NullRange,
get_global_nd_range(global_size, local_size),
get_local_nd_range(global_size, local_size));
command_queue_.finish();
}
private :
cl::Platform platform_;
std::vector<cl::Platform> platform_vec_;
cl::Context context_;
cl::Device device_;
std::vector<cl::Device> device_vec_;
cl::CommandQueue command_queue_;
bool setup_;
mutable std::size_t read_buffer_pool_bytes_;
mutable std::size_t write_buffer_pool_bytes_;
mutable void *read_buffer_pool_;
mutable void *write_buffer_pool_;
CLManager () :
setup_(false), read_buffer_pool_bytes_(0), write_buffer_pool_bytes_(0),
read_buffer_pool_(VSMC_NULLPTR), write_buffer_pool_(VSMC_NULLPTR)
{
cl_device_type dev = OpenCLDeviceTypeTrait<ID>::value ?
OpenCLDeviceTypeTrait<ID>::type::value :
CLDefault::opencl_device_type::value;
setup_cl_manager(dev);
}
CLManager (const CLManager<ID> &);
CLManager<ID> &operator= (const CLManager<ID> &);
~CLManager ()
{
std::free(read_buffer_pool_);
std::free(write_buffer_pool_);
}
void setup_cl_manager (cl_device_type dev)
{
try {
cl::Platform::get(&platform_vec_);
} catch (cl::Error) {
platform_vec_.clear();
}
for (std::size_t p = 0; p != platform_vec_.size(); ++p) {
try {
platform_ = platform_vec_[p];
std::string pname;
platform_.getInfo(CL_PLATFORM_NAME, &pname);
if (!CheckOpenCLPlatformTrait<ID>::check(pname)) {
platform_ = cl::Platform();
continue;
}
cl_context_properties context_properties[] = {
CL_CONTEXT_PLATFORM,
(cl_context_properties)(platform_)(), 0
};
context_ = cl::Context(dev, context_properties);
device_vec_ = context_.getInfo<CL_CONTEXT_DEVICES>();
bool device_found = false;
for (std::size_t d = 0; d != device_vec_.size(); ++d) {
std::string dname;
device_vec_[d].getInfo(CL_DEVICE_NAME, &dname);
if (CheckOpenCLDeviceTrait<ID>::check(dname)) {
device_ = device_vec_[d];
device_found = true;
break;
}
}
if (!device_found) {
platform_ = cl::Platform();
context_ = cl::Context();
device_ = cl::Device();
continue;
}
command_queue_ = cl::CommandQueue(context_, device_, 0);
setup_ = true;
break;
} catch (cl::Error) {
platform_ = cl::Platform();
context_ = cl::Context();
device_ = cl::Device();
command_queue_ = cl::CommandQueue();
device_vec_.clear();
}
}
}
template <typename CLType>
CLType *read_buffer_pool (std::size_t num) const
{
std::size_t new_bytes = num * sizeof(CLType);
if (new_bytes > read_buffer_pool_bytes_) {
std::free(read_buffer_pool_);
read_buffer_pool_ = std::malloc(new_bytes);
if (!read_buffer_pool_ && new_bytes)
throw std::bad_alloc();
read_buffer_pool_bytes_ = new_bytes;
}
return reinterpret_cast<CLType *>(read_buffer_pool_);
}
template <typename CLType>
CLType *write_buffer_pool (std::size_t num) const
{
std::size_t new_bytes = num * sizeof(CLType);
if (new_bytes > write_buffer_pool_bytes_) {
std::free(write_buffer_pool_);
write_buffer_pool_ = std::malloc(new_bytes);
if (!write_buffer_pool_ && new_bytes)
throw std::bad_alloc();
write_buffer_pool_bytes_ = new_bytes;
}
return reinterpret_cast<CLType *>(write_buffer_pool_);
}
cl::NDRange get_global_nd_range (
std::size_t global_size, std::size_t local_size) const
{
return (local_size && global_size % local_size) ?
cl::NDRange((global_size / local_size + 1) * local_size):
cl::NDRange(global_size);
}
cl::NDRange get_local_nd_range (
std::size_t global_size, std::size_t local_size) const
{
return local_size ? cl::NDRange(local_size) : cl::NullRange;
}
}; // clss CLManager
} // namespace vsmc
#endif // VSMC_UTILITY_CL_MANAGER_HPP
<commit_msg>gmm cl save counters between kernels<commit_after>#ifndef VSMC_UTILITY_CL_MANAGER_HPP
#define VSMC_UTILITY_CL_MANAGER_HPP
#include <vsmc/internal/config.hpp>
#include <vsmc/internal/assert.hpp>
#include <vsmc/internal/defines.hpp>
#include <vsmc/internal/forward.hpp>
#include <vsmc/internal/traits.hpp>
#include <vsmc/utility/cl_wrapper.hpp>
#include <cstddef>
#include <cstdlib>
#include <string>
#include <vector>
namespace vsmc {
struct CLDefault
{
typedef cxx11::integral_constant<cl_device_type, CL_DEVICE_TYPE_DEFAULT>
opencl_device_type;
};
/// \brief OpenCL Manager
/// \ingroup Utility
template <typename ID>
class CLManager
{
public :
static CLManager<ID> &instance ()
{
static CLManager<ID> manager;
return manager;
}
const cl::Platform &platform () const
{
return platform_;
}
const std::vector<cl::Platform> &platform_vec () const
{
return platform_vec_;
}
const cl::Context &context () const
{
return context_;
}
const cl::Device &device () const
{
return device_;
}
const std::vector<cl::Device> &device_vec () const
{
return device_vec_;
}
const cl::CommandQueue &command_queue () const
{
return command_queue_;
}
bool setup () const
{
return setup_;
}
bool setup (cl_device_type dev)
{
setup_ = false;
setup_cl_manager(dev);
return setup_;
}
bool setup (const cl::Platform &plat, const cl::Context &ctx,
const cl::Device &dev, const cl::CommandQueue &cmd)
{
setup_ = false;
platform_ = plat;
cl::Platform::get(&platform_vec_);
context_ = ctx;
device_ = dev;
device_vec_ = context_.getInfo<CL_CONTEXT_DEVICES>();
command_queue_ = cmd;
setup_ = true;
return setup_;
}
template<typename CLType>
cl::Buffer create_buffer (std::size_t num) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(create_buffer);
if (!num)
return cl::Buffer();
return cl::Buffer(context_, CL_MEM_READ_WRITE, sizeof(CLType) * num);
}
template<typename CLType, typename InputIter>
cl::Buffer create_buffer (InputIter first, InputIter last) const
{
using std::distance;
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(create_buffer);
std::size_t num = static_cast<std::size_t>(
std::abs(distance(first, last)));
if (!num)
return cl::Buffer();
cl::Buffer buf(create_buffer<CLType>(num));
write_buffer<CLType>(buf, num, first);
return buf;
}
template <typename CLType, typename OutputIter>
OutputIter read_buffer (const cl::Buffer &buf, std::size_t num,
OutputIter first) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(read_buffer);
CLType *temp = read_buffer_pool<CLType>(num);
command_queue_.finish();
command_queue_.enqueueReadBuffer(buf, CL_TRUE, 0,
sizeof(CLType) * num, (void *) temp);
for (std::size_t i = 0; i != num; ++i, ++first)
*first = temp[i];
return first;
}
template <typename CLType>
CLType *read_buffer (const cl::Buffer &buf, std::size_t num,
CLType *first) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(read_buffer);
command_queue_.finish();
command_queue_.enqueueReadBuffer(buf, CL_TRUE, 0,
sizeof(CLType) * num, (void *) first);
return first + num;
}
template <typename CLType, typename InputIter>
InputIter write_buffer (const cl::Buffer &buf, std::size_t num,
InputIter first) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(write_buffer);
CLType *temp = write_buffer_pool<CLType>(num);
for (std::size_t i = 0; i != num; ++i, ++first)
temp[i] = *first;
command_queue_.finish();
command_queue_.enqueueWriteBuffer(buf, CL_TRUE, 0,
sizeof(CLType) * num, (void *) temp);
return first;
}
template <typename CLType>
const CLType *write_buffer (const cl::Buffer &buf, std::size_t num,
const CLType *first) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(write_buffer);
command_queue_.finish();
command_queue_.enqueueWriteBuffer(buf, CL_TRUE, 0,
sizeof(CLType) * num, (void *) first);
return first + num;
}
template <typename CLType>
CLType *write_buffer (const cl::Buffer &buf, std::size_t num,
CLType *first) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(write_buffer);
command_queue_.finish();
command_queue_.enqueueWriteBuffer(buf, CL_TRUE, 0,
sizeof(CLType) * num, (void *) first);
return first + num;
}
template <typename CLType>
void copy_buffer (const cl::Buffer &src, std::size_t num,
const cl::Buffer &dst) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(copy_buffer);
command_queue_.finish();
command_queue_.enqueueCopyBuffer(src, dst, 0, 0, sizeof(CLType) * num);
command_queue_.finish();
}
cl::Program create_program (const std::string &source) const
{
return cl::Program(context_, source);
}
void run_kernel (const cl::Kernel &kern,
std::size_t global_size, std::size_t local_size) const
{
command_queue_.finish();
command_queue_.enqueueNDRangeKernel(kern, cl::NullRange,
get_global_nd_range(global_size, local_size),
get_local_nd_range(global_size, local_size));
command_queue_.finish();
}
private :
cl::Platform platform_;
std::vector<cl::Platform> platform_vec_;
cl::Context context_;
cl::Device device_;
std::vector<cl::Device> device_vec_;
cl::CommandQueue command_queue_;
bool setup_;
mutable std::size_t read_buffer_pool_bytes_;
mutable std::size_t write_buffer_pool_bytes_;
mutable void *read_buffer_pool_;
mutable void *write_buffer_pool_;
CLManager () :
setup_(false), read_buffer_pool_bytes_(0), write_buffer_pool_bytes_(0),
read_buffer_pool_(VSMC_NULLPTR), write_buffer_pool_(VSMC_NULLPTR)
{
cl_device_type dev = OpenCLDeviceTypeTrait<ID>::value ?
OpenCLDeviceTypeTrait<ID>::type::value :
CLDefault::opencl_device_type::value;
setup_cl_manager(dev);
}
CLManager (const CLManager<ID> &);
CLManager<ID> &operator= (const CLManager<ID> &);
~CLManager ()
{
std::free(read_buffer_pool_);
std::free(write_buffer_pool_);
}
void setup_cl_manager (cl_device_type dev)
{
try {
cl::Platform::get(&platform_vec_);
} catch (cl::Error) {
platform_vec_.clear();
}
for (std::size_t p = 0; p != platform_vec_.size(); ++p) {
try {
platform_ = platform_vec_[p];
std::string pname;
platform_.getInfo(CL_PLATFORM_NAME, &pname);
if (!CheckOpenCLPlatformTrait<ID>::check(pname)) {
platform_ = cl::Platform();
continue;
}
cl_context_properties context_properties[] = {
CL_CONTEXT_PLATFORM,
(cl_context_properties)(platform_)(), 0
};
context_ = cl::Context(dev, context_properties);
device_vec_ = context_.getInfo<CL_CONTEXT_DEVICES>();
bool device_found = false;
for (std::size_t d = 0; d != device_vec_.size(); ++d) {
std::string dname;
device_vec_[d].getInfo(CL_DEVICE_NAME, &dname);
if (CheckOpenCLDeviceTrait<ID>::check(dname)) {
device_ = device_vec_[d];
device_found = true;
break;
}
}
if (!device_found) {
platform_ = cl::Platform();
context_ = cl::Context();
device_ = cl::Device();
continue;
}
command_queue_ = cl::CommandQueue(context_, device_, 0);
setup_ = true;
break;
} catch (cl::Error) {
platform_ = cl::Platform();
context_ = cl::Context();
device_ = cl::Device();
command_queue_ = cl::CommandQueue();
device_vec_.clear();
}
}
}
template <typename CLType>
CLType *read_buffer_pool (std::size_t num) const
{
std::size_t new_bytes = num * sizeof(CLType);
if (new_bytes > read_buffer_pool_bytes_) {
std::free(read_buffer_pool_);
read_buffer_pool_ = std::malloc(new_bytes);
if (!read_buffer_pool_ && new_bytes)
throw std::bad_alloc();
read_buffer_pool_bytes_ = new_bytes;
}
return reinterpret_cast<CLType *>(read_buffer_pool_);
}
template <typename CLType>
CLType *write_buffer_pool (std::size_t num) const
{
std::size_t new_bytes = num * sizeof(CLType);
if (new_bytes > write_buffer_pool_bytes_) {
std::free(write_buffer_pool_);
write_buffer_pool_ = std::malloc(new_bytes);
if (!write_buffer_pool_ && new_bytes)
throw std::bad_alloc();
write_buffer_pool_bytes_ = new_bytes;
}
return reinterpret_cast<CLType *>(write_buffer_pool_);
}
cl::NDRange get_global_nd_range (
std::size_t global_size, std::size_t local_size) const
{
return (local_size && global_size % local_size) ?
cl::NDRange((global_size / local_size + 1) * local_size):
cl::NDRange(global_size);
}
cl::NDRange get_local_nd_range (
std::size_t global_size, std::size_t local_size) const
{
return local_size ? cl::NDRange(local_size) : cl::NullRange;
}
}; // clss CLManager
} // namespace vsmc
#endif // VSMC_UTILITY_CL_MANAGER_HPP
<|endoftext|> |
<commit_before>/*!
\copyright (c) RDO-Team, 2012
\file function.h
\author ([email protected])
\date 14.12.2012
\brief -
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
#include "simulator/compiler/parser/pch.h"
// ----------------------------------------------------------------------- INCLUDES
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/range/algorithm/find_if.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/compiler/parser/src/function/function.h"
#include "simulator/compiler/parser/rdoparser.h"
// --------------------------------------------------------------------------------
OPEN_RDO_PARSER_NAMESPACE
Function::Function(CREF(LPTypeInfo) pReturnType, CREF(RDOParserSrcInfo) srcInfo)
: RDOParserSrcInfo(srcInfo)
, m_pReturnType(pReturnType)
{
ASSERT(m_pReturnType);
}
Function::~Function()
{}
void Function::setCall(CREF(rdo::runtime::LPRDOCalc) pCalc)
{
ASSERT(!m_pCallpCalc);
ASSERT(pCalc);
m_pCallpCalc = pCalc;
}
LPExpression Function::expression() const
{
ASSERT(m_pCallpCalc);
LPExpression pExpression = rdo::Factory<Expression>::create(
rdo::Factory<TypeInfo>::create(m_pFunctionType, m_pFunctionType->src_info()),
m_pCallpCalc,
src_info()
);
ASSERT(pExpression);
return pExpression;
}
void Function::pushContext()
{
RDOParser::s_parser()->contextStack()->push(this);
}
void Function::popContext()
{
RDOParser::s_parser()->contextStack()->pop_safe<Function>();
}
void Function::pushParamDefinitionContext()
{
LPContextParamDefinition pContextParamDefinition = rdo::Factory<ContextParamDefinition>::create(
boost::bind(&Function::onPushParam, this, _1)
);
ASSERT(pContextParamDefinition);
RDOParser::s_parser()->contextStack()->push(pContextParamDefinition);
}
void Function::popParamDefinitionContext()
{
RDOParser::s_parser()->contextStack()->pop_safe<ContextParamDefinition>();
m_pFunctionType = generateType();
ASSERT(m_pFunctionType);
}
void Function::onPushParam(CREF(LPRDOParam) pParam)
{
ASSERT(pParam);
LPRDOParam pParamPrev = findParam(pParam->name());
if (pParamPrev)
{
RDOParser::s_parser()->error().push_only(pParam->src_info(), rdo::format(_T(" : %s"), pParam->name().c_str()));
RDOParser::s_parser()->error().push_only(pParamPrev->src_info(), _T(". "));
RDOParser::s_parser()->error().push_done();
}
m_paramList.push_back(pParam);
}
LPRDOParam Function::findParam(CREF(tstring) paramName) const
{
ParamList::const_iterator it = find(paramName);
return it != m_paramList.end()
? *it
: LPRDOParam(NULL);
}
Function::ParamID Function::findParamID(CREF(tstring) paramName) const
{
ParamList::const_iterator it = find(paramName);
return it != m_paramList.end()
? it - m_paramList.begin()
: ParamID();
}
Function::ParamList::const_iterator Function::find(CREF(tstring) paramName) const
{
return boost::range::find_if(m_paramList, compareName<RDOParam>(paramName));
}
LPFunctionType Function::generateType() const
{
ASSERT(m_pReturnType);
FunctionParamType::ParamList paramTypeList;
BOOST_FOREACH(const LPRDOParam& pParam, m_paramList)
{
paramTypeList.push_back(pParam->getTypeInfo());
}
LPFunctionParamType pParamType = rdo::Factory<FunctionParamType>::create(paramTypeList, src_info());
ASSERT(pParamType);
return rdo::Factory<FunctionType>::create(m_pReturnType, pParamType, src_info());
}
void Function::pushFunctionBodyContext()
{
ASSERT(!m_pContextMemory);
m_pContextMemory = rdo::Factory<ContextMemory>::create();
ASSERT(m_pContextMemory);
RDOParser::s_parser()->contextStack()->push(m_pContextMemory);
ContextMemory::push();
}
void Function::popFunctionBodyContext()
{
ContextMemory::pop();
RDOParser::s_parser()->contextStack()->pop_safe<ContextMemory>();
}
Context::FindResult Function::onFindContext(CREF(LPRDOValue) pValue) const
{
ASSERT(pValue);
LPRDOParam pParam = findParam(pValue->value().getIdentificator());
if (pParam)
{
rdo::runtime::RDOType::TypeID typeID = pParam->getTypeInfo()->type()->typeID();
if (typeID == rdo::runtime::RDOType::t_identificator || typeID == rdo::runtime::RDOType::t_unknow)
{
RDOParser::s_parser()->error().push_only(
pValue->src_info(),
rdo::format(_T(" '%s' "), pValue->src_info().src_text().c_str())
);
RDOParser::s_parser()->error().push_only(pParam->getTypeInfo()->src_info(), _T(". "));
RDOParser::s_parser()->error().push_done();
}
ParamID paramID = findParamID(pValue->value().getIdentificator());
ASSERT(paramID.is_initialized());
LPExpression pExpression = rdo::Factory<Expression>::create(
pParam->getTypeInfo(),
rdo::Factory<rdo::runtime::RDOCalcFuncParam>::create(*paramID, pParam->src_info()),
pValue->src_info()
);
ASSERT(pExpression);
return Context::FindResult(const_cast<PTR(Function)>(this), pExpression, pValue, pParam);
}
return Context::FindResult();
}
CLOSE_RDO_PARSER_NAMESPACE
<commit_msg> - добавлена инициализация пустого списка параметров через void<commit_after>/*!
\copyright (c) RDO-Team, 2012
\file function.h
\author ([email protected])
\date 14.12.2012
\brief -
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
#include "simulator/compiler/parser/pch.h"
// ----------------------------------------------------------------------- INCLUDES
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/range/algorithm/find_if.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/compiler/parser/src/function/function.h"
#include "simulator/compiler/parser/rdoparser.h"
// --------------------------------------------------------------------------------
OPEN_RDO_PARSER_NAMESPACE
Function::Function(CREF(LPTypeInfo) pReturnType, CREF(RDOParserSrcInfo) srcInfo)
: RDOParserSrcInfo(srcInfo)
, m_pReturnType(pReturnType)
{
ASSERT(m_pReturnType);
}
Function::~Function()
{}
void Function::setCall(CREF(rdo::runtime::LPRDOCalc) pCalc)
{
ASSERT(!m_pCallpCalc);
ASSERT(pCalc);
m_pCallpCalc = pCalc;
}
LPExpression Function::expression() const
{
ASSERT(m_pCallpCalc);
LPExpression pExpression = rdo::Factory<Expression>::create(
rdo::Factory<TypeInfo>::create(m_pFunctionType, m_pFunctionType->src_info()),
m_pCallpCalc,
src_info()
);
ASSERT(pExpression);
return pExpression;
}
void Function::pushContext()
{
RDOParser::s_parser()->contextStack()->push(this);
}
void Function::popContext()
{
RDOParser::s_parser()->contextStack()->pop_safe<Function>();
}
void Function::pushParamDefinitionContext()
{
LPContextParamDefinition pContextParamDefinition = rdo::Factory<ContextParamDefinition>::create(
boost::bind(&Function::onPushParam, this, _1)
);
ASSERT(pContextParamDefinition);
RDOParser::s_parser()->contextStack()->push(pContextParamDefinition);
}
void Function::popParamDefinitionContext()
{
RDOParser::s_parser()->contextStack()->pop_safe<ContextParamDefinition>();
m_pFunctionType = generateType();
ASSERT(m_pFunctionType);
}
void Function::onPushParam(CREF(LPRDOParam) pParam)
{
ASSERT(pParam);
LPRDOParam pParamPrev = findParam(pParam->name());
if (pParamPrev)
{
RDOParser::s_parser()->error().push_only(pParam->src_info(), rdo::format(_T(" : %s"), pParam->name().c_str()));
RDOParser::s_parser()->error().push_only(pParamPrev->src_info(), _T(". "));
RDOParser::s_parser()->error().push_done();
}
m_paramList.push_back(pParam);
}
LPRDOParam Function::findParam(CREF(tstring) paramName) const
{
ParamList::const_iterator it = find(paramName);
return it != m_paramList.end()
? *it
: LPRDOParam(NULL);
}
Function::ParamID Function::findParamID(CREF(tstring) paramName) const
{
ParamList::const_iterator it = find(paramName);
return it != m_paramList.end()
? it - m_paramList.begin()
: ParamID();
}
Function::ParamList::const_iterator Function::find(CREF(tstring) paramName) const
{
return boost::range::find_if(m_paramList, compareName<RDOParam>(paramName));
}
LPFunctionType Function::generateType() const
{
ASSERT(m_pReturnType);
FunctionParamType::ParamList paramTypeList;
BOOST_FOREACH(const LPRDOParam& pParam, m_paramList)
{
paramTypeList.push_back(pParam->getTypeInfo());
}
if (paramTypeList.empty())
{
paramTypeList.push_back(
rdo::Factory<TypeInfo>::delegate<RDOType__void>(src_info())
);
}
LPFunctionParamType pParamType = rdo::Factory<FunctionParamType>::create(paramTypeList, src_info());
ASSERT(pParamType);
return rdo::Factory<FunctionType>::create(m_pReturnType, pParamType, src_info());
}
void Function::pushFunctionBodyContext()
{
ASSERT(!m_pContextMemory);
m_pContextMemory = rdo::Factory<ContextMemory>::create();
ASSERT(m_pContextMemory);
RDOParser::s_parser()->contextStack()->push(m_pContextMemory);
ContextMemory::push();
}
void Function::popFunctionBodyContext()
{
ContextMemory::pop();
RDOParser::s_parser()->contextStack()->pop_safe<ContextMemory>();
}
Context::FindResult Function::onFindContext(CREF(LPRDOValue) pValue) const
{
ASSERT(pValue);
LPRDOParam pParam = findParam(pValue->value().getIdentificator());
if (pParam)
{
rdo::runtime::RDOType::TypeID typeID = pParam->getTypeInfo()->type()->typeID();
if (typeID == rdo::runtime::RDOType::t_identificator || typeID == rdo::runtime::RDOType::t_unknow)
{
RDOParser::s_parser()->error().push_only(
pValue->src_info(),
rdo::format(_T(" '%s' "), pValue->src_info().src_text().c_str())
);
RDOParser::s_parser()->error().push_only(pParam->getTypeInfo()->src_info(), _T(". "));
RDOParser::s_parser()->error().push_done();
}
ParamID paramID = findParamID(pValue->value().getIdentificator());
ASSERT(paramID.is_initialized());
LPExpression pExpression = rdo::Factory<Expression>::create(
pParam->getTypeInfo(),
rdo::Factory<rdo::runtime::RDOCalcFuncParam>::create(*paramID, pParam->src_info()),
pValue->src_info()
);
ASSERT(pExpression);
return Context::FindResult(const_cast<PTR(Function)>(this), pExpression, pValue, pParam);
}
return Context::FindResult();
}
CLOSE_RDO_PARSER_NAMESPACE
<|endoftext|> |
<commit_before>#include "midiconnectionsmodel.h"
#include "iomidi.h"
#include <QtDebug>
bool operator==(const snd_seq_addr_t& lhs, const snd_seq_addr_t& rhs) {
return lhs.client == rhs.client && lhs.port == rhs.port;
}
MidiConnectionsModel::MidiConnectionsModel(IOMidi* io) :
QAbstractListModel(io),
m_io(io)
{
Q_CHECK_PTR(m_io);
connect(
m_io,
&IOMidi::eventReceived,
this,
&MidiConnectionsModel::handleMidiEvent);
connect(
this,
&MidiConnectionsModel::dataChanged,
[=]() {
emit connectedPortChanged(connectedPort());
emit connectedChanged(connected());
emit externallyManagedChanged(externallyManaged());
}
);
m_addrs.append({0, 0}); // Row for disconnect choice
// Loop from already connected clients and ports to populate the addresses list
snd_seq_client_info_t *cinfo;
snd_seq_client_info_alloca(&cinfo);
snd_seq_port_info_t *pinfo;
snd_seq_port_info_alloca(&pinfo);
snd_seq_client_info_set_client(cinfo, -1);
while (snd_seq_query_next_client(m_io->handle(), cinfo) >= 0) {
if (!acceptClient(cinfo)) {
continue;
}
snd_seq_port_info_set_client(pinfo, snd_seq_client_info_get_client(cinfo));
snd_seq_port_info_set_port(pinfo, -1);
while (snd_seq_query_next_port(m_io->handle(), pinfo) >= 0) {
if (!acceptPort(pinfo)) {
continue;
}
const snd_seq_addr_t* addr = snd_seq_port_info_get_addr(pinfo);
Q_CHECK_PTR(addr);
addAddress(addr);
}
}
}
int MidiConnectionsModel::rowCount(const QModelIndex &parent) const {
return parent.isValid() ? 0 : m_addrs.count();
}
QVariant MidiConnectionsModel::data(const QModelIndex &index, int role) const {
if (index.row() == 0) {
if (role == Qt::DisplayRole) {
return "Disconnect";
}
}
if (role == Qt::DisplayRole) {
return portName(index);
}
return QVariant();
}
QModelIndex MidiConnectionsModel::connectedPort() const {
Q_ASSERT(m_addrs.count() > 0);
QModelIndex ret = index(0);
for (int r = 1 ; r < m_addrs.count() ; ++r) {
switch (portConnection(m_addrs[r])) {
case Direction::Disconnected:
break;
// Partially connected, done externally
case Direction::From:
case Direction::To:
return QModelIndex();
// If a second addr is connected both ways, done externally
case Direction::BothWays:
if (ret.row() != 0) {
return QModelIndex();
}
ret = index(r);
break;
}
}
return ret;
}
bool MidiConnectionsModel::connected() const {
for (int r = 0 ; r < m_addrs.count() ; ++r) {
if (portConnection(m_addrs[r]) > Direction::Disconnected) {
return true;
}
}
return false;
}
bool MidiConnectionsModel::externallyManaged() const {
return connected() && !connectedPort().isValid();
}
void MidiConnectionsModel::connectPort(const QModelIndex &idx) {
Q_ASSERT(idx.isValid());
disconnectAllPorts();
if (idx.row() > 0) {
connectPort(m_addrs[idx.row()]);
}
emit dataChanged(index(0), index(m_addrs.count()));
}
void MidiConnectionsModel::disconnectAllPorts() const {
Q_CHECK_PTR(m_io);
snd_seq_query_subscribe_t *subs;
snd_seq_query_subscribe_alloca(&subs);
const snd_seq_addr_t ownaddr = {m_io->clientId(), m_io->portId()};
snd_seq_query_subscribe_set_root(subs, &ownaddr);
snd_seq_addr_t addr;
snd_seq_query_subscribe_set_index(subs, 0);
snd_seq_query_subscribe_set_type(subs, SND_SEQ_QUERY_SUBS_READ);
while (snd_seq_query_port_subscribers(m_io->handle(), subs) >= 0) {
addr = *snd_seq_query_subscribe_get_addr(subs);
if (snd_seq_disconnect_to(m_io->handle(), m_io->portId(), addr.client, addr.port)) {
qWarning() << "Cannot disconnect to" << addr.client << addr.port;
}
}
snd_seq_query_subscribe_set_index(subs, 0);
snd_seq_query_subscribe_set_type(subs, SND_SEQ_QUERY_SUBS_WRITE);
while (snd_seq_query_port_subscribers(m_io->handle(), subs) >= 0) {
addr = *snd_seq_query_subscribe_get_addr(subs);
if (snd_seq_disconnect_from(m_io->handle(), m_io->portId(), addr.client, addr.port)) {
qWarning() << "Cannot disconnect from" << addr.client << addr.port;
}
}
}
void MidiConnectionsModel::connectPort(const snd_seq_addr_t &addr) {
Q_CHECK_PTR(m_io);
if (snd_seq_connect_from(m_io->handle(), m_io->portId(), addr.client, addr.port) < 0) {
qWarning() << "Cannot connect from";
}
if (snd_seq_connect_to(m_io->handle(), m_io->portId(), addr.client, addr.port) < 0) {
qWarning() << "Cannot connect to";
}
}
void MidiConnectionsModel::handleMidiEvent(const snd_seq_event_t* ev) {
Q_CHECK_PTR(m_io);
Q_CHECK_PTR(ev);
const snd_seq_addr_t ownaddr = {m_io->clientId(), m_io->portId()};
switch (ev->type) {
case SND_SEQ_EVENT_PORT_START:
return addAddressIfAccepted(&ev->data.addr);
case SND_SEQ_EVENT_PORT_EXIT:
return removeAddressIfAccepted(&ev->data.addr);
case SND_SEQ_EVENT_PORT_CHANGE:
return notifyDataChangedForAddress(&ev->data.addr);
case SND_SEQ_EVENT_PORT_SUBSCRIBED:
case SND_SEQ_EVENT_PORT_UNSUBSCRIBED:
if (ownaddr == ev->data.connect.sender || ownaddr == ev->data.connect.dest) {
if (ownaddr == ev->data.connect.sender) {
return notifyDataChangedForAddress(&ev->data.connect.dest);
}
if (ownaddr == ev->data.connect.dest) {
return notifyDataChangedForAddress(&ev->data.connect.sender);
}
}
return;
case SND_SEQ_EVENT_CLIENT_START:
case SND_SEQ_EVENT_CLIENT_EXIT:
emit connectedPortChanged(connectedPort());
return;
default:
return;
}
}
void MidiConnectionsModel::addAddressIfAccepted(const snd_seq_addr_t *addr) {
Q_CHECK_PTR(addr);
if (acceptAddress(addr)) {
addAddress(addr);
}
}
void MidiConnectionsModel::removeAddressIfAccepted(const snd_seq_addr_t *addr) {
Q_CHECK_PTR(addr);
const int r = m_addrs.indexOf(*addr);
if (r >= 0) {
beginRemoveRows(QModelIndex(), r, r);
m_addrs.removeAt(r);
endRemoveRows();
}
}
void MidiConnectionsModel::notifyDataChangedForAddress(const snd_seq_addr_t *addr) {
Q_CHECK_PTR(addr);
const int r = m_addrs.indexOf(*addr);
if (r >= 0) {
const QModelIndex idx = index(r);
emit dataChanged(idx, idx);
}
}
void MidiConnectionsModel::addAddress(const snd_seq_addr_t *addr) {
Q_CHECK_PTR(addr);
Q_ASSERT(!m_addrs.contains(*addr));
beginInsertRows(QModelIndex(), m_addrs.count(), m_addrs.count());
m_addrs.append(*addr);
endInsertRows();
}
bool MidiConnectionsModel::acceptAddress(const snd_seq_addr_t *addr) const {
Q_CHECK_PTR(addr);
snd_seq_client_info_t *cinfo;
snd_seq_client_info_alloca(&cinfo);
if (snd_seq_get_any_client_info(m_io->handle(), addr->client, cinfo) < 0 ||
!acceptClient(cinfo)) {
return false;
}
snd_seq_port_info_t *pinfo;
snd_seq_port_info_alloca(&pinfo);
return snd_seq_get_any_port_info(m_io->handle(), addr->client, addr->port, pinfo) == 0 &&
acceptPort(pinfo);
}
bool MidiConnectionsModel::acceptClient(const snd_seq_client_info_t *info) const {
Q_CHECK_PTR(m_io);
Q_CHECK_PTR(info);
const int id = snd_seq_client_info_get_client(info);
return id != m_io->clientId() && id != SND_SEQ_CLIENT_SYSTEM;
}
bool MidiConnectionsModel::acceptPort(const snd_seq_port_info_t *info) const {
Q_CHECK_PTR(info);
const unsigned int caps = snd_seq_port_info_get_capability(info);
return !(caps & SND_SEQ_PORT_CAP_NO_EXPORT) &&
caps & SND_SEQ_PORT_CAP_READ &&
caps & SND_SEQ_PORT_CAP_WRITE;
}
QString MidiConnectionsModel::portName(const QModelIndex& index) const {
Q_ASSERT(index.isValid());
const snd_seq_addr_t &addr = m_addrs[index.row()];
snd_seq_port_info_t *info;
snd_seq_port_info_alloca(&info);
const int res = snd_seq_get_any_port_info(m_io->handle(), addr.client, addr.port, info);
Q_UNUSED(res);
Q_ASSERT(res >= 0);
return snd_seq_port_info_get_name(info);
}
MidiConnectionsModel::Directions MidiConnectionsModel::portConnection(const QModelIndex& index) const {
Q_CHECK_PTR(m_io);
Q_ASSERT(index.isValid());
return portConnection(m_addrs[index.row()]);
}
MidiConnectionsModel::Directions MidiConnectionsModel::portConnection(const snd_seq_addr_t& addr) const {
Q_CHECK_PTR(m_io);
MidiConnectionsModel::Directions ret = Direction::Disconnected;
const snd_seq_addr_t ownaddr = {m_io->clientId(), m_io->portId()};
snd_seq_port_subscribe_t *subs;
snd_seq_port_subscribe_alloca(&subs);
snd_seq_port_subscribe_set_sender(subs, &ownaddr);
snd_seq_port_subscribe_set_dest(subs, &addr);
if (snd_seq_get_port_subscription(m_io->handle(), subs) == 0) {
ret |= Direction::To;
}
snd_seq_port_subscribe_set_sender(subs, &addr);
snd_seq_port_subscribe_set_dest(subs, &ownaddr);
if (snd_seq_get_port_subscription(m_io->handle(), subs) == 0) {
ret |= Direction::From;
}
return ret;
}
<commit_msg>Fix bad return value check<commit_after>#include "midiconnectionsmodel.h"
#include "iomidi.h"
#include <QtDebug>
bool operator==(const snd_seq_addr_t& lhs, const snd_seq_addr_t& rhs) {
return lhs.client == rhs.client && lhs.port == rhs.port;
}
MidiConnectionsModel::MidiConnectionsModel(IOMidi* io) :
QAbstractListModel(io),
m_io(io)
{
Q_CHECK_PTR(m_io);
connect(
m_io,
&IOMidi::eventReceived,
this,
&MidiConnectionsModel::handleMidiEvent);
connect(
this,
&MidiConnectionsModel::dataChanged,
[=]() {
emit connectedPortChanged(connectedPort());
emit connectedChanged(connected());
emit externallyManagedChanged(externallyManaged());
}
);
m_addrs.append({0, 0}); // Row for disconnect choice
// Loop from already connected clients and ports to populate the addresses list
snd_seq_client_info_t *cinfo;
snd_seq_client_info_alloca(&cinfo);
snd_seq_port_info_t *pinfo;
snd_seq_port_info_alloca(&pinfo);
snd_seq_client_info_set_client(cinfo, -1);
while (snd_seq_query_next_client(m_io->handle(), cinfo) >= 0) {
if (!acceptClient(cinfo)) {
continue;
}
snd_seq_port_info_set_client(pinfo, snd_seq_client_info_get_client(cinfo));
snd_seq_port_info_set_port(pinfo, -1);
while (snd_seq_query_next_port(m_io->handle(), pinfo) >= 0) {
if (!acceptPort(pinfo)) {
continue;
}
const snd_seq_addr_t* addr = snd_seq_port_info_get_addr(pinfo);
Q_CHECK_PTR(addr);
addAddress(addr);
}
}
}
int MidiConnectionsModel::rowCount(const QModelIndex &parent) const {
return parent.isValid() ? 0 : m_addrs.count();
}
QVariant MidiConnectionsModel::data(const QModelIndex &index, int role) const {
if (index.row() == 0) {
if (role == Qt::DisplayRole) {
return "Disconnect";
}
}
if (role == Qt::DisplayRole) {
return portName(index);
}
return QVariant();
}
QModelIndex MidiConnectionsModel::connectedPort() const {
Q_ASSERT(m_addrs.count() > 0);
QModelIndex ret = index(0);
for (int r = 1 ; r < m_addrs.count() ; ++r) {
switch (portConnection(m_addrs[r])) {
case Direction::Disconnected:
break;
// Partially connected, done externally
case Direction::From:
case Direction::To:
return QModelIndex();
// If a second addr is connected both ways, done externally
case Direction::BothWays:
if (ret.row() != 0) {
return QModelIndex();
}
ret = index(r);
break;
}
}
return ret;
}
bool MidiConnectionsModel::connected() const {
for (int r = 0 ; r < m_addrs.count() ; ++r) {
if (portConnection(m_addrs[r]) > Direction::Disconnected) {
return true;
}
}
return false;
}
bool MidiConnectionsModel::externallyManaged() const {
return connected() && !connectedPort().isValid();
}
void MidiConnectionsModel::connectPort(const QModelIndex &idx) {
Q_ASSERT(idx.isValid());
disconnectAllPorts();
if (idx.row() > 0) {
connectPort(m_addrs[idx.row()]);
}
emit dataChanged(index(0), index(m_addrs.count()));
}
void MidiConnectionsModel::disconnectAllPorts() const {
Q_CHECK_PTR(m_io);
snd_seq_query_subscribe_t *subs;
snd_seq_query_subscribe_alloca(&subs);
const snd_seq_addr_t ownaddr = {m_io->clientId(), m_io->portId()};
snd_seq_query_subscribe_set_root(subs, &ownaddr);
snd_seq_addr_t addr;
snd_seq_query_subscribe_set_index(subs, 0);
snd_seq_query_subscribe_set_type(subs, SND_SEQ_QUERY_SUBS_READ);
while (snd_seq_query_port_subscribers(m_io->handle(), subs) >= 0) {
addr = *snd_seq_query_subscribe_get_addr(subs);
if (snd_seq_disconnect_to(m_io->handle(), m_io->portId(), addr.client, addr.port) < 0) {
qWarning() << "Cannot disconnect to" << addr.client << addr.port;
}
}
snd_seq_query_subscribe_set_index(subs, 0);
snd_seq_query_subscribe_set_type(subs, SND_SEQ_QUERY_SUBS_WRITE);
while (snd_seq_query_port_subscribers(m_io->handle(), subs) >= 0) {
addr = *snd_seq_query_subscribe_get_addr(subs);
if (snd_seq_disconnect_from(m_io->handle(), m_io->portId(), addr.client, addr.port) < 0) {
qWarning() << "Cannot disconnect from" << addr.client << addr.port;
}
}
}
void MidiConnectionsModel::connectPort(const snd_seq_addr_t &addr) {
Q_CHECK_PTR(m_io);
if (snd_seq_connect_from(m_io->handle(), m_io->portId(), addr.client, addr.port) < 0) {
qWarning() << "Cannot connect from";
}
if (snd_seq_connect_to(m_io->handle(), m_io->portId(), addr.client, addr.port) < 0) {
qWarning() << "Cannot connect to";
}
}
void MidiConnectionsModel::handleMidiEvent(const snd_seq_event_t* ev) {
Q_CHECK_PTR(m_io);
Q_CHECK_PTR(ev);
const snd_seq_addr_t ownaddr = {m_io->clientId(), m_io->portId()};
switch (ev->type) {
case SND_SEQ_EVENT_PORT_START:
return addAddressIfAccepted(&ev->data.addr);
case SND_SEQ_EVENT_PORT_EXIT:
return removeAddressIfAccepted(&ev->data.addr);
case SND_SEQ_EVENT_PORT_CHANGE:
return notifyDataChangedForAddress(&ev->data.addr);
case SND_SEQ_EVENT_PORT_SUBSCRIBED:
case SND_SEQ_EVENT_PORT_UNSUBSCRIBED:
if (ownaddr == ev->data.connect.sender || ownaddr == ev->data.connect.dest) {
if (ownaddr == ev->data.connect.sender) {
return notifyDataChangedForAddress(&ev->data.connect.dest);
}
if (ownaddr == ev->data.connect.dest) {
return notifyDataChangedForAddress(&ev->data.connect.sender);
}
}
return;
case SND_SEQ_EVENT_CLIENT_START:
case SND_SEQ_EVENT_CLIENT_EXIT:
emit connectedPortChanged(connectedPort());
return;
default:
return;
}
}
void MidiConnectionsModel::addAddressIfAccepted(const snd_seq_addr_t *addr) {
Q_CHECK_PTR(addr);
if (acceptAddress(addr)) {
addAddress(addr);
}
}
void MidiConnectionsModel::removeAddressIfAccepted(const snd_seq_addr_t *addr) {
Q_CHECK_PTR(addr);
const int r = m_addrs.indexOf(*addr);
if (r >= 0) {
beginRemoveRows(QModelIndex(), r, r);
m_addrs.removeAt(r);
endRemoveRows();
}
}
void MidiConnectionsModel::notifyDataChangedForAddress(const snd_seq_addr_t *addr) {
Q_CHECK_PTR(addr);
const int r = m_addrs.indexOf(*addr);
if (r >= 0) {
const QModelIndex idx = index(r);
emit dataChanged(idx, idx);
}
}
void MidiConnectionsModel::addAddress(const snd_seq_addr_t *addr) {
Q_CHECK_PTR(addr);
Q_ASSERT(!m_addrs.contains(*addr));
beginInsertRows(QModelIndex(), m_addrs.count(), m_addrs.count());
m_addrs.append(*addr);
endInsertRows();
}
bool MidiConnectionsModel::acceptAddress(const snd_seq_addr_t *addr) const {
Q_CHECK_PTR(addr);
snd_seq_client_info_t *cinfo;
snd_seq_client_info_alloca(&cinfo);
if (snd_seq_get_any_client_info(m_io->handle(), addr->client, cinfo) < 0 ||
!acceptClient(cinfo)) {
return false;
}
snd_seq_port_info_t *pinfo;
snd_seq_port_info_alloca(&pinfo);
return snd_seq_get_any_port_info(m_io->handle(), addr->client, addr->port, pinfo) == 0 &&
acceptPort(pinfo);
}
bool MidiConnectionsModel::acceptClient(const snd_seq_client_info_t *info) const {
Q_CHECK_PTR(m_io);
Q_CHECK_PTR(info);
const int id = snd_seq_client_info_get_client(info);
return id != m_io->clientId() && id != SND_SEQ_CLIENT_SYSTEM;
}
bool MidiConnectionsModel::acceptPort(const snd_seq_port_info_t *info) const {
Q_CHECK_PTR(info);
const unsigned int caps = snd_seq_port_info_get_capability(info);
return !(caps & SND_SEQ_PORT_CAP_NO_EXPORT) &&
caps & SND_SEQ_PORT_CAP_READ &&
caps & SND_SEQ_PORT_CAP_WRITE;
}
QString MidiConnectionsModel::portName(const QModelIndex& index) const {
Q_ASSERT(index.isValid());
const snd_seq_addr_t &addr = m_addrs[index.row()];
snd_seq_port_info_t *info;
snd_seq_port_info_alloca(&info);
const int res = snd_seq_get_any_port_info(m_io->handle(), addr.client, addr.port, info);
Q_UNUSED(res);
Q_ASSERT(res >= 0);
return snd_seq_port_info_get_name(info);
}
MidiConnectionsModel::Directions MidiConnectionsModel::portConnection(const QModelIndex& index) const {
Q_CHECK_PTR(m_io);
Q_ASSERT(index.isValid());
return portConnection(m_addrs[index.row()]);
}
MidiConnectionsModel::Directions MidiConnectionsModel::portConnection(const snd_seq_addr_t& addr) const {
Q_CHECK_PTR(m_io);
MidiConnectionsModel::Directions ret = Direction::Disconnected;
const snd_seq_addr_t ownaddr = {m_io->clientId(), m_io->portId()};
snd_seq_port_subscribe_t *subs;
snd_seq_port_subscribe_alloca(&subs);
snd_seq_port_subscribe_set_sender(subs, &ownaddr);
snd_seq_port_subscribe_set_dest(subs, &addr);
if (snd_seq_get_port_subscription(m_io->handle(), subs) == 0) {
ret |= Direction::To;
}
snd_seq_port_subscribe_set_sender(subs, &addr);
snd_seq_port_subscribe_set_dest(subs, &ownaddr);
if (snd_seq_get_port_subscription(m_io->handle(), subs) == 0) {
ret |= Direction::From;
}
return ret;
}
<|endoftext|> |
<commit_before>#include "shader.h"
#include "glslUtility.h"
using namespace glslUtility;
ShaderProgram::ShaderProgram()
{
program = 0;
vs = 0;
fs = 0;
gs = 0;
}
ShaderProgram::~ShaderProgram()
{
glDeleteProgram( program );
glDeleteShader( vs );
glDeleteShader( fs );
glDeleteShader( gs );
}
int ShaderProgram::init(const char* vs_source, const char* fs_source, const char* gs_source )
{
//load shader sources and compile
shaders_t shaderSet = loadShaders( vs_source, fs_source, gs_source );
vs = shaderSet.vertex;
fs = shaderSet.fragment;
gs = shaderSet.geometry;
//create program
program = glCreateProgram();
//attach shader
attachAndLinkProgram( program, shaderSet );
return 0;
}
void ShaderProgram::use()
{
glUseProgram( program );
}
void ShaderProgram::unuse()
{
glUseProgram( 0 );
}
void ShaderProgram::setParameter( shaderAttrib type, void* param, char* name )
{
switch( type )
{
case f1:
glUniform1f( glGetUniformLocation( program, name ), *((float*)param) );
break;
case fv3:
glUniform3fv( glGetUniformLocation( program, name ), 1, (float*)param );
break;
case fv4:
glUniform4fv( glGetUniformLocation( program, name ), 1, (float*)param );
break;
case mat4:
glUniformMatrix4fv( glGetUniformLocation( program, name ), 1, GL_FALSE, (float*)param );
break;
case mat3:
glUniformMatrix3fv( glGetUniformLocation( program, name ), 1, GL_FALSE, (float*)param );
break;
}
}<commit_msg>clean bugs on loading shader files<commit_after>// Sparse Voxel Octree and Voxel Cone Tracing
//
// University of Pennsylvania CIS565 final project
// copyright (c) 2013 Cheng-Tso Lin
#include <gl/glew.h>
#include "shader.h"
#include "glslUtility.h"
using namespace glslUtility;
ShaderProgram::ShaderProgram()
{
program = 0;
vs = 0;
fs = 0;
gs = 0;
}
ShaderProgram::~ShaderProgram()
{
glDeleteProgram( program );
glDeleteShader( vs );
glDeleteShader( fs );
glDeleteShader( gs );
}
int ShaderProgram::init(const char* vs_source, const char* fs_source, const char* gs_source )
{
//load shader sources and compile
shaders_t shaderSet = loadShaders( vs_source, fs_source, gs_source );
vs = shaderSet.vertex;
fs = shaderSet.fragment;
gs = shaderSet.geometry;
//create program
program = glCreateProgram();
//attach shader
attachAndLinkProgram( program, shaderSet );
return 0;
}
void ShaderProgram::use()
{
glUseProgram( program );
}
void ShaderProgram::unuse()
{
glUseProgram( 0 );
}
void ShaderProgram::setParameter( shaderAttrib type, void* param, char* name )
{
switch( type )
{
case f1:
glUniform1f( glGetUniformLocation( program, name ), *((float*)param) );
break;
case fv3:
glUniform3fv( glGetUniformLocation( program, name ), 1, (float*)param );
break;
case fv4:
glUniform4fv( glGetUniformLocation( program, name ), 1, (float*)param );
break;
case mat4x4:
glUniformMatrix4fv( glGetUniformLocation( program, name ), 1, GL_FALSE, (float*)param );
break;
case mat3x3:
glUniformMatrix3fv( glGetUniformLocation( program, name ), 1, GL_FALSE, (float*)param );
break;
}
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: vendorbase.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-06-20 00:10:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "osl/file.hxx"
#include "vendorbase.hxx"
#include "util.hxx"
#include "sunjre.hxx"
using namespace std;
using namespace rtl;
using namespace osl;
namespace jfw_plugin
{
rtl::Reference<VendorBase> createInstance(createInstance_func pFunc,
vector<pair<OUString, OUString> > properties);
//##############################################################################
MalformedVersionException::MalformedVersionException()
{}
MalformedVersionException::MalformedVersionException(
const MalformedVersionException & )
{}
MalformedVersionException::~MalformedVersionException()
{}
MalformedVersionException &
MalformedVersionException::operator =(
const MalformedVersionException &)
{
return *this;
}
//##############################################################################
VendorBase::VendorBase(): m_bAccessibility(false)
{
}
char const* const * VendorBase::getJavaExePaths(int* size)
{
static char const * ar[] = {
#ifdef WNT
"java.exe",
"bin/java.exe"
#elif UNX
"java",
"bin/java"
#endif
};
*size = sizeof(ar) / sizeof(char*);
return ar;
}
rtl::Reference<VendorBase> VendorBase::createInstance()
{
VendorBase *pBase = new VendorBase();
return rtl::Reference<VendorBase>(pBase);
}
bool VendorBase::initialize(vector<pair<OUString, OUString> > props)
{
//get java.vendor, java.version, java.home,
//javax.accessibility.assistive_technologies from system properties
OUString sVendor;
typedef vector<pair<OUString, OUString> >::const_iterator it_prop;
OUString sVendorProperty(
RTL_CONSTASCII_USTRINGPARAM("java.vendor"));
OUString sVersionProperty(
RTL_CONSTASCII_USTRINGPARAM("java.version"));
OUString sHomeProperty(
RTL_CONSTASCII_USTRINGPARAM("java.home"));
OUString sAccessProperty(
RTL_CONSTASCII_USTRINGPARAM("javax.accessibility.assistive_technologies"));
bool bVersion = false;
bool bVendor = false;
bool bHome = false;
bool bAccess = false;
typedef vector<pair<OUString, OUString> >::const_iterator it_prop;
for (it_prop i = props.begin(); i != props.end(); i++)
{
if(! bVendor && sVendorProperty.equals(i->first))
{
m_sVendor = i->second;
bVendor = true;
}
else if (!bVersion && sVersionProperty.equals(i->first))
{
m_sVersion = i->second;
bVersion = true;
}
else if (!bHome && sHomeProperty.equals(i->first))
{
OUString fileURL;
if (osl_getFileURLFromSystemPath(i->second.pData,& fileURL.pData) ==
osl_File_E_None)
{
//make sure that the drive letter have all the same case
//otherwise file:///c:/jre and file:///C:/jre produce two
//different objects!!!
if (makeDriveLetterSame( & fileURL))
{
m_sHome = fileURL;
bHome = true;
}
}
}
else if (!bAccess && sAccessProperty.equals(i->first))
{
if (i->second.getLength() > 0)
{
m_bAccessibility = true;
bAccess = true;
}
}
// the javax.accessibility.xxx property may not be set. Therefore we
//must search through all properties.
}
if (!bVersion || !bVendor || !bHome)
return false;
// init m_sRuntimeLibrary
OSL_ASSERT(m_sHome.getLength());
//call virtual function to get the possible paths to the runtime library.
int size = 0;
char const* const* arRtPaths = getRuntimePaths( & size);
vector<OUString> libpaths = getVectorFromCharArray(arRtPaths, size);
bool bRt = false;
typedef vector<OUString>::const_iterator i_path;
for(i_path ip = libpaths.begin(); ip != libpaths.end(); ip++)
{
//Construct an absolute path to the possible runtime
OUString usRt= m_sHome + *ip;
DirectoryItem item;
if(DirectoryItem::get(usRt, item) == File::E_None)
{
//found runtime lib
m_sRuntimeLibrary = usRt;
bRt = true;
break;
}
}
if (!bRt)
return false;
// init m_sLD_LIBRARY_PATH
OSL_ASSERT(m_sHome.getLength());
size = 0;
char const * const * arLDPaths = getLibraryPaths( & size);
vector<OUString> ld_paths = getVectorFromCharArray(arLDPaths, size);
char arSep[]= {SAL_PATHSEPARATOR, 0};
OUString sPathSep= OUString::createFromAscii(arSep);
bool bLdPath = true;
int c = 0;
for(i_path il = ld_paths.begin(); il != ld_paths.end(); il ++, c++)
{
OUString usAbsUrl= m_sHome + *il;
// convert to system path
OUString usSysPath;
if(File::getSystemPathFromFileURL(usAbsUrl, usSysPath) == File::E_None)
{
if(c > 0)
m_sLD_LIBRARY_PATH+= sPathSep;
m_sLD_LIBRARY_PATH+= usSysPath;
}
else
{
bLdPath = false;
break;
}
}
if (bLdPath == false)
return false;
return true;
}
char const* const* VendorBase::getRuntimePaths(int* /*size*/)
{
return NULL;
}
char const* const* VendorBase::getLibraryPaths(int* /*size*/)
{
return NULL;
}
const OUString & VendorBase::getVendor() const
{
return m_sVendor;
}
const OUString & VendorBase::getVersion() const
{
return m_sVersion;
}
const OUString & VendorBase::getHome() const
{
return m_sHome;
}
const OUString & VendorBase::getLibraryPaths() const
{
return m_sLD_LIBRARY_PATH;
}
const OUString & VendorBase::getRuntimeLibrary() const
{
return m_sRuntimeLibrary;
}
bool VendorBase::supportsAccessibility() const
{
return m_bAccessibility;
}
bool VendorBase::needsRestart() const
{
if (getLibraryPaths().getLength() > 0)
return true;
return false;
}
int VendorBase::compareVersions(const rtl::OUString& /*sSecond*/) const
{
OSL_ENSURE(0, "[Java framework] VendorBase::compareVersions must be "
"overridden in derived class.");
return 0;
}
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.16); FILE MERGED 2006/09/01 17:31:40 kaib 1.5.16.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: vendorbase.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-16 17:47:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_jvmfwk.hxx"
#include "osl/file.hxx"
#include "vendorbase.hxx"
#include "util.hxx"
#include "sunjre.hxx"
using namespace std;
using namespace rtl;
using namespace osl;
namespace jfw_plugin
{
rtl::Reference<VendorBase> createInstance(createInstance_func pFunc,
vector<pair<OUString, OUString> > properties);
//##############################################################################
MalformedVersionException::MalformedVersionException()
{}
MalformedVersionException::MalformedVersionException(
const MalformedVersionException & )
{}
MalformedVersionException::~MalformedVersionException()
{}
MalformedVersionException &
MalformedVersionException::operator =(
const MalformedVersionException &)
{
return *this;
}
//##############################################################################
VendorBase::VendorBase(): m_bAccessibility(false)
{
}
char const* const * VendorBase::getJavaExePaths(int* size)
{
static char const * ar[] = {
#ifdef WNT
"java.exe",
"bin/java.exe"
#elif UNX
"java",
"bin/java"
#endif
};
*size = sizeof(ar) / sizeof(char*);
return ar;
}
rtl::Reference<VendorBase> VendorBase::createInstance()
{
VendorBase *pBase = new VendorBase();
return rtl::Reference<VendorBase>(pBase);
}
bool VendorBase::initialize(vector<pair<OUString, OUString> > props)
{
//get java.vendor, java.version, java.home,
//javax.accessibility.assistive_technologies from system properties
OUString sVendor;
typedef vector<pair<OUString, OUString> >::const_iterator it_prop;
OUString sVendorProperty(
RTL_CONSTASCII_USTRINGPARAM("java.vendor"));
OUString sVersionProperty(
RTL_CONSTASCII_USTRINGPARAM("java.version"));
OUString sHomeProperty(
RTL_CONSTASCII_USTRINGPARAM("java.home"));
OUString sAccessProperty(
RTL_CONSTASCII_USTRINGPARAM("javax.accessibility.assistive_technologies"));
bool bVersion = false;
bool bVendor = false;
bool bHome = false;
bool bAccess = false;
typedef vector<pair<OUString, OUString> >::const_iterator it_prop;
for (it_prop i = props.begin(); i != props.end(); i++)
{
if(! bVendor && sVendorProperty.equals(i->first))
{
m_sVendor = i->second;
bVendor = true;
}
else if (!bVersion && sVersionProperty.equals(i->first))
{
m_sVersion = i->second;
bVersion = true;
}
else if (!bHome && sHomeProperty.equals(i->first))
{
OUString fileURL;
if (osl_getFileURLFromSystemPath(i->second.pData,& fileURL.pData) ==
osl_File_E_None)
{
//make sure that the drive letter have all the same case
//otherwise file:///c:/jre and file:///C:/jre produce two
//different objects!!!
if (makeDriveLetterSame( & fileURL))
{
m_sHome = fileURL;
bHome = true;
}
}
}
else if (!bAccess && sAccessProperty.equals(i->first))
{
if (i->second.getLength() > 0)
{
m_bAccessibility = true;
bAccess = true;
}
}
// the javax.accessibility.xxx property may not be set. Therefore we
//must search through all properties.
}
if (!bVersion || !bVendor || !bHome)
return false;
// init m_sRuntimeLibrary
OSL_ASSERT(m_sHome.getLength());
//call virtual function to get the possible paths to the runtime library.
int size = 0;
char const* const* arRtPaths = getRuntimePaths( & size);
vector<OUString> libpaths = getVectorFromCharArray(arRtPaths, size);
bool bRt = false;
typedef vector<OUString>::const_iterator i_path;
for(i_path ip = libpaths.begin(); ip != libpaths.end(); ip++)
{
//Construct an absolute path to the possible runtime
OUString usRt= m_sHome + *ip;
DirectoryItem item;
if(DirectoryItem::get(usRt, item) == File::E_None)
{
//found runtime lib
m_sRuntimeLibrary = usRt;
bRt = true;
break;
}
}
if (!bRt)
return false;
// init m_sLD_LIBRARY_PATH
OSL_ASSERT(m_sHome.getLength());
size = 0;
char const * const * arLDPaths = getLibraryPaths( & size);
vector<OUString> ld_paths = getVectorFromCharArray(arLDPaths, size);
char arSep[]= {SAL_PATHSEPARATOR, 0};
OUString sPathSep= OUString::createFromAscii(arSep);
bool bLdPath = true;
int c = 0;
for(i_path il = ld_paths.begin(); il != ld_paths.end(); il ++, c++)
{
OUString usAbsUrl= m_sHome + *il;
// convert to system path
OUString usSysPath;
if(File::getSystemPathFromFileURL(usAbsUrl, usSysPath) == File::E_None)
{
if(c > 0)
m_sLD_LIBRARY_PATH+= sPathSep;
m_sLD_LIBRARY_PATH+= usSysPath;
}
else
{
bLdPath = false;
break;
}
}
if (bLdPath == false)
return false;
return true;
}
char const* const* VendorBase::getRuntimePaths(int* /*size*/)
{
return NULL;
}
char const* const* VendorBase::getLibraryPaths(int* /*size*/)
{
return NULL;
}
const OUString & VendorBase::getVendor() const
{
return m_sVendor;
}
const OUString & VendorBase::getVersion() const
{
return m_sVersion;
}
const OUString & VendorBase::getHome() const
{
return m_sHome;
}
const OUString & VendorBase::getLibraryPaths() const
{
return m_sLD_LIBRARY_PATH;
}
const OUString & VendorBase::getRuntimeLibrary() const
{
return m_sRuntimeLibrary;
}
bool VendorBase::supportsAccessibility() const
{
return m_bAccessibility;
}
bool VendorBase::needsRestart() const
{
if (getLibraryPaths().getLength() > 0)
return true;
return false;
}
int VendorBase::compareVersions(const rtl::OUString& /*sSecond*/) const
{
OSL_ENSURE(0, "[Java framework] VendorBase::compareVersions must be "
"overridden in derived class.");
return 0;
}
}
<|endoftext|> |
<commit_before>/**
* @file signal.cpp
* @author Albert Uchytil (xuchyt03)
* @brief SignalHandler
*/
#include "signal.hpp"
/**
* Model to print stats.
*/
Simulation* SignalHandler::simulation = NULL;
/**
* Handles received signals.
*/
void SignalHandler::handler(int signum)
{
debug("SignalHandler", "signal handled");
if (SignalHandler::simulation != NULL) {
simulation->PrintStats();
delete simulation;
}
exit(1);
}
/**
* Sets up simulation to print when handling.
*
* @param simulation Model to watch
*/
void SignalHandler::SetupSim(Simulation *simulation)
{
debug("SignalHandler", "setting up simulation for handling");
SignalHandler::simulation = simulation;
}
/**
* Sets up signal handling.
*/
void SignalHandler::SetupHandlers()
{
debug("SignalHandler", "setting up signal handlers");
if (signal((int)SIGTERM, SignalHandler::handler) == SIG_ERR ||
signal((int)SIGQUIT, SignalHandler::handler) == SIG_ERR ||
signal((int)SIGINT, SignalHandler::handler) == SIG_ERR)
std::cerr << "Unable to register signal handlers" << std::endl;
}
<commit_msg>[signal] swithced to simulation insteda of model, hotfix<commit_after>/**
* @file signal.cpp
* @author Albert Uchytil (xuchyt03)
* @brief SignalHandler
*/
#include "signal.hpp"
/**
* Model to print stats.
*/
Simulation* SignalHandler::simulation = NULL;
/**
* Handles received signals.
*/
void SignalHandler::handler(int signum)
{
debug("SignalHandler", "signal handled");
if (SignalHandler::simulation != NULL) {
simulation->PrintStats();
}
exit(1);
}
/**
* Sets up simulation to print when handling.
*
* @param simulation Model to watch
*/
void SignalHandler::SetupSim(Simulation *simulation)
{
debug("SignalHandler", "setting up simulation for handling");
SignalHandler::simulation = simulation;
}
/**
* Sets up signal handling.
*/
void SignalHandler::SetupHandlers()
{
debug("SignalHandler", "setting up signal handlers");
if (signal((int)SIGTERM, SignalHandler::handler) == SIG_ERR ||
signal((int)SIGQUIT, SignalHandler::handler) == SIG_ERR ||
signal((int)SIGINT, SignalHandler::handler) == SIG_ERR)
std::cerr << "Unable to register signal handlers" << std::endl;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <memory>
#include <unordered_map>
using std::swap;
//
// The classes
struct Shape
{
virtual ~Shape()
{
}
virtual double area() const = 0;
virtual double perimeter() const = 0;
};
static const double pi = 3.14159265359;
class Circle : public Shape
{
const double radius_;
public:
double area() const override
{
return pi * radius_ * radius_;
}
double perimeter() const override
{
return 2 * pi * radius_;
}
Circle(double r) : radius_(r)
{
}
};
//
// The C bridge
extern "C" {
void* Circle_new(double r)
{
return new (std::nothrow) Circle(r);
}
void Shape_delete(const void* shape)
{
delete ((const Shape*)shape);
}
double Shape_area(const void* shape)
{
return ((const Shape*)shape)->area();
}
double Shape_perimeter(const void* shape)
{
return ((const Shape*)shape)->perimeter();
}
}
//
// The handles bridge
using HANDLE = const char*;
enum RC
{
LOOKUP_FAIL = -999,
SUCCESS = 0
};
struct TableEntry
{
void* obj_ = nullptr;
void (*del_)(const void*) = nullptr;
TableEntry& operator=(TableEntry&& t)
{
swap(t.obj_, obj_);
swap(t.del_, del_);
t.~TableEntry();
return *this;
}
~TableEntry()
{
if (del_) del_(obj_);
}
};
class HandleTable // not thread-safe
{
std::unordered_map<std::string, TableEntry> handle_table;
public:
struct LookupFailureException : public std::runtime_error
{
LookupFailureException(HANDLE handle) : std::runtime_error(handle)
{
}
};
void InsertOrOverwrite(HANDLE handle, void* object,
void (*deleter)(const void*))
{
TableEntry t;
t.obj_ = object;
t.del_ = deleter;
handle_table[handle] = std::move(t);
}
void* Lookup(HANDLE handle) const
{
auto find_it = handle_table.find(handle);
if (find_it != handle_table.end())
{
return find_it->second.obj_;
}
throw LookupFailureException(handle);
}
void* TryLookup(HANDLE handle) const
{
auto find_it = handle_table.find(handle);
if (find_it != handle_table.end())
{
return find_it->second.obj_;
}
return nullptr;
}
};
static HandleTable handle_table;
extern "C" {
void CircleH_new(HANDLE circle, double r, int* rc)
{
handle_table.InsertOrOverwrite(circle, Circle_new(r), Shape_delete);
*rc = SUCCESS;
}
void ShapeH_delete(HANDLE shape, int* rc)
{
try
{
*rc = SUCCESS;
Shape_delete(handle_table.Lookup(shape));
}
catch (const HandleTable::LookupFailureException& e)
{
*rc = LOOKUP_FAIL;
}
}
double ShapeH_area(HANDLE shape, int* rc)
{
try
{
*rc = SUCCESS;
return Shape_area(handle_table.Lookup(shape));
}
catch (const HandleTable::LookupFailureException& e)
{
*rc = LOOKUP_FAIL;
return 0.0;
}
}
double ShapeH_perimeter(HANDLE shape, int* rc)
{
try
{
*rc = SUCCESS;
return Shape_perimeter(handle_table.Lookup(shape));
}
catch (const HandleTable::LookupFailureException& e)
{
*rc = LOOKUP_FAIL;
return 0.0;
}
}
}
int main(int argc, char* argv[])
{
int rc;
auto name = "myCircle";
CircleH_new(name, 10, &rc);
if (rc != SUCCESS)
{
std::cerr << "Failed to construct circle\n";
return -1;
}
double area = ShapeH_area(name, &rc);
if (rc != SUCCESS)
{
std::cerr << "Failed to get circle area\n";
return -1;
}
std::cout << "Area=" << area << "\n";
double perimeter = ShapeH_perimeter(name, &rc);
if (rc != SUCCESS)
{
std::cerr << "Failed to get circle perimeter\n";
return -1;
}
std::cout << "Perimeter=" << perimeter << "\n";
}
<commit_msg>assert not move assigning to self<commit_after>#include <iostream>
#include <cassert>
#include <memory>
#include <unordered_map>
using std::swap;
//
// The classes
struct Shape
{
virtual ~Shape()
{
}
virtual double area() const = 0;
virtual double perimeter() const = 0;
};
static const double pi = 3.14159265359;
class Circle : public Shape
{
const double radius_;
public:
double area() const override
{
return pi * radius_ * radius_;
}
double perimeter() const override
{
return 2 * pi * radius_;
}
Circle(double r) : radius_(r)
{
}
};
//
// The C bridge
extern "C" {
void* Circle_new(double r)
{
return new (std::nothrow) Circle(r);
}
void Shape_delete(const void* shape)
{
delete ((const Shape*)shape);
}
double Shape_area(const void* shape)
{
return ((const Shape*)shape)->area();
}
double Shape_perimeter(const void* shape)
{
return ((const Shape*)shape)->perimeter();
}
}
//
// The handles bridge
using HANDLE = const char*;
enum RC
{
LOOKUP_FAIL = -999,
SUCCESS = 0
};
struct TableEntry
{
void* obj_ = nullptr;
void (*del_)(const void*) = nullptr;
TableEntry& operator=(TableEntry&& t)
{
assert(&t != this);
swap(t.obj_, obj_);
swap(t.del_, del_);
t.~TableEntry();
return *this;
}
~TableEntry()
{
if (del_) del_(obj_);
}
};
class HandleTable // not thread-safe
{
std::unordered_map<std::string, TableEntry> handle_table;
public:
struct LookupFailureException : public std::runtime_error
{
LookupFailureException(HANDLE handle) : std::runtime_error(handle)
{
}
};
void InsertOrOverwrite(HANDLE handle, void* object,
void (*deleter)(const void*))
{
TableEntry t;
t.obj_ = object;
t.del_ = deleter;
handle_table[handle] = std::move(t);
}
void* Lookup(HANDLE handle) const
{
auto find_it = handle_table.find(handle);
if (find_it != handle_table.end())
{
return find_it->second.obj_;
}
throw LookupFailureException(handle);
}
void* TryLookup(HANDLE handle) const
{
auto find_it = handle_table.find(handle);
if (find_it != handle_table.end())
{
return find_it->second.obj_;
}
return nullptr;
}
};
static HandleTable handle_table;
extern "C" {
void CircleH_new(HANDLE circle, double r, int* rc)
{
handle_table.InsertOrOverwrite(circle, Circle_new(r), Shape_delete);
*rc = SUCCESS;
}
void ShapeH_delete(HANDLE shape, int* rc)
{
try
{
*rc = SUCCESS;
Shape_delete(handle_table.Lookup(shape));
}
catch (const HandleTable::LookupFailureException& e)
{
*rc = LOOKUP_FAIL;
}
}
double ShapeH_area(HANDLE shape, int* rc)
{
try
{
*rc = SUCCESS;
return Shape_area(handle_table.Lookup(shape));
}
catch (const HandleTable::LookupFailureException& e)
{
*rc = LOOKUP_FAIL;
return 0.0;
}
}
double ShapeH_perimeter(HANDLE shape, int* rc)
{
try
{
*rc = SUCCESS;
return Shape_perimeter(handle_table.Lookup(shape));
}
catch (const HandleTable::LookupFailureException& e)
{
*rc = LOOKUP_FAIL;
return 0.0;
}
}
}
int main(int argc, char* argv[])
{
int rc;
auto name = "myCircle";
CircleH_new(name, 10, &rc);
if (rc != SUCCESS)
{
std::cerr << "Failed to construct circle\n";
return -1;
}
double area = ShapeH_area(name, &rc);
if (rc != SUCCESS)
{
std::cerr << "Failed to get circle area\n";
return -1;
}
std::cout << "Area=" << area << "\n";
double perimeter = ShapeH_perimeter(name, &rc);
if (rc != SUCCESS)
{
std::cerr << "Failed to get circle perimeter\n";
return -1;
}
std::cout << "Perimeter=" << perimeter << "\n";
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector <string> Census;
void Census2017(){
// Census.push_back("Name @ GitHub link");
Census.push_back("Allen Comp Sci @ https://github.com/AllenCompSci");
Census.push_back("Mr. Hudson @ https://github.com/theshrewedshrew");
Census.push_back("BEST Team 58 @ https://github.com/BESTTeam58");
Census.push_back("TexasSnow @ https://github.com/TexasSnow");
Census.push_back("hotdogshabab @ https://github.com/hotdogshabab");
Census.push_back("alansunglee @ https://github.com/alansunglee");
Census.push_back("Rahultheman12 @ https://github.com/Rahultheman12");
Census.push_back("spicyboi @ https://github.com/spicyboi");
Census.push_back("John Nguyen @ https://github.com/jawnlovesfreestuff");
Census.push_back("Devin Petersen @ https://github.com/DevinPetersen");
Census.push_back("Cameron Mathis @ https://github.com/Phylux");
}
void printCensus(){
for(int i = 0; i < (int)Census.size(); i++){
cout << "Hello World from "Your name" + Census[i] << "\n";
}
}
void main(){
Census2017();
printCensus();
}
<commit_msg>Update HelloWorld.cpp<commit_after>#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector <string> Census;
void Census2017(){
// Census.push_back("Name @ GitHub link");
Census.push_back("Allen Comp Sci @ https://github.com/AllenCompSci");
Census.push_back("Mr. Hudson @ https://github.com/theshrewedshrew");
Census.push_back("BEST Team 58 @ https://github.com/BESTTeam58");
Census.push_back("TexasSnow @ https://github.com/TexasSnow");
Census.push_back("hotdogshabab @ https://github.com/hotdogshabab");
Census.push_back("alansunglee @ https://github.com/alansunglee");
Census.push_back("Rahultheman12 @ https://github.com/Rahultheman12");
Census.push_back("spicyboi @ https://github.com/spicyboi");
Census.push_back("John Nguyen @ https://github.com/jawnlovesfreestuff");
Census.push_back("Cameron Mathis @ https://github.com/Phylux");
Census.push_back("Samuel Woon @ https://github.com/samuel-w")
}
void printCensus(){
for(int i = 0; i < (int)Census.size(); i++){
cout << "Hello World from "Your name" + Census[i] << "\n";
}
}
void main(){
Census2017();
printCensus();
}
<|endoftext|> |
<commit_before>#include "openmc/source.h"
#include <algorithm> // for move
#include <sstream> // for stringstream
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
#include <dlfcn.h> // for dlopen
#endif
#include <fmt/core.h>
#include "xtensor/xadapt.hpp"
#include "openmc/bank.h"
#include "openmc/cell.h"
#include "openmc/error.h"
#include "openmc/file_utils.h"
#include "openmc/hdf5_interface.h"
#include "openmc/material.h"
#include "openmc/message_passing.h"
#include "openmc/mgxs_interface.h"
#include "openmc/nuclide.h"
#include "openmc/capi.h"
#include "openmc/random_lcg.h"
#include "openmc/search.h"
#include "openmc/settings.h"
#include "openmc/simulation.h"
#include "openmc/state_point.h"
#include "openmc/xml_interface.h"
namespace openmc {
//==============================================================================
// Global variables
//==============================================================================
namespace model {
std::vector<SourceDistribution> external_sources;
}
//==============================================================================
// SourceDistribution implementation
//==============================================================================
SourceDistribution::SourceDistribution(UPtrSpace space, UPtrAngle angle, UPtrDist energy)
: space_{std::move(space)}, angle_{std::move(angle)}, energy_{std::move(energy)} { }
SourceDistribution::SourceDistribution(pugi::xml_node node)
{
// Check for particle type
if (check_for_node(node, "particle")) {
auto temp_str = get_node_value(node, "particle", true, true);
if (temp_str == "neutron") {
particle_ = Particle::Type::neutron;
} else if (temp_str == "photon") {
particle_ = Particle::Type::photon;
settings::photon_transport = true;
} else {
fatal_error(std::string("Unknown source particle type: ") + temp_str);
}
}
// Check for source strength
if (check_for_node(node, "strength")) {
strength_ = std::stod(get_node_value(node, "strength"));
}
// Check for external source file
if (check_for_node(node, "file")) {
// Copy path of source file
settings::path_source = get_node_value(node, "file", false, true);
// Check if source file exists
if (!file_exists(settings::path_source)) {
fatal_error(fmt::format("Source file '{}' does not exist.",
settings::path_source));
}
} else if (check_for_node(node, "library")) {
settings::path_source_library = get_node_value(node, "library", false, true);
// check if it exists
if (!file_exists(settings::path_source_library)) {
std::stringstream msg;
msg << "Library file " << settings::path_source_library << "' does not exist.";
fatal_error(msg);
}
} else {
// Spatial distribution for external source
if (check_for_node(node, "space")) {
// Get pointer to spatial distribution
pugi::xml_node node_space = node.child("space");
// Check for type of spatial distribution and read
std::string type;
if (check_for_node(node_space, "type"))
type = get_node_value(node_space, "type", true, true);
if (type == "cartesian") {
space_ = UPtrSpace{new CartesianIndependent(node_space)};
} else if (type == "cylindrical") {
space_ = UPtrSpace{new CylindricalIndependent(node_space)};
} else if (type == "spherical") {
space_ = UPtrSpace{new SphericalIndependent(node_space)};
} else if (type == "box") {
space_ = UPtrSpace{new SpatialBox(node_space)};
} else if (type == "fission") {
space_ = UPtrSpace{new SpatialBox(node_space, true)};
} else if (type == "point") {
space_ = UPtrSpace{new SpatialPoint(node_space)};
} else {
fatal_error(fmt::format(
"Invalid spatial distribution for external source: {}", type));
}
} else {
// If no spatial distribution specified, make it a point source
space_ = UPtrSpace{new SpatialPoint()};
}
// Determine external source angular distribution
if (check_for_node(node, "angle")) {
// Get pointer to angular distribution
pugi::xml_node node_angle = node.child("angle");
// Check for type of angular distribution
std::string type;
if (check_for_node(node_angle, "type"))
type = get_node_value(node_angle, "type", true, true);
if (type == "isotropic") {
angle_ = UPtrAngle{new Isotropic()};
} else if (type == "monodirectional") {
angle_ = UPtrAngle{new Monodirectional(node_angle)};
} else if (type == "mu-phi") {
angle_ = UPtrAngle{new PolarAzimuthal(node_angle)};
} else {
fatal_error(fmt::format(
"Invalid angular distribution for external source: {}", type));
}
} else {
angle_ = UPtrAngle{new Isotropic()};
}
// Determine external source energy distribution
if (check_for_node(node, "energy")) {
pugi::xml_node node_dist = node.child("energy");
energy_ = distribution_from_xml(node_dist);
} else {
// Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1
energy_ = UPtrDist{new Watt(0.988e6, 2.249e-6)};
}
}
}
Particle::Bank SourceDistribution::sample(uint64_t* seed) const
{
Particle::Bank site;
// Set weight to one by default
site.wgt = 1.0;
// Repeat sampling source location until a good site has been found
bool found = false;
int n_reject = 0;
static int n_accept = 0;
while (!found) {
// Set particle type
site.particle = particle_;
// Sample spatial distribution
site.r = space_->sample(seed);
double xyz[] {site.r.x, site.r.y, site.r.z};
// Now search to see if location exists in geometry
int32_t cell_index, instance;
int err = openmc_find_cell(xyz, &cell_index, &instance);
found = (err != OPENMC_E_GEOMETRY);
// Check if spatial site is in fissionable material
if (found) {
auto space_box = dynamic_cast<SpatialBox*>(space_.get());
if (space_box) {
if (space_box->only_fissionable()) {
// Determine material
const auto& c = model::cells[cell_index];
auto mat_index = c->material_.size() == 1
? c->material_[0] : c->material_[instance];
if (mat_index == MATERIAL_VOID) {
found = false;
} else {
if (!model::materials[mat_index]->fissionable_) found = false;
}
}
}
}
// Check for rejection
if (!found) {
++n_reject;
if (n_reject >= EXTSRC_REJECT_THRESHOLD &&
static_cast<double>(n_accept)/n_reject <= EXTSRC_REJECT_FRACTION) {
fatal_error("More than 95% of external source sites sampled were "
"rejected. Please check your external source definition.");
}
}
}
// Increment number of accepted samples
++n_accept;
// Sample angle
site.u = angle_->sample(seed);
// Check for monoenergetic source above maximum particle energy
auto p = static_cast<int>(particle_);
auto energy_ptr = dynamic_cast<Discrete*>(energy_.get());
if (energy_ptr) {
auto energies = xt::adapt(energy_ptr->x());
if (xt::any(energies > data::energy_max[p])) {
fatal_error("Source energy above range of energies of at least "
"one cross section table");
} else if (xt::any(energies < data::energy_min[p])) {
fatal_error("Source energy below range of energies of at least "
"one cross section table");
}
}
while (true) {
// Sample energy spectrum
site.E = energy_->sample(seed);
// Resample if energy falls outside minimum or maximum particle energy
if (site.E < data::energy_max[p] && site.E > data::energy_min[p]) break;
}
// Set delayed group
site.delayed_group = 0;
return site;
}
//==============================================================================
// Non-member functions
//==============================================================================
void initialize_source()
{
write_message("Initializing source particles...", 5);
if (settings::path_source != "") {
// Read the source from a binary file instead of sampling from some
// assumed source distribution
write_message(fmt::format("Reading source file from {}...",
settings::path_source), 6);
// Open the binary file
hid_t file_id = file_open(settings::path_source, 'r', true);
// Read the file type
std::string filetype;
read_attribute(file_id, "filetype", filetype);
// Check to make sure this is a source file
if (filetype != "source" && filetype != "statepoint") {
fatal_error("Specified starting source file not a source file type.");
}
// Read in the source bank
read_source_bank(file_id);
// Close file
file_close(file_id);
} else if ( settings::path_source_library != "" ) {
// Get the source from a library object
std::stringstream msg;
msg << "Sampling from library source " << settings::path_source << "...";
write_message(msg, 6);
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
// Open the library
void* source_library = dlopen(settings::path_source_library.c_str(),RTLD_LAZY);
if(!source_library) {
std::stringstream msg("Couldnt open source library " + settings::path_source_library);
fatal_error(msg);
}
#else
std::stringstream msg("This feature has not yet been implemented for non POSIX systems");
fatal_error(msg);
#endif
// load the symbol
typedef Particle::Bank (*sample_t)();
// reset errors
dlerror();
// get the function from the library
sample_t sample_source = (sample_t) dlsym(source_library, "sample_source");
const char *dlsym_error = dlerror();
// check for any dlsym errors
if (dlsym_error) {
std::cout << dlsym_error << std::endl;
dlclose(source_library);
fatal_error("Couldnt open the sample_source symbol");
}
// Generation source sites from specified distribution in the
// library source
for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
// initialize random number seed
int64_t id = simulation::total_gen*settings::n_particles +
simulation::work_index[mpi::rank] + i + 1;
set_particle_seed(id);
// sample external source distribution
simulation::source_bank[i] = sample_source();
}
// release the library
dlclose(source_library);
} else {
// Generation source sites from specified distribution in user input
for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
// initialize random number seed
int64_t id = simulation::total_gen*settings::n_particles +
simulation::work_index[mpi::rank] + i + 1;
uint64_t seed = init_seed(id, STREAM_SOURCE);
// sample external source distribution
simulation::source_bank[i] = sample_external_source(&seed);
}
}
// Write out initial source
if (settings::write_initial_source) {
write_message("Writing out initial source...", 5);
std::string filename = settings::path_output + "initial_source.h5";
hid_t file_id = file_open(filename, 'w', true);
write_source_bank(file_id);
file_close(file_id);
}
}
Particle::Bank sample_external_source(uint64_t* seed)
{
// Determine total source strength
double total_strength = 0.0;
for (auto& s : model::external_sources)
total_strength += s.strength();
// Sample from among multiple source distributions
int i = 0;
if (model::external_sources.size() > 1) {
double xi = prn(seed)*total_strength;
double c = 0.0;
for (; i < model::external_sources.size(); ++i) {
c += model::external_sources[i].strength();
if (xi < c) break;
}
}
// Sample source site from i-th source distribution
Particle::Bank site {model::external_sources[i].sample(seed)};
// If running in MG, convert site.E to group
if (!settings::run_CE) {
site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(),
data::mg.rev_energy_bins_.end(), site.E);
site.E = data::mg.num_energy_groups_ - site.E - 1.;
}
return site;
}
void free_memory_source()
{
model::external_sources.clear();
}
void fill_source_bank_fixedsource()
{
if (settings::path_source.empty() && settings::path_source_library.empty()) {
for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
// initialize random number seed
int64_t id = (simulation::total_gen + overall_generation()) *
settings::n_particles + simulation::work_index[mpi::rank] + i + 1;
uint64_t seed = init_seed(id, STREAM_SOURCE);
// sample external source distribution
simulation::source_bank[i] = sample_external_source(&seed);
}
} else if (settings::path_source.empty() && !settings::path_source.empty()) {
std::stringstream msg;
// Open the library
void* source_library = dlopen(settings::path_source_library.c_str(),RTLD_LAZY);
if(!source_library) {
std::stringstream msg("Couldnt open source library " + settings::path_source_library);
fatal_error(msg);
}
// load the symbol
typedef Particle::Bank (*sample_t)();
// reset errors
dlerror();
// get the function from the library
sample_t sample_source = (sample_t) dlsym(source_library, "sample_source");
const char *dlsym_error = dlerror();
// check for any dlsym errors
if (dlsym_error) {
std::cout << dlsym_error << std::endl;
dlclose(source_library);
fatal_error("Couldnt open the sample_source symbol");
}
// Generation source sites from specified distribution in the
// library source
for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
// initialize random number seed
int64_t id = simulation::total_gen*settings::n_particles +
simulation::work_index[mpi::rank] + i + 1;
set_particle_seed(id);
// sample external source distribution
simulation::source_bank[i] = sample_source();
}
// release the library
dlclose(source_library);
}
}
} // namespace openmc
<commit_msg>updated signatures according to new changes in how seed is set<commit_after>#include "openmc/source.h"
#include <algorithm> // for move
#include <sstream> // for stringstream
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
#include <dlfcn.h> // for dlopen
#endif
#include <fmt/core.h>
#include "xtensor/xadapt.hpp"
#include "openmc/bank.h"
#include "openmc/cell.h"
#include "openmc/error.h"
#include "openmc/file_utils.h"
#include "openmc/hdf5_interface.h"
#include "openmc/material.h"
#include "openmc/message_passing.h"
#include "openmc/mgxs_interface.h"
#include "openmc/nuclide.h"
#include "openmc/capi.h"
#include "openmc/random_lcg.h"
#include "openmc/search.h"
#include "openmc/settings.h"
#include "openmc/simulation.h"
#include "openmc/state_point.h"
#include "openmc/xml_interface.h"
namespace openmc {
//==============================================================================
// Global variables
//==============================================================================
namespace model {
std::vector<SourceDistribution> external_sources;
}
//==============================================================================
// SourceDistribution implementation
//==============================================================================
SourceDistribution::SourceDistribution(UPtrSpace space, UPtrAngle angle, UPtrDist energy)
: space_{std::move(space)}, angle_{std::move(angle)}, energy_{std::move(energy)} { }
SourceDistribution::SourceDistribution(pugi::xml_node node)
{
// Check for particle type
if (check_for_node(node, "particle")) {
auto temp_str = get_node_value(node, "particle", true, true);
if (temp_str == "neutron") {
particle_ = Particle::Type::neutron;
} else if (temp_str == "photon") {
particle_ = Particle::Type::photon;
settings::photon_transport = true;
} else {
fatal_error(std::string("Unknown source particle type: ") + temp_str);
}
}
// Check for source strength
if (check_for_node(node, "strength")) {
strength_ = std::stod(get_node_value(node, "strength"));
}
// Check for external source file
if (check_for_node(node, "file")) {
// Copy path of source file
settings::path_source = get_node_value(node, "file", false, true);
// Check if source file exists
if (!file_exists(settings::path_source)) {
fatal_error(fmt::format("Source file '{}' does not exist.",
settings::path_source));
}
} else if (check_for_node(node, "library")) {
settings::path_source_library = get_node_value(node, "library", false, true);
// check if it exists
if (!file_exists(settings::path_source_library)) {
std::stringstream msg;
msg << "Library file " << settings::path_source_library << "' does not exist.";
fatal_error(msg);
}
} else {
// Spatial distribution for external source
if (check_for_node(node, "space")) {
// Get pointer to spatial distribution
pugi::xml_node node_space = node.child("space");
// Check for type of spatial distribution and read
std::string type;
if (check_for_node(node_space, "type"))
type = get_node_value(node_space, "type", true, true);
if (type == "cartesian") {
space_ = UPtrSpace{new CartesianIndependent(node_space)};
} else if (type == "cylindrical") {
space_ = UPtrSpace{new CylindricalIndependent(node_space)};
} else if (type == "spherical") {
space_ = UPtrSpace{new SphericalIndependent(node_space)};
} else if (type == "box") {
space_ = UPtrSpace{new SpatialBox(node_space)};
} else if (type == "fission") {
space_ = UPtrSpace{new SpatialBox(node_space, true)};
} else if (type == "point") {
space_ = UPtrSpace{new SpatialPoint(node_space)};
} else {
fatal_error(fmt::format(
"Invalid spatial distribution for external source: {}", type));
}
} else {
// If no spatial distribution specified, make it a point source
space_ = UPtrSpace{new SpatialPoint()};
}
// Determine external source angular distribution
if (check_for_node(node, "angle")) {
// Get pointer to angular distribution
pugi::xml_node node_angle = node.child("angle");
// Check for type of angular distribution
std::string type;
if (check_for_node(node_angle, "type"))
type = get_node_value(node_angle, "type", true, true);
if (type == "isotropic") {
angle_ = UPtrAngle{new Isotropic()};
} else if (type == "monodirectional") {
angle_ = UPtrAngle{new Monodirectional(node_angle)};
} else if (type == "mu-phi") {
angle_ = UPtrAngle{new PolarAzimuthal(node_angle)};
} else {
fatal_error(fmt::format(
"Invalid angular distribution for external source: {}", type));
}
} else {
angle_ = UPtrAngle{new Isotropic()};
}
// Determine external source energy distribution
if (check_for_node(node, "energy")) {
pugi::xml_node node_dist = node.child("energy");
energy_ = distribution_from_xml(node_dist);
} else {
// Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1
energy_ = UPtrDist{new Watt(0.988e6, 2.249e-6)};
}
}
}
Particle::Bank SourceDistribution::sample(uint64_t* seed) const
{
Particle::Bank site;
// Set weight to one by default
site.wgt = 1.0;
// Repeat sampling source location until a good site has been found
bool found = false;
int n_reject = 0;
static int n_accept = 0;
while (!found) {
// Set particle type
site.particle = particle_;
// Sample spatial distribution
site.r = space_->sample(seed);
double xyz[] {site.r.x, site.r.y, site.r.z};
// Now search to see if location exists in geometry
int32_t cell_index, instance;
int err = openmc_find_cell(xyz, &cell_index, &instance);
found = (err != OPENMC_E_GEOMETRY);
// Check if spatial site is in fissionable material
if (found) {
auto space_box = dynamic_cast<SpatialBox*>(space_.get());
if (space_box) {
if (space_box->only_fissionable()) {
// Determine material
const auto& c = model::cells[cell_index];
auto mat_index = c->material_.size() == 1
? c->material_[0] : c->material_[instance];
if (mat_index == MATERIAL_VOID) {
found = false;
} else {
if (!model::materials[mat_index]->fissionable_) found = false;
}
}
}
}
// Check for rejection
if (!found) {
++n_reject;
if (n_reject >= EXTSRC_REJECT_THRESHOLD &&
static_cast<double>(n_accept)/n_reject <= EXTSRC_REJECT_FRACTION) {
fatal_error("More than 95% of external source sites sampled were "
"rejected. Please check your external source definition.");
}
}
}
// Increment number of accepted samples
++n_accept;
// Sample angle
site.u = angle_->sample(seed);
// Check for monoenergetic source above maximum particle energy
auto p = static_cast<int>(particle_);
auto energy_ptr = dynamic_cast<Discrete*>(energy_.get());
if (energy_ptr) {
auto energies = xt::adapt(energy_ptr->x());
if (xt::any(energies > data::energy_max[p])) {
fatal_error("Source energy above range of energies of at least "
"one cross section table");
} else if (xt::any(energies < data::energy_min[p])) {
fatal_error("Source energy below range of energies of at least "
"one cross section table");
}
}
while (true) {
// Sample energy spectrum
site.E = energy_->sample(seed);
// Resample if energy falls outside minimum or maximum particle energy
if (site.E < data::energy_max[p] && site.E > data::energy_min[p]) break;
}
// Set delayed group
site.delayed_group = 0;
return site;
}
//==============================================================================
// Non-member functions
//==============================================================================
void initialize_source()
{
write_message("Initializing source particles...", 5);
if (settings::path_source != "") {
// Read the source from a binary file instead of sampling from some
// assumed source distribution
write_message(fmt::format("Reading source file from {}...",
settings::path_source), 6);
// Open the binary file
hid_t file_id = file_open(settings::path_source, 'r', true);
// Read the file type
std::string filetype;
read_attribute(file_id, "filetype", filetype);
// Check to make sure this is a source file
if (filetype != "source" && filetype != "statepoint") {
fatal_error("Specified starting source file not a source file type.");
}
// Read in the source bank
read_source_bank(file_id);
// Close file
file_close(file_id);
} else if ( settings::path_source_library != "" ) {
// Get the source from a library object
std::stringstream msg;
msg << "Sampling from library source " << settings::path_source << "...";
write_message(msg, 6);
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
// Open the library
void* source_library = dlopen(settings::path_source_library.c_str(),RTLD_LAZY);
if(!source_library) {
std::stringstream msg("Couldnt open source library " + settings::path_source_library);
fatal_error(msg);
}
#else
std::stringstream msg("This feature has not yet been implemented for non POSIX systems");
fatal_error(msg);
#endif
// load the symbol
typedef Particle::Bank (*sample_t)(uint64_t *seed);
// reset errors
dlerror();
// get the function from the library
sample_t sample_source = (sample_t) dlsym(source_library, "sample_source");
const char *dlsym_error = dlerror();
// check for any dlsym errors
if (dlsym_error) {
std::cout << dlsym_error << std::endl;
dlclose(source_library);
fatal_error("Couldnt open the sample_source symbol");
}
// Generation source sites from specified distribution in the
// library source
for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
// initialize random number seed
int64_t id = simulation::total_gen*settings::n_particles +
simulation::work_index[mpi::rank] + i + 1;
uint64_t seed = init_seed(id, STREAM_SOURCE);
// sample external source distribution
simulation::source_bank[i] = sample_source(&seed);
}
// release the library
dlclose(source_library);
} else {
// Generation source sites from specified distribution in user input
for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
// initialize random number seed
int64_t id = simulation::total_gen*settings::n_particles +
simulation::work_index[mpi::rank] + i + 1;
uint64_t seed = init_seed(id, STREAM_SOURCE);
// sample external source distribution
simulation::source_bank[i] = sample_external_source(&seed);
}
}
// Write out initial source
if (settings::write_initial_source) {
write_message("Writing out initial source...", 5);
std::string filename = settings::path_output + "initial_source.h5";
hid_t file_id = file_open(filename, 'w', true);
write_source_bank(file_id);
file_close(file_id);
}
}
Particle::Bank sample_external_source(uint64_t* seed)
{
// Determine total source strength
double total_strength = 0.0;
for (auto& s : model::external_sources)
total_strength += s.strength();
// Sample from among multiple source distributions
int i = 0;
if (model::external_sources.size() > 1) {
double xi = prn(seed)*total_strength;
double c = 0.0;
for (; i < model::external_sources.size(); ++i) {
c += model::external_sources[i].strength();
if (xi < c) break;
}
}
// Sample source site from i-th source distribution
Particle::Bank site {model::external_sources[i].sample(seed)};
// If running in MG, convert site.E to group
if (!settings::run_CE) {
site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(),
data::mg.rev_energy_bins_.end(), site.E);
site.E = data::mg.num_energy_groups_ - site.E - 1.;
}
return site;
}
void free_memory_source()
{
model::external_sources.clear();
}
void fill_source_bank_fixedsource()
{
if (settings::path_source.empty() && settings::path_source_library.empty()) {
for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
// initialize random number seed
int64_t id = (simulation::total_gen + overall_generation()) *
settings::n_particles + simulation::work_index[mpi::rank] + i + 1;
uint64_t seed = init_seed(id, STREAM_SOURCE);
// sample external source distribution
simulation::source_bank[i] = sample_external_source(&seed);
}
} else if (settings::path_source.empty() && !settings::path_source.empty()) {
std::stringstream msg;
// Open the library
void* source_library = dlopen(settings::path_source_library.c_str(),RTLD_LAZY);
if(!source_library) {
std::stringstream msg("Couldnt open source library " + settings::path_source_library);
fatal_error(msg);
}
// load the symbol
typedef Particle::Bank (*sample_t)(uint64_t *seed);
// reset errors
dlerror();
// get the function from the library
sample_t sample_source = (sample_t) dlsym(source_library, "sample_source");
const char *dlsym_error = dlerror();
// check for any dlsym errors
if (dlsym_error) {
std::cout << dlsym_error << std::endl;
dlclose(source_library);
fatal_error("Couldnt open the sample_source symbol");
}
// Generation source sites from specified distribution in the
// library source
for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
// initialize random number seed
int64_t id = simulation::total_gen*settings::n_particles +
simulation::work_index[mpi::rank] + i + 1;
uint64_t seed = init_seed(id, STREAM_SOURCE);
// sample external source distribution
simulation::source_bank[i] = sample_source(&seed);
}
// release the library
dlclose(source_library);
}
}
} // namespace openmc
<|endoftext|> |
<commit_before>//=============================================================================================================
/**
* @file main.cpp
* @author Christoph Dinh <[email protected]>;
* Matti Hamalainen <[email protected]>
* @version 1.0
* @date July, 2012
*
* @section LICENSE
*
* Copyright (C) 2012, Christoph Dinh and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of MNE-CPP authors nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief Example of a clusteredInverse application
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <fs/label.h>
#include <fs/surface.h>
#include <fs/surfaceset.h>
#include <fs/annotationset.h>
#include <fiff/fiff_evoked.h>
#include <mne/mne_sourceestimate.h>
#include <inverse/minimumNorm/minimumnorm.h>
#include <disp3D/view3D.h>
#include <disp3D/control/control3dwidget.h>
#include <utils/mnemath.h>
#include <iostream>
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QApplication>
#include <QCommandLineParser>
#include <QSet>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace MNELIB;
using namespace FSLIB;
using namespace FIFFLIB;
using namespace INVERSELIB;
using namespace DISP3DLIB;
using namespace UTILSLIB;
//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================
//=============================================================================================================
/**
* The function main marks the entry point of the program.
* By default, main has the storage class extern.
*
* @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
* @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
* @return the value that was set to exit() (which is 0 if exit() is called via quit()).
*/
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// Command Line Parser
QCommandLineParser parser;
parser.setApplicationDescription("Clustered Inverse Example");
parser.addHelpOption();
QCommandLineOption sampleFwdFileOption("f", "Path to forward solution <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif");
QCommandLineOption sampleCovFileOption("c", "Path to covariance <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis-cov.fif");
QCommandLineOption sampleEvokedFileOption("e", "Path to evoked <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis-ave.fif");
parser.addOption(sampleFwdFileOption);
parser.addOption(sampleCovFileOption);
parser.addOption(sampleEvokedFileOption);
parser.process(app);
//########################################################################################
// Source Estimate
QFile t_fileFwd(parser.value(sampleFwdFileOption));
QFile t_fileCov(parser.value(sampleCovFileOption));
QFile t_fileEvoked(parser.value(sampleEvokedFileOption));
double snr = 1.0f;//3.0f;//0.1f;//3.0f;
QString method("dSPM"); //"MNE" | "dSPM" | "sLORETA"
QString t_sFileNameClusteredInv("");
QString t_sFileNameStc("");
// Parse command line parameters
for(qint32 i = 0; i < argc; ++i)
{
if(strcmp(argv[i], "-snr") == 0 || strcmp(argv[i], "--snr") == 0)
{
if(i + 1 < argc)
snr = atof(argv[i+1]);
}
else if(strcmp(argv[i], "-method") == 0 || strcmp(argv[i], "--method") == 0)
{
if(i + 1 < argc)
method = QString::fromUtf8(argv[i+1]);
}
else if(strcmp(argv[i], "-inv") == 0 || strcmp(argv[i], "--inv") == 0)
{
if(i + 1 < argc)
t_sFileNameClusteredInv = QString::fromUtf8(argv[i+1]);
}
else if(strcmp(argv[i], "-stc") == 0 || strcmp(argv[i], "--stc") == 0)
{
if(i + 1 < argc)
t_sFileNameStc = QString::fromUtf8(argv[i+1]);
}
}
double lambda2 = 1.0 / pow(snr, 2);
qDebug() << "Start calculation with: SNR" << snr << "; Lambda" << lambda2 << "; Method" << method << "; stc:" << t_sFileNameStc;
// Load data
fiff_int_t setno = 0;
QPair<QVariant, QVariant> baseline(QVariant(), 0);
FiffEvoked evoked(t_fileEvoked, setno, baseline);
if(evoked.isEmpty())
return 1;
std::cout << "evoked first " << evoked.first << "; last " << evoked.last << std::endl;
MNEForwardSolution t_Fwd(t_fileFwd);
if(t_Fwd.isEmpty())
return 1;
AnnotationSet t_annotationSet("sample", 2, "aparc.a2009s", "./MNE-sample-data/subjects");
FiffCov noise_cov(t_fileCov);
// regularize noise covariance
noise_cov = noise_cov.regularize(evoked.info, 0.05, 0.05, 0.1, true);
//
// Cluster forward solution;
//
MNEForwardSolution t_clusteredFwd = t_Fwd.cluster_forward_solution(t_annotationSet, 20);//40);
// std::cout << "Size " << t_clusteredFwd.sol->data.rows() << " x " << t_clusteredFwd.sol->data.cols() << std::endl;
// std::cout << "Clustered Fwd:\n" << t_clusteredFwd.sol->data.row(0) << std::endl;
//
// make an inverse operators
//
FiffInfo info = evoked.info;
MNEInverseOperator inverse_operator(info, t_clusteredFwd, noise_cov, 0.2f, 0.8f);
//
// save clustered inverse
//
if(!t_sFileNameClusteredInv.isEmpty())
{
QFile t_fileClusteredInverse(t_sFileNameClusteredInv);
inverse_operator.write(t_fileClusteredInverse);
}
//
// Compute inverse solution
//
MinimumNorm minimumNorm(inverse_operator, lambda2, method);
MNESourceEstimate sourceEstimate = minimumNorm.calculateInverse(evoked);
if(sourceEstimate.isEmpty())
return 1;
// View activation time-series
std::cout << "\nsourceEstimate:\n" << sourceEstimate.data.block(0,0,10,10) << std::endl;
std::cout << "time\n" << sourceEstimate.times.block(0,0,1,10) << std::endl;
std::cout << "timeMin\n" << sourceEstimate.times[0] << std::endl;
std::cout << "timeMax\n" << sourceEstimate.times[sourceEstimate.times.size()-1] << std::endl;
std::cout << "time step\n" << sourceEstimate.tstep << std::endl;
//Condition Numbers
// MatrixXd mags(102, t_Fwd.sol->data.cols());
// qint32 count = 0;
// for(qint32 i = 2; i < 306; i += 3)
// {
// mags.row(count) = t_Fwd.sol->data.row(i);
// ++count;
// }
// MatrixXd magsClustered(102, t_clusteredFwd.sol->data.cols());
// count = 0;
// for(qint32 i = 2; i < 306; i += 3)
// {
// magsClustered.row(count) = t_clusteredFwd.sol->data.row(i);
// ++count;
// }
// MatrixXd grads(204, t_Fwd.sol->data.cols());
// count = 0;
// for(qint32 i = 0; i < 306; i += 3)
// {
// grads.row(count) = t_Fwd.sol->data.row(i);
// ++count;
// grads.row(count) = t_Fwd.sol->data.row(i+1);
// ++count;
// }
// MatrixXd gradsClustered(204, t_clusteredFwd.sol->data.cols());
// count = 0;
// for(qint32 i = 0; i < 306; i += 3)
// {
// gradsClustered.row(count) = t_clusteredFwd.sol->data.row(i);
// ++count;
// gradsClustered.row(count) = t_clusteredFwd.sol->data.row(i+1);
// ++count;
// }
VectorXd s;
double t_dConditionNumber = MNEMath::getConditionNumber(t_Fwd.sol->data, s);
double t_dConditionNumberClustered = MNEMath::getConditionNumber(t_clusteredFwd.sol->data, s);
std::cout << "Condition Number:\n" << t_dConditionNumber << std::endl;
std::cout << "Clustered Condition Number:\n" << t_dConditionNumberClustered << std::endl;
std::cout << "ForwardSolution" << t_Fwd.sol->data.block(0,0,10,10) << std::endl;
std::cout << "Clustered ForwardSolution" << t_clusteredFwd.sol->data.block(0,0,10,10) << std::endl;
// double t_dConditionNumberMags = MNEMath::getConditionNumber(mags, s);
// double t_dConditionNumberMagsClustered = MNEMath::getConditionNumber(magsClustered, s);
// std::cout << "Condition Number Magnetometers:\n" << t_dConditionNumberMags << std::endl;
// std::cout << "Clustered Condition Number Magnetometers:\n" << t_dConditionNumberMagsClustered << std::endl;
// double t_dConditionNumberGrads = MNEMath::getConditionNumber(grads, s);
// double t_dConditionNumberGradsClustered = MNEMath::getConditionNumber(gradsClustered, s);
// std::cout << "Condition Number Gradiometers:\n" << t_dConditionNumberGrads << std::endl;
// std::cout << "Clustered Condition Number Gradiometers:\n" << t_dConditionNumberGradsClustered << std::endl;
//Source Estimate end
//########################################################################################
// SurfaceSet t_surfSet("./MNE-sample-data/subjects/sample/surf/lh.white", "./MNE-sample-data/subjects/sample/surf/rh.white");
// SurfaceSet t_surfSet("/home/chdinh/sl_data/subjects/mind006/surf/lh.white", "/home/chdinh/sl_data/subjects/mind006/surf/rh.white");
SurfaceSet t_surfSet("E:/Data/sl_data/subjects/mind006/surf/lh.white", "E:/Data/sl_data/subjects/mind006/surf/rh.white");
// //only one time point - P100
// qint32 sample = 0;
// for(qint32 i = 0; i < sourceEstimate.times.size(); ++i)
// {
// if(sourceEstimate.times(i) >= 0)
// {
// sample = i;
// break;
// }
// }
// sample += (qint32)ceil(0.106/sourceEstimate.tstep); //100ms
// sourceEstimate = sourceEstimate.reduce(sample, 1);
// View3D::SPtr testWindow = View3D::SPtr(new View3D());
// testWindow->addBrainData("HemiLRSet", t_surfSet, t_annotationSet);
// QList<BrainRTSourceLocDataTreeItem*> rtItemList = testWindow->addRtBrainData("HemiLRSet", sourceEstimate, t_clusteredFwd);
// testWindow->show();
if(!t_sFileNameStc.isEmpty())
{
QFile t_fileClusteredStc(t_sFileNameStc);
sourceEstimate.write(t_fileClusteredStc);
}
//*/
return app.exec();//1;
}
<commit_msg>change to default sample data files<commit_after>//=============================================================================================================
/**
* @file main.cpp
* @author Christoph Dinh <[email protected]>;
* Matti Hamalainen <[email protected]>
* @version 1.0
* @date July, 2012
*
* @section LICENSE
*
* Copyright (C) 2012, Christoph Dinh and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of MNE-CPP authors nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief Example of a clusteredInverse application
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <fs/label.h>
#include <fs/surface.h>
#include <fs/surfaceset.h>
#include <fs/annotationset.h>
#include <fiff/fiff_evoked.h>
#include <mne/mne_sourceestimate.h>
#include <inverse/minimumNorm/minimumnorm.h>
#include <disp3D/view3D.h>
#include <disp3D/control/control3dwidget.h>
#include <utils/mnemath.h>
#include <iostream>
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QApplication>
#include <QCommandLineParser>
#include <QSet>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace MNELIB;
using namespace FSLIB;
using namespace FIFFLIB;
using namespace INVERSELIB;
using namespace DISP3DLIB;
using namespace UTILSLIB;
//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================
//=============================================================================================================
/**
* The function main marks the entry point of the program.
* By default, main has the storage class extern.
*
* @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
* @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
* @return the value that was set to exit() (which is 0 if exit() is called via quit()).
*/
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// Command Line Parser
QCommandLineParser parser;
parser.setApplicationDescription("Clustered Inverse Example");
parser.addHelpOption();
QCommandLineOption sampleFwdFileOption("f", "Path to forward solution <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif");
QCommandLineOption sampleCovFileOption("c", "Path to covariance <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis-cov.fif");
QCommandLineOption sampleEvokedFileOption("e", "Path to evoked <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis-ave.fif");
parser.addOption(sampleFwdFileOption);
parser.addOption(sampleCovFileOption);
parser.addOption(sampleEvokedFileOption);
parser.process(app);
//########################################################################################
// Source Estimate
QFile t_fileFwd(parser.value(sampleFwdFileOption));
QFile t_fileCov(parser.value(sampleCovFileOption));
QFile t_fileEvoked(parser.value(sampleEvokedFileOption));
double snr = 1.0f;//3.0f;//0.1f;//3.0f;
QString method("dSPM"); //"MNE" | "dSPM" | "sLORETA"
QString t_sFileNameClusteredInv("");
QString t_sFileNameStc("");
// Parse command line parameters
for(qint32 i = 0; i < argc; ++i)
{
if(strcmp(argv[i], "-snr") == 0 || strcmp(argv[i], "--snr") == 0)
{
if(i + 1 < argc)
snr = atof(argv[i+1]);
}
else if(strcmp(argv[i], "-method") == 0 || strcmp(argv[i], "--method") == 0)
{
if(i + 1 < argc)
method = QString::fromUtf8(argv[i+1]);
}
else if(strcmp(argv[i], "-inv") == 0 || strcmp(argv[i], "--inv") == 0)
{
if(i + 1 < argc)
t_sFileNameClusteredInv = QString::fromUtf8(argv[i+1]);
}
else if(strcmp(argv[i], "-stc") == 0 || strcmp(argv[i], "--stc") == 0)
{
if(i + 1 < argc)
t_sFileNameStc = QString::fromUtf8(argv[i+1]);
}
}
double lambda2 = 1.0 / pow(snr, 2);
qDebug() << "Start calculation with: SNR" << snr << "; Lambda" << lambda2 << "; Method" << method << "; stc:" << t_sFileNameStc;
// Load data
fiff_int_t setno = 0;
QPair<QVariant, QVariant> baseline(QVariant(), 0);
FiffEvoked evoked(t_fileEvoked, setno, baseline);
if(evoked.isEmpty())
return 1;
std::cout << "evoked first " << evoked.first << "; last " << evoked.last << std::endl;
MNEForwardSolution t_Fwd(t_fileFwd);
if(t_Fwd.isEmpty())
return 1;
AnnotationSet t_annotationSet("sample", 2, "aparc.a2009s", "./MNE-sample-data/subjects");
FiffCov noise_cov(t_fileCov);
// regularize noise covariance
noise_cov = noise_cov.regularize(evoked.info, 0.05, 0.05, 0.1, true);
//
// Cluster forward solution;
//
MNEForwardSolution t_clusteredFwd = t_Fwd.cluster_forward_solution(t_annotationSet, 20);//40);
// std::cout << "Size " << t_clusteredFwd.sol->data.rows() << " x " << t_clusteredFwd.sol->data.cols() << std::endl;
// std::cout << "Clustered Fwd:\n" << t_clusteredFwd.sol->data.row(0) << std::endl;
//
// make an inverse operators
//
FiffInfo info = evoked.info;
MNEInverseOperator inverse_operator(info, t_clusteredFwd, noise_cov, 0.2f, 0.8f);
//
// save clustered inverse
//
if(!t_sFileNameClusteredInv.isEmpty())
{
QFile t_fileClusteredInverse(t_sFileNameClusteredInv);
inverse_operator.write(t_fileClusteredInverse);
}
//
// Compute inverse solution
//
MinimumNorm minimumNorm(inverse_operator, lambda2, method);
MNESourceEstimate sourceEstimate = minimumNorm.calculateInverse(evoked);
if(sourceEstimate.isEmpty())
return 1;
// View activation time-series
std::cout << "\nsourceEstimate:\n" << sourceEstimate.data.block(0,0,10,10) << std::endl;
std::cout << "time\n" << sourceEstimate.times.block(0,0,1,10) << std::endl;
std::cout << "timeMin\n" << sourceEstimate.times[0] << std::endl;
std::cout << "timeMax\n" << sourceEstimate.times[sourceEstimate.times.size()-1] << std::endl;
std::cout << "time step\n" << sourceEstimate.tstep << std::endl;
//Condition Numbers
// MatrixXd mags(102, t_Fwd.sol->data.cols());
// qint32 count = 0;
// for(qint32 i = 2; i < 306; i += 3)
// {
// mags.row(count) = t_Fwd.sol->data.row(i);
// ++count;
// }
// MatrixXd magsClustered(102, t_clusteredFwd.sol->data.cols());
// count = 0;
// for(qint32 i = 2; i < 306; i += 3)
// {
// magsClustered.row(count) = t_clusteredFwd.sol->data.row(i);
// ++count;
// }
// MatrixXd grads(204, t_Fwd.sol->data.cols());
// count = 0;
// for(qint32 i = 0; i < 306; i += 3)
// {
// grads.row(count) = t_Fwd.sol->data.row(i);
// ++count;
// grads.row(count) = t_Fwd.sol->data.row(i+1);
// ++count;
// }
// MatrixXd gradsClustered(204, t_clusteredFwd.sol->data.cols());
// count = 0;
// for(qint32 i = 0; i < 306; i += 3)
// {
// gradsClustered.row(count) = t_clusteredFwd.sol->data.row(i);
// ++count;
// gradsClustered.row(count) = t_clusteredFwd.sol->data.row(i+1);
// ++count;
// }
VectorXd s;
double t_dConditionNumber = MNEMath::getConditionNumber(t_Fwd.sol->data, s);
double t_dConditionNumberClustered = MNEMath::getConditionNumber(t_clusteredFwd.sol->data, s);
std::cout << "Condition Number:\n" << t_dConditionNumber << std::endl;
std::cout << "Clustered Condition Number:\n" << t_dConditionNumberClustered << std::endl;
std::cout << "ForwardSolution" << t_Fwd.sol->data.block(0,0,10,10) << std::endl;
std::cout << "Clustered ForwardSolution" << t_clusteredFwd.sol->data.block(0,0,10,10) << std::endl;
// double t_dConditionNumberMags = MNEMath::getConditionNumber(mags, s);
// double t_dConditionNumberMagsClustered = MNEMath::getConditionNumber(magsClustered, s);
// std::cout << "Condition Number Magnetometers:\n" << t_dConditionNumberMags << std::endl;
// std::cout << "Clustered Condition Number Magnetometers:\n" << t_dConditionNumberMagsClustered << std::endl;
// double t_dConditionNumberGrads = MNEMath::getConditionNumber(grads, s);
// double t_dConditionNumberGradsClustered = MNEMath::getConditionNumber(gradsClustered, s);
// std::cout << "Condition Number Gradiometers:\n" << t_dConditionNumberGrads << std::endl;
// std::cout << "Clustered Condition Number Gradiometers:\n" << t_dConditionNumberGradsClustered << std::endl;
//Source Estimate end
//########################################################################################
SurfaceSet t_surfSet("./MNE-sample-data/subjects/sample/surf/lh.white", "./MNE-sample-data/subjects/sample/surf/rh.white");
// SurfaceSet t_surfSet("/home/chdinh/sl_data/subjects/mind006/surf/lh.white", "/home/chdinh/sl_data/subjects/mind006/surf/rh.white");
// SurfaceSet t_surfSet("E:/Data/sl_data/subjects/mind006/surf/lh.white", "E:/Data/sl_data/subjects/mind006/surf/rh.white");
// //only one time point - P100
// qint32 sample = 0;
// for(qint32 i = 0; i < sourceEstimate.times.size(); ++i)
// {
// if(sourceEstimate.times(i) >= 0)
// {
// sample = i;
// break;
// }
// }
// sample += (qint32)ceil(0.106/sourceEstimate.tstep); //100ms
// sourceEstimate = sourceEstimate.reduce(sample, 1);
// View3D::SPtr testWindow = View3D::SPtr(new View3D());
// testWindow->addBrainData("HemiLRSet", t_surfSet, t_annotationSet);
// QList<BrainRTSourceLocDataTreeItem*> rtItemList = testWindow->addRtBrainData("HemiLRSet", sourceEstimate, t_clusteredFwd);
// testWindow->show();
if(!t_sFileNameStc.isEmpty())
{
QFile t_fileClusteredStc(t_sFileNameStc);
sourceEstimate.write(t_fileClusteredStc);
}
//*/
return app.exec();//1;
}
<|endoftext|> |
<commit_before>//===-- EmitFunctions.cpp - interface to insert instrumentation --*- C++ -*--=//
//
// This inserts a global constant table with function pointers all along
//
//===----------------------------------------------------------------------===//
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
namespace {
struct EmitFunctionTable : public Pass {
bool run(Module &M);
};
RegisterOpt<EmitFunctionTable> X("emitfuncs", "Emit a Function Table");
}
// Per Module pass for inserting function table
bool EmitFunctionTable::run(Module &M){
std::vector<const Type*> vType;
std::vector<Constant *> vConsts;
for(Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
if (!MI->isExternal()) {
vType.push_back(MI->getType());
vConsts.push_back(ConstantPointerRef::get(MI));
}
StructType *sttype = StructType::get(vType);
ConstantStruct *cstruct = ConstantStruct::get(sttype, vConsts);
GlobalVariable *gb = new GlobalVariable(cstruct->getType(), true,
GlobalValue::ExternalLinkage,
cstruct, "llvmFunctionTable");
M.getGlobalList().push_back(gb);
return true; // Always modifies program
}
<commit_msg>Added the #(internal functions) to output<commit_after>//===-- EmitFunctions.cpp - interface to insert instrumentation --*- C++ -*--=//
//
// This inserts a global constant table with function pointers all along
//
//===----------------------------------------------------------------------===//
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
namespace {
struct EmitFunctionTable : public Pass {
bool run(Module &M);
};
RegisterOpt<EmitFunctionTable> X("emitfuncs", "Emit a Function Table");
}
// Per Module pass for inserting function table
bool EmitFunctionTable::run(Module &M){
std::vector<const Type*> vType;
std::vector<Constant *> vConsts;
unsigned char counter = 0;
for(Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
if (!MI->isExternal()) {
vType.push_back(MI->getType());
vConsts.push_back(ConstantPointerRef::get(MI));
counter++;
}
StructType *sttype = StructType::get(vType);
ConstantStruct *cstruct = ConstantStruct::get(sttype, vConsts);
GlobalVariable *gb = new GlobalVariable(cstruct->getType(), true,
GlobalValue::ExternalLinkage,
cstruct, "llvmFunctionTable");
M.getGlobalList().push_back(gb);
ConstantInt *cnst = ConstantInt::get(Type::IntTy, counter);
GlobalVariable *fnCount = new GlobalVariable(Type::IntTy, true,
GlobalValue::ExternalLinkage,
cnst, "llvmFunctionCount");
M.getGlobalList().push_back(fnCount);
return true; // Always modifies program
}
<|endoftext|> |
<commit_before>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/// @file
/// @author Don Gagne <[email protected]>
#include "Fact.h"
#include <QtQml>
Fact::Fact(QString name, FactMetaData::ValueType_t type, QObject* parent) :
QObject(parent),
_name(name),
_type(type),
_metaData(NULL)
{
_value = 0;
}
void Fact::setValue(const QVariant& value)
{
_value = value;
emit valueChanged(_value);
emit _containerValueChanged(_value);
}
void Fact::_containerSetValue(const QVariant& value)
{
_value = value;
emit valueChanged(_value);
}
QString Fact::name(void) const
{
return _name;
}
QVariant Fact::value(void) const
{
return _value;
}
QString Fact::valueString(void) const
{
return _value.toString();
}
QVariant Fact::defaultValue(void)
{
Q_ASSERT(_metaData);
return _metaData->defaultValue;
}
FactMetaData::ValueType_t Fact::type(void)
{
return _type;
}
QString Fact::shortDescription(void)
{
if (_metaData) {
return _metaData->shortDescription;
} else {
return QString();
}
}
QString Fact::longDescription(void)
{
if (_metaData) {
return _metaData->longDescription;
} else {
return QString();
}
}
QString Fact::units(void)
{
if (_metaData) {
return _metaData->units;
} else {
return QString();
}
}
QVariant Fact::min(void)
{
Q_ASSERT(_metaData);
return _metaData->min;
}
QVariant Fact::max(void)
{
Q_ASSERT(_metaData);
return _metaData->max;
}
void Fact::setMetaData(FactMetaData* metaData)
{
_metaData = metaData;
}
<commit_msg>Type checking in Fact::setValue() FactTextField, when setting the value from its "text" field, was converting the value to string. This was causing (QML JavaScript) code that uses the value for computation to stop working once the user changed the value.<commit_after>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/// @file
/// @author Don Gagne <[email protected]>
#include "Fact.h"
#include <QtQml>
Fact::Fact(QString name, FactMetaData::ValueType_t type, QObject* parent) :
QObject(parent),
_name(name),
_type(type),
_metaData(NULL)
{
_value = 0;
}
void Fact::setValue(const QVariant& value)
{
switch (type()) {
case FactMetaData::valueTypeInt8:
case FactMetaData::valueTypeInt16:
case FactMetaData::valueTypeInt32:
_value.setValue(QVariant(value.toInt()));
break;
case FactMetaData::valueTypeUint8:
case FactMetaData::valueTypeUint16:
case FactMetaData::valueTypeUint32:
_value.setValue(value.toUInt());
break;
case FactMetaData::valueTypeFloat:
_value.setValue(value.toFloat());
break;
case FactMetaData::valueTypeDouble:
_value.setValue(value.toDouble());
break;
}
emit valueChanged(_value);
emit _containerValueChanged(_value);
}
void Fact::_containerSetValue(const QVariant& value)
{
_value = value;
emit valueChanged(_value);
}
QString Fact::name(void) const
{
return _name;
}
QVariant Fact::value(void) const
{
return _value;
}
QString Fact::valueString(void) const
{
return _value.toString();
}
QVariant Fact::defaultValue(void)
{
Q_ASSERT(_metaData);
return _metaData->defaultValue;
}
FactMetaData::ValueType_t Fact::type(void)
{
return _type;
}
QString Fact::shortDescription(void)
{
if (_metaData) {
return _metaData->shortDescription;
} else {
return QString();
}
}
QString Fact::longDescription(void)
{
if (_metaData) {
return _metaData->longDescription;
} else {
return QString();
}
}
QString Fact::units(void)
{
if (_metaData) {
return _metaData->units;
} else {
return QString();
}
}
QVariant Fact::min(void)
{
Q_ASSERT(_metaData);
return _metaData->min;
}
QVariant Fact::max(void)
{
Q_ASSERT(_metaData);
return _metaData->max;
}
void Fact::setMetaData(FactMetaData* metaData)
{
_metaData = metaData;
}
<|endoftext|> |
<commit_before>// StringUtil.cc for fluxbox
// Copyright (c) 2001 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#include "StringUtil.hh"
#ifdef HAVE_CSTDIO
#include <cstdio>
#else
#include <stdio.h>
#endif
#ifdef HAVE_CSTDLIB
#include <cstdlib>
#else
#include <stdlib.h>
#endif
#ifdef HAVE_CCTYPE
#include <cctype>
#else
#include <ctype.h>
#endif
#ifdef HAVE_CASSERT
#include <cassert>
#else
#include <assert.h>
#endif
#ifdef HAVE_CSTRING
#include <cstring>
#else
#include <string.h>
#endif
#ifdef HAVE_CERRNO
#include <cerrno>
#else
#include <errno.h>
#endif
#include <memory>
#include <algorithm>
#include <string>
using std::string;
using std::transform;
namespace {
template <typename T>
int extractBigNumber(const char* in, T (*extractFunc)(const char*, char**, int), T& out) {
errno = 0;
int ret = 0;
char* end = 0;
T result = extractFunc(in, &end, 0);
if (errno == 0 && end != in) {
out = result;
ret = 1;
}
return ret;
}
template<typename T>
int extractSignedNumber(const std::string& in, T& out) {
long long int result = 0;
if (::extractBigNumber(in.c_str(), strtoll, result)) {
out = static_cast<T>(result);
return 1;
}
return 0;
}
template<typename T>
int extractUnsignedNumber(const std::string& in, T& out) {
unsigned long long int result = 0;
if (::extractBigNumber(in.c_str(), strtoull, result) && result >= 0) {
out = static_cast<T>(result);
return 1;
}
return 0;
}
}
namespace FbTk {
namespace StringUtil {
int extractNumber(const std::string& in, int& out) {
return ::extractSignedNumber<int>(in, out);
}
int extractNumber(const std::string& in, unsigned int& out) {
return ::extractUnsignedNumber<unsigned int>(in, out);
}
int extractNumber(const std::string& in, long& out) {
return ::extractSignedNumber<long>(in, out);
}
int extractNumber(const std::string& in, unsigned long& out) {
return ::extractUnsignedNumber<unsigned long>(in, out);
}
int extractNumber(const std::string& in, long long& out) {
return ::extractSignedNumber<long long>(in, out);
}
int extractNumber(const std::string& in, unsigned long long& out) {
return ::extractUnsignedNumber<unsigned long long>(in, out);
}
std::string number2String(long long num) {
char s[128];
sprintf(s, "%lld", num);
return std::string(s);
}
/**
Tries to find a string in another and
ignoring the case of the characters
Returns 0 on failure else pointer to str.
*/
const char *strcasestr(const char *str, const char *ptn) {
const char *s2, *p2;
for( ; *str; str++) {
for(s2=str, p2=ptn; ; s2++,p2++) {
// check if we reached the end of ptn, if so, return str
if (!*p2)
return str;
// check if the chars match(ignoring case)
if (toupper(*s2) != toupper(*p2))
break;
}
}
return 0;
}
/**
if ~ then expand it to home of user
returns expanded filename
*/
string expandFilename(const string &filename) {
string retval;
size_t pos = filename.find_first_not_of(" \t");
if (pos != string::npos && filename[pos] == '~') {
retval = getenv("HOME");
if (pos != filename.size()) {
// copy from the character after '~'
retval += static_cast<const char *>(filename.c_str() + pos + 1);
}
} else
return filename; //return unmodified value
return retval;
}
/**
@return string from last "." to end of string
*/
string findExtension(const string &filename) {
//get start of extension
string::size_type start_pos = filename.find_last_of(".");
if (start_pos == string::npos && start_pos != filename.size())
return "";
// return from last . to end of string
return filename.substr(start_pos + 1);
}
string::size_type findCharFromAlphabetAfterTrigger(const std::string& in, char trigger, const char alphabet[], size_t len_alphabet, size_t* found) {
for (const char* s = in.c_str(); *s != '\0'; ) {
if (*s++ == trigger && *s != '\0') {
for (const char* a = alphabet; (a - alphabet) < static_cast<ssize_t>(len_alphabet); ++a) {
if (*s == *a) {
if (found) {
*found = a - alphabet;
}
return s - in.c_str() - 1;
}
}
s++;
}
}
return string::npos;
}
string replaceString(const string &original,
const char *findthis,
const char *replace) {
size_t i = 0;
const int size_of_replace = strlen(replace);
const int size_of_find = strlen(findthis);
string ret_str(original);
while (i < ret_str.size()) {
i = ret_str.find(findthis, i);
if (i == string::npos)
break;
// erase old string and insert replacement
ret_str.erase(i, size_of_find);
ret_str.insert(i, replace);
// jump to next position after insert
i += size_of_replace;
}
return ret_str;
}
/**
Parses a string between "first" and "last" characters
and ignoring ok_chars as whitespaces. The value is
returned in "out".
Returns negative value on error and this value is the position
in the in-string where the error occured.
Returns positive value on success and this value is
for the position + 1 in the in-string where the "last"-char value
was found.
*/
int getStringBetween(string& out, const char *instr, char first, char last,
const char *ok_chars, bool allow_nesting) {
assert(first);
assert(last);
assert(instr);
string::size_type i = 0;
string::size_type total_add=0; //used to add extra if there is a \last to skip
string in(instr);
// eat leading whitespace
i = in.find_first_not_of(ok_chars);
if (i == string::npos)
return -in.size(); // nothing left but whitespace
if (in[i]!=first)
return -i; //return position to error
// find the end of the token
string::size_type j = i, k;
int nesting = 0;
while (1) {
k = in.find_first_of(first, j+1);
j = in.find_first_of(last, j+1);
if (j==string::npos)
return -in.size(); //send negative size
if (allow_nesting && k < j && in[k-1] != '\\') {
nesting++;
j = k;
continue;
}
//we found the last char, check so it doesn't have a '\' before
if (j>1 && in[j-1] != '\\') {
if (allow_nesting && nesting > 0) nesting--;
else
break;
} else if (j>1 && !allow_nesting) { // we leave escapes if we're allowing nesting
in.erase(j-1, 1); //remove the '\'
j--;
total_add++; //save numchars removed so we can calculate totalpos
}
}
out = in.substr(i+1, j-i-1); //copy the string between first and last
//return value to last character
return (j+1+total_add);
}
string toLower(const string &conv) {
string ret = conv;
transform(ret.begin(), ret.end(), ret.begin(), tolower);
return ret;
}
string toUpper(const string &conv) {
string ret = conv;
transform(ret.begin(), ret.end(), ret.begin(), toupper);
return ret;
}
string basename(const string &filename) {
string::size_type first_pos = filename.find_last_of("/");
if (first_pos != string::npos)
return filename.substr(first_pos + 1);
return filename;
}
string::size_type removeFirstWhitespace(string &str) {
string::size_type first_pos = str.find_first_not_of(" \t");
str.erase(0, first_pos);
return first_pos;
}
string::size_type removeTrailingWhitespace(string &str) {
// strip trailing whitespace
string::size_type first_pos = str.find_last_not_of(" \t");
string::size_type last_pos = str.find_first_of(" \t", first_pos);
if (last_pos != string::npos)
str.erase(last_pos);
return first_pos;
}
void getFirstWord(const std::string &in, std::string &word, std::string &rest) {
word = in;
string::size_type first_pos = StringUtil::removeFirstWhitespace(word);
string::size_type second_pos = word.find_first_of(" \t", first_pos);
if (second_pos != string::npos) {
rest = word.substr(second_pos);
word.erase(second_pos);
}
}
} // end namespace StringUtil
} // end namespace FbTk
<commit_msg>FbTk/StringUtil.cc: Fix out-of-range memory access.<commit_after>// StringUtil.cc for fluxbox
// Copyright (c) 2001 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#include "StringUtil.hh"
#ifdef HAVE_CSTDIO
#include <cstdio>
#else
#include <stdio.h>
#endif
#ifdef HAVE_CSTDLIB
#include <cstdlib>
#else
#include <stdlib.h>
#endif
#ifdef HAVE_CCTYPE
#include <cctype>
#else
#include <ctype.h>
#endif
#ifdef HAVE_CASSERT
#include <cassert>
#else
#include <assert.h>
#endif
#ifdef HAVE_CSTRING
#include <cstring>
#else
#include <string.h>
#endif
#ifdef HAVE_CERRNO
#include <cerrno>
#else
#include <errno.h>
#endif
#include <memory>
#include <algorithm>
#include <string>
using std::string;
using std::transform;
namespace {
template <typename T>
int extractBigNumber(const char* in, T (*extractFunc)(const char*, char**, int), T& out) {
errno = 0;
int ret = 0;
char* end = 0;
T result = extractFunc(in, &end, 0);
if (errno == 0 && end != in) {
out = result;
ret = 1;
}
return ret;
}
template<typename T>
int extractSignedNumber(const std::string& in, T& out) {
long long int result = 0;
if (::extractBigNumber(in.c_str(), strtoll, result)) {
out = static_cast<T>(result);
return 1;
}
return 0;
}
template<typename T>
int extractUnsignedNumber(const std::string& in, T& out) {
unsigned long long int result = 0;
if (::extractBigNumber(in.c_str(), strtoull, result) && result >= 0) {
out = static_cast<T>(result);
return 1;
}
return 0;
}
}
namespace FbTk {
namespace StringUtil {
int extractNumber(const std::string& in, int& out) {
return ::extractSignedNumber<int>(in, out);
}
int extractNumber(const std::string& in, unsigned int& out) {
return ::extractUnsignedNumber<unsigned int>(in, out);
}
int extractNumber(const std::string& in, long& out) {
return ::extractSignedNumber<long>(in, out);
}
int extractNumber(const std::string& in, unsigned long& out) {
return ::extractUnsignedNumber<unsigned long>(in, out);
}
int extractNumber(const std::string& in, long long& out) {
return ::extractSignedNumber<long long>(in, out);
}
int extractNumber(const std::string& in, unsigned long long& out) {
return ::extractUnsignedNumber<unsigned long long>(in, out);
}
std::string number2String(long long num) {
char s[128];
sprintf(s, "%lld", num);
return std::string(s);
}
/**
Tries to find a string in another and
ignoring the case of the characters
Returns 0 on failure else pointer to str.
*/
const char *strcasestr(const char *str, const char *ptn) {
const char *s2, *p2;
for( ; *str; str++) {
for(s2=str, p2=ptn; ; s2++,p2++) {
// check if we reached the end of ptn, if so, return str
if (!*p2)
return str;
// check if the chars match(ignoring case)
if (toupper(*s2) != toupper(*p2))
break;
}
}
return 0;
}
/**
if ~ then expand it to home of user
returns expanded filename
*/
string expandFilename(const string &filename) {
string retval;
size_t pos = filename.find_first_not_of(" \t");
if (pos != string::npos && filename[pos] == '~') {
retval = getenv("HOME");
if (pos + 1 < filename.size()) {
// copy from the character after '~'
retval += static_cast<const char *>(filename.c_str() + pos + 1);
}
} else
return filename; //return unmodified value
return retval;
}
/**
@return string from last "." to end of string
*/
string findExtension(const string &filename) {
//get start of extension
string::size_type start_pos = filename.find_last_of(".");
if (start_pos == string::npos && start_pos != filename.size())
return "";
// return from last . to end of string
return filename.substr(start_pos + 1);
}
string::size_type findCharFromAlphabetAfterTrigger(const std::string& in, char trigger, const char alphabet[], size_t len_alphabet, size_t* found) {
for (const char* s = in.c_str(); *s != '\0'; ) {
if (*s++ == trigger && *s != '\0') {
for (const char* a = alphabet; (a - alphabet) < static_cast<ssize_t>(len_alphabet); ++a) {
if (*s == *a) {
if (found) {
*found = a - alphabet;
}
return s - in.c_str() - 1;
}
}
s++;
}
}
return string::npos;
}
string replaceString(const string &original,
const char *findthis,
const char *replace) {
size_t i = 0;
const int size_of_replace = strlen(replace);
const int size_of_find = strlen(findthis);
string ret_str(original);
while (i < ret_str.size()) {
i = ret_str.find(findthis, i);
if (i == string::npos)
break;
// erase old string and insert replacement
ret_str.erase(i, size_of_find);
ret_str.insert(i, replace);
// jump to next position after insert
i += size_of_replace;
}
return ret_str;
}
/**
Parses a string between "first" and "last" characters
and ignoring ok_chars as whitespaces. The value is
returned in "out".
Returns negative value on error and this value is the position
in the in-string where the error occured.
Returns positive value on success and this value is
for the position + 1 in the in-string where the "last"-char value
was found.
*/
int getStringBetween(string& out, const char *instr, char first, char last,
const char *ok_chars, bool allow_nesting) {
assert(first);
assert(last);
assert(instr);
string::size_type i = 0;
string::size_type total_add=0; //used to add extra if there is a \last to skip
string in(instr);
// eat leading whitespace
i = in.find_first_not_of(ok_chars);
if (i == string::npos)
return -in.size(); // nothing left but whitespace
if (in[i]!=first)
return -i; //return position to error
// find the end of the token
string::size_type j = i, k;
int nesting = 0;
while (1) {
k = in.find_first_of(first, j+1);
j = in.find_first_of(last, j+1);
if (j==string::npos)
return -in.size(); //send negative size
if (allow_nesting && k < j && in[k-1] != '\\') {
nesting++;
j = k;
continue;
}
//we found the last char, check so it doesn't have a '\' before
if (j>1 && in[j-1] != '\\') {
if (allow_nesting && nesting > 0) nesting--;
else
break;
} else if (j>1 && !allow_nesting) { // we leave escapes if we're allowing nesting
in.erase(j-1, 1); //remove the '\'
j--;
total_add++; //save numchars removed so we can calculate totalpos
}
}
out = in.substr(i+1, j-i-1); //copy the string between first and last
//return value to last character
return (j+1+total_add);
}
string toLower(const string &conv) {
string ret = conv;
transform(ret.begin(), ret.end(), ret.begin(), tolower);
return ret;
}
string toUpper(const string &conv) {
string ret = conv;
transform(ret.begin(), ret.end(), ret.begin(), toupper);
return ret;
}
string basename(const string &filename) {
string::size_type first_pos = filename.find_last_of("/");
if (first_pos != string::npos)
return filename.substr(first_pos + 1);
return filename;
}
string::size_type removeFirstWhitespace(string &str) {
string::size_type first_pos = str.find_first_not_of(" \t");
str.erase(0, first_pos);
return first_pos;
}
string::size_type removeTrailingWhitespace(string &str) {
// strip trailing whitespace
string::size_type first_pos = str.find_last_not_of(" \t");
string::size_type last_pos = str.find_first_of(" \t", first_pos);
if (last_pos != string::npos)
str.erase(last_pos);
return first_pos;
}
void getFirstWord(const std::string &in, std::string &word, std::string &rest) {
word = in;
string::size_type first_pos = StringUtil::removeFirstWhitespace(word);
string::size_type second_pos = word.find_first_of(" \t", first_pos);
if (second_pos != string::npos) {
rest = word.substr(second_pos);
word.erase(second_pos);
}
}
} // end namespace StringUtil
} // end namespace FbTk
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <v8.h>
#include <node.h>
#include <node_buffer.h>
namespace bdispose {
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Handle;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
void BufferDispose(const FunctionCallbackInfo<Value>& args) {
// Safe since we've already done the IsObject check from JS.
Local<Object> buf = args[0].As<Object>();
char* data = static_cast<char*>(buf->GetIndexedPropertiesExternalArrayData());
size_t length = buf->GetIndexedPropertiesExternalArrayDataLength();
if (length > 0) {
args.GetIsolate()->AdjustAmountOfExternalAllocatedMemory(-length);
buf->SetIndexedPropertiesToExternalArrayData(NULL,
v8::kExternalUnsignedByteArray,
0);
}
if (data != NULL) {
free(data);
}
}
void BufferUnslice(const FunctionCallbackInfo<Value>& args) {
Local<Object> buf = args[0].As<Object>();
size_t length = buf->GetIndexedPropertiesExternalArrayDataLength();
if (length > 0) {
buf->SetIndexedPropertiesToExternalArrayData(NULL,
v8::kExternalUnsignedByteArray,
0);
}
}
void Initialize(Handle<Object> target) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
Local<FunctionTemplate> t = FunctionTemplate::New(BufferDispose);
Local<String> name = String::NewFromUtf8(isolate, "dispose");
t->SetClassName(name);
target->Set(name, t->GetFunction());
t = FunctionTemplate::New(BufferUnslice);
name = String::NewFromUtf8(isolate, "unslice");
t->SetClassName(name);
target->Set(name, t->GetFunction());
}
} // namespace bdispose
NODE_MODULE(buffer_dispose, bdispose::Initialize)
<commit_msg>Update V8 API for new use of Isolate<commit_after>#include <stdlib.h>
#include <v8.h>
#include <node.h>
#include <node_buffer.h>
namespace bdispose {
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Handle;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
void BufferDispose(const FunctionCallbackInfo<Value>& args) {
// Safe since we've already done the IsObject check from JS.
Local<Object> buf = args[0].As<Object>();
char* data = static_cast<char*>(buf->GetIndexedPropertiesExternalArrayData());
size_t length = buf->GetIndexedPropertiesExternalArrayDataLength();
if (length > 0) {
args.GetIsolate()->AdjustAmountOfExternalAllocatedMemory(-length);
buf->SetIndexedPropertiesToExternalArrayData(NULL,
v8::kExternalUnsignedByteArray,
0);
}
if (data != NULL) {
free(data);
}
}
void BufferUnslice(const FunctionCallbackInfo<Value>& args) {
Local<Object> buf = args[0].As<Object>();
size_t length = buf->GetIndexedPropertiesExternalArrayDataLength();
if (length > 0) {
buf->SetIndexedPropertiesToExternalArrayData(NULL,
v8::kExternalUnsignedByteArray,
0);
}
}
void Initialize(Handle<Object> target) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
Local<FunctionTemplate> t = FunctionTemplate::New(isolate, BufferDispose);
Local<String> name = String::NewFromUtf8(isolate, "dispose");
t->SetClassName(name);
target->Set(name, t->GetFunction());
t = FunctionTemplate::New(isolate, BufferUnslice);
name = String::NewFromUtf8(isolate, "unslice");
t->SetClassName(name);
target->Set(name, t->GetFunction());
}
} // namespace bdispose
NODE_MODULE(buffer_dispose, bdispose::Initialize)
<|endoftext|> |
<commit_before>#include "string.h"
namespace std {
int strlen(const char* str) {
int i;
while(str[i] != '\0')
i++;
return i;
}
const char* begin(const char* str) {
return str;
}
const char* end(const char* str) {
// Find the end of the string (where the nul is found)
while(*str != '\0')
str++;
return str;
}
}
<commit_msg>Fix a potential bug in strlen(). I forgot to initialize my counter!<commit_after>#include "string.h"
namespace std {
int strlen(const char* str) {
int i = 0;
while(str[i] != '\0')
i++;
return i;
}
const char* begin(const char* str) {
return str;
}
const char* end(const char* str) {
// Find the end of the string (where the nul is found)
while(*str != '\0')
str++;
return str;
}
}
<|endoftext|> |
<commit_before><commit_msg>WebMediaPlayerGStreamer: do not call delegate_->DidPlay twice in a row<commit_after><|endoftext|> |
<commit_before>//===-- sanitizer_common_libcdep.cc ---------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer
// run-time libraries.
//===----------------------------------------------------------------------===//
#include "sanitizer_common.h"
#include "sanitizer_allocator_interface.h"
#include "sanitizer_file.h"
#include "sanitizer_flags.h"
#include "sanitizer_procmaps.h"
#include "sanitizer_report_decorator.h"
#include "sanitizer_stackdepot.h"
#include "sanitizer_stacktrace.h"
#include "sanitizer_symbolizer.h"
#if SANITIZER_POSIX
#include "sanitizer_posix.h"
#include <sys/mman.h>
#endif
namespace __sanitizer {
#if !SANITIZER_FUCHSIA
bool ReportFile::SupportsColors() {
SpinMutexLock l(mu);
ReopenIfNecessary();
return SupportsColoredOutput(fd);
}
static INLINE bool ReportSupportsColors() {
return report_file.SupportsColors();
}
#else // SANITIZER_FUCHSIA
// Fuchsia's logs always go through post-processing that handles colorization.
static INLINE bool ReportSupportsColors() { return true; }
#endif // !SANITIZER_FUCHSIA
bool ColorizeReports() {
// FIXME: Add proper Windows support to AnsiColorDecorator and re-enable color
// printing on Windows.
if (SANITIZER_WINDOWS)
return false;
const char *flag = common_flags()->color;
return internal_strcmp(flag, "always") == 0 ||
(internal_strcmp(flag, "auto") == 0 && ReportSupportsColors());
}
void ReportErrorSummary(const char *error_type, const StackTrace *stack,
const char *alt_tool_name) {
#if !SANITIZER_GO
if (!common_flags()->print_summary)
return;
if (stack->size == 0) {
ReportErrorSummary(error_type);
return;
}
// Currently, we include the first stack frame into the report summary.
// Maybe sometimes we need to choose another frame (e.g. skip memcpy/etc).
uptr pc = StackTrace::GetPreviousInstructionPc(stack->trace[0]);
SymbolizedStack *frame = Symbolizer::GetOrInit()->SymbolizePC(pc);
ReportErrorSummary(error_type, frame->info, alt_tool_name);
frame->ClearAll();
#endif
}
void ReportMmapWriteExec(int prot) {
#if SANITIZER_POSIX && (!SANITIZER_GO && !SANITIZER_ANDROID)
if ((prot & (PROT_WRITE | PROT_EXEC)) != (PROT_WRITE | PROT_EXEC))
return;
ScopedErrorReportLock l;
SanitizerCommonDecorator d;
InternalScopedBuffer<BufferedStackTrace> stack_buffer(1);
BufferedStackTrace *stack = stack_buffer.data();
stack->Reset();
uptr top = 0;
uptr bottom = 0;
GET_CALLER_PC_BP_SP;
(void)sp;
bool fast = common_flags()->fast_unwind_on_fatal;
if (fast)
GetThreadStackTopAndBottom(false, &top, &bottom);
stack->Unwind(kStackTraceMax, pc, bp, nullptr, top, bottom, fast);
Printf("%s", d.Warning());
Report("WARNING: %s: writable-executable page usage\n", SanitizerToolName);
Printf("%s", d.Default());
stack->Print();
ReportErrorSummary("w-and-x-usage", stack);
#endif
}
static void (*SoftRssLimitExceededCallback)(bool exceeded);
void SetSoftRssLimitExceededCallback(void (*Callback)(bool exceeded)) {
CHECK_EQ(SoftRssLimitExceededCallback, nullptr);
SoftRssLimitExceededCallback = Callback;
}
#if SANITIZER_LINUX && !SANITIZER_GO
void BackgroundThread(void *arg) {
uptr hard_rss_limit_mb = common_flags()->hard_rss_limit_mb;
uptr soft_rss_limit_mb = common_flags()->soft_rss_limit_mb;
bool heap_profile = common_flags()->heap_profile;
uptr prev_reported_rss = 0;
uptr prev_reported_stack_depot_size = 0;
bool reached_soft_rss_limit = false;
uptr rss_during_last_reported_profile = 0;
while (true) {
SleepForMillis(100);
uptr current_rss_mb = GetRSS() >> 20;
if (Verbosity()) {
// If RSS has grown 10% since last time, print some information.
if (prev_reported_rss * 11 / 10 < current_rss_mb) {
Printf("%s: RSS: %zdMb\n", SanitizerToolName, current_rss_mb);
prev_reported_rss = current_rss_mb;
}
// If stack depot has grown 10% since last time, print it too.
StackDepotStats *stack_depot_stats = StackDepotGetStats();
if (prev_reported_stack_depot_size * 11 / 10 <
stack_depot_stats->allocated) {
Printf("%s: StackDepot: %zd ids; %zdM allocated\n",
SanitizerToolName,
stack_depot_stats->n_uniq_ids,
stack_depot_stats->allocated >> 20);
prev_reported_stack_depot_size = stack_depot_stats->allocated;
}
}
// Check RSS against the limit.
if (hard_rss_limit_mb && hard_rss_limit_mb < current_rss_mb) {
Report("%s: hard rss limit exhausted (%zdMb vs %zdMb)\n",
SanitizerToolName, hard_rss_limit_mb, current_rss_mb);
DumpProcessMap();
Die();
}
if (soft_rss_limit_mb) {
if (soft_rss_limit_mb < current_rss_mb && !reached_soft_rss_limit) {
reached_soft_rss_limit = true;
Report("%s: soft rss limit exhausted (%zdMb vs %zdMb)\n",
SanitizerToolName, soft_rss_limit_mb, current_rss_mb);
if (SoftRssLimitExceededCallback)
SoftRssLimitExceededCallback(true);
} else if (soft_rss_limit_mb >= current_rss_mb &&
reached_soft_rss_limit) {
reached_soft_rss_limit = false;
if (SoftRssLimitExceededCallback)
SoftRssLimitExceededCallback(false);
}
}
if (heap_profile &&
current_rss_mb > rss_during_last_reported_profile * 1.1) {
Printf("\n\nHEAP PROFILE at RSS %zdMb\n", current_rss_mb);
__sanitizer_print_memory_profile(90, 20);
rss_during_last_reported_profile = current_rss_mb;
}
}
}
#endif
#if !SANITIZER_FUCHSIA && !SANITIZER_GO
void StartReportDeadlySignal() {
// Write the first message using fd=2, just in case.
// It may actually fail to write in case stderr is closed.
CatastrophicErrorWrite(SanitizerToolName, internal_strlen(SanitizerToolName));
static const char kDeadlySignal[] = ":DEADLYSIGNAL\n";
CatastrophicErrorWrite(kDeadlySignal, sizeof(kDeadlySignal) - 1);
}
static void MaybeReportNonExecRegion(uptr pc) {
#if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD
MemoryMappingLayout proc_maps(/*cache_enabled*/ true);
MemoryMappedSegment segment;
while (proc_maps.Next(&segment)) {
if (pc >= segment.start && pc < segment.end && !segment.IsExecutable())
Report("Hint: PC is at a non-executable region. Maybe a wild jump?\n");
}
#endif
}
static void PrintMemoryByte(InternalScopedString *str, const char *before,
u8 byte) {
SanitizerCommonDecorator d;
str->append("%s%s%x%x%s ", before, d.MemoryByte(), byte >> 4, byte & 15,
d.Default());
}
static void MaybeDumpInstructionBytes(uptr pc) {
if (!common_flags()->dump_instruction_bytes || (pc < GetPageSizeCached()))
return;
InternalScopedString str(1024);
str.append("First 16 instruction bytes at pc: ");
if (IsAccessibleMemoryRange(pc, 16)) {
for (int i = 0; i < 16; ++i) {
PrintMemoryByte(&str, "", ((u8 *)pc)[i]);
}
str.append("\n");
} else {
str.append("unaccessible\n");
}
Report("%s", str.data());
}
static void MaybeDumpRegisters(void *context) {
if (!common_flags()->dump_registers) return;
SignalContext::DumpAllRegisters(context);
}
static void ReportStackOverflowImpl(const SignalContext &sig, u32 tid,
UnwindSignalStackCallbackType unwind,
const void *unwind_context) {
SanitizerCommonDecorator d;
Printf("%s", d.Warning());
static const char kDescription[] = "stack-overflow";
Report("ERROR: %s: %s on address %p (pc %p bp %p sp %p T%d)\n",
SanitizerToolName, kDescription, (void *)sig.addr, (void *)sig.pc,
(void *)sig.bp, (void *)sig.sp, tid);
Printf("%s", d.Default());
InternalScopedBuffer<BufferedStackTrace> stack_buffer(1);
BufferedStackTrace *stack = stack_buffer.data();
stack->Reset();
unwind(sig, unwind_context, stack);
stack->Print();
ReportErrorSummary(kDescription, stack);
}
static void ReportDeadlySignalImpl(const SignalContext &sig, u32 tid,
UnwindSignalStackCallbackType unwind,
const void *unwind_context) {
SanitizerCommonDecorator d;
Printf("%s", d.Warning());
const char *description = sig.Describe();
Report("ERROR: %s: %s on unknown address %p (pc %p bp %p sp %p T%d)\n",
SanitizerToolName, description, (void *)sig.addr, (void *)sig.pc,
(void *)sig.bp, (void *)sig.sp, tid);
Printf("%s", d.Default());
if (sig.pc < GetPageSizeCached())
Report("Hint: pc points to the zero page.\n");
if (sig.is_memory_access) {
const char *access_type =
sig.write_flag == SignalContext::WRITE
? "WRITE"
: (sig.write_flag == SignalContext::READ ? "READ" : "UNKNOWN");
Report("The signal is caused by a %s memory access.\n", access_type);
if (sig.addr < GetPageSizeCached())
Report("Hint: address points to the zero page.\n");
}
MaybeReportNonExecRegion(sig.pc);
InternalScopedBuffer<BufferedStackTrace> stack_buffer(1);
BufferedStackTrace *stack = stack_buffer.data();
stack->Reset();
unwind(sig, unwind_context, stack);
stack->Print();
MaybeDumpInstructionBytes(sig.pc);
MaybeDumpRegisters(sig.context);
Printf("%s can not provide additional info.\n", SanitizerToolName);
ReportErrorSummary(description, stack);
}
void ReportDeadlySignal(const SignalContext &sig, u32 tid,
UnwindSignalStackCallbackType unwind,
const void *unwind_context) {
if (sig.IsStackOverflow())
ReportStackOverflowImpl(sig, tid, unwind, unwind_context);
else
ReportDeadlySignalImpl(sig, tid, unwind, unwind_context);
}
void HandleDeadlySignal(void *siginfo, void *context, u32 tid,
UnwindSignalStackCallbackType unwind,
const void *unwind_context) {
StartReportDeadlySignal();
ScopedErrorReportLock rl;
SignalContext sig(siginfo, context);
ReportDeadlySignal(sig, tid, unwind, unwind_context);
Report("ABORTING\n");
Die();
}
#endif // !SANITIZER_FUCHSIA && !SANITIZER_GO
void WriteToSyslog(const char *msg) {
InternalScopedString msg_copy(kErrorMessageBufferSize);
msg_copy.append("%s", msg);
char *p = msg_copy.data();
char *q;
// Print one line at a time.
// syslog, at least on Android, has an implicit message length limit.
do {
q = internal_strchr(p, '\n');
if (q)
*q = '\0';
WriteOneLineToSyslog(p);
if (q)
p = q + 1;
} while (q);
}
void MaybeStartBackgroudThread() {
#if SANITIZER_LINUX && \
!SANITIZER_GO // Need to implement/test on other platforms.
// Start the background thread if one of the rss limits is given.
if (!common_flags()->hard_rss_limit_mb &&
!common_flags()->soft_rss_limit_mb &&
!common_flags()->heap_profile) return;
if (!&real_pthread_create) return; // Can't spawn the thread anyway.
internal_start_thread(BackgroundThread, nullptr);
#endif
}
static atomic_uintptr_t reporting_thread = {0};
static StaticSpinMutex CommonSanitizerReportMutex;
ScopedErrorReportLock::ScopedErrorReportLock() {
uptr current = GetThreadSelf();
for (;;) {
uptr expected = 0;
if (atomic_compare_exchange_strong(&reporting_thread, &expected, current,
memory_order_relaxed)) {
// We've claimed reporting_thread so proceed.
CommonSanitizerReportMutex.Lock();
return;
}
if (expected == current) {
// This is either asynch signal or nested error during error reporting.
// Fail simple to avoid deadlocks in Report().
// Can't use Report() here because of potential deadlocks in nested
// signal handlers.
CatastrophicErrorWrite(SanitizerToolName,
internal_strlen(SanitizerToolName));
static const char msg[] = ": nested bug in the same thread, aborting.\n";
CatastrophicErrorWrite(msg, sizeof(msg) - 1);
internal__exit(common_flags()->exitcode);
}
internal_sched_yield();
}
}
ScopedErrorReportLock::~ScopedErrorReportLock() {
CommonSanitizerReportMutex.Unlock();
atomic_store_relaxed(&reporting_thread, 0);
}
void ScopedErrorReportLock::CheckLocked() {
CommonSanitizerReportMutex.CheckLocked();
}
static void (*sandboxing_callback)();
void SetSandboxingCallback(void (*f)()) {
sandboxing_callback = f;
}
} // namespace __sanitizer
SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_sandbox_on_notify,
__sanitizer_sandbox_arguments *args) {
__sanitizer::PlatformPrepareForSandboxing(args);
if (__sanitizer::sandboxing_callback)
__sanitizer::sandboxing_callback();
}
<commit_msg>[sanitizer] Allow BackgroundThread to not depend on StackDepot v2<commit_after>//===-- sanitizer_common_libcdep.cc ---------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer
// run-time libraries.
//===----------------------------------------------------------------------===//
#include "sanitizer_common.h"
#include "sanitizer_allocator_interface.h"
#include "sanitizer_file.h"
#include "sanitizer_flags.h"
#include "sanitizer_procmaps.h"
#include "sanitizer_report_decorator.h"
#include "sanitizer_stacktrace.h"
#include "sanitizer_symbolizer.h"
#if SANITIZER_POSIX
#include "sanitizer_posix.h"
#include <sys/mman.h>
#endif
namespace __sanitizer {
#if !SANITIZER_FUCHSIA
bool ReportFile::SupportsColors() {
SpinMutexLock l(mu);
ReopenIfNecessary();
return SupportsColoredOutput(fd);
}
static INLINE bool ReportSupportsColors() {
return report_file.SupportsColors();
}
#else // SANITIZER_FUCHSIA
// Fuchsia's logs always go through post-processing that handles colorization.
static INLINE bool ReportSupportsColors() { return true; }
#endif // !SANITIZER_FUCHSIA
bool ColorizeReports() {
// FIXME: Add proper Windows support to AnsiColorDecorator and re-enable color
// printing on Windows.
if (SANITIZER_WINDOWS)
return false;
const char *flag = common_flags()->color;
return internal_strcmp(flag, "always") == 0 ||
(internal_strcmp(flag, "auto") == 0 && ReportSupportsColors());
}
void ReportErrorSummary(const char *error_type, const StackTrace *stack,
const char *alt_tool_name) {
#if !SANITIZER_GO
if (!common_flags()->print_summary)
return;
if (stack->size == 0) {
ReportErrorSummary(error_type);
return;
}
// Currently, we include the first stack frame into the report summary.
// Maybe sometimes we need to choose another frame (e.g. skip memcpy/etc).
uptr pc = StackTrace::GetPreviousInstructionPc(stack->trace[0]);
SymbolizedStack *frame = Symbolizer::GetOrInit()->SymbolizePC(pc);
ReportErrorSummary(error_type, frame->info, alt_tool_name);
frame->ClearAll();
#endif
}
void ReportMmapWriteExec(int prot) {
#if SANITIZER_POSIX && (!SANITIZER_GO && !SANITIZER_ANDROID)
if ((prot & (PROT_WRITE | PROT_EXEC)) != (PROT_WRITE | PROT_EXEC))
return;
ScopedErrorReportLock l;
SanitizerCommonDecorator d;
InternalScopedBuffer<BufferedStackTrace> stack_buffer(1);
BufferedStackTrace *stack = stack_buffer.data();
stack->Reset();
uptr top = 0;
uptr bottom = 0;
GET_CALLER_PC_BP_SP;
(void)sp;
bool fast = common_flags()->fast_unwind_on_fatal;
if (fast)
GetThreadStackTopAndBottom(false, &top, &bottom);
stack->Unwind(kStackTraceMax, pc, bp, nullptr, top, bottom, fast);
Printf("%s", d.Warning());
Report("WARNING: %s: writable-executable page usage\n", SanitizerToolName);
Printf("%s", d.Default());
stack->Print();
ReportErrorSummary("w-and-x-usage", stack);
#endif
}
static void (*SoftRssLimitExceededCallback)(bool exceeded);
void SetSoftRssLimitExceededCallback(void (*Callback)(bool exceeded)) {
CHECK_EQ(SoftRssLimitExceededCallback, nullptr);
SoftRssLimitExceededCallback = Callback;
}
#if SANITIZER_LINUX && !SANITIZER_GO
// Weak default implementation for when sanitizer_stackdepot is not linked in.
SANITIZER_WEAK_ATTRIBUTE StackDepotStats *StackDepotGetStats() {
return nullptr;
}
void BackgroundThread(void *arg) {
const uptr hard_rss_limit_mb = common_flags()->hard_rss_limit_mb;
const uptr soft_rss_limit_mb = common_flags()->soft_rss_limit_mb;
const bool heap_profile = common_flags()->heap_profile;
uptr prev_reported_rss = 0;
uptr prev_reported_stack_depot_size = 0;
bool reached_soft_rss_limit = false;
uptr rss_during_last_reported_profile = 0;
while (true) {
SleepForMillis(100);
const uptr current_rss_mb = GetRSS() >> 20;
if (Verbosity()) {
// If RSS has grown 10% since last time, print some information.
if (prev_reported_rss * 11 / 10 < current_rss_mb) {
Printf("%s: RSS: %zdMb\n", SanitizerToolName, current_rss_mb);
prev_reported_rss = current_rss_mb;
}
// If stack depot has grown 10% since last time, print it too.
StackDepotStats *stack_depot_stats = StackDepotGetStats();
if (stack_depot_stats) {
if (prev_reported_stack_depot_size * 11 / 10 <
stack_depot_stats->allocated) {
Printf("%s: StackDepot: %zd ids; %zdM allocated\n",
SanitizerToolName,
stack_depot_stats->n_uniq_ids,
stack_depot_stats->allocated >> 20);
prev_reported_stack_depot_size = stack_depot_stats->allocated;
}
}
}
// Check RSS against the limit.
if (hard_rss_limit_mb && hard_rss_limit_mb < current_rss_mb) {
Report("%s: hard rss limit exhausted (%zdMb vs %zdMb)\n",
SanitizerToolName, hard_rss_limit_mb, current_rss_mb);
DumpProcessMap();
Die();
}
if (soft_rss_limit_mb) {
if (soft_rss_limit_mb < current_rss_mb && !reached_soft_rss_limit) {
reached_soft_rss_limit = true;
Report("%s: soft rss limit exhausted (%zdMb vs %zdMb)\n",
SanitizerToolName, soft_rss_limit_mb, current_rss_mb);
if (SoftRssLimitExceededCallback)
SoftRssLimitExceededCallback(true);
} else if (soft_rss_limit_mb >= current_rss_mb &&
reached_soft_rss_limit) {
reached_soft_rss_limit = false;
if (SoftRssLimitExceededCallback)
SoftRssLimitExceededCallback(false);
}
}
if (heap_profile &&
current_rss_mb > rss_during_last_reported_profile * 1.1) {
Printf("\n\nHEAP PROFILE at RSS %zdMb\n", current_rss_mb);
__sanitizer_print_memory_profile(90, 20);
rss_during_last_reported_profile = current_rss_mb;
}
}
}
#endif
#if !SANITIZER_FUCHSIA && !SANITIZER_GO
void StartReportDeadlySignal() {
// Write the first message using fd=2, just in case.
// It may actually fail to write in case stderr is closed.
CatastrophicErrorWrite(SanitizerToolName, internal_strlen(SanitizerToolName));
static const char kDeadlySignal[] = ":DEADLYSIGNAL\n";
CatastrophicErrorWrite(kDeadlySignal, sizeof(kDeadlySignal) - 1);
}
static void MaybeReportNonExecRegion(uptr pc) {
#if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD
MemoryMappingLayout proc_maps(/*cache_enabled*/ true);
MemoryMappedSegment segment;
while (proc_maps.Next(&segment)) {
if (pc >= segment.start && pc < segment.end && !segment.IsExecutable())
Report("Hint: PC is at a non-executable region. Maybe a wild jump?\n");
}
#endif
}
static void PrintMemoryByte(InternalScopedString *str, const char *before,
u8 byte) {
SanitizerCommonDecorator d;
str->append("%s%s%x%x%s ", before, d.MemoryByte(), byte >> 4, byte & 15,
d.Default());
}
static void MaybeDumpInstructionBytes(uptr pc) {
if (!common_flags()->dump_instruction_bytes || (pc < GetPageSizeCached()))
return;
InternalScopedString str(1024);
str.append("First 16 instruction bytes at pc: ");
if (IsAccessibleMemoryRange(pc, 16)) {
for (int i = 0; i < 16; ++i) {
PrintMemoryByte(&str, "", ((u8 *)pc)[i]);
}
str.append("\n");
} else {
str.append("unaccessible\n");
}
Report("%s", str.data());
}
static void MaybeDumpRegisters(void *context) {
if (!common_flags()->dump_registers) return;
SignalContext::DumpAllRegisters(context);
}
static void ReportStackOverflowImpl(const SignalContext &sig, u32 tid,
UnwindSignalStackCallbackType unwind,
const void *unwind_context) {
SanitizerCommonDecorator d;
Printf("%s", d.Warning());
static const char kDescription[] = "stack-overflow";
Report("ERROR: %s: %s on address %p (pc %p bp %p sp %p T%d)\n",
SanitizerToolName, kDescription, (void *)sig.addr, (void *)sig.pc,
(void *)sig.bp, (void *)sig.sp, tid);
Printf("%s", d.Default());
InternalScopedBuffer<BufferedStackTrace> stack_buffer(1);
BufferedStackTrace *stack = stack_buffer.data();
stack->Reset();
unwind(sig, unwind_context, stack);
stack->Print();
ReportErrorSummary(kDescription, stack);
}
static void ReportDeadlySignalImpl(const SignalContext &sig, u32 tid,
UnwindSignalStackCallbackType unwind,
const void *unwind_context) {
SanitizerCommonDecorator d;
Printf("%s", d.Warning());
const char *description = sig.Describe();
Report("ERROR: %s: %s on unknown address %p (pc %p bp %p sp %p T%d)\n",
SanitizerToolName, description, (void *)sig.addr, (void *)sig.pc,
(void *)sig.bp, (void *)sig.sp, tid);
Printf("%s", d.Default());
if (sig.pc < GetPageSizeCached())
Report("Hint: pc points to the zero page.\n");
if (sig.is_memory_access) {
const char *access_type =
sig.write_flag == SignalContext::WRITE
? "WRITE"
: (sig.write_flag == SignalContext::READ ? "READ" : "UNKNOWN");
Report("The signal is caused by a %s memory access.\n", access_type);
if (sig.addr < GetPageSizeCached())
Report("Hint: address points to the zero page.\n");
}
MaybeReportNonExecRegion(sig.pc);
InternalScopedBuffer<BufferedStackTrace> stack_buffer(1);
BufferedStackTrace *stack = stack_buffer.data();
stack->Reset();
unwind(sig, unwind_context, stack);
stack->Print();
MaybeDumpInstructionBytes(sig.pc);
MaybeDumpRegisters(sig.context);
Printf("%s can not provide additional info.\n", SanitizerToolName);
ReportErrorSummary(description, stack);
}
void ReportDeadlySignal(const SignalContext &sig, u32 tid,
UnwindSignalStackCallbackType unwind,
const void *unwind_context) {
if (sig.IsStackOverflow())
ReportStackOverflowImpl(sig, tid, unwind, unwind_context);
else
ReportDeadlySignalImpl(sig, tid, unwind, unwind_context);
}
void HandleDeadlySignal(void *siginfo, void *context, u32 tid,
UnwindSignalStackCallbackType unwind,
const void *unwind_context) {
StartReportDeadlySignal();
ScopedErrorReportLock rl;
SignalContext sig(siginfo, context);
ReportDeadlySignal(sig, tid, unwind, unwind_context);
Report("ABORTING\n");
Die();
}
#endif // !SANITIZER_FUCHSIA && !SANITIZER_GO
void WriteToSyslog(const char *msg) {
InternalScopedString msg_copy(kErrorMessageBufferSize);
msg_copy.append("%s", msg);
char *p = msg_copy.data();
char *q;
// Print one line at a time.
// syslog, at least on Android, has an implicit message length limit.
do {
q = internal_strchr(p, '\n');
if (q)
*q = '\0';
WriteOneLineToSyslog(p);
if (q)
p = q + 1;
} while (q);
}
void MaybeStartBackgroudThread() {
#if SANITIZER_LINUX && \
!SANITIZER_GO // Need to implement/test on other platforms.
// Start the background thread if one of the rss limits is given.
if (!common_flags()->hard_rss_limit_mb &&
!common_flags()->soft_rss_limit_mb &&
!common_flags()->heap_profile) return;
if (!&real_pthread_create) return; // Can't spawn the thread anyway.
internal_start_thread(BackgroundThread, nullptr);
#endif
}
static atomic_uintptr_t reporting_thread = {0};
static StaticSpinMutex CommonSanitizerReportMutex;
ScopedErrorReportLock::ScopedErrorReportLock() {
uptr current = GetThreadSelf();
for (;;) {
uptr expected = 0;
if (atomic_compare_exchange_strong(&reporting_thread, &expected, current,
memory_order_relaxed)) {
// We've claimed reporting_thread so proceed.
CommonSanitizerReportMutex.Lock();
return;
}
if (expected == current) {
// This is either asynch signal or nested error during error reporting.
// Fail simple to avoid deadlocks in Report().
// Can't use Report() here because of potential deadlocks in nested
// signal handlers.
CatastrophicErrorWrite(SanitizerToolName,
internal_strlen(SanitizerToolName));
static const char msg[] = ": nested bug in the same thread, aborting.\n";
CatastrophicErrorWrite(msg, sizeof(msg) - 1);
internal__exit(common_flags()->exitcode);
}
internal_sched_yield();
}
}
ScopedErrorReportLock::~ScopedErrorReportLock() {
CommonSanitizerReportMutex.Unlock();
atomic_store_relaxed(&reporting_thread, 0);
}
void ScopedErrorReportLock::CheckLocked() {
CommonSanitizerReportMutex.CheckLocked();
}
static void (*sandboxing_callback)();
void SetSandboxingCallback(void (*f)()) {
sandboxing_callback = f;
}
} // namespace __sanitizer
SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_sandbox_on_notify,
__sanitizer_sandbox_arguments *args) {
__sanitizer::PlatformPrepareForSandboxing(args);
if (__sanitizer::sandboxing_callback)
__sanitizer::sandboxing_callback();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: MQueryHelper.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hjs $ $Date: 2004-06-25 18:34:08 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_MAB_QUERYHELPER_HXX_
#define _CONNECTIVITY_MAB_QUERYHELPER_HXX_
#include <MNSInclude.hxx>
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _OSL_CONDITN_HXX_
#include <osl/conditn.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _THREAD_HXX_
#include <osl/thread.hxx>
#endif
namespace connectivity
{
namespace mozab
{
class MQueryHelperResultEntry
{
private:
mutable ::osl::Mutex m_aMutex;
DECLARE_STL_USTRINGACCESS_MAP(::rtl::OUString,fieldMap);
fieldMap m_Fields;
nsCOMPtr<nsIAbCard> m_Card;
sal_Int32 m_RowStates;
public:
MQueryHelperResultEntry();
~MQueryHelperResultEntry();
void insert( const rtl::OUString &key, rtl::OUString &value );
rtl::OUString getValue( const rtl::OUString &key ) const;
rtl::OUString setValue( const rtl::OUString &key, const rtl::OUString & rValue);
void setCard(nsIAbCard *card);
nsIAbCard *getCard();
sal_Bool setRowStates(sal_Int32 state){m_RowStates = state; return sal_True;};
sal_Int32 getRowStates() { return m_RowStates;};
};
class MQueryHelper : public nsIAbDirectoryQueryResultListener
{
private:
typedef std::vector< MQueryHelperResultEntry* > resultsArray;
mutable ::osl::Mutex m_aMutex;
::osl::Condition m_aCondition;
resultsArray m_aResults;
sal_Int32 m_nIndex;
sal_Bool m_bHasMore;
sal_Bool m_bAtEnd;
sal_Bool m_bErrorCondition;
sal_Bool m_bQueryComplete;
void append(MQueryHelperResultEntry* resEnt );
void clear_results();
void clearResultOrComplete();
void notifyResultOrComplete();
sal_Bool waitForResultOrComplete( );
void addCardAttributeAndValue(const ::rtl::OUString& sName, nsXPIDLString sValue,MQueryHelperResultEntry *resEntry);
void getCardAttributeAndValue(const ::rtl::OUString& sName, ::rtl::OUString &ouValue, MQueryHelperResultEntry *resEntry) ;
void getCardValues(nsIAbCard *card,sal_Int32 rowIndex=0);
#if OSL_DEBUG_LEVEL > 0
oslThreadIdentifier m_oThreadID;
#endif
mutable ::rtl::OUString m_aErrorString;
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIABDIRECTORYQUERYRESULTLISTENER
MQueryHelper();
~MQueryHelper();
void reset();
void rewind();
MQueryHelperResultEntry* next( );
MQueryHelperResultEntry* getByIndex( sal_Int32 nRow );
sal_Bool isError() const;
sal_Bool hasMore() const;
sal_Bool atEnd() const;
sal_Bool queryComplete() const;
sal_Bool waitForQueryComplete( );
sal_Bool waitForRow( sal_Int32 rowNum );
sal_Int32 getResultCount() const;
sal_uInt32 getRealCount() const;
sal_Int32 createNewCard(); //return Row count number
sal_Bool resyncRow(sal_Int32 rowIndex);
void notifyQueryError() ;
sal_Bool setCardValues(const sal_Int32 rowIndex);
sal_Int32 commitCard(const sal_Int32 rowIndex, nsIAbDirectory * directory);
sal_Int32 deleteCard(const sal_Int32 rowIndex, nsIAbDirectory * directory);
const ::rtl::OUString& getErrorString() const
{ return m_aErrorString; };
};
}
}
#endif // _CONNECTIVITY_MAB_QUERYHELPER_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.138); FILE MERGED 2005/09/05 17:24:37 rt 1.4.138.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MQueryHelper.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 06:30:18 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_MAB_QUERYHELPER_HXX_
#define _CONNECTIVITY_MAB_QUERYHELPER_HXX_
#include <MNSInclude.hxx>
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _OSL_CONDITN_HXX_
#include <osl/conditn.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _THREAD_HXX_
#include <osl/thread.hxx>
#endif
namespace connectivity
{
namespace mozab
{
class MQueryHelperResultEntry
{
private:
mutable ::osl::Mutex m_aMutex;
DECLARE_STL_USTRINGACCESS_MAP(::rtl::OUString,fieldMap);
fieldMap m_Fields;
nsCOMPtr<nsIAbCard> m_Card;
sal_Int32 m_RowStates;
public:
MQueryHelperResultEntry();
~MQueryHelperResultEntry();
void insert( const rtl::OUString &key, rtl::OUString &value );
rtl::OUString getValue( const rtl::OUString &key ) const;
rtl::OUString setValue( const rtl::OUString &key, const rtl::OUString & rValue);
void setCard(nsIAbCard *card);
nsIAbCard *getCard();
sal_Bool setRowStates(sal_Int32 state){m_RowStates = state; return sal_True;};
sal_Int32 getRowStates() { return m_RowStates;};
};
class MQueryHelper : public nsIAbDirectoryQueryResultListener
{
private:
typedef std::vector< MQueryHelperResultEntry* > resultsArray;
mutable ::osl::Mutex m_aMutex;
::osl::Condition m_aCondition;
resultsArray m_aResults;
sal_Int32 m_nIndex;
sal_Bool m_bHasMore;
sal_Bool m_bAtEnd;
sal_Bool m_bErrorCondition;
sal_Bool m_bQueryComplete;
void append(MQueryHelperResultEntry* resEnt );
void clear_results();
void clearResultOrComplete();
void notifyResultOrComplete();
sal_Bool waitForResultOrComplete( );
void addCardAttributeAndValue(const ::rtl::OUString& sName, nsXPIDLString sValue,MQueryHelperResultEntry *resEntry);
void getCardAttributeAndValue(const ::rtl::OUString& sName, ::rtl::OUString &ouValue, MQueryHelperResultEntry *resEntry) ;
void getCardValues(nsIAbCard *card,sal_Int32 rowIndex=0);
#if OSL_DEBUG_LEVEL > 0
oslThreadIdentifier m_oThreadID;
#endif
mutable ::rtl::OUString m_aErrorString;
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIABDIRECTORYQUERYRESULTLISTENER
MQueryHelper();
~MQueryHelper();
void reset();
void rewind();
MQueryHelperResultEntry* next( );
MQueryHelperResultEntry* getByIndex( sal_Int32 nRow );
sal_Bool isError() const;
sal_Bool hasMore() const;
sal_Bool atEnd() const;
sal_Bool queryComplete() const;
sal_Bool waitForQueryComplete( );
sal_Bool waitForRow( sal_Int32 rowNum );
sal_Int32 getResultCount() const;
sal_uInt32 getRealCount() const;
sal_Int32 createNewCard(); //return Row count number
sal_Bool resyncRow(sal_Int32 rowIndex);
void notifyQueryError() ;
sal_Bool setCardValues(const sal_Int32 rowIndex);
sal_Int32 commitCard(const sal_Int32 rowIndex, nsIAbDirectory * directory);
sal_Int32 deleteCard(const sal_Int32 rowIndex, nsIAbDirectory * directory);
const ::rtl::OUString& getErrorString() const
{ return m_aErrorString; };
};
}
}
#endif // _CONNECTIVITY_MAB_QUERYHELPER_HXX_
<|endoftext|> |
<commit_before>#include <GLUL/G2D/Point.h>
#include <GLUL/G2D/Quad.h>
namespace GLUL {
namespace G2D {
Point::Point(unsigned int size) : _color(glm::vec4 { 1.0f }), size(size) { }
Point::Point(const glm::vec2& position, unsigned int size) : Point(size) {
setPosition(position);
}
Point& Point::operator=(const glm::vec2& position) {
setPosition(position);
return *this;
}
void Point::setPosition(const glm::vec2& position) {
_position = position;
}
void Point::setPosition(const Point& point) {
_position = point.getPosition();
}
const glm::vec2& Point::getPosition() const {
return _position;
}
void Point::setColor(const glm::vec4& color) {
_color = color;
}
const glm::vec4& Point::getColor() const {
return _color;
}
void Point::_pushToBatch(GeometryBatch& geometryBatch) const {
Quad quad;
Point bottomLeftPoint = *this;
bottomLeftPoint.setPosition(getPosition() - glm::vec2 { static_cast<float>((size / 2)) });
quad.setSquare(bottomLeftPoint, static_cast<float>(size));
geometryBatch.addPrimitive(quad);
}
}
}
<commit_msg>[#64] Fixed warning in G2D::Point constructor.<commit_after>#include <GLUL/G2D/Point.h>
#include <GLUL/G2D/Quad.h>
namespace GLUL {
namespace G2D {
Point::Point(unsigned int size) : size(size), _color({ 1.0f }) { }
Point::Point(const glm::vec2& position, unsigned int size) : Point(size) {
setPosition(position);
}
Point& Point::operator=(const glm::vec2& position) {
setPosition(position);
return *this;
}
void Point::setPosition(const glm::vec2& position) {
_position = position;
}
void Point::setPosition(const Point& point) {
_position = point.getPosition();
}
const glm::vec2& Point::getPosition() const {
return _position;
}
void Point::setColor(const glm::vec4& color) {
_color = color;
}
const glm::vec4& Point::getColor() const {
return _color;
}
void Point::_pushToBatch(GeometryBatch& geometryBatch) const {
Quad quad;
Point bottomLeftPoint = *this;
bottomLeftPoint.setPosition(getPosition() - glm::vec2 { static_cast<float>((size / 2)) });
quad.setSquare(bottomLeftPoint, static_cast<float>(size));
geometryBatch.addPrimitive(quad);
}
}
}
<|endoftext|> |
<commit_before>/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Damon Hart-Davis 2016
*/
/*
* OpenTRV radiator valve physical UI controls and output as an actuator.
*
* A base class, a null class, and one or more implementations are provided
* for different stock behaviour with different hardware.
*
* A mixture of template and constructor parameters
* is used to configure the different types.
*/
#include <stddef.h>
#include <stdint.h>
#include <OTV0p2Base.h>
#include <OTRadValve_ActuatorPhysicalUI.h>
// Use namespaces to help avoid collisions.
namespace OTRadValve
{
#if defined(ModeButtonAndPotActuatorPhysicalUI_DEFINED)
//// Use WDT-based timer for xxxPause() routines.
//// Very tiny low-power sleep.
//static const uint8_t VERYTINY_PAUSE_MS = 5;
//static void inline veryTinyPause() { OTV0P2BASE::sleepLowPowerMs(VERYTINY_PAUSE_MS); }
//// Tiny low-power sleep to approximately match the PICAXE V0.09 routine of the same name.
//static const uint8_t TINY_PAUSE_MS = 15;
//static void inline tinyPause() { OTV0P2BASE::nap(WDTO_15MS); } // 15ms vs 18ms nominal for PICAXE V0.09 impl.
//// Small low-power sleep.
//static const uint8_t SMALL_PAUSE_MS = 30;
//static void inline smallPause() { OTV0P2BASE::nap(WDTO_30MS); }
//// Medium low-power sleep to approximately match the PICAXE V0.09 routine of the same name.
//// Premature wakeups MAY be allowed to avoid blocking I/O polling for too long.
//static const uint8_t MEDIUM_PAUSE_MS = 60;
//static void inline mediumPause() { OTV0P2BASE::nap(WDTO_60MS); } // 60ms vs 144ms nominal for PICAXE V0.09 impl.
//// Big low-power sleep to approximately match the PICAXE V0.09 routine of the same name.
//// Premature wakeups MAY be allowed to avoid blocking I/O polling for too long.
//static const uint8_t BIG_PAUSE_MS = 120;
//static void inline bigPause() { OTV0P2BASE::nap(WDTO_120MS); } // 120ms vs 288ms nominal for PICAXE V0.09 impl.
//
//// Pause between flashes to allow them to be distinguished (>100ms); was mediumPause() for PICAXE V0.09 impl.
//static void inline offPause()
// {
// bigPause(); // 120ms, was V0.09 144ms mediumPause() for PICAXE V0.09 impl.
//// pollIO(); // Slip in an I/O poll.
// }
// Record local manual operation of a physical UI control, eg not remote or via CLI.
// Marks room as occupied amongst other things.
// To be thread-/ISR- safe, everything that this touches or calls must be.
// Thread-safe.
void ModeButtonAndPotActuatorPhysicalUI::markUIControlUsed()
{
statusChange = true; // Note user interaction with the system.
uiTimeoutM = UI_DEFAULT_RECENT_USE_TIMEOUT_M; // Ensure that UI controls are kept 'warm' for a little while.
// FIXME
// #if defined(ENABLE_UI_WAKES_CLI)
// // Make CLI active for a while (at some slight possibly-significant energy cost).
// resetCLIActiveTimer(); // Thread-safe.
// #endif
// User operation of physical controls is strong indication of presence.
occupancy->markAsOccupied(); // Thread-safe.
}
// Record significant local manual operation of a physical UI control, eg not remote or via CLI.
// Marks room as occupied amongst other things.
// As markUIControlUsed() but likely to generate some feedback to the user, ASAP.
// Thread-safe.
void ModeButtonAndPotActuatorPhysicalUI::markUIControlUsedSignificant()
{
// Provide some instant visual feedback if possible.
if(NULL != safeISRLEDonOpt) { safeISRLEDonOpt(); }
// Flag up need for feedback.
significantUIOp = true;
// Do main UI-touched work.
markUIControlUsed();
}
// Call this nominally on even numbered seconds to allow the UI to operate.
// In practice call early once per 2s major cycle.
// Should never be skipped, so as to allow the UI to remain responsive.
// Runs in 350ms or less; usually takes only a few milliseconds or microseconds.
// Returns a non-zero value iff the user interacted with the system, and maybe caused a status change.
// NOTE: since this is on the minimum idle-loop code path, minimise CPU cycles, esp in frost mode.
// Replaces: bool tickUI(uint_fast8_t sec).
uint8_t ModeButtonAndPotActuatorPhysicalUI::read()
{
// True on every 4th tick/call, ie every ~8 seconds.
const bool forthTick = !((++tickCount) & 3); // True on every 4th tick.
// Perform any once-per-minute-ish operations, every 32 ticks.
const bool sec0 = (0 == (tickCount & 0x1f));
if(sec0)
{
ATOMIC_BLOCK (ATOMIC_RESTORESTATE)
{
// Run down UI interaction timer if need be, one tick per minute(ish).
if(uiTimeoutM > 0) { --uiTimeoutM; }
}
}
// const bool reportedRecently = occupancy->reportedRecently();
// Provide enhanced feedback when the has been very recent interaction with the UI,
// since the user is still quite likely to be continuing.
const bool enhancedUIFeedback = veryRecentUIControlUse();
if(NULL != tempPotOpt)
{
// Force relatively-frequent re-read of temp pot UI device
// and if there has been recent UI manual controls activity,
// to keep the valve UI responsive.
// #if !defined(ENABLE_FAST_TEMP_POT_SAMPLING) || !defined(ENABLE_OCCUPANCY_SUPPORT)
// if(enhancedUIFeedback || forthTick)
// #else
// // Even more responsive at some possible energy cost...
// Polls pot on every tick unless the room has been vacant for a day or two or is in FROST mode.
if(enhancedUIFeedback || forthTick || (valveMode->inWarmMode() && !occupancy->longLongVacant()))
// #endif
{
tempPotOpt->read();
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINT_FLASHSTRING("TP");
DEBUG_SERIAL_PRINT(TempPot.getRaw());
DEBUG_SERIAL_PRINTLN();
#endif
// Force to FROST mode (and cancel any erroneous BAKE, etc) when at FROST end of dial.
const bool isLo = tempPotOpt->isAtLoEndStop();
if(isLo) { valveMode->setWarmModeDebounced(false); }
// Feed back significant change in pot position, ie at temperature boundaries.
// Synthesise a 'warm' target temp that distinguishes the end stops...
const uint8_t nominalWarmTarget = isLo ? 1 :
(tempPotOpt->isAtHiEndStop() ? 99 :
tempControl->getWARMTargetC());
// Record of 'last' nominalWarmTarget; initially 0.
static uint8_t lastNominalWarmTarget;
if(nominalWarmTarget != lastNominalWarmTarget)
{
// Note if a boundary was crossed, ignoring any false 'start-up' transient.
if(0 != lastNominalWarmTarget) { significantUIOp = true; }
#if 1 && defined(DEBUG)
DEBUG_SERIAL_PRINT_FLASHSTRING("WT");
DEBUG_SERIAL_PRINT(nominalWarmTarget);
DEBUG_SERIAL_PRINTLN();
#endif
lastNominalWarmTarget = nominalWarmTarget;
}
}
}
// Provide extra user feedback for significant UI actions...
if(significantUIOp) { userOpFeedback(); }
// Support cycling through modes polling the MODE button.
// If MODE button is active skip normal LED UI activity.
if(!pollMODEButton())
{
// Keep reporting UI status if the user has just touched the unit in some way or UI feedback is enhanced.
const bool justTouched = statusChange || enhancedUIFeedback;
// Mode button not pressed: indicate current mode with flash(es); more flashes if actually calling for heat.
// Force display while UI controls are being used, eg to indicate temp pot position.
if(justTouched || valveMode->inWarmMode()) // Generate flash(es) if in WARM mode or fiddling with UI other than Mode button.
{
// DHD20131223: only flash if the room not known to be dark so as to save energy and avoid disturbing sleep, etc.
// In this case force resample of light level frequently in case user turns light on eg to operate unit.
// Do show LED flash if user has recently operated controls (other than mode button) manually.
// Flash infrequently if no recently operated controls and not in BAKE mode and not actually calling for heat;
// this is to conserve batteries for those people who leave the valves in WARM mode all the time.
if(justTouched ||
((forthTick
|| valveController->isCallingForHeat()
|| valveMode->inBakeMode()) && !ambLight->isRoomDark()))
{
// First flash to indicate WARM mode (or pot being twiddled).
LEDon();
// LED on stepwise proportional to temp pot setting.
// Small number of steps (3) should help make positioning more obvious.
const uint8_t wt = tempControl->getWARMTargetC();
// Makes vtiny|tiny|medium flash for cool|OK|warm temperature target.
// Stick to minimum length flashes to save energy unless just touched.
if(!justTouched || tempControl->isEcoTemperature(wt)) { veryTinyPause(); }
else if(!tempControl->isComfortTemperature(wt)) { tinyPause(); }
else { mediumPause(); }
// Second flash to indicate actually calling for heat,
// or likely to be calling for heat while interacting with the controls, to give fast user feedback (TODO-695).
if((enhancedUIFeedback && valveController->isUnderTarget()) ||
valveController->isCallingForHeat() ||
valveMode->inBakeMode())
{
LEDoff();
offPause(); // V0.09 was mediumPause().
LEDon(); // flash
// Stick to minimum length flashes to save energy unless just touched.
if(!justTouched || tempControl->isEcoTemperature(wt)) { veryTinyPause(); }
else if(!tempControl->isComfortTemperature(wt)) { OTV0P2BASE::sleepLowPowerMs((VERYTINY_PAUSE_MS + TINY_PAUSE_MS) / 2); }
else { tinyPause(); }
if(valveMode->inBakeMode())
{
// Third (lengthened) flash to indicate BAKE mode.
LEDoff();
mediumPause(); // Note different flash off time to try to distinguish this last flash.
LEDon();
// Makes tiny|small|medium flash for eco|OK|comfort temperature target.
// Stick to minimum length flashes to save energy unless just touched.
if(!justTouched || tempControl->isEcoTemperature(wt)) { veryTinyPause(); }
else if(!tempControl->isComfortTemperature(wt)) { smallPause(); }
else { mediumPause(); }
}
}
}
}
// Even in FROST mode, and if actually calling for heat (eg opening the rad valve significantly, etc)
// then emit a tiny double flash on every 4th tick.
// This call for heat may be frost protection or pre-warming / anticipating demand.
// DHD20130528: new 4th-tick flash in FROST mode...
// DHD20131223: only flash if the room is not dark (ie or if no working light sensor) so as to save energy and avoid disturbing sleep, etc.
else if(forthTick &&
!ambLight->isRoomDark() &&
valveController->isCallingForHeat() /* &&
NominalRadValve.isControlledValveReallyOpen() */ )
{
// Double flash every 4th tick indicates call for heat while in FROST MODE (matches call for heat in WARM mode).
LEDon(); // flash
veryTinyPause();
LEDoff();
offPause();
LEDon(); // flash
veryTinyPause();
}
}
// Ensure that the LED forced off unconditionally at least once each cycle.
LEDoff();
// Handle LEARN buttons (etc) in derived classes.
// Also can be used to handle any simple user schedules.
handleOtherUserControls(statusChange);
const bool statusChanged = statusChange;
statusChange = false; // Potential race.
return(statusChanged);
}
#endif // ModeButtonAndPotActuatorPhysicalUI_DEFINED
}
<commit_msg>tidyup<commit_after>/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Damon Hart-Davis 2016
*/
/*
* OpenTRV radiator valve physical UI controls and output as an actuator.
*
* A base class, a null class, and one or more implementations are provided
* for different stock behaviour with different hardware.
*
* A mixture of template and constructor parameters
* is used to configure the different types.
*/
#include <stddef.h>
#include <stdint.h>
#include <OTV0p2Base.h>
#include <OTRadValve_ActuatorPhysicalUI.h>
// Use namespaces to help avoid collisions.
namespace OTRadValve
{
#if defined(ModeButtonAndPotActuatorPhysicalUI_DEFINED)
//// Use WDT-based timer for xxxPause() routines.
//// Very tiny low-power sleep.
//static const uint8_t VERYTINY_PAUSE_MS = 5;
//static void inline veryTinyPause() { OTV0P2BASE::sleepLowPowerMs(VERYTINY_PAUSE_MS); }
//// Tiny low-power sleep to approximately match the PICAXE V0.09 routine of the same name.
//static const uint8_t TINY_PAUSE_MS = 15;
//static void inline tinyPause() { OTV0P2BASE::nap(WDTO_15MS); } // 15ms vs 18ms nominal for PICAXE V0.09 impl.
//// Small low-power sleep.
//static const uint8_t SMALL_PAUSE_MS = 30;
//static void inline smallPause() { OTV0P2BASE::nap(WDTO_30MS); }
//// Medium low-power sleep to approximately match the PICAXE V0.09 routine of the same name.
//// Premature wakeups MAY be allowed to avoid blocking I/O polling for too long.
//static const uint8_t MEDIUM_PAUSE_MS = 60;
//static void inline mediumPause() { OTV0P2BASE::nap(WDTO_60MS); } // 60ms vs 144ms nominal for PICAXE V0.09 impl.
//// Big low-power sleep to approximately match the PICAXE V0.09 routine of the same name.
//// Premature wakeups MAY be allowed to avoid blocking I/O polling for too long.
//static const uint8_t BIG_PAUSE_MS = 120;
//static void inline bigPause() { OTV0P2BASE::nap(WDTO_120MS); } // 120ms vs 288ms nominal for PICAXE V0.09 impl.
//
//// Pause between flashes to allow them to be distinguished (>100ms); was mediumPause() for PICAXE V0.09 impl.
//static void inline offPause()
// {
// bigPause(); // 120ms, was V0.09 144ms mediumPause() for PICAXE V0.09 impl.
//// pollIO(); // Slip in an I/O poll.
// }
// Record local manual operation of a physical UI control, eg not remote or via CLI.
// Marks room as occupied amongst other things.
// To be thread-/ISR- safe, everything that this touches or calls must be.
// Thread-safe.
void ModeButtonAndPotActuatorPhysicalUI::markUIControlUsed()
{
statusChange = true; // Note user interaction with the system.
uiTimeoutM = UI_DEFAULT_RECENT_USE_TIMEOUT_M; // Ensure that UI controls are kept 'warm' for a little while.
// FIXME
// #if defined(ENABLE_UI_WAKES_CLI)
// // Make CLI active for a while (at some slight possibly-significant energy cost).
// resetCLIActiveTimer(); // Thread-safe.
// #endif
// User operation of physical controls is strong indication of presence.
occupancy->markAsOccupied(); // Thread-safe.
}
// Record significant local manual operation of a physical UI control, eg not remote or via CLI.
// Marks room as occupied amongst other things.
// As markUIControlUsed() but likely to generate some feedback to the user, ASAP.
// Thread-safe.
void ModeButtonAndPotActuatorPhysicalUI::markUIControlUsedSignificant()
{
// Provide some instant visual feedback if possible.
if(NULL != safeISRLEDonOpt) { safeISRLEDonOpt(); }
// Flag up need for feedback.
significantUIOp = true;
// Do main UI-touched work.
markUIControlUsed();
}
// Call this nominally on even numbered seconds to allow the UI to operate.
// In practice call early once per 2s major cycle.
// Should never be skipped, so as to allow the UI to remain responsive.
// Runs in 350ms or less; usually takes only a few milliseconds or microseconds.
// Returns a non-zero value iff the user interacted with the system, and maybe caused a status change.
// NOTE: since this is on the minimum idle-loop code path, minimise CPU cycles, esp in frost mode.
// Replaces: bool tickUI(uint_fast8_t sec).
uint8_t ModeButtonAndPotActuatorPhysicalUI::read()
{
// True on every 4th tick/call, ie every ~8 seconds.
const bool forthTick = !((++tickCount) & 3); // True on every 4th tick.
// Perform any once-per-minute-ish operations, every 32 ticks.
const bool sec0 = (0 == (tickCount & 0x1f));
if(sec0)
{
ATOMIC_BLOCK (ATOMIC_RESTORESTATE)
{
// Run down UI interaction timer if need be, one tick per minute(ish).
if(uiTimeoutM > 0) { --uiTimeoutM; }
}
}
// const bool reportedRecently = occupancy->reportedRecently();
// Provide enhanced feedback when the has been very recent interaction with the UI,
// since the user is still quite likely to be continuing.
const bool enhancedUIFeedback = veryRecentUIControlUse();
if(NULL != tempPotOpt)
{
// Force relatively-frequent re-read of temp pot UI device
// and if there has been recent UI manual controls activity,
// to keep the valve UI responsive.
// #if !defined(ENABLE_FAST_TEMP_POT_SAMPLING) || !defined(ENABLE_OCCUPANCY_SUPPORT)
// if(enhancedUIFeedback || forthTick)
// #else
// // Even more responsive at some possible energy cost...
// Polls pot on every tick unless the room has been vacant for a day or two or is in FROST mode.
if(enhancedUIFeedback || forthTick || (valveMode->inWarmMode() && !occupancy->longLongVacant()))
// #endif
{
tempPotOpt->read();
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINT_FLASHSTRING("TP");
DEBUG_SERIAL_PRINT(TempPot.getRaw());
DEBUG_SERIAL_PRINTLN();
#endif
// Force to FROST mode (and cancel any erroneous BAKE, etc) when at FROST end of dial.
const bool isLo = tempPotOpt->isAtLoEndStop();
if(isLo) { valveMode->setWarmModeDebounced(false); }
// Feed back significant change in pot position, ie at temperature boundaries.
// Synthesise a 'hot' target temperature that distinguishes the end stops...
const uint8_t nominalWarmTarget = isLo ? 1 :
(tempPotOpt->isAtHiEndStop() ? 99 :
tempControl->getWARMTargetC());
// Record of 'last' nominalWarmTarget; initially 0.
static uint8_t lastNominalWarmTarget;
if(nominalWarmTarget != lastNominalWarmTarget)
{
// Note if a boundary was crossed, ignoring any false 'start-up' transient.
if(0 != lastNominalWarmTarget) { significantUIOp = true; }
#if 1 && defined(DEBUG)
DEBUG_SERIAL_PRINT_FLASHSTRING("WT");
DEBUG_SERIAL_PRINT(nominalWarmTarget);
DEBUG_SERIAL_PRINTLN();
#endif
lastNominalWarmTarget = nominalWarmTarget;
}
}
}
// Provide extra user feedback for significant UI actions...
if(significantUIOp) { userOpFeedback(); }
// Support cycling through modes polling the MODE button.
// If MODE button is active skip normal LED UI activity.
if(!pollMODEButton())
{
// Keep reporting UI status if the user has just touched the unit in some way or UI feedback is enhanced.
const bool justTouched = statusChange || enhancedUIFeedback;
// Mode button not pressed: indicate current mode with flash(es); more flashes if actually calling for heat.
// Force display while UI controls are being used, eg to indicate temp pot position.
if(justTouched || valveMode->inWarmMode()) // Generate flash(es) if in WARM mode or fiddling with UI other than Mode button.
{
// DHD20131223: only flash if the room not known to be dark so as to save energy and avoid disturbing sleep, etc.
// In this case force resample of light level frequently in case user turns light on eg to operate unit.
// Do show LED flash if user has recently operated controls (other than mode button) manually.
// Flash infrequently if no recently operated controls and not in BAKE mode and not actually calling for heat;
// this is to conserve batteries for those people who leave the valves in WARM mode all the time.
if(justTouched ||
((forthTick
|| valveController->isCallingForHeat()
|| valveMode->inBakeMode()) && !ambLight->isRoomDark()))
{
// First flash to indicate WARM mode (or pot being twiddled).
LEDon();
// LED on stepwise proportional to temp pot setting.
// Small number of steps (3) should help make positioning more obvious.
const uint8_t wt = tempControl->getWARMTargetC();
// Makes vtiny|tiny|medium flash for cool|OK|warm temperature target.
// Stick to minimum length flashes to save energy unless just touched.
if(!justTouched || tempControl->isEcoTemperature(wt)) { veryTinyPause(); }
else if(!tempControl->isComfortTemperature(wt)) { tinyPause(); }
else { mediumPause(); }
// Second flash to indicate actually calling for heat,
// or likely to be calling for heat while interacting with the controls, to give fast user feedback (TODO-695).
if((enhancedUIFeedback && valveController->isUnderTarget()) ||
valveController->isCallingForHeat() ||
valveMode->inBakeMode())
{
LEDoff();
offPause(); // V0.09 was mediumPause().
LEDon(); // flash
// Stick to minimum length flashes to save energy unless just touched.
if(!justTouched || tempControl->isEcoTemperature(wt)) { veryTinyPause(); }
else if(!tempControl->isComfortTemperature(wt)) { OTV0P2BASE::sleepLowPowerMs((VERYTINY_PAUSE_MS + TINY_PAUSE_MS) / 2); }
else { tinyPause(); }
if(valveMode->inBakeMode())
{
// Third (lengthened) flash to indicate BAKE mode.
LEDoff();
mediumPause(); // Note different flash off time to try to distinguish this last flash.
LEDon();
// Makes tiny|small|medium flash for eco|OK|comfort temperature target.
// Stick to minimum length flashes to save energy unless just touched.
if(!justTouched || tempControl->isEcoTemperature(wt)) { veryTinyPause(); }
else if(!tempControl->isComfortTemperature(wt)) { smallPause(); }
else { mediumPause(); }
}
}
}
}
// Even in FROST mode, and if actually calling for heat (eg opening the rad valve significantly, etc)
// then emit a tiny double flash on every 4th tick.
// This call for heat may be frost protection or pre-warming / anticipating demand.
// DHD20130528: new 4th-tick flash in FROST mode...
// DHD20131223: only flash if the room is not dark (ie or if no working light sensor) so as to save energy and avoid disturbing sleep, etc.
else if(forthTick &&
!ambLight->isRoomDark() &&
valveController->isCallingForHeat() /* &&
NominalRadValve.isControlledValveReallyOpen() */ )
{
// Double flash every 4th tick indicates call for heat while in FROST MODE (matches call for heat in WARM mode).
LEDon(); // flash
veryTinyPause();
LEDoff();
offPause();
LEDon(); // flash
veryTinyPause();
}
}
// Ensure that the main UI LED is forced off unconditionally at least once each cycle.
LEDoff();
// Handle LEARN buttons (etc) in derived classes.
// Also can be used to handle any simple user schedules.
handleOtherUserControls(statusChange);
const bool statusChanged = statusChange;
statusChange = false; // Potential race.
return(statusChanged);
}
#endif // ModeButtonAndPotActuatorPhysicalUI_DEFINED
}
<|endoftext|> |
<commit_before>//---------------------------------------------------------
// Copyright 2018 Ontario Institute for Cancer Research
// Written by Jared Simpson ([email protected])
//---------------------------------------------------------
//
// nanopolish_vcf2fasta - write a new genome sequence
// by introducing variants from a set of vcf files
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <vector>
#include <map>
#include <inttypes.h>
#include <assert.h>
#include <math.h>
#include <sys/time.h>
#include <algorithm>
#include <sstream>
#include <set>
#include <omp.h>
#include <getopt.h>
#include <fast5.hpp>
#include "htslib/faidx.h"
#include "nanopolish_common.h"
#include "nanopolish_variant.h"
#include "nanopolish_eventalign.h"
#include "nanopolish_haplotype.h"
//
// Getopt
//
#define SUBPROGRAM "vcf2fasta"
static const char *VCF2FASTA_VERSION_MESSAGE =
SUBPROGRAM " Version " PACKAGE_VERSION "\n"
"Written by Jared Simpson.\n"
"\n"
"Copyright 2018 Ontario Institute for Cancer Research\n";
static const char *VCF2FASTA_USAGE_MESSAGE =
"Usage: " PACKAGE_NAME " " SUBPROGRAM " [OPTIONS] segment1.vcf segment2.vcf ...\n"
"Write a new genome sequence by introducing variants from the input files\n"
"\n"
" -v, --verbose display verbose output\n"
" --version display version\n"
" --help display this help and exit\n"
" -g, --genome=FILE the input genome is in FILE\n"
"\nReport bugs to " PACKAGE_BUGREPORT "\n\n";
namespace opt
{
static unsigned int verbose;
static std::vector<std::string> input_vcf_files;
static std::string genome_file;
}
static const char* shortopts = "g:v";
enum { OPT_HELP = 1, OPT_VERSION };
static const struct option longopts[] = {
{ "verbose", no_argument, NULL, 'v' },
{ "help", no_argument, NULL, OPT_HELP },
{ "version", no_argument, NULL, OPT_VERSION },
{ "genome", required_argument, NULL, 'g' },
{ NULL, 0, NULL, 0 }
};
void parse_vcf2fasta_options(int argc, char** argv)
{
bool die = false;
for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) {
std::istringstream arg(optarg != NULL ? optarg : "");
switch (c) {
case '?': die = true; break;
case 'v': opt::verbose++; break;
case 'g': arg >> opt::genome_file; break;
case OPT_HELP:
std::cout << VCF2FASTA_USAGE_MESSAGE;
exit(EXIT_SUCCESS);
case OPT_VERSION:
std::cout << VCF2FASTA_VERSION_MESSAGE;
exit(EXIT_SUCCESS);
}
}
if (argc - optind < 1) {
std::cerr << SUBPROGRAM ": not enough arguments\n";
die = true;
}
if (die)
{
std::cout << "\n" << VCF2FASTA_USAGE_MESSAGE;
exit(EXIT_FAILURE);
}
for(; optind < argc; ++optind) {
opt::input_vcf_files.push_back(argv[optind]);
}
}
int vcf2fasta_main(int argc, char** argv)
{
parse_vcf2fasta_options(argc, argv);
// Read genome file
faidx_t *fai = fai_load(opt::genome_file.c_str());
// Read VCF files and gather variants for each contig and the polishing window coordinates
std::map<std::string, std::vector<Variant>> variants_by_contig;
std::map<std::string, std::vector<std::pair<int, int>>> windows_by_contig;
for(const auto& filename : opt::input_vcf_files) {
std::string window_str;
std::vector<Variant> out;
std::ifstream infile(filename);
std::string line;
while(getline(infile, line)) {
// parse header
if(line[0] == '#') {
// check for window coordinates
if(line.find("nanopolish_window") != std::string::npos) {
std::vector<std::string> fields = split(line, '=');
assert(fields.size() == 2);
window_str = fields[1];
}
} else {
Variant v(line);
variants_by_contig[v.ref_name].push_back(v);
}
}
if(window_str.empty()) {
fprintf(stderr, "error: could not detect polishing window from input file %s\n", filename.c_str());
exit(EXIT_FAILURE);
}
std::string window_contig;
int window_start, window_end;
parse_region_string(window_str, window_contig, window_start, window_end);
windows_by_contig[window_contig].push_back(std::make_pair(window_start, window_end));
}
size_t n_contigs = faidx_nseq(fai);
for(size_t contig_idx = 0; contig_idx < n_contigs; ++contig_idx) {
std::string contig = faidx_iseq(fai, contig_idx);
int contig_length = faidx_seq_len(fai, contig.c_str());
// Confirm that all windows on this contig have been polished
bool window_check_ok = true;
auto& windows = windows_by_contig[contig];
std::sort(windows.begin(), windows.end());
if(windows[0].first != 0) {
fprintf(stderr, "error: first %d bases are not covered by a polished window for contig %s.\n", windows[0].first, contig.c_str());
window_check_ok = false;
}
for(size_t window_idx = 1; window_idx < windows.size(); ++window_idx) {
int prev_start = windows[window_idx - 1].first;
int prev_end = windows[window_idx - 1].second;
int curr_start = windows[window_idx].first;
int curr_end = windows[window_idx].second;
if(curr_start > prev_end) {
fprintf(stderr, "error: adjacent polishing windows do not overlap (%d-%d and %d-%d)\n", prev_start, prev_end, curr_start, curr_end);
window_check_ok = false;
}
}
int end_gap = contig_length - windows.back().second;
if(end_gap > 500) {
fprintf(stderr, "error: last %d bases are not covered by a polished window for contig %s.\n", end_gap, contig.c_str());
window_check_ok = false;
}
if(!window_check_ok) {
fprintf(stderr, "error: one or more polishing windows are missing. Please check that all nanopolish variants --consensus jobs ran to completion\n");
exit(EXIT_FAILURE);
}
int length;
char* seq = fai_fetch(fai, contig.c_str(), &length);
if(length < 0) {
fprintf(stderr, "error: could not fetch contig %s\n", contig.c_str());
exit(EXIT_FAILURE);
}
auto& variants = variants_by_contig[contig];
std::sort(variants.begin(), variants.end(), sortByPosition);
// remove duplicate variants
VariantKeyEqualityComp vkec;
auto last = std::unique(variants.begin(), variants.end(), vkec);
variants.erase(last, variants.end());
assert(variants.size() < (1 << 30));
uint32_t deleted_tag = 1 << 30;
uint32_t variant_tag = 1 << 31;
// make a vector holding either a literal character or an index to the variant that needs to be applied
std::vector<uint32_t> consensus_record(length);
for(size_t i = 0; i < length; ++i) {
consensus_record[i] = seq[i];
}
size_t num_skipped = 0;
size_t num_subs = 0;
size_t num_insertions = 0;
size_t num_deletions = 0;
// update the consensus record according to the variants for this contig
size_t applied_variants = 0;
for(size_t variant_idx = 0; variant_idx < variants.size(); ++variant_idx) {
const Variant& v = variants[variant_idx];
// check if the variant record matches the reference sequence
bool matches_ref = true;
for(size_t i = 0; i < v.ref_seq.length(); ++i) {
matches_ref = matches_ref && v.ref_seq[i] == consensus_record[v.ref_position + i];
}
if(!matches_ref) {
num_skipped += 1;
continue;
}
// mark the first base of the reference sequence as a variant and set the index
consensus_record[v.ref_position] = variant_tag | variant_idx;
// mark the subsequent bases of the reference as deleted
for(size_t i = 1; i < v.ref_seq.length(); ++i) {
consensus_record[v.ref_position + i] = deleted_tag;
}
num_subs += v.ref_seq.length() == v.alt_seq.length();
num_insertions += v.ref_seq.length() < v.alt_seq.length();
num_deletions += v.ref_seq.length() > v.alt_seq.length();
}
// write out the consensus record
std::string out;
out.reserve(length);
for(size_t i = 0; i < length; ++i) {
uint32_t r = consensus_record[i];
if(r & variant_tag) {
out.append(variants[r & ~variant_tag].alt_seq);
} else if(r & ~deleted_tag) {
out.append(1, r);
} else {
assert(r & deleted_tag);
}
}
fprintf(stderr, "[vcf2fasta] rewrote contig %s with %zu subs, %zu ins, %zu dels (%zu skipped)\n", contig.c_str(), num_subs, num_insertions, num_deletions, num_skipped);
fprintf(stdout, ">%s\n%s\n", contig.c_str(), out.c_str());
free(seq);
seq = NULL;
}
return 0;
}
<commit_msg>vcf2fasta: -g parameter is required<commit_after>//---------------------------------------------------------
// Copyright 2018 Ontario Institute for Cancer Research
// Written by Jared Simpson ([email protected])
//---------------------------------------------------------
//
// nanopolish_vcf2fasta - write a new genome sequence
// by introducing variants from a set of vcf files
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <vector>
#include <map>
#include <inttypes.h>
#include <assert.h>
#include <math.h>
#include <sys/time.h>
#include <algorithm>
#include <sstream>
#include <set>
#include <omp.h>
#include <getopt.h>
#include <fast5.hpp>
#include "htslib/faidx.h"
#include "nanopolish_common.h"
#include "nanopolish_variant.h"
#include "nanopolish_eventalign.h"
#include "nanopolish_haplotype.h"
//
// Getopt
//
#define SUBPROGRAM "vcf2fasta"
static const char *VCF2FASTA_VERSION_MESSAGE =
SUBPROGRAM " Version " PACKAGE_VERSION "\n"
"Written by Jared Simpson.\n"
"\n"
"Copyright 2018 Ontario Institute for Cancer Research\n";
static const char *VCF2FASTA_USAGE_MESSAGE =
"Usage: " PACKAGE_NAME " " SUBPROGRAM " -g draft.fa segment1.vcf segment2.vcf ...\n"
"Write a new genome sequence by introducing variants from the input files\n"
"\n"
" -v, --verbose display verbose output\n"
" --version display version\n"
" --help display this help and exit\n"
" -g, --genome=FILE the input genome is in FILE\n"
"\nReport bugs to " PACKAGE_BUGREPORT "\n\n";
namespace opt
{
static unsigned int verbose;
static std::vector<std::string> input_vcf_files;
static std::string genome_file;
}
static const char* shortopts = "g:v";
enum { OPT_HELP = 1, OPT_VERSION };
static const struct option longopts[] = {
{ "verbose", no_argument, NULL, 'v' },
{ "help", no_argument, NULL, OPT_HELP },
{ "version", no_argument, NULL, OPT_VERSION },
{ "genome", required_argument, NULL, 'g' },
{ NULL, 0, NULL, 0 }
};
void parse_vcf2fasta_options(int argc, char** argv)
{
bool die = false;
for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) {
std::istringstream arg(optarg != NULL ? optarg : "");
switch (c) {
case '?': die = true; break;
case 'v': opt::verbose++; break;
case 'g': arg >> opt::genome_file; break;
case OPT_HELP:
std::cout << VCF2FASTA_USAGE_MESSAGE;
exit(EXIT_SUCCESS);
case OPT_VERSION:
std::cout << VCF2FASTA_VERSION_MESSAGE;
exit(EXIT_SUCCESS);
}
}
if(opt::genome_file.empty()) {
std::cerr << SUBPROGRAM ": -g/--genome file is required\n";
die = true;
}
if (argc - optind < 1) {
std::cerr << SUBPROGRAM ": not enough arguments\n";
die = true;
}
if (die)
{
std::cout << "\n" << VCF2FASTA_USAGE_MESSAGE;
exit(EXIT_FAILURE);
}
for(; optind < argc; ++optind) {
opt::input_vcf_files.push_back(argv[optind]);
}
}
int vcf2fasta_main(int argc, char** argv)
{
parse_vcf2fasta_options(argc, argv);
// Read genome file
faidx_t *fai = fai_load(opt::genome_file.c_str());
// Read VCF files and gather variants for each contig and the polishing window coordinates
std::map<std::string, std::vector<Variant>> variants_by_contig;
std::map<std::string, std::vector<std::pair<int, int>>> windows_by_contig;
for(const auto& filename : opt::input_vcf_files) {
std::string window_str;
std::vector<Variant> out;
std::ifstream infile(filename);
std::string line;
while(getline(infile, line)) {
// parse header
if(line[0] == '#') {
// check for window coordinates
if(line.find("nanopolish_window") != std::string::npos) {
std::vector<std::string> fields = split(line, '=');
assert(fields.size() == 2);
window_str = fields[1];
}
} else {
Variant v(line);
variants_by_contig[v.ref_name].push_back(v);
}
}
if(window_str.empty()) {
fprintf(stderr, "error: could not detect polishing window from input file %s\n", filename.c_str());
exit(EXIT_FAILURE);
}
std::string window_contig;
int window_start, window_end;
parse_region_string(window_str, window_contig, window_start, window_end);
windows_by_contig[window_contig].push_back(std::make_pair(window_start, window_end));
}
size_t n_contigs = faidx_nseq(fai);
for(size_t contig_idx = 0; contig_idx < n_contigs; ++contig_idx) {
std::string contig = faidx_iseq(fai, contig_idx);
int contig_length = faidx_seq_len(fai, contig.c_str());
// Confirm that all windows on this contig have been polished
bool window_check_ok = true;
auto& windows = windows_by_contig[contig];
std::sort(windows.begin(), windows.end());
if(windows[0].first != 0) {
fprintf(stderr, "error: first %d bases are not covered by a polished window for contig %s.\n", windows[0].first, contig.c_str());
window_check_ok = false;
}
for(size_t window_idx = 1; window_idx < windows.size(); ++window_idx) {
int prev_start = windows[window_idx - 1].first;
int prev_end = windows[window_idx - 1].second;
int curr_start = windows[window_idx].first;
int curr_end = windows[window_idx].second;
if(curr_start > prev_end) {
fprintf(stderr, "error: adjacent polishing windows do not overlap (%d-%d and %d-%d)\n", prev_start, prev_end, curr_start, curr_end);
window_check_ok = false;
}
}
int end_gap = contig_length - windows.back().second;
if(end_gap > 500) {
fprintf(stderr, "error: last %d bases are not covered by a polished window for contig %s.\n", end_gap, contig.c_str());
window_check_ok = false;
}
if(!window_check_ok) {
fprintf(stderr, "error: one or more polishing windows are missing. Please check that all nanopolish variants --consensus jobs ran to completion\n");
exit(EXIT_FAILURE);
}
int length;
char* seq = fai_fetch(fai, contig.c_str(), &length);
if(length < 0) {
fprintf(stderr, "error: could not fetch contig %s\n", contig.c_str());
exit(EXIT_FAILURE);
}
auto& variants = variants_by_contig[contig];
std::sort(variants.begin(), variants.end(), sortByPosition);
// remove duplicate variants
VariantKeyEqualityComp vkec;
auto last = std::unique(variants.begin(), variants.end(), vkec);
variants.erase(last, variants.end());
assert(variants.size() < (1 << 30));
uint32_t deleted_tag = 1 << 30;
uint32_t variant_tag = 1 << 31;
// make a vector holding either a literal character or an index to the variant that needs to be applied
std::vector<uint32_t> consensus_record(length);
for(size_t i = 0; i < length; ++i) {
consensus_record[i] = seq[i];
}
size_t num_skipped = 0;
size_t num_subs = 0;
size_t num_insertions = 0;
size_t num_deletions = 0;
// update the consensus record according to the variants for this contig
size_t applied_variants = 0;
for(size_t variant_idx = 0; variant_idx < variants.size(); ++variant_idx) {
const Variant& v = variants[variant_idx];
// check if the variant record matches the reference sequence
bool matches_ref = true;
for(size_t i = 0; i < v.ref_seq.length(); ++i) {
matches_ref = matches_ref && v.ref_seq[i] == consensus_record[v.ref_position + i];
}
if(!matches_ref) {
num_skipped += 1;
continue;
}
// mark the first base of the reference sequence as a variant and set the index
consensus_record[v.ref_position] = variant_tag | variant_idx;
// mark the subsequent bases of the reference as deleted
for(size_t i = 1; i < v.ref_seq.length(); ++i) {
consensus_record[v.ref_position + i] = deleted_tag;
}
num_subs += v.ref_seq.length() == v.alt_seq.length();
num_insertions += v.ref_seq.length() < v.alt_seq.length();
num_deletions += v.ref_seq.length() > v.alt_seq.length();
}
// write out the consensus record
std::string out;
out.reserve(length);
for(size_t i = 0; i < length; ++i) {
uint32_t r = consensus_record[i];
if(r & variant_tag) {
out.append(variants[r & ~variant_tag].alt_seq);
} else if(r & ~deleted_tag) {
out.append(1, r);
} else {
assert(r & deleted_tag);
}
}
fprintf(stderr, "[vcf2fasta] rewrote contig %s with %zu subs, %zu ins, %zu dels (%zu skipped)\n", contig.c_str(), num_subs, num_insertions, num_deletions, num_skipped);
fprintf(stdout, ">%s\n%s\n", contig.c_str(), out.c_str());
free(seq);
seq = NULL;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "../stdafx.h"
#include "wcashjson.h"
#include "wpkistore.h"
void WCashJson::Init(v8::Handle<v8::Object> exports){
METHOD_BEGIN();
v8::Local<v8::String> className = Nan::New("CashJson").ToLocalChecked();
// Basic instance setup
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(className);
tpl->InstanceTemplate()->SetInternalFieldCount(1); // req'd by ObjectWrap
Nan::SetPrototypeMethod(tpl, "import", Import);
Nan::SetPrototypeMethod(tpl, "export", Export);
// Store the constructor in the target bindings.
constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked());
exports->Set(className, tpl->GetFunction());
}
NAN_METHOD(WCashJson::New){
METHOD_BEGIN();
try{
WCashJson *obj = new WCashJson();
if (info[0]->IsUndefined()){
Nan::ThrowError("Parameter 1 is required");
return;
}
else {
#if defined(OPENSSL_SYS_WINDOWS)
LPCWSTR wCont = (LPCWSTR)* v8::String::Value(info[0]->ToString());
int string_len = WideCharToMultiByte(CP_ACP, 0, wCont, -1, NULL, 0, NULL, NULL);
if (!string_len) {
Nan::ThrowError("Error WideCharToMultiByte");
}
char* converted = new char[string_len];
if (!converted) {
Nan::ThrowError("Error LocalAlloc");
}
string_len = WideCharToMultiByte(CP_ACP, 0, wCont, -1, converted, string_len, NULL, NULL);
if (!string_len)
{
free(converted);
Nan::ThrowError("Error WideCharToMultiByte");
}
std::string result = converted;
delete[] converted;
const char *json = result.c_str();
#else
v8::String::Utf8Value v8Str(info[0]->ToString());
char *json = *v8Str;
#endif // OPENSSL_SYS_WINDOWS
obj->data_ = new CashJson(new std::string(json));
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
return;
}
}
TRY_END();
}
NAN_METHOD(WCashJson::Import) {
METHOD_BEGIN();
try {
LOGGER_ARG("items");
WPkiItem * wItem = WPkiItem::Unwrap<WPkiItem>(info[0]->ToObject());
UNWRAP_DATA(CashJson);
_this->importJson(wItem->data_);
return;
}
TRY_END();
}
NAN_METHOD(WCashJson::Export) {
METHOD_BEGIN();
try{
UNWRAP_DATA(CashJson);
Handle<PkiItemCollection> res = _this->exportJson();
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Local<v8::Array> array8 = v8::Array::New(isolate, res->length());
for (int i = 0; i < res->length(); i++){
v8::Local<v8::Object> tempObj = v8::Object::New(isolate);
Handle<PkiItem> item = res->items(i);
tempObj->Set(v8::String::NewFromUtf8(isolate, "type"),
v8::String::NewFromUtf8(isolate, item->type->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "format"),
v8::String::NewFromUtf8(isolate, item->format->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "provider"),
v8::String::NewFromUtf8(isolate, item->provider->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "category"),
v8::String::NewFromUtf8(isolate, item->category->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "uri"),
v8::String::NewFromUtf8(isolate, item->uri->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "hash"),
v8::String::NewFromUtf8(isolate, item->hash->c_str()));
if (strcmp(item->type->c_str(), "CERTIFICATE") == 0){
tempObj->Set(v8::String::NewFromUtf8(isolate, "subjectName"),
v8::String::NewFromUtf8(isolate, item->certSubjectName->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "subjectFriendlyName"),
v8::String::NewFromUtf8(isolate, item->certSubjectFriendlyName->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "issuerName"),
v8::String::NewFromUtf8(isolate, item->certIssuerName->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "issuerFriendlyName"),
v8::String::NewFromUtf8(isolate, item->certIssuerFriendlyName->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "notBefore"),
v8::String::NewFromUtf8(isolate, item->certNotBefore->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "notAfter"),
v8::String::NewFromUtf8(isolate, item->certNotAfter->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "serial"),
v8::String::NewFromUtf8(isolate, item->certSerial->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "key"),
v8::String::NewFromUtf8(isolate, item->certKey->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "organizationName"),
v8::String::NewFromUtf8(isolate, item->certOrganizationName->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "signatureAlgorithm"),
v8::String::NewFromUtf8(isolate, item->certSignatureAlgorithm->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "signatureDigestAlgorithm"),
v8::String::NewFromUtf8(isolate, item->certSignatureDigestAlgorithm->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "publicKeyAlgorithm"),
v8::String::NewFromUtf8(isolate, item->certPublicKeyAlgorithm->c_str()));
array8->Set(i, tempObj);
continue;
}
if (strcmp(item->type->c_str(), "CRL") == 0){
tempObj->Set(v8::String::NewFromUtf8(isolate, "issuerName"),
v8::String::NewFromUtf8(isolate, item->crlIssuerName->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "issuerFriendlyName"),
v8::String::NewFromUtf8(isolate, item->crlIssuerFriendlyName->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "lastUpdate"),
v8::String::NewFromUtf8(isolate, item->crlLastUpdate->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "nextUpdate"),
v8::String::NewFromUtf8(isolate, item->crlNextUpdate->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "signatureAlgorithm"),
v8::String::NewFromUtf8(isolate, item->crlSignatureAlgorithm->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "signatureDigestAlgorithm"),
v8::String::NewFromUtf8(isolate, item->crlSignatureDigestAlgorithm->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "authorityKeyid"),
v8::String::NewFromUtf8(isolate, item->crlAuthorityKeyid->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "crlNumber"),
v8::String::NewFromUtf8(isolate, item->crlCrlNumber->c_str()));
array8->Set(i, tempObj);
continue;
}
if (strcmp(item->type->c_str(), "REQUEST") == 0){
tempObj->Set(v8::String::NewFromUtf8(isolate, "subjectName"),
v8::String::NewFromUtf8(isolate, item->csrSubjectName->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "subjectFriendlyName"),
v8::String::NewFromUtf8(isolate, item->csrSubjectFriendlyName->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "key"),
v8::String::NewFromUtf8(isolate, item->csrKey->c_str()));
array8->Set(i, tempObj);
continue;
}
if (strcmp(item->type->c_str(), "KEY") == 0){
tempObj->Set(v8::String::NewFromUtf8(isolate, "encrypted"),
v8::Boolean::New(isolate, item->keyEncrypted));
array8->Set(i, tempObj);
continue;
}
}
info.GetReturnValue().Set(array8);
return;
}
TRY_END();
}<commit_msg>fix memory released using the 'free' function<commit_after>#include "../stdafx.h"
#include "wcashjson.h"
#include "wpkistore.h"
void WCashJson::Init(v8::Handle<v8::Object> exports){
METHOD_BEGIN();
v8::Local<v8::String> className = Nan::New("CashJson").ToLocalChecked();
// Basic instance setup
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(className);
tpl->InstanceTemplate()->SetInternalFieldCount(1); // req'd by ObjectWrap
Nan::SetPrototypeMethod(tpl, "import", Import);
Nan::SetPrototypeMethod(tpl, "export", Export);
// Store the constructor in the target bindings.
constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked());
exports->Set(className, tpl->GetFunction());
}
NAN_METHOD(WCashJson::New){
METHOD_BEGIN();
try{
WCashJson *obj = new WCashJson();
if (info[0]->IsUndefined()){
Nan::ThrowError("Parameter 1 is required");
return;
}
else {
#if defined(OPENSSL_SYS_WINDOWS)
LPCWSTR wCont = (LPCWSTR)* v8::String::Value(info[0]->ToString());
int string_len = WideCharToMultiByte(CP_ACP, 0, wCont, -1, NULL, 0, NULL, NULL);
if (!string_len) {
Nan::ThrowError("Error WideCharToMultiByte");
}
char* converted = new char[string_len];
if (!converted) {
Nan::ThrowError("Error LocalAlloc");
}
string_len = WideCharToMultiByte(CP_ACP, 0, wCont, -1, converted, string_len, NULL, NULL);
if (!string_len)
{
delete[] converted;
Nan::ThrowError("Error WideCharToMultiByte");
}
std::string result = converted;
delete[] converted;
const char *json = result.c_str();
#else
v8::String::Utf8Value v8Str(info[0]->ToString());
char *json = *v8Str;
#endif // OPENSSL_SYS_WINDOWS
obj->data_ = new CashJson(new std::string(json));
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
return;
}
}
TRY_END();
}
NAN_METHOD(WCashJson::Import) {
METHOD_BEGIN();
try {
LOGGER_ARG("items");
WPkiItem * wItem = WPkiItem::Unwrap<WPkiItem>(info[0]->ToObject());
UNWRAP_DATA(CashJson);
_this->importJson(wItem->data_);
return;
}
TRY_END();
}
NAN_METHOD(WCashJson::Export) {
METHOD_BEGIN();
try{
UNWRAP_DATA(CashJson);
Handle<PkiItemCollection> res = _this->exportJson();
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Local<v8::Array> array8 = v8::Array::New(isolate, res->length());
for (int i = 0; i < res->length(); i++){
v8::Local<v8::Object> tempObj = v8::Object::New(isolate);
Handle<PkiItem> item = res->items(i);
tempObj->Set(v8::String::NewFromUtf8(isolate, "type"),
v8::String::NewFromUtf8(isolate, item->type->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "format"),
v8::String::NewFromUtf8(isolate, item->format->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "provider"),
v8::String::NewFromUtf8(isolate, item->provider->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "category"),
v8::String::NewFromUtf8(isolate, item->category->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "uri"),
v8::String::NewFromUtf8(isolate, item->uri->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "hash"),
v8::String::NewFromUtf8(isolate, item->hash->c_str()));
if (strcmp(item->type->c_str(), "CERTIFICATE") == 0){
tempObj->Set(v8::String::NewFromUtf8(isolate, "subjectName"),
v8::String::NewFromUtf8(isolate, item->certSubjectName->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "subjectFriendlyName"),
v8::String::NewFromUtf8(isolate, item->certSubjectFriendlyName->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "issuerName"),
v8::String::NewFromUtf8(isolate, item->certIssuerName->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "issuerFriendlyName"),
v8::String::NewFromUtf8(isolate, item->certIssuerFriendlyName->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "notBefore"),
v8::String::NewFromUtf8(isolate, item->certNotBefore->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "notAfter"),
v8::String::NewFromUtf8(isolate, item->certNotAfter->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "serial"),
v8::String::NewFromUtf8(isolate, item->certSerial->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "key"),
v8::String::NewFromUtf8(isolate, item->certKey->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "organizationName"),
v8::String::NewFromUtf8(isolate, item->certOrganizationName->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "signatureAlgorithm"),
v8::String::NewFromUtf8(isolate, item->certSignatureAlgorithm->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "signatureDigestAlgorithm"),
v8::String::NewFromUtf8(isolate, item->certSignatureDigestAlgorithm->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "publicKeyAlgorithm"),
v8::String::NewFromUtf8(isolate, item->certPublicKeyAlgorithm->c_str()));
array8->Set(i, tempObj);
continue;
}
if (strcmp(item->type->c_str(), "CRL") == 0){
tempObj->Set(v8::String::NewFromUtf8(isolate, "issuerName"),
v8::String::NewFromUtf8(isolate, item->crlIssuerName->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "issuerFriendlyName"),
v8::String::NewFromUtf8(isolate, item->crlIssuerFriendlyName->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "lastUpdate"),
v8::String::NewFromUtf8(isolate, item->crlLastUpdate->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "nextUpdate"),
v8::String::NewFromUtf8(isolate, item->crlNextUpdate->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "signatureAlgorithm"),
v8::String::NewFromUtf8(isolate, item->crlSignatureAlgorithm->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "signatureDigestAlgorithm"),
v8::String::NewFromUtf8(isolate, item->crlSignatureDigestAlgorithm->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "authorityKeyid"),
v8::String::NewFromUtf8(isolate, item->crlAuthorityKeyid->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "crlNumber"),
v8::String::NewFromUtf8(isolate, item->crlCrlNumber->c_str()));
array8->Set(i, tempObj);
continue;
}
if (strcmp(item->type->c_str(), "REQUEST") == 0){
tempObj->Set(v8::String::NewFromUtf8(isolate, "subjectName"),
v8::String::NewFromUtf8(isolate, item->csrSubjectName->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "subjectFriendlyName"),
v8::String::NewFromUtf8(isolate, item->csrSubjectFriendlyName->c_str()));
tempObj->Set(v8::String::NewFromUtf8(isolate, "key"),
v8::String::NewFromUtf8(isolate, item->csrKey->c_str()));
array8->Set(i, tempObj);
continue;
}
if (strcmp(item->type->c_str(), "KEY") == 0){
tempObj->Set(v8::String::NewFromUtf8(isolate, "encrypted"),
v8::Boolean::New(isolate, item->keyEncrypted));
array8->Set(i, tempObj);
continue;
}
}
info.GetReturnValue().Set(array8);
return;
}
TRY_END();
}<|endoftext|> |
<commit_before>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#include<atomic>
#include<mutex>
#include<sstream>
#include<string>
#include"ork/file_utils.hpp"
#include"ork/orientation.hpp"
#include"ork/tagger.hpp"
namespace ork {
class tagger_statics {
private:
file::path _debug_root = { ORK("./debug") };//Global guarded by mutex
std::mutex _mutex = { };
public:
tagger_statics() {}
ORK_NON_COPYABLE(tagger_statics)
public:
file::path debug_root() {
std::lock_guard<std::mutex> lock(_mutex);
return _debug_root;
}
void set_debug_root(const file::path&directory) {
std::lock_guard<std::mutex> lock(_mutex);
_debug_root = directory;
}
};
tagger_statics&g_tagger_statics() {
static tagger_statics statics;
return statics;
}
struct tagger::impl {
public:
std::atomic<unsigned>count;//Local static
const bool number_folder;//Local static constant
const string tag;//Local static constant
public:
impl(const string&tag)
: count(0)
, number_folder(true)
, tag(tag)
{}
impl(const string&tag, const bool numbered_folders)
: count(0)
, number_folder(numbered_folders)
, tag(tag)
{}
ORK_NON_COPYABLE(impl)
};
tagger::tagger(const string&tag) : _pimpl{ new impl(tag) } {}
tagger::tagger(const string&tag, bool numbered_folders) : _pimpl{ new impl(tag, numbered_folders) } {}
tagger::~tagger() {}
string tagger::sub_tag(const string&tag, size_t&index) {
string_stream stream;
stream << tag << index++ << ORK("_");
return stream.str();
}
string tagger::operator()() {
string_stream stream;
file::path p(g_tagger_statics().debug_root());
if(_pimpl->number_folder) {
stream << _pimpl->tag << ORK("_") << _pimpl->count++ << ORK("/");
p /= stream.str();
return p.ORK_GEN_STR();
}
else {
stream << _pimpl->tag << ORK("/");
p /= stream.str();
return p.ORK_GEN_STR() + std::to_string(_pimpl->count++) + ORK("_");
}
}
unsigned tagger::count() {
return _pimpl->count.load();
}
void tagger::set_debug_root(const string&directory) {
g_tagger_statics().set_debug_root(directory);
}
void tagger::set_debug_root(const string&as_is_path, const string&to_be_path) {
file::path directory(ORK("./debug/"));
directory /= file::path(as_is_path).stem();
directory /= file::path(to_be_path).stem();
g_tagger_statics().set_debug_root(directory.ORK_GEN_STR() + ORK("/"));
}
struct setup_hierarchy::impl {
public:
string setup_directory;
bool cached;
unsigned score;
std::vector<orientation>setups;
public:
impl()
: setup_directory()
, cached(false)
, score(0)
, setups()
{}
};
setup_hierarchy::setup_hierarchy(const string&setup_root, const string&as_is_path, const string&to_be_path)
: _pimpl{ new impl{ } }
{
if(!file::ensure_directory(setup_root))ORK_THROW(ORK("Setup root could not be created: ") << setup_root);
//if(!test_file(as_is_path))ORK_THROW(ORK("As-is file could not be found: ") << as_is_path);
//if(!test_file(to_be_path))ORK_THROW(ORK("To-Be file could not be found: ") << to_be_path);
const string as_is_name(file::path(as_is_path).stem().ORK_GEN_STR());
const string to_be_name(file::path(to_be_path).stem().ORK_GEN_STR());
file::path setup_path(setup_root);
setup_path /= as_is_name + ORK("/");
setup_path /= to_be_name + ORK("/");
_pimpl->setup_directory = setup_path.ORK_GEN_STR();
}
file::path setup_hierarchy::get_subdirectory() {
file::path setup_dir;
if(!top_subdirectory(get_path(), setup_dir))ORK_THROW(ORK("Setup directory not found for root: ") << get_path());
_pimpl->cached = false;//Dirty, in case the client fetches more than one setup
return setup_dir /= ORK("/");
}
struct setup_match {
string setups;
file::path setup_dir;
setup_match(const string&exact_setups) :setups(exact_setups), setup_dir() {}
void operator()(const file::path&p) {
if(!setup_dir.empty())return;//Already found (this could be a superstring, so find might work)
if(!ext_file::is_directory(p))return;//Just in case
const string dir_name(p.stem().ORK_GEN_STR());
if(dir_name.find(setups) != string::npos)setup_dir = p;
}
};
const string&setup_hierarchy::get_path() {
return _pimpl->setup_directory;
}
file::path setup_hierarchy::get_subdirectory(const string&exact_setups) {
setup_match match(exact_setups);
iterate_directory<setup_match, flat_search, sorted>::run(get_path(), match);
if(match.setup_dir.empty())ORK_THROW(ORK("Setup permutation not found: ") << exact_setups);
_pimpl->cached = false;//Dirty, in case the client fetches more than one setup
return match.setup_dir;
}
const std::vector<orientation>& setup_hierarchy::get_setups() {
return do_get_setups(file::canonical_normalized_trimmed(get_subdirectory()).filename().ORK_GEN_STR());
}
const std::vector<orientation>& setup_hierarchy::get_setups(const string&exact_setups) {
return do_get_setups(file::canonical_normalized_trimmed(get_subdirectory(exact_setups)).filename().ORK_GEN_STR());
}
const std::vector<orientation>&setup_hierarchy::do_get_setups(const string&setup_dir) {
if(!_pimpl->cached) {
//Directory format: score [orientation]+
//TODO: abstract writing, reading setups into a utility (right now process_plan class does the writing, but uses ACIS)
i_string_stream strm(setup_dir);
strm >> _pimpl->score;
string setup;
strm >> setup;
while(strm) {
_pimpl->setups.push_back(string2orientation(setup));
strm >> setup;
}
if(_pimpl->setups.empty())ORK_THROW(ORK("Setup directory not formatted correctly: ") << get_path() << ORK("/") << setup_dir);
_pimpl->cached = true;
}
if(_pimpl->setups.empty())ORK_THROW(ORK("Setups not found for directory: ") << setup_dir);
return _pimpl->setups;
}
}//namespace ork
<commit_msg>Tagger now uses string conversion for count<commit_after>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#include<atomic>
#include<mutex>
#include<sstream>
#include<string>
#include"ork/file_utils.hpp"
#include"ork/orientation.hpp"
#include"ork/string_utils.hpp"
#include"ork/tagger.hpp"
namespace ork {
class tagger_statics {
private:
file::path _debug_root = { ORK("./debug") };//Global guarded by mutex
std::mutex _mutex = { };
public:
tagger_statics() {}
ORK_NON_COPYABLE(tagger_statics)
public:
file::path debug_root() {
std::lock_guard<std::mutex> lock(_mutex);
return _debug_root;
}
void set_debug_root(const file::path&directory) {
std::lock_guard<std::mutex> lock(_mutex);
_debug_root = directory;
}
};
tagger_statics&g_tagger_statics() {
static tagger_statics statics;
return statics;
}
struct tagger::impl {
public:
std::atomic<unsigned>count;//Local static
const bool number_folder;//Local static constant
const string tag;//Local static constant
public:
impl(const string&tag)
: count(0)
, number_folder(true)
, tag(tag)
{}
impl(const string&tag, const bool numbered_folders)
: count(0)
, number_folder(numbered_folders)
, tag(tag)
{}
ORK_NON_COPYABLE(impl)
};
tagger::tagger(const string&tag) : _pimpl{ new impl(tag) } {}
tagger::tagger(const string&tag, bool numbered_folders) : _pimpl{ new impl(tag, numbered_folders) } {}
tagger::~tagger() {}
string tagger::sub_tag(const string&tag, size_t&index) {
string_stream stream;
stream << tag << index++ << ORK("_");
return stream.str();
}
string tagger::operator()() {
string_stream stream;
file::path p(g_tagger_statics().debug_root());
if(_pimpl->number_folder) {
stream << _pimpl->tag << ORK("_") << _pimpl->count++ << ORK("/");
p /= stream.str();
return p.ORK_GEN_STR();
}
else {
stream << _pimpl->tag << ORK("/");
p /= stream.str();
return p.ORK_GEN_STR() + to_string(_pimpl->count++) + ORK("_");
}
}
unsigned tagger::count() {
return _pimpl->count.load();
}
void tagger::set_debug_root(const string&directory) {
g_tagger_statics().set_debug_root(directory);
}
void tagger::set_debug_root(const string&as_is_path, const string&to_be_path) {
file::path directory(ORK("./debug/"));
directory /= file::path(as_is_path).stem();
directory /= file::path(to_be_path).stem();
g_tagger_statics().set_debug_root(directory.ORK_GEN_STR() + ORK("/"));
}
struct setup_hierarchy::impl {
public:
string setup_directory;
bool cached;
unsigned score;
std::vector<orientation>setups;
public:
impl()
: setup_directory()
, cached(false)
, score(0)
, setups()
{}
};
setup_hierarchy::setup_hierarchy(const string&setup_root, const string&as_is_path, const string&to_be_path)
: _pimpl{ new impl{ } }
{
if(!file::ensure_directory(setup_root))ORK_THROW(ORK("Setup root could not be created: ") << setup_root);
//if(!test_file(as_is_path))ORK_THROW(ORK("As-is file could not be found: ") << as_is_path);
//if(!test_file(to_be_path))ORK_THROW(ORK("To-Be file could not be found: ") << to_be_path);
const string as_is_name(file::path(as_is_path).stem().ORK_GEN_STR());
const string to_be_name(file::path(to_be_path).stem().ORK_GEN_STR());
file::path setup_path(setup_root);
setup_path /= as_is_name + ORK("/");
setup_path /= to_be_name + ORK("/");
_pimpl->setup_directory = setup_path.ORK_GEN_STR();
}
file::path setup_hierarchy::get_subdirectory() {
file::path setup_dir;
if(!top_subdirectory(get_path(), setup_dir))ORK_THROW(ORK("Setup directory not found for root: ") << get_path());
_pimpl->cached = false;//Dirty, in case the client fetches more than one setup
return setup_dir /= ORK("/");
}
struct setup_match {
string setups;
file::path setup_dir;
setup_match(const string&exact_setups) :setups(exact_setups), setup_dir() {}
void operator()(const file::path&p) {
if(!setup_dir.empty())return;//Already found (this could be a superstring, so find might work)
if(!ext_file::is_directory(p))return;//Just in case
const string dir_name(p.stem().ORK_GEN_STR());
if(dir_name.find(setups) != string::npos)setup_dir = p;
}
};
const string&setup_hierarchy::get_path() {
return _pimpl->setup_directory;
}
file::path setup_hierarchy::get_subdirectory(const string&exact_setups) {
setup_match match(exact_setups);
iterate_directory<setup_match, flat_search, sorted>::run(get_path(), match);
if(match.setup_dir.empty())ORK_THROW(ORK("Setup permutation not found: ") << exact_setups);
_pimpl->cached = false;//Dirty, in case the client fetches more than one setup
return match.setup_dir;
}
const std::vector<orientation>& setup_hierarchy::get_setups() {
return do_get_setups(file::canonical_normalized_trimmed(get_subdirectory()).filename().ORK_GEN_STR());
}
const std::vector<orientation>& setup_hierarchy::get_setups(const string&exact_setups) {
return do_get_setups(file::canonical_normalized_trimmed(get_subdirectory(exact_setups)).filename().ORK_GEN_STR());
}
const std::vector<orientation>&setup_hierarchy::do_get_setups(const string&setup_dir) {
if(!_pimpl->cached) {
//Directory format: score [orientation]+
//TODO: abstract writing, reading setups into a utility (right now process_plan class does the writing, but uses ACIS)
i_string_stream strm(setup_dir);
strm >> _pimpl->score;
string setup;
strm >> setup;
while(strm) {
_pimpl->setups.push_back(string2orientation(setup));
strm >> setup;
}
if(_pimpl->setups.empty())ORK_THROW(ORK("Setup directory not formatted correctly: ") << get_path() << ORK("/") << setup_dir);
_pimpl->cached = true;
}
if(_pimpl->setups.empty())ORK_THROW(ORK("Setups not found for directory: ") << setup_dir);
return _pimpl->setups;
}
}//namespace ork
<|endoftext|> |
<commit_before>#include <pthread.h>
#include <cstddef>
#include <cstdio>
#include "thread.h"
/*
* Initialize a thread object
*/
Thread::Thread() :
state(INIT)
{
// Initialize synchronization primitives
pthread_attr_init(&attr);
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&start_signal, NULL);
pthread_cond_init(&stop_signal, NULL);
pthread_mutex_lock(&mutex);
// Initialize some thread attributes
pthread_attr_setstacksize(&attr, 16000);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
// Try to create a thread
if (pthread_create(&id, &attr, Thread::dispatch, (void*) this) == 0) {
// Hold until the created thread reaches a certain execution point
pthread_cond_wait(&stop_signal, &mutex);
// Mark the thread as started
state = STARTED;
} else {
// Mark the thread as failed
state = STOPPED;
// TODO: Add error handling if thread creation failed
//pthread_mutex_unlock(&mutex);
//throw "Failed to create thread";
}
pthread_mutex_unlock(&mutex);
}
/*
* Destroy a thread object
*/
Thread::~Thread()
{
// Call stop. Note that this will *not* call stop for a derived class.
stop();
// Destroy synchronization primitives
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&start_signal);
pthread_cond_destroy(&stop_signal);
}
/*
* Start the thread
*/
void Thread::start()
{
pthread_mutex_lock(&mutex);
if (state == STARTED) {
// Mark the thread as good to go
state = RUNNING;
// Signal to the waiting thread that it's good to go
pthread_cond_signal(&start_signal);
}
pthread_mutex_unlock(&mutex);
}
/*
* Stop the thread
*/
void Thread::stop()
{
pthread_mutex_lock(&mutex);
if (state != STOPPED) {
// The client hasn't called start(), signal to the waiting thread that
// it should start and stop immediatly.
if (state != RUNNING) {
state = STOPPED;
pthread_cond_signal(&start_signal);
}
// Wait for the thread to finish up, we assume that the derived class'
// stop() implementation has been called, and that run() behaves properly.
pthread_cond_wait(&stop_signal, &mutex);
state = STOPPED;
}
pthread_mutex_unlock(&mutex);
}
/*
* Invoke run on a derived class
*/
void* Thread::dispatch(void* object)
{
Thread* thread = static_cast<Thread*>(object);
pthread_mutex_lock(&thread->mutex);
// Notify parent thread that we have been created
pthread_cond_signal(&thread->stop_signal);
// Wait until further notice
pthread_cond_wait(&thread->start_signal, &thread->mutex);
// Check if we are still good to go
bool run = thread->state == RUNNING;
pthread_mutex_unlock(&thread->mutex);
// Call the run() method of the derived class
if (run) {
thread->run();
}
pthread_mutex_lock(&thread->mutex);
// Notify parent thread that we are shutting down
pthread_cond_broadcast(&thread->stop_signal);
pthread_mutex_unlock(&thread->mutex);
pthread_exit(NULL);
}
<commit_msg>refactored the threading class<commit_after>#include <pthread.h>
#include <cstddef>
#include "thread.h"
/*
* Initialize a thread object
*/
Thread::Thread() :
state(INIT)
{
// Initialize synchronization primitives
pthread_attr_init(&attr);
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&start_signal, NULL);
pthread_cond_init(&stop_signal, NULL);
pthread_mutex_lock(&mutex);
// Initialize some thread attributes
pthread_attr_setstacksize(&attr, 16000);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
// Try to create a thread
if (pthread_create(&id, &attr, Thread::dispatch, (void*) this) == 0) {
// Hold until the created thread reaches a certain execution point
pthread_cond_wait(&stop_signal, &mutex);
// Mark the thread as started
state = STARTED;
} else {
// Mark the thread as failed
state = STOPPED;
// TODO: Add error handling if thread creation failed
//pthread_mutex_unlock(&mutex);
//throw "Failed to create thread";
}
pthread_mutex_unlock(&mutex);
}
/*
* Destroy a thread object
*/
Thread::~Thread()
{
// Stop thread
stop();
// Destroy synchronization primitives
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&start_signal);
pthread_cond_destroy(&stop_signal);
}
/*
* Start the thread
*/
void Thread::start()
{
pthread_mutex_lock(&mutex);
if (state == STARTED) {
// Mark the thread as good to go
state = RUNNING;
// Signal to the waiting thread that it's good to go
pthread_cond_signal(&start_signal);
}
pthread_mutex_unlock(&mutex);
}
void Thread::stop()
{
pthread_mutex_lock(&mutex);
if (state != STOPPED) {
// The client hasn't called start(), signal to the waiting thread that
// it should start and stop immediatly.
if (state != RUNNING) {
state = STOPPED;
pthread_cond_signal(&start_signal);
pthread_cond_wait(&stop_signal, &mutex);
}
// Wait for the thread to finish up, we assume that the derived class'
// stop() implementation has been called, and that run() behaves properly.
state = STOPPED;
pthread_join(id, NULL);
}
pthread_mutex_unlock(&mutex);
}
/*
* Invoke run on a derived class
*/
void* Thread::dispatch(void* object)
{
Thread* thread = static_cast<Thread*>(object);
pthread_mutex_lock(&thread->mutex);
// Notify parent thread that we have been created
pthread_cond_signal(&thread->stop_signal);
// Wait until further notice
pthread_cond_wait(&thread->start_signal, &thread->mutex);
// Check if we are still good to go
bool run = thread->state == RUNNING;
pthread_mutex_unlock(&thread->mutex);
// Call the run() method of the derived class
if (run) {
thread->run();
}
pthread_cond_signal(&thread->stop_signal);
pthread_exit(NULL);
}
<|endoftext|> |
<commit_before>#include "saiga/opengl/shader/shader.h"
#include "saiga/opengl/texture/raw_texture.h"
#include "saiga/util/error.h"
#include <fstream>
#include <algorithm>
#include "saiga/util/assert.h"
GLuint Shader::boundShader = 0;
Shader::Shader(){
}
Shader::~Shader(){
destroyProgram();
}
// ===================================== program stuff =====================================
GLuint Shader::createProgram(){
program = glCreateProgram();
//attach all shaders
for (auto& sp : shaders){
glAttachShader(program, sp->id);
}
assert_no_glerror();
glLinkProgram(program);
if (!printProgramLog()){
return 0;
}
assert_no_glerror();
for (auto& sp : shaders){
sp->deleteGLShader();
}
assert_no_glerror();
checkUniforms();
assert_no_glerror();
return program;
}
void Shader::destroyProgram()
{
if (program != 0){
glDeleteProgram(program);
program = 0;
assert_no_glerror();
}
}
bool Shader::printProgramLog(){
//Make sure name is shader
if (glIsProgram(program) == GL_TRUE)
{
//Program log length
int infoLogLength = 0;
int maxLength = infoLogLength;
//Get info std::string length
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength);
//Allocate std::string
char* infoLog = new char[maxLength];
//Get info log
glGetProgramInfoLog(program, maxLength, &infoLogLength, infoLog);
if (infoLogLength > 0)
{
//Print Log
std::cout << "program error:" << std::endl;
std::cout << infoLog << std::endl;
}
assert_no_glerror();
//Deallocate std::string
delete[] infoLog;
return infoLogLength == 0;
}
else
{
cout << "Name " << program << " is not a program" << endl;
return false;
}
}
void Shader::bind(){
assert(program);
//allow double bind
assert(boundShader == program || boundShader == 0);
boundShader = program;
glUseProgram(program);
assert_no_glerror();
}
void Shader::unbind(){
//allow double unbind
assert(boundShader == program || boundShader == 0);
boundShader = 0;
#if defined(SAIGA_DEBUG)
glUseProgram(0);
#endif
assert_no_glerror();
}
bool Shader::isBound(){
return boundShader == program;
}
// ===================================== Compute Shaders =====================================
glm::uvec3 Shader::getComputeWorkGroupSize()
{
GLint work_size[3];
glGetProgramiv(program, GL_COMPUTE_WORK_GROUP_SIZE, work_size);
assert_no_glerror();
return glm::uvec3(work_size[0], work_size[1], work_size[2]);
}
glm::uvec3 Shader::getNumGroupsCeil(const glm::uvec3 &problem_size)
{
return getNumGroupsCeil(problem_size, getComputeWorkGroupSize());
}
glm::uvec3 Shader::getNumGroupsCeil(const glm::uvec3 &problem_size, const glm::uvec3 &work_group_size)
{
// glm::uvec3 ret = problem_size/work_group_size;
// glm::uvec3 rest = problem_size%work_group_size;
// ret.x += rest.x ? 1 : 0;
// ret.y += rest.y ? 1 : 0;
// ret.z += rest.z ? 1 : 0;
// return ret;
return (problem_size + work_group_size - glm::uvec3(1)) / (work_group_size);
}
void Shader::dispatchCompute(const glm::uvec3 &num_groups)
{
assert(isBound());
dispatchCompute(num_groups.x, num_groups.y, num_groups.z);
assert_no_glerror();
}
void Shader::dispatchCompute(GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z)
{
assert(isBound());
glDispatchCompute(num_groups_x, num_groups_y, num_groups_z);
assert_no_glerror();
}
void Shader::memoryBarrier(MemoryBarrierMask barriers)
{
glMemoryBarrier(barriers);
assert_no_glerror();
}
void Shader::memoryBarrierTextureFetch()
{
memoryBarrier(GL_TEXTURE_FETCH_BARRIER_BIT);
assert_no_glerror();
}
void Shader::memoryBarrierImageAccess()
{
memoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
assert_no_glerror();
}
// ===================================== uniforms =====================================
GLint Shader::getUniformLocation(const char* name){
GLint i = glGetUniformLocation(program, name);
return i;
}
void Shader::getUniformInfo(GLuint location){
const GLsizei bufSize = 128;
GLsizei length;
GLint size;
GLenum type;
GLchar name[bufSize];
glGetActiveUniform(program, location, bufSize, &length, &size, &type, name);
cout << "uniform info " << location << endl;
cout << "name " << name << endl;
// cout<<"length "<<length<<endl;
cout << "size " << size << endl;
cout << "type " << type << endl;
}
// ===================================== uniform blocks =====================================
GLuint Shader::getUniformBlockLocation(const char *name)
{
GLuint blockIndex = glGetUniformBlockIndex(program, name);
if (blockIndex == GL_INVALID_INDEX){
std::cerr << "glGetUniformBlockIndex: uniform block invalid!" << endl;
}
return blockIndex;
}
void Shader::setUniformBlockBinding(GLuint blockLocation, GLuint bindingPoint)
{
glUniformBlockBinding(program, blockLocation, bindingPoint);
}
GLint Shader::getUniformBlockSize(GLuint blockLocation)
{
GLint ret;
glGetActiveUniformBlockiv(program, blockLocation, GL_UNIFORM_BLOCK_DATA_SIZE, &ret);
return ret;
}
std::vector<GLint> Shader::getUniformBlockIndices(GLuint blockLocation)
{
GLint ret;
glGetActiveUniformBlockiv(program, blockLocation, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &ret);
std::vector<GLint> indices(ret);
glGetActiveUniformBlockiv(program, blockLocation, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, &indices[0]);
return indices;
}
std::vector<GLint> Shader::getUniformBlockSize(std::vector<GLint> indices)
{
std::vector<GLint> ret(indices.size());
glGetActiveUniformsiv(program, indices.size(), (GLuint*)indices.data(), GL_UNIFORM_SIZE, ret.data());
return ret;
}
std::vector<GLint> Shader::getUniformBlockType(std::vector<GLint> indices)
{
std::vector<GLint> ret(indices.size());
glGetActiveUniformsiv(program, indices.size(), (GLuint*)indices.data(), GL_UNIFORM_TYPE, ret.data());
return ret;
}
std::vector<GLint> Shader::getUniformBlockOffset(std::vector<GLint> indices)
{
std::vector<GLint> ret(indices.size());
glGetActiveUniformsiv(program, indices.size(), (GLuint*)indices.data(), GL_UNIFORM_OFFSET, ret.data());
return ret;
}
// ===================================== uniform uploads =====================================
void Shader::upload(int location, const mat4 &m){
assert(isBound());
glUniformMatrix4fv(location, 1, GL_FALSE, (GLfloat*)&m[0]);
assert_no_glerror();
}
void Shader::upload(int location, const vec4 &v){
assert(isBound());
glUniform4fv(location, 1, (GLfloat*)&v[0]);
assert_no_glerror();
}
void Shader::upload(int location, const vec3 &v){
assert(isBound());
glUniform3fv(location, 1, (GLfloat*)&v[0]);
assert_no_glerror();
}
void Shader::upload(int location, const vec2 &v){
assert(isBound());
glUniform2fv(location, 1, (GLfloat*)&v[0]);
assert_no_glerror();
}
void Shader::upload(int location, const int &i){
assert(isBound());
glUniform1i(location, (GLint)i);
assert_no_glerror();
}
void Shader::upload(int location, const float &f){
assert(isBound());
glUniform1f(location, (GLfloat)f);
assert_no_glerror();
}
void Shader::upload(int location, int count, mat4* m){
assert(isBound());
glUniformMatrix4fv(location, count, GL_FALSE, (GLfloat*)m);
assert_no_glerror();
}
void Shader::upload(int location, int count, vec4* v){
assert(isBound());
glUniform4fv(location, count, (GLfloat*)v);
assert_no_glerror();
}
void Shader::upload(int location, int count, vec3* v){
assert(isBound());
glUniform3fv(location, count, (GLfloat*)v);
assert_no_glerror();
}
void Shader::upload(int location, int count, vec2* v){
assert(isBound());
glUniform2fv(location, count, (GLfloat*)v);
assert_no_glerror();
}
void Shader::upload(int location, raw_Texture *texture, int textureUnit)
{
assert(isBound());
texture->bind(textureUnit);
Shader::upload(location, textureUnit);
assert_no_glerror();
}
<commit_msg>added assert<commit_after>#include "saiga/opengl/shader/shader.h"
#include "saiga/opengl/texture/raw_texture.h"
#include "saiga/util/error.h"
#include <fstream>
#include <algorithm>
#include "saiga/util/assert.h"
GLuint Shader::boundShader = 0;
Shader::Shader(){
}
Shader::~Shader(){
destroyProgram();
}
// ===================================== program stuff =====================================
GLuint Shader::createProgram(){
program = glCreateProgram();
//attach all shaders
for (auto& sp : shaders){
glAttachShader(program, sp->id);
}
assert_no_glerror();
glLinkProgram(program);
if (!printProgramLog()){
assert(0);
return 0;
}
assert_no_glerror();
for (auto& sp : shaders){
sp->deleteGLShader();
}
assert_no_glerror();
checkUniforms();
assert_no_glerror();
return program;
}
void Shader::destroyProgram()
{
if (program != 0){
glDeleteProgram(program);
program = 0;
assert_no_glerror();
}
}
bool Shader::printProgramLog(){
//Make sure name is shader
if (glIsProgram(program) == GL_TRUE)
{
//Program log length
int infoLogLength = 0;
int maxLength = infoLogLength;
//Get info std::string length
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength);
//Allocate std::string
char* infoLog = new char[maxLength];
//Get info log
glGetProgramInfoLog(program, maxLength, &infoLogLength, infoLog);
if (infoLogLength > 0)
{
//Print Log
std::cout << "program error:" << std::endl;
std::cout << infoLog << std::endl;
}
assert_no_glerror();
//Deallocate std::string
delete[] infoLog;
return infoLogLength == 0;
}
else
{
cout << "Name " << program << " is not a program" << endl;
return false;
}
}
void Shader::bind(){
assert(program);
//allow double bind
assert(boundShader == program || boundShader == 0);
boundShader = program;
glUseProgram(program);
assert_no_glerror();
}
void Shader::unbind(){
//allow double unbind
assert(boundShader == program || boundShader == 0);
boundShader = 0;
#if defined(SAIGA_DEBUG)
glUseProgram(0);
#endif
assert_no_glerror();
}
bool Shader::isBound(){
return boundShader == program;
}
// ===================================== Compute Shaders =====================================
glm::uvec3 Shader::getComputeWorkGroupSize()
{
GLint work_size[3];
glGetProgramiv(program, GL_COMPUTE_WORK_GROUP_SIZE, work_size);
assert_no_glerror();
return glm::uvec3(work_size[0], work_size[1], work_size[2]);
}
glm::uvec3 Shader::getNumGroupsCeil(const glm::uvec3 &problem_size)
{
return getNumGroupsCeil(problem_size, getComputeWorkGroupSize());
}
glm::uvec3 Shader::getNumGroupsCeil(const glm::uvec3 &problem_size, const glm::uvec3 &work_group_size)
{
// glm::uvec3 ret = problem_size/work_group_size;
// glm::uvec3 rest = problem_size%work_group_size;
// ret.x += rest.x ? 1 : 0;
// ret.y += rest.y ? 1 : 0;
// ret.z += rest.z ? 1 : 0;
// return ret;
return (problem_size + work_group_size - glm::uvec3(1)) / (work_group_size);
}
void Shader::dispatchCompute(const glm::uvec3 &num_groups)
{
assert(isBound());
dispatchCompute(num_groups.x, num_groups.y, num_groups.z);
assert_no_glerror();
}
void Shader::dispatchCompute(GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z)
{
assert(isBound());
glDispatchCompute(num_groups_x, num_groups_y, num_groups_z);
assert_no_glerror();
}
void Shader::memoryBarrier(MemoryBarrierMask barriers)
{
glMemoryBarrier(barriers);
assert_no_glerror();
}
void Shader::memoryBarrierTextureFetch()
{
memoryBarrier(GL_TEXTURE_FETCH_BARRIER_BIT);
assert_no_glerror();
}
void Shader::memoryBarrierImageAccess()
{
memoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
assert_no_glerror();
}
// ===================================== uniforms =====================================
GLint Shader::getUniformLocation(const char* name){
GLint i = glGetUniformLocation(program, name);
return i;
}
void Shader::getUniformInfo(GLuint location){
const GLsizei bufSize = 128;
GLsizei length;
GLint size;
GLenum type;
GLchar name[bufSize];
glGetActiveUniform(program, location, bufSize, &length, &size, &type, name);
cout << "uniform info " << location << endl;
cout << "name " << name << endl;
// cout<<"length "<<length<<endl;
cout << "size " << size << endl;
cout << "type " << type << endl;
}
// ===================================== uniform blocks =====================================
GLuint Shader::getUniformBlockLocation(const char *name)
{
GLuint blockIndex = glGetUniformBlockIndex(program, name);
if (blockIndex == GL_INVALID_INDEX){
std::cerr << "glGetUniformBlockIndex: uniform block invalid!" << endl;
}
return blockIndex;
}
void Shader::setUniformBlockBinding(GLuint blockLocation, GLuint bindingPoint)
{
glUniformBlockBinding(program, blockLocation, bindingPoint);
}
GLint Shader::getUniformBlockSize(GLuint blockLocation)
{
GLint ret;
glGetActiveUniformBlockiv(program, blockLocation, GL_UNIFORM_BLOCK_DATA_SIZE, &ret);
return ret;
}
std::vector<GLint> Shader::getUniformBlockIndices(GLuint blockLocation)
{
GLint ret;
glGetActiveUniformBlockiv(program, blockLocation, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &ret);
std::vector<GLint> indices(ret);
glGetActiveUniformBlockiv(program, blockLocation, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, &indices[0]);
return indices;
}
std::vector<GLint> Shader::getUniformBlockSize(std::vector<GLint> indices)
{
std::vector<GLint> ret(indices.size());
glGetActiveUniformsiv(program, indices.size(), (GLuint*)indices.data(), GL_UNIFORM_SIZE, ret.data());
return ret;
}
std::vector<GLint> Shader::getUniformBlockType(std::vector<GLint> indices)
{
std::vector<GLint> ret(indices.size());
glGetActiveUniformsiv(program, indices.size(), (GLuint*)indices.data(), GL_UNIFORM_TYPE, ret.data());
return ret;
}
std::vector<GLint> Shader::getUniformBlockOffset(std::vector<GLint> indices)
{
std::vector<GLint> ret(indices.size());
glGetActiveUniformsiv(program, indices.size(), (GLuint*)indices.data(), GL_UNIFORM_OFFSET, ret.data());
return ret;
}
// ===================================== uniform uploads =====================================
void Shader::upload(int location, const mat4 &m){
assert(isBound());
glUniformMatrix4fv(location, 1, GL_FALSE, (GLfloat*)&m[0]);
assert_no_glerror();
}
void Shader::upload(int location, const vec4 &v){
assert(isBound());
glUniform4fv(location, 1, (GLfloat*)&v[0]);
assert_no_glerror();
}
void Shader::upload(int location, const vec3 &v){
assert(isBound());
glUniform3fv(location, 1, (GLfloat*)&v[0]);
assert_no_glerror();
}
void Shader::upload(int location, const vec2 &v){
assert(isBound());
glUniform2fv(location, 1, (GLfloat*)&v[0]);
assert_no_glerror();
}
void Shader::upload(int location, const int &i){
assert(isBound());
glUniform1i(location, (GLint)i);
assert_no_glerror();
}
void Shader::upload(int location, const float &f){
assert(isBound());
glUniform1f(location, (GLfloat)f);
assert_no_glerror();
}
void Shader::upload(int location, int count, mat4* m){
assert(isBound());
glUniformMatrix4fv(location, count, GL_FALSE, (GLfloat*)m);
assert_no_glerror();
}
void Shader::upload(int location, int count, vec4* v){
assert(isBound());
glUniform4fv(location, count, (GLfloat*)v);
assert_no_glerror();
}
void Shader::upload(int location, int count, vec3* v){
assert(isBound());
glUniform3fv(location, count, (GLfloat*)v);
assert_no_glerror();
}
void Shader::upload(int location, int count, vec2* v){
assert(isBound());
glUniform2fv(location, count, (GLfloat*)v);
assert_no_glerror();
}
void Shader::upload(int location, raw_Texture *texture, int textureUnit)
{
assert(isBound());
texture->bind(textureUnit);
Shader::upload(location, textureUnit);
assert_no_glerror();
}
<|endoftext|> |
<commit_before>/**
@file LimeUtil.cpp
@author Lime Microsystems
@brief Command line test app
*/
#include <VersionInfo.h>
#include <ConnectionRegistry.h>
#include <IConnection.h>
#include <LMS7002M.h>
#include <iostream>
#include <chrono>
using namespace lime;
int deviceTestTiming(const std::string &argStr)
{
auto handles = ConnectionRegistry::findConnections(argStr);
if(handles.size() == 0)
{
std::cout << "No devices found" << std::endl;
return EXIT_FAILURE;
}
std::cout << "Connected to [" << handles[0].serialize() << "]" << std::endl;
auto conn = ConnectionRegistry::makeConnection(handles[0]);
std::cout << "Creating instance of LMS7002M:" << std::endl;
auto lms7 = new LMS7002M;
lms7->SetConnection(conn);
//time spi write access
{
const size_t numIters(1000);
auto t0 = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < numIters; i++)
{
lms7->SPI_write(0x0000, 0x0000);
}
auto t1 = std::chrono::high_resolution_clock::now();
const auto secsPerOp = std::chrono::duration<double>(t1-t0).count()/numIters;
std::cout << ">>> SPI write operation:\t" << (secsPerOp/1e-6) << " us" << std::endl;
}
//time spi read access
{
const size_t numIters(1000);
auto t0 = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < numIters; i++)
{
lms7->SPI_read(0x0000, true);
}
auto t1 = std::chrono::high_resolution_clock::now();
const auto secsPerOp = std::chrono::duration<double>(t1-t0).count()/numIters;
std::cout << ">>> SPI read operation: \t" << (secsPerOp/1e-6) << " us" << std::endl;
}
//time CGEN tuning
{
const size_t numIters(100);
auto t0 = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < numIters; i++)
{
lms7->SetFrequencyCGEN(1e6*(100+i), false);
}
auto t1 = std::chrono::high_resolution_clock::now();
const auto secsPerOp = std::chrono::duration<double>(t1-t0).count()/numIters;
std::cout << ">>> CGEN re-tune operation: \t" << (secsPerOp/1e-3) << " ms" << std::endl;
}
//time LO tuning
{
const size_t numIters(100);
auto t0 = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < numIters; i++)
{
lms7->SetFrequencySX(LMS7002M::Tx, 1e6*(100+i));
}
auto t1 = std::chrono::high_resolution_clock::now();
const auto secsPerOp = std::chrono::duration<double>(t1-t0).count()/numIters;
std::cout << ">>> RF LO re-tune operation:\t" << (secsPerOp/1e-3) << " ms" << std::endl;
}
delete lms7;
ConnectionRegistry::freeConnection(conn);
return EXIT_SUCCESS;
}
<commit_msg>time filters, other basic operations<commit_after>/**
@file LimeUtil.cpp
@author Lime Microsystems
@brief Command line test app
*/
#include <VersionInfo.h>
#include <ConnectionRegistry.h>
#include <IConnection.h>
#include <LMS7002M.h>
#include <iostream>
#include <chrono>
using namespace lime;
struct LMS7002M_quiet : LMS7002M
{
void Log(const char* text, LogType type)
{
if (type == LOG_INFO) return;
LMS7002M::Log(text, type);
}
};
int deviceTestTiming(const std::string &argStr)
{
auto handles = ConnectionRegistry::findConnections(argStr);
if(handles.size() == 0)
{
std::cout << "No devices found" << std::endl;
return EXIT_FAILURE;
}
std::cout << "Connected to [" << handles[0].serialize() << "]" << std::endl;
auto conn = ConnectionRegistry::makeConnection(handles[0]);
std::cout << "Creating instance of LMS7002M:" << std::endl;
auto lms7 = new LMS7002M_quiet;
lms7->SetConnection(conn);
std::cout << std::endl;
std::cout << "Timing basic operations:" << std::endl;
//time spi write access
{
const size_t numIters(1000);
auto t0 = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < numIters; i++)
{
lms7->SPI_write(0x0000, 0x0000);
}
auto t1 = std::chrono::high_resolution_clock::now();
const auto secsPerOp = std::chrono::duration<double>(t1-t0).count()/numIters;
std::cout << " >>> SPI write register:\t" << (secsPerOp/1e-6) << " us" << std::endl;
}
//time spi read access
{
const size_t numIters(1000);
auto t0 = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < numIters; i++)
{
lms7->SPI_read(0x0000, true);
}
auto t1 = std::chrono::high_resolution_clock::now();
const auto secsPerOp = std::chrono::duration<double>(t1-t0).count()/numIters;
std::cout << " >>> SPI read register:\t" << (secsPerOp/1e-6) << " us" << std::endl;
}
//time NCO setting
{
const size_t numIters(1000);
auto t0 = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < numIters; i++)
{
lms7->SetNCOFrequency(LMS7002M::Tx, 0, i*(1e6/numIters));
}
auto t1 = std::chrono::high_resolution_clock::now();
const auto secsPerOp = std::chrono::duration<double>(t1-t0).count()/numIters;
std::cout << " >>> TSP NCO setting:\t\t" << (secsPerOp/1e-6) << " us" << std::endl;
}
//time LNA setting
{
const size_t numIters(1000);
auto t0 = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < numIters; i++)
{
lms7->SetRFELNA_dB(0);
}
auto t1 = std::chrono::high_resolution_clock::now();
const auto secsPerOp = std::chrono::duration<double>(t1-t0).count()/numIters;
std::cout << " >>> RFE gain setting:\t\t" << (secsPerOp/1e-6) << " us" << std::endl;
}
//time PAD setting
{
const size_t numIters(1000);
auto t0 = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < numIters; i++)
{
lms7->SetTRFPAD_dB(0);
}
auto t1 = std::chrono::high_resolution_clock::now();
const auto secsPerOp = std::chrono::duration<double>(t1-t0).count()/numIters;
std::cout << " >>> TRF gain setting:\t\t" << (secsPerOp/1e-6) << " us" << std::endl;
}
std::cout << std::endl;
std::cout << "Timing tuning operations:" << std::endl;
//time CGEN tuning
{
const size_t numIters(100);
auto t0 = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < numIters; i++)
{
lms7->SetFrequencyCGEN(1e6*(100+i), false);
}
auto t1 = std::chrono::high_resolution_clock::now();
const auto secsPerOp = std::chrono::duration<double>(t1-t0).count()/numIters;
std::cout << " >>> CGEN PLL tuning:\t\t" << (secsPerOp/1e-3) << " ms" << std::endl;
}
//time LO tuning
{
const size_t numIters(100);
auto t0 = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < numIters; i++)
{
lms7->SetFrequencySX(LMS7002M::Tx, 1e6*(100+i));
}
auto t1 = std::chrono::high_resolution_clock::now();
const auto secsPerOp = std::chrono::duration<double>(t1-t0).count()/numIters;
std::cout << " >>> RF PLL tuning:\t\t" << (secsPerOp/1e-3) << " ms" << std::endl;
}
//time TX filter
{
const size_t numIters(20);
auto t0 = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < numIters; i++)
{
lms7->TuneTxFilter(10e6 + i*(3e6/numIters));
}
auto t1 = std::chrono::high_resolution_clock::now();
const auto secsPerOp = std::chrono::duration<double>(t1-t0).count()/numIters;
std::cout << " >>> TBB filter tuning:\t" << (secsPerOp/1e-3) << " ms" << std::endl;
}
//time RX filter
{
const size_t numIters(20);
auto t0 = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < numIters; i++)
{
lms7->TuneRxFilter(10e6 + i*(3e6/numIters));
}
auto t1 = std::chrono::high_resolution_clock::now();
const auto secsPerOp = std::chrono::duration<double>(t1-t0).count()/numIters;
std::cout << " >>> RBB filter tuning:\t" << (secsPerOp/1e-3) << " ms" << std::endl;
}
std::cout << std::endl;
std::cout << "Done timing!" << std::endl;
delete lms7;
ConnectionRegistry::freeConnection(conn);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* Connection pooling for the translation server.
*
* author: Max Kellermann <[email protected]>
*/
#include "tstock.hxx"
#include "TranslateHandler.hxx"
#include "translate_client.hxx"
#include "stock/GetHandler.hxx"
#include "tcp_stock.hxx"
#include "lease.hxx"
#include "pool.hxx"
#include "net/AllocatedSocketAddress.hxx"
#include <daemon/log.h>
struct TranslateStock {
StockMap &tcp_stock;
AllocatedSocketAddress address;
const char *const address_string;
TranslateStock(StockMap &_tcp_stock, const char *path)
:tcp_stock(_tcp_stock), address_string(path) {
address.SetLocal(path);
}
};
struct TranslateStockRequest final : public StockGetHandler, Lease {
struct pool &pool;
TranslateStock &stock;
StockItem *item;
const TranslateRequest &request;
const TranslateHandler &handler;
void *handler_ctx;
struct async_operation_ref &async_ref;
TranslateStockRequest(TranslateStock &_stock, struct pool &_pool,
const TranslateRequest &_request,
const TranslateHandler &_handler, void *_ctx,
struct async_operation_ref &_async_ref)
:pool(_pool), stock(_stock),
request(_request),
handler(_handler), handler_ctx(_ctx),
async_ref(_async_ref) {}
/* virtual methods from class StockGetHandler */
void OnStockItemReady(StockItem &item) override;
void OnStockItemError(GError *error) override;
/* virtual methods from class Lease */
void ReleaseLease(bool reuse) override {
tcp_stock_put(&stock.tcp_stock, *item, !reuse);
}
};
/*
* stock callback
*
*/
void
TranslateStockRequest::OnStockItemReady(StockItem &_item)
{
item = &_item;
translate(pool, tcp_stock_item_get(_item),
*this,
request, handler, handler_ctx,
async_ref);
}
void
TranslateStockRequest::OnStockItemError(GError *error)
{
handler.error(error, handler_ctx);
}
/*
* constructor
*
*/
TranslateStock *
tstock_new(struct pool &pool, StockMap &tcp_stock, const char *socket_path)
{
return NewFromPool<TranslateStock>(pool, tcp_stock, socket_path);
}
void
tstock_free(struct pool &pool, TranslateStock *stock)
{
DeleteFromPool(pool, stock);
}
void
tstock_translate(TranslateStock &stock, struct pool &pool,
const TranslateRequest &request,
const TranslateHandler &handler, void *ctx,
struct async_operation_ref &async_ref)
{
auto r = NewFromPool<TranslateStockRequest>(pool, stock, pool, request,
handler, ctx, async_ref);
tcp_stock_get(&stock.tcp_stock, &pool, stock.address_string,
false, SocketAddress::Null(),
stock.address,
10,
*r, async_ref);
}
<commit_msg>tstock: add wrapper methods<commit_after>/*
* Connection pooling for the translation server.
*
* author: Max Kellermann <[email protected]>
*/
#include "tstock.hxx"
#include "TranslateHandler.hxx"
#include "translate_client.hxx"
#include "stock/GetHandler.hxx"
#include "tcp_stock.hxx"
#include "lease.hxx"
#include "pool.hxx"
#include "net/AllocatedSocketAddress.hxx"
#include <daemon/log.h>
struct TranslateStock {
StockMap &tcp_stock;
AllocatedSocketAddress address;
const char *const address_string;
TranslateStock(StockMap &_tcp_stock, const char *path)
:tcp_stock(_tcp_stock), address_string(path) {
address.SetLocal(path);
}
void Get(struct pool &pool, StockGetHandler &handler,
struct async_operation_ref &async_ref) {
tcp_stock_get(&tcp_stock, &pool, address_string,
false, SocketAddress::Null(),
address,
10,
handler, async_ref);
}
void Put(StockItem &item, bool destroy) {
tcp_stock_put(&tcp_stock, item, destroy);
}
};
struct TranslateStockRequest final : public StockGetHandler, Lease {
struct pool &pool;
TranslateStock &stock;
StockItem *item;
const TranslateRequest &request;
const TranslateHandler &handler;
void *handler_ctx;
struct async_operation_ref &async_ref;
TranslateStockRequest(TranslateStock &_stock, struct pool &_pool,
const TranslateRequest &_request,
const TranslateHandler &_handler, void *_ctx,
struct async_operation_ref &_async_ref)
:pool(_pool), stock(_stock),
request(_request),
handler(_handler), handler_ctx(_ctx),
async_ref(_async_ref) {}
/* virtual methods from class StockGetHandler */
void OnStockItemReady(StockItem &item) override;
void OnStockItemError(GError *error) override;
/* virtual methods from class Lease */
void ReleaseLease(bool reuse) override {
stock.Put(*item, !reuse);
}
};
/*
* stock callback
*
*/
void
TranslateStockRequest::OnStockItemReady(StockItem &_item)
{
item = &_item;
translate(pool, tcp_stock_item_get(_item),
*this,
request, handler, handler_ctx,
async_ref);
}
void
TranslateStockRequest::OnStockItemError(GError *error)
{
handler.error(error, handler_ctx);
}
/*
* constructor
*
*/
TranslateStock *
tstock_new(struct pool &pool, StockMap &tcp_stock, const char *socket_path)
{
return NewFromPool<TranslateStock>(pool, tcp_stock, socket_path);
}
void
tstock_free(struct pool &pool, TranslateStock *stock)
{
DeleteFromPool(pool, stock);
}
void
tstock_translate(TranslateStock &stock, struct pool &pool,
const TranslateRequest &request,
const TranslateHandler &handler, void *ctx,
struct async_operation_ref &async_ref)
{
auto r = NewFromPool<TranslateStockRequest>(pool, stock, pool, request,
handler, ctx, async_ref);
stock.Get(pool, *r, async_ref);
}
<|endoftext|> |
<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2016 Northeastern University
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "Eigen/Dense"
#include "gtest/gtest.h"
#include "include/logistic_regression.h"
#include "include/matrix.h"
template<typename T>
class LogisticRegressionTest: public ::testing::Test {
public:
int iterations;
T alpha;
Nice::Matrix<T> training_x;
Nice::Vector<T> training_y;
Nice::Matrix<T> predict_x;
Nice::Vector<T> predictions;
Nice::LogisticRegression<T> testModel1;
Nice::LogisticRegression<T> testModel2;
// Runs the Fit function for a specific model
void LogisticRegressionFit(Nice::LogisticRegression<T> &testModel) {
testModel.Fit(training_x, training_y, iterations, alpha);
}
// Runs the Predict function for a specific model
void LogisticRegressionPredict(Nice::LogisticRegression<T> &testModel) {
predictions = testModel.Predict(predict_x);
}
};
typedef ::testing::Types<float, double> MyTypes;
TYPED_TEST_CASE(LogisticRegressionTest, MyTypes);
// Runs both the fit and predict function on a single model.
TYPED_TEST(LogisticRegressionTest, MatrixLogisticRegressionOneModel) {
// Setup for the Fit function
this->training_x.resize(10, 2);
this->iterations = 10000;
this->alpha = 0.3;
this->training_x << 2.781, 2.550,
1.465, 2.362,
3.396, 4.400,
1.388, 1.850,
3.064, 3.005,
7.627, 2.759,
5.332, 2.088,
6.922, 1.771,
8.675, -0.242,
7.673, 3.508;
this->training_y.resize(10);
this->training_y << 0, 0, 0, 0, 0, 1, 1, 1, 1, 1;
this->LogisticRegressionFit(this->testModel1);
// Setup for the Predict function
this->predict_x.resize(10, 2);
this->predict_x << 2.781, 2.550,
1.465, 2.362,
3.396, 4.400,
1.388, 1.850,
3.064, 3.005,
7.627, 2.759,
5.332, 2.088,
6.922, 1.771,
8.675, -0.242,
7.673, 3.508;
this->LogisticRegressionPredict(this->testModel1);
this->predictions.resize(10);
std::cout << this->predictions << std::endl;
ASSERT_TRUE(true);
}
// Runs both the fit and predict function on two separate models in
// the same test.
TYPED_TEST(LogisticRegressionTest, MatrixLogisticRegressionTwoModels) {
// Setup for Model 1's Fit function
this->training_x.resize(10, 2);
this->iterations = 10000;
this->alpha = 0.3;
this->training_x << 2.781, 2.550,
1.465, 2.362,
3.396, 4.400,
1.388, 1.850,
3.064, 3.005,
7.627, 2.759,
5.332, 2.088,
6.922, 1.771,
8.675, -0.242,
7.673, 3.508;
this->training_y.resize(10);
this->training_y << 0, 0, 0, 0, 0, 1, 1, 1, 1, 1;
this->LogisticRegressionFit(this->testModel1);
// Setup for Model 2's Fit function
this->training_x << 2, .5,
2, 0,
4, 1,
5, 2,
7, 3,
1, 3,
2, 2,
4, 3,
3, 5,
6, 3.5;
this->LogisticRegressionFit(this->testModel2);
// Setup for Model 1's Predict function
this->predict_x.resize(10, 2);
this->predict_x << 2.781, 2.550,
1.465, 2.362,
3.396, 4.400,
1.388, 1.850,
3.064, 3.005,
7.627, 2.759,
5.332, 2.088,
6.922, 1.771,
8.675, -0.242,
7.673, 3.508;
this->LogisticRegressionPredict(this->testModel1);
// Setup for Model 2's Fit function
this->predictions.resize(10);
std::cout << this->predictions << std::endl;
this->predict_x << 2, .5,
2, 0,
4, 1,
5, 2,
7, 3,
1, 3,
2, 2,
4, 3,
3, 5,
6, 3.5;
this->LogisticRegressionPredict(this->testModel2);
std::cout << this->predictions << std::endl;
ASSERT_TRUE(true);
}
<commit_msg>Fixed all cpplint errors<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2016 Northeastern University
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "Eigen/Dense"
#include "gtest/gtest.h"
#include "include/logistic_regression.h"
#include "include/matrix.h"
template<typename T>
class LogisticRegressionTest: public ::testing::Test {
public:
int iterations;
T alpha;
Nice::Matrix<T> training_x;
Nice::Vector<T> training_y;
Nice::Matrix<T> predict_x;
Nice::Vector<T> predictions;
Nice::LogisticRegression<T> testModel1;
Nice::LogisticRegression<T> testModel2;
};
typedef ::testing::Types<float, double> MyTypes;
TYPED_TEST_CASE(LogisticRegressionTest, MyTypes);
// Runs both the fit and predict function on a single model.
TYPED_TEST(LogisticRegressionTest, MatrixLogisticRegressionOneModel) {
// Setup for the Fit function
this->training_x.resize(10, 2);
this->iterations = 10000;
this->alpha = 0.3;
this->training_x << 2.781, 2.550,
1.465, 2.362,
3.396, 4.400,
1.388, 1.850,
3.064, 3.005,
7.627, 2.759,
5.332, 2.088,
6.922, 1.771,
8.675, -0.242,
7.673, 3.508;
this->training_y.resize(10);
this->training_y << 0, 0, 0, 0, 0, 1, 1, 1, 1, 1;
this->testModel1.Fit(this->training_x, this->training_y, this->iterations,
this->alpha);
// Setup for the Predict function
this->predict_x.resize(10, 2);
this->predict_x << 2.781, 2.550,
1.465, 2.362,
3.396, 4.400,
1.388, 1.850,
3.064, 3.005,
7.627, 2.759,
5.332, 2.088,
6.922, 1.771,
8.675, -0.242,
7.673, 3.508;
this->predictions = this->testModel1.Predict(this->predict_x);
this->predictions.resize(10);
std::cout << this->predictions << std::endl;
ASSERT_TRUE(true);
}
// Runs both the fit and predict function on two separate models in
// the same test.
TYPED_TEST(LogisticRegressionTest, MatrixLogisticRegressionTwoModels) {
// Setup for Model 1's Fit function
this->training_x.resize(10, 2);
this->iterations = 10000;
this->alpha = 0.3;
this->training_x << 2.781, 2.550,
1.465, 2.362,
3.396, 4.400,
1.388, 1.850,
3.064, 3.005,
7.627, 2.759,
5.332, 2.088,
6.922, 1.771,
8.675, -0.242,
7.673, 3.508;
this->training_y.resize(10);
this->training_y << 0, 0, 0, 0, 0, 1, 1, 1, 1, 1;
this->testModel1.Fit(this->training_x, this->training_y, this->iterations,
this->alpha);
// Setup for Model 2's Fit function
this->training_x << 2, .5,
2, 0,
4, 1,
5, 2,
7, 3,
1, 3,
2, 2,
4, 3,
3, 5,
6, 3.5;
this->testModel2.Fit(this->training_x, this->training_y,
this->iterations, this->alpha);
// Setup for Model 1's Predict function
this->predict_x.resize(10, 2);
this->predict_x << 2.781, 2.550,
1.465, 2.362,
3.396, 4.400,
1.388, 1.850,
3.064, 3.005,
7.627, 2.759,
5.332, 2.088,
6.922, 1.771,
8.675, -0.242,
7.673, 3.508;
this->predictions = this->testModel1.Predict(this->predict_x);
// Setup for Model 2's Fit function
this->predictions.resize(10);
std::cout << this->predictions << std::endl;
this->predict_x << 2, .5,
2, 0,
4, 1,
5, 2,
7, 3,
1, 3,
2, 2,
4, 3,
3, 5,
6, 3.5;
this->predictions = this->testModel2.Predict(this->predict_x);
std::cout << this->predictions << std::endl;
ASSERT_TRUE(true);
}
<|endoftext|> |
<commit_before>/// \file UsernameEntry.cpp
//-----------------------------------------------------------------------------
#include "stdafx.h"
#include "PasswordSafe.h"
#include "UsernameEntry.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//-----------------------------------------------------------------------------
CUsernameEntry::CUsernameEntry(CWnd* pParent)
: CDialog(CUsernameEntry::IDD, pParent)
{
m_makedefuser = FALSE;
m_username = "";
}
void CUsernameEntry::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Check(pDX, IDC_MAKEDEF, m_makedefuser);
DDX_Text(pDX, IDC_USERNAME, m_username.m_mystring);
}
BEGIN_MESSAGE_MAP(CUsernameEntry, CDialog)
END_MESSAGE_MAP()
void
CUsernameEntry::OnOK()
{
UpdateData(TRUE);
app.WriteProfileInt("", "usedefuser", m_makedefuser);
if (m_makedefuser==TRUE)
app.WriteProfileString("", "defusername", m_username.m_mystring);
CDialog::OnOK();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
<commit_msg>ThisMfcApp header<commit_after>/// \file UsernameEntry.cpp
//-----------------------------------------------------------------------------
#include "stdafx.h"
#include "PasswordSafe.h"
#include "ThisMfcApp.h"
#include "resource.h"
#include "UsernameEntry.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//-----------------------------------------------------------------------------
CUsernameEntry::CUsernameEntry(CWnd* pParent)
: CDialog(CUsernameEntry::IDD, pParent)
{
m_makedefuser = FALSE;
m_username = "";
}
void CUsernameEntry::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Check(pDX, IDC_MAKEDEF, m_makedefuser);
DDX_Text(pDX, IDC_USERNAME, m_username.m_mystring);
}
BEGIN_MESSAGE_MAP(CUsernameEntry, CDialog)
END_MESSAGE_MAP()
void
CUsernameEntry::OnOK()
{
UpdateData(TRUE);
app.WriteProfileInt("", "usedefuser", m_makedefuser);
if (m_makedefuser==TRUE)
app.WriteProfileString("", "defusername", m_username.m_mystring);
CDialog::OnOK();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>#include "NetworkManager.hpp"
NetworkManager::NetworkManager()
{
esp.begin(9600);
connected = false;
protocol = "TCP";
hostname = "api.thingspeak.com";
port = "80";
apiKey = "P1U3BM0XT5L8M4UI";
}
bool NetworkManager::wifiConnect(const String &ssid, const String &password)
{
esp.println("AT+CWMODE=1");
delay(200);
esp.println("AT+CWJAP=\"" + ssid + "\",\"" + password + "\"");
if (esp.available()) {
Serial.write(esp.read());
connected = true;
return true;
}
else
return false;
}
bool NetworkManager::isConnected()
{
return connected;
}
bool NetworkManager::updateFeed(float temperature, float rain, double pressure, unsigned long lightLevel)
{
String request = "GET /update?api_key=" + apiKey
+ "&field1=" + String(temperature)
+ "&field2=" + String(rain)
+ "&field3=" + String(pressure)
+ "&field4=" + String(lightLevel);
delay(100);
sendCommand("AT+CIPSTART=\""
+ protocol + "\",\""
+ hostname + "\","
+ port, 250);
sendCommand("AT+CIPSEND=" + String(request.length() + 2), 500);
delay(100);
sendCommand(request, 500);
}
String NetworkManager::sendCommand(String& command, const unsigned int timeout)
{
Serial.println(command);
String response = "";
esp.println(command);
unsigned long int time = millis();
while((time+timeout) > millis())
{
while(esp.available())
{
char c = esp.read();
response += c;
}
}
Serial.println(response);
return response;
}
<commit_msg>Przebudowano funkcję `updateFeed`<commit_after>#include "NetworkManager.hpp"
NetworkManager::NetworkManager()
{
esp.begin(9600);
connected = false;
protocol = "TCP";
hostname = "api.thingspeak.com";
port = "80";
apiKey = "P1U3BM0XT5L8M4UI";
}
bool NetworkManager::wifiConnect(const String &ssid, const String &password)
{
esp.println("AT+CWMODE=1");
delay(200);
esp.println("AT+CWJAP=\"" + ssid + "\",\"" + password + "\"");
if (esp.available()) {
Serial.write(esp.read());
connected = true;
return true;
}
else
return false;
}
bool NetworkManager::isConnected()
{
return connected;
}
bool NetworkManager::updateFeed(float temperature, float rain, double pressure, unsigned long lightLevel)
{
String request = "GET /update?api_key=" + apiKey
+ "&field1=" + String(temperature)
+ "&field2=" + String(rain)
+ "&field3=" + String(pressure)
+ "&field4=" + String(lightLevel);
sendCommand("AT+CIPSTART=\""
+ protocol + "\",\""
+ hostname + "\","
+ port, 1000);
sendCommand("AT+CIPSEND=" + String(request.length() + 2), 500);
delay(200);
sendCommand(request, 500);
}
String NetworkManager::sendCommand(String& command, const unsigned int timeout)
{
// Serial.println(command);
String response = "";
esp.println(command);
unsigned long int time = millis();
while((time+timeout) > millis())
{
while(esp.available())
{
char c = esp.read();
response += c;
}
}
Serial.println(response);
return response;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2016 Kasper Kronborg Isager and Radosław Niemczyk.
#include "vector.hpp"
namespace lsh {
/**
* Create a new vector from existing component chunks.
*
* @param components The existing component chunks.
* @param size The number of components.
*/
vector::vector(const std::vector<unsigned short>& cs, unsigned short s) {
this->size_ = s;
unsigned int n = cs.size();
this->components_.resize(n, 0);
for (unsigned int i = 0; i < n; i++) {
this->components_[i] = cs[i];
}
}
/**
* Construct a new vector.
*
* @param components The components of the vector.
*/
vector::vector(const std::vector<bool>& cs) {
this->size_ = cs.size();
unsigned int s = this->size_;
unsigned int c = this->chunk_size_;
unsigned int i = 0;
unsigned int k = 0;
unsigned int n = (s + c - 1) / c;
this->components_.resize(n, 0);
while (i < s) {
// Compute the number of bits in the current chunk.
unsigned int b = i + c > s ? s - i : c;
for (unsigned int j = 0; j < b; j++) {
this->components_[k] |= cs[i + j] << (b - j - 1);
}
i += b;
k += 1;
}
}
/**
* Get the number of components in this vector.
*
* @return The number of components in this vector.
*/
unsigned short vector::size() const {
return this->size_;
}
/**
* Get the component at the specified index of this vector.
*
* @param index The index of the component to get.
* @return The component at the index.
*/
bool vector::get(unsigned short i) const {
unsigned int s = this->size_;
unsigned int c = this->chunk_size_;
if (i >= s) {
throw std::out_of_range("Invalid index");
}
// Compute the index of the target chunk.
unsigned int d = i / s;
// Compute the index of the first bit of the target chunk.
unsigned int j = d * s;
// Compute the number of bits in the target chunk.
unsigned int b = j + c > s ? s - j : c;
return (this->components_[d] >> (b - (i % s) - 1)) & 1;
}
/**
* Get a string representation of this vector.
*
* @return The string representation of the vector.
*/
std::string vector::to_string() const {
unsigned int n = this->size_;
std::string value = "Vector[";
for (unsigned int i = 0; i < n; i++) {
value += std::to_string(this->get(i));
}
return value + "]";
}
/**
* Check if this vector equals another vector.
*
* @param vector The other vector.
* @return `true` if this vector equals the other vector, otherwise `false`.
*/
bool vector::operator==(const vector& v) const {
if (this->size() != v.size()) {
throw std::invalid_argument("Invalid vector size");
}
return vector::distance(*this, v) == 0;
}
/**
* Compute the dot product of this and another vector.
*
* @param vector The other vector.
* @return The dot product of this and another vector.
*/
unsigned int vector::operator*(const vector& v) const {
if (this->size() != v.size()) {
throw std::invalid_argument("Invalid vector size");
}
unsigned int d = 0;
unsigned int n = this->components_.size();
for (unsigned int i = 0; i < n; i++) {
d += __builtin_popcount(this->components_[i] & v.components_[i]);
}
return d;
}
/**
* Compute the dot product of this vector and an integer.
*
* @param integer The integer.
* @return The dot product of this vector and an integer.
*/
unsigned int vector::operator*(unsigned int it) const {
unsigned int d = 0;
unsigned int s = this->size_;
unsigned int c = this->chunk_size_;
unsigned int n = this->components_.size();
for (unsigned int i = 0; i < n; i++) {
// Compute the index of the first bit of the current chunk.
unsigned int j = c * i;
// Compute the number of bits in the current chunk.
unsigned int m = j + c > s ? s - j : c;
// Grab the bits of the integer that correspond to the current chunk.
unsigned int b = (it >> (s - j - m)) & (1 << m) - 1;
d += __builtin_popcount(this->components_[i] & b);
}
return d;
}
/**
* Compute the bitwise AND of this and another vector.
*
* @param vector The other vector.
* @return The bitwise AND of this and another vector.
*/
vector vector::operator&(const vector& v) const {
if (this->size() != v.size()) {
throw std::invalid_argument("Invalid vector size");
}
unsigned int n = this->components_.size();
std::vector<unsigned short> c(n);
for (unsigned int i = 0; i < n; i++) {
c[i] = this->components_[i] & v.components_[i];
}
return vector(c, this->size_);
}
/**
* Compupte the hash of this vector.
*
* @return The hash of this vector.
*/
unsigned long vector::hash() const {
unsigned int n = this->components_.size();
unsigned long h = 7;
for (unsigned int i = 0; i < n; i++) {
h = 31 * h + this->components_[i];
}
return h;
}
/**
* Compute the distance between two vectors.
*
* @param u The first vector.
* @param v The second vector.
* @return The distance between the two vectors.
*/
unsigned short vector::distance(const vector& u, const vector& v) {
if (u.size() != v.size()) {
throw std::invalid_argument("Invalid vector size");
}
unsigned int d = 0;
unsigned int n = u.components_.size();
for (unsigned int i = 0; i < n; i++) {
d += __builtin_popcount(u.components_[i] ^ v.components_[i]);
}
return d;
}
/**
* Construct a random vector of a given dimensionality.
*
* @param dimensions The number of dimensions in the vector.
* @return The randomly generated vector.
*/
vector vector::random(unsigned short d) {
std::random_device random;
std::mt19937 generator(random());
std::uniform_int_distribution<> components(0, 1);
std::vector<bool> c(d);
for (unsigned int i = 0; i < d; i++) {
c[i] = components(generator);
}
return vector(c);
}
}
<commit_msg>Fix the build!<commit_after>// Copyright (c) 2016 Kasper Kronborg Isager and Radosław Niemczyk.
#include "vector.hpp"
namespace lsh {
/**
* Create a new vector from existing component chunks.
*
* @param components The existing component chunks.
* @param size The number of components.
*/
vector::vector(const std::vector<unsigned short>& cs, unsigned short s) {
this->size_ = s;
unsigned int n = cs.size();
this->components_.resize(n, 0);
for (unsigned int i = 0; i < n; i++) {
this->components_[i] = cs[i];
}
}
/**
* Construct a new vector.
*
* @param components The components of the vector.
*/
vector::vector(const std::vector<bool>& cs) {
this->size_ = cs.size();
unsigned int s = this->size_;
unsigned int c = this->chunk_size_;
unsigned int i = 0;
unsigned int k = 0;
unsigned int n = (s + c - 1) / c;
this->components_.resize(n, 0);
while (i < s) {
// Compute the number of bits in the current chunk.
unsigned int b = i + c > s ? s - i : c;
for (unsigned int j = 0; j < b; j++) {
this->components_[k] |= cs[i + j] << (b - j - 1);
}
i += b;
k += 1;
}
}
/**
* Get the number of components in this vector.
*
* @return The number of components in this vector.
*/
unsigned short vector::size() const {
return this->size_;
}
/**
* Get the component at the specified index of this vector.
*
* @param index The index of the component to get.
* @return The component at the index.
*/
bool vector::get(unsigned short i) const {
unsigned int s = this->size_;
unsigned int c = this->chunk_size_;
if (i >= s) {
throw std::out_of_range("Invalid index");
}
// Compute the index of the target chunk.
unsigned int d = i / s;
// Compute the index of the first bit of the target chunk.
unsigned int j = d * s;
// Compute the number of bits in the target chunk.
unsigned int b = j + c > s ? s - j : c;
return (this->components_[d] >> (b - (i % s) - 1)) & 1;
}
/**
* Get a string representation of this vector.
*
* @return The string representation of the vector.
*/
std::string vector::to_string() const {
unsigned int n = this->size_;
std::string value = "Vector[";
for (unsigned int i = 0; i < n; i++) {
value += std::to_string(this->get(i));
}
return value + "]";
}
/**
* Check if this vector equals another vector.
*
* @param vector The other vector.
* @return `true` if this vector equals the other vector, otherwise `false`.
*/
bool vector::operator==(const vector& v) const {
if (this->size() != v.size()) {
throw std::invalid_argument("Invalid vector size");
}
return vector::distance(*this, v) == 0;
}
/**
* Compute the dot product of this and another vector.
*
* @param vector The other vector.
* @return The dot product of this and another vector.
*/
unsigned int vector::operator*(const vector& v) const {
if (this->size() != v.size()) {
throw std::invalid_argument("Invalid vector size");
}
unsigned int d = 0;
unsigned int n = this->components_.size();
for (unsigned int i = 0; i < n; i++) {
d += __builtin_popcount(this->components_[i] & v.components_[i]);
}
return d;
}
/**
* Compute the dot product of this vector and an integer.
*
* @param integer The integer.
* @return The dot product of this vector and an integer.
*/
unsigned int vector::operator*(unsigned int it) const {
unsigned int d = 0;
unsigned int s = this->size_;
unsigned int c = this->chunk_size_;
unsigned int n = this->components_.size();
for (unsigned int i = 0; i < n; i++) {
// Compute the index of the first bit of the current chunk.
unsigned int j = c * i;
// Compute the number of bits in the current chunk.
unsigned int m = j + c > s ? s - j : c;
// Grab the bits of the integer that correspond to the current chunk.
unsigned int b = (it >> (s - j - m)) & ((1 << m) - 1);
d += __builtin_popcount(this->components_[i] & b);
}
return d;
}
/**
* Compute the bitwise AND of this and another vector.
*
* @param vector The other vector.
* @return The bitwise AND of this and another vector.
*/
vector vector::operator&(const vector& v) const {
if (this->size() != v.size()) {
throw std::invalid_argument("Invalid vector size");
}
unsigned int n = this->components_.size();
std::vector<unsigned short> c(n);
for (unsigned int i = 0; i < n; i++) {
c[i] = this->components_[i] & v.components_[i];
}
return vector(c, this->size_);
}
/**
* Compupte the hash of this vector.
*
* @return The hash of this vector.
*/
unsigned long vector::hash() const {
unsigned int n = this->components_.size();
unsigned long h = 7;
for (unsigned int i = 0; i < n; i++) {
h = 31 * h + this->components_[i];
}
return h;
}
/**
* Compute the distance between two vectors.
*
* @param u The first vector.
* @param v The second vector.
* @return The distance between the two vectors.
*/
unsigned short vector::distance(const vector& u, const vector& v) {
if (u.size() != v.size()) {
throw std::invalid_argument("Invalid vector size");
}
unsigned int d = 0;
unsigned int n = u.components_.size();
for (unsigned int i = 0; i < n; i++) {
d += __builtin_popcount(u.components_[i] ^ v.components_[i]);
}
return d;
}
/**
* Construct a random vector of a given dimensionality.
*
* @param dimensions The number of dimensions in the vector.
* @return The randomly generated vector.
*/
vector vector::random(unsigned short d) {
std::random_device random;
std::mt19937 generator(random());
std::uniform_int_distribution<> components(0, 1);
std::vector<bool> c(d);
for (unsigned int i = 0; i < d; i++) {
c[i] = components(generator);
}
return vector(c);
}
}
<|endoftext|> |
<commit_before>#pragma once
#include "allocator.hpp"
namespace Mirb
{
template<class T, class A = StdLibAllocator> class Vector
{
protected:
T *table;
typename A::Storage alloc_ref;
size_t _size;
size_t _capacity;
public:
Vector(size_t initial) : alloc_ref(A::Storage::def_ref())
{
_size = 0;
_capacity = 1 << initial;
table = (T *)alloc_ref.alloc(sizeof(T) * _capacity);
}
Vector(size_t initial, typename A::Ref alloc_ref) : alloc_ref(alloc_ref)
{
_size = 0;
_capacity = 1 << initial;
table = (T *)alloc_ref.alloc(sizeof(T) * _capacity);
}
Vector() : alloc_ref(A::Storage::def_ref())
{
_size = 0;
_capacity = 0;
table = 0;
}
Vector(typename A::Ref alloc_ref) : alloc_ref(alloc_ref)
{
_size = 0;
_capacity = 0;
table = 0;
}
~Vector()
{
if(table)
alloc_ref.free((void *)table);
}
size_t size()
{
return _size;
}
T &first()
{
return *table;
}
T &last()
{
return &table[_size - 1];
}
T operator [](size_t index)
{
assert(index < _size);
return table[index];
}
void push(T entry)
{
if(_size + 1 > _capacity)
{
if(table)
{
size_t old_capacity = _capacity;
_capacity <<= 1;
table = (T *)alloc_ref.realloc((void *)table, sizeof(T) * old_capacity, sizeof(T) * _capacity);
}
else
{
_capacity = 1;
table = (T *)alloc_ref.alloc(sizeof(T) * _capacity);
}
}
table[_size++] = entry;
}
T *find(T entry)
{
for(auto i = begin(); i != end(); ++i)
{
if(*i == entry)
return i.position();
}
return 0;
}
class Iterator
{
private:
T *current;
public:
Iterator(T *start) : current(start) {}
bool operator ==(const Iterator &other) const
{
return current == other.current;
}
bool operator !=(const Iterator &other) const
{
return current != other.current;
}
T *position() const
{
return current;
}
T &operator ++()
{
return *++current;
}
/*
T &operator ++(int)
{
return *current++;
}
*/
T operator*() const
{
return *current;
}
T operator ()() const
{
return *current;
}
};
Iterator begin()
{
return Iterator(&first());
}
Iterator end()
{
return Iterator(&table[_size]);
}
};
};
<commit_msg>Uncommented some code in vector.<commit_after>#pragma once
#include "allocator.hpp"
namespace Mirb
{
template<class T, class A = StdLibAllocator> class Vector
{
protected:
T *table;
typename A::Storage alloc_ref;
size_t _size;
size_t _capacity;
public:
Vector(size_t initial) : alloc_ref(A::Storage::def_ref())
{
_size = 0;
_capacity = 1 << initial;
table = (T *)alloc_ref.alloc(sizeof(T) * _capacity);
}
Vector(size_t initial, typename A::Ref alloc_ref) : alloc_ref(alloc_ref)
{
_size = 0;
_capacity = 1 << initial;
table = (T *)alloc_ref.alloc(sizeof(T) * _capacity);
}
Vector() : alloc_ref(A::Storage::def_ref())
{
_size = 0;
_capacity = 0;
table = 0;
}
Vector(typename A::Ref alloc_ref) : alloc_ref(alloc_ref)
{
_size = 0;
_capacity = 0;
table = 0;
}
~Vector()
{
if(table)
alloc_ref.free((void *)table);
}
size_t size()
{
return _size;
}
T &first()
{
return *table;
}
T &last()
{
return &table[_size - 1];
}
T operator [](size_t index)
{
assert(index < _size);
return table[index];
}
void push(T entry)
{
if(_size + 1 > _capacity)
{
if(table)
{
size_t old_capacity = _capacity;
_capacity <<= 1;
table = (T *)alloc_ref.realloc((void *)table, sizeof(T) * old_capacity, sizeof(T) * _capacity);
}
else
{
_capacity = 1;
table = (T *)alloc_ref.alloc(sizeof(T) * _capacity);
}
}
table[_size++] = entry;
}
T *find(T entry)
{
for(auto i = begin(); i != end(); ++i)
{
if(*i == entry)
return i.position();
}
return 0;
}
class Iterator
{
private:
T *current;
public:
Iterator(T *start) : current(start) {}
bool operator ==(const Iterator &other) const
{
return current == other.current;
}
bool operator !=(const Iterator &other) const
{
return current != other.current;
}
T *position() const
{
return current;
}
T &operator ++()
{
return *++current;
}
T &operator ++(int)
{
return *current++;
}
T operator*() const
{
return *current;
}
T operator ()() const
{
return *current;
}
};
Iterator begin()
{
return Iterator(&first());
}
Iterator end()
{
return Iterator(&table[_size]);
}
};
};
<|endoftext|> |
<commit_before>#include "fingerprint.h"
using namespace v8;
using v8::FunctionTemplate;
typedef struct __VERIFY_STOP__ {
uv_async_t async;
Nan::Persistent<Function> callback;
} VERIFY_STOP;
typedef struct __VERIFY_START__ {
uv_async_t async;
Nan::Persistent<Function> callback;
int result;
struct fp_print_data *fpdata;
} VERIFY_START;
static const char *verify_result_to_name(int result)
{
switch (result) {
case FP_VERIFY_MATCH: return "verfiy-succeeded";
case FP_VERIFY_NO_MATCH: return "verify-failed";
case FP_VERIFY_RETRY: return "verify-retry-scan";
case FP_VERIFY_RETRY_TOO_SHORT: return "verify-swipe-too-short";
case FP_VERIFY_RETRY_CENTER_FINGER: return "verify-finger-not-centered";
case FP_VERIFY_RETRY_REMOVE_FINGER: return "verify-remove-and-retry";
default: return "verify-unknown-error";
}
}
void verify_stop_after(uv_handle_t* handle)
{
VERIFY_STOP *data = container_of((uv_async_t *)handle, VERIFY_STOP, async);
if(!data)
return;
delete data;
}
#ifndef OLD_UV_RUN_SIGNATURE
void report_verify_stop(uv_async_t *handle)
#else
void report_verify_stop(uv_async_t *handle, int status)
#endif
{
VERIFY_STOP *data = container_of(handle, VERIFY_STOP, async);
Nan::HandleScope();
if(!data)
return;
Nan::Callback callback(Nan::New<Function>(data->callback));
callback.Call(0, NULL);
uv_close((uv_handle_t*)&data->async, verify_stop_after);
}
static void verify_stop_cb(struct fp_dev *dev, void *user_data)
{
VERIFY_STOP *data = (VERIFY_STOP*)user_data;
if(!data)
return;
uv_async_send(&data->async);
}
NAN_METHOD(verifyStop) {
bool ret = false;
struct fp_dev *dev;
VERIFY_STOP *data;
if(info.Length() < 2)
goto error;
dev = toFPDev(info[0]->ToNumber()->Value());
if(initalized != 0 || dev == NULL)
goto error;
data = new VERIFY_STOP;
data->callback.Reset(v8::Local<v8::Function>::Cast(info[1]));
uv_async_init(uv_default_loop(), &data->async, report_verify_stop);
ret = fp_async_verify_stop(dev, verify_stop_cb, data) == 0;
error:
info.GetReturnValue().Set(Nan::New(ret));
}
void verify_start_after(uv_handle_t* handle)
{
VERIFY_START *data = container_of((uv_async_t *)handle, VERIFY_START, async);
if(!data)
return;
if(data->fpdata) {
fp_print_data_free(data->fpdata);
}
delete data;
}
#ifndef OLD_UV_RUN_SIGNATURE
void report_verify_start(uv_async_t *handle)
#else
void report_verify_start(uv_async_t *handle, int status)
#endif
{
VERIFY_START *data = container_of(handle, VERIFY_START, async);
Nan::HandleScope();
if(!data)
return;
Nan::Callback callback(Nan::New<Function>(data->callback));
Local<Value> argv[2];
argv[0] = Nan::New(data->result);
argv[1] = Nan::Null();
if(verify_result_to_name(data->result))
argv[1] = Nan::New(verify_result_to_name(data->result)).ToLocalChecked();
callback.Call(2, argv);
if(data->result == FP_VERIFY_NO_MATCH || data->result == FP_VERIFY_MATCH) {
uv_close((uv_handle_t*)&data->async, verify_start_after);
}
}
static void verify_start_cb(struct fp_dev *dev, int result, struct fp_img *img, void *user_data)
{
VERIFY_START *data = (VERIFY_START*)user_data;
if(!data)
return;
data->result = result;
uv_async_send(&data->async);
if(img) fp_img_free(img);
}
NAN_METHOD(verifyStart) {
bool ret = false;
struct fp_dev *dev;
VERIFY_START *data;
std::string s;
unsigned char *tmp;
unsigned long length;
if(info.Length() < 3)
goto error;
dev = toFPDev(info[0]->ToNumber()->Value());
if(initalized != 0 || dev == NULL)
goto error;
data = new VERIFY_START;
data->callback.Reset(v8::Local<v8::Function>::Cast(info[2]));
s = *String::Utf8Value(info[1]->ToString());
tmp = fromString(s, &length);
if(tmp) {
data->fpdata = fp_print_data_from_data(tmp, length);
free(tmp);
if(data->fpdata) {
uv_async_init(uv_default_loop(), &data->async, report_verify_start);
ret = fp_async_verify_start(dev, data->fpdata, verify_start_cb, data) == 0;
}
}
else {
printf("Fingerprint:\n%s\n", s.c_str());
printf("fromString returned: NULL\n");
}
error:
info.GetReturnValue().Set(Nan::New(ret));
}
<commit_msg>Update HandleScope to run on nodejs 4.4.3<commit_after>#include "fingerprint.h"
using namespace v8;
using v8::FunctionTemplate;
typedef struct __VERIFY_STOP__ {
uv_async_t async;
Nan::Persistent<Function> callback;
} VERIFY_STOP;
typedef struct __VERIFY_START__ {
uv_async_t async;
Nan::Persistent<Function> callback;
int result;
struct fp_print_data *fpdata;
} VERIFY_START;
static const char *verify_result_to_name(int result)
{
switch (result) {
case FP_VERIFY_MATCH: return "verfiy-succeeded";
case FP_VERIFY_NO_MATCH: return "verify-failed";
case FP_VERIFY_RETRY: return "verify-retry-scan";
case FP_VERIFY_RETRY_TOO_SHORT: return "verify-swipe-too-short";
case FP_VERIFY_RETRY_CENTER_FINGER: return "verify-finger-not-centered";
case FP_VERIFY_RETRY_REMOVE_FINGER: return "verify-remove-and-retry";
default: return "verify-unknown-error";
}
}
void verify_stop_after(uv_handle_t* handle)
{
VERIFY_STOP *data = container_of((uv_async_t *)handle, VERIFY_STOP, async);
if(!data)
return;
delete data;
}
#ifndef OLD_UV_RUN_SIGNATURE
void report_verify_stop(uv_async_t *handle)
#else
void report_verify_stop(uv_async_t *handle, int status)
#endif
{
VERIFY_STOP *data = container_of(handle, VERIFY_STOP, async);
Nan::HandleScope scope;
if(!data)
return;
Nan::Callback callback(Nan::New<Function>(data->callback));
callback.Call(0, NULL);
uv_close((uv_handle_t*)&data->async, verify_stop_after);
}
static void verify_stop_cb(struct fp_dev *dev, void *user_data)
{
VERIFY_STOP *data = (VERIFY_STOP*)user_data;
if(!data)
return;
uv_async_send(&data->async);
}
NAN_METHOD(verifyStop) {
bool ret = false;
struct fp_dev *dev;
VERIFY_STOP *data;
if(info.Length() < 2)
goto error;
dev = toFPDev(info[0]->ToNumber()->Value());
if(initalized != 0 || dev == NULL)
goto error;
data = new VERIFY_STOP;
data->callback.Reset(v8::Local<v8::Function>::Cast(info[1]));
uv_async_init(uv_default_loop(), &data->async, report_verify_stop);
ret = fp_async_verify_stop(dev, verify_stop_cb, data) == 0;
error:
info.GetReturnValue().Set(Nan::New(ret));
}
void verify_start_after(uv_handle_t* handle)
{
VERIFY_START *data = container_of((uv_async_t *)handle, VERIFY_START, async);
if(!data)
return;
if(data->fpdata) {
fp_print_data_free(data->fpdata);
}
delete data;
}
#ifndef OLD_UV_RUN_SIGNATURE
void report_verify_start(uv_async_t *handle)
#else
void report_verify_start(uv_async_t *handle, int status)
#endif
{
VERIFY_START *data = container_of(handle, VERIFY_START, async);
Nan::HandleScope scope;
if(!data)
return;
Nan::Callback callback(Nan::New<Function>(data->callback));
Local<Value> argv[2];
argv[0] = Nan::New(data->result);
argv[1] = Nan::Null();
if(verify_result_to_name(data->result))
argv[1] = Nan::New(verify_result_to_name(data->result)).ToLocalChecked();
callback.Call(2, argv);
if(data->result == FP_VERIFY_NO_MATCH || data->result == FP_VERIFY_MATCH) {
uv_close((uv_handle_t*)&data->async, verify_start_after);
}
}
static void verify_start_cb(struct fp_dev *dev, int result, struct fp_img *img, void *user_data)
{
VERIFY_START *data = (VERIFY_START*)user_data;
if(!data)
return;
data->result = result;
uv_async_send(&data->async);
if(img) fp_img_free(img);
}
NAN_METHOD(verifyStart) {
bool ret = false;
struct fp_dev *dev;
VERIFY_START *data;
std::string s;
unsigned char *tmp;
unsigned long length;
if(info.Length() < 3)
goto error;
dev = toFPDev(info[0]->ToNumber()->Value());
if(initalized != 0 || dev == NULL)
goto error;
data = new VERIFY_START;
data->callback.Reset(v8::Local<v8::Function>::Cast(info[2]));
s = *String::Utf8Value(info[1]->ToString());
tmp = fromString(s, &length);
if(tmp) {
data->fpdata = fp_print_data_from_data(tmp, length);
free(tmp);
if(data->fpdata) {
uv_async_init(uv_default_loop(), &data->async, report_verify_start);
ret = fp_async_verify_start(dev, data->fpdata, verify_start_cb, data) == 0;
}
}
else {
printf("Fingerprint:\n%s\n", s.c_str());
printf("fromString returned: NULL\n");
}
error:
info.GetReturnValue().Set(Nan::New(ret));
}
<|endoftext|> |
<commit_before>// Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "v8.h"
#include "version.h"
// These macros define the version number for the current version.
// NOTE these macros are used by the SCons build script so their names
// cannot be changed without changing the SCons build script.
#define MAJOR_VERSION 3
#define MINOR_VERSION 17
#define BUILD_NUMBER 17
#define PATCH_LEVEL 0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1
// Define SONAME to have the SCons build the put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the SCons build script.
#define SONAME ""
#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif
#define SX(x) #x
#define S(x) SX(x)
#if PATCH_LEVEL > 0
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \
S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \
CANDIDATE_STRING
#endif
namespace v8 {
namespace internal {
int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;
// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
const char* is_simulator = " SIMULATOR";
#else
const char* is_simulator = "";
#endif // USE_SIMULATOR
if (GetPatch() > 0) {
OS::SNPrintF(str, "%d.%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
is_simulator);
} else {
OS::SNPrintF(str, "%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), candidate,
is_simulator);
}
}
// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
if (soname_ == NULL || *soname_ == '\0') {
// Generate generic SONAME if no specific SONAME is defined.
const char* candidate = IsCandidate() ? "-candidate" : "";
if (GetPatch() > 0) {
OS::SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
} else {
OS::SNPrintF(str, "libv8-%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), candidate);
}
} else {
// Use specific SONAME.
OS::SNPrintF(str, "%s", soname_);
}
}
} } // namespace v8::internal
<commit_msg>Fast-forward version number on bleeding_edge. Now working on version 3.18.0.<commit_after>// Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "v8.h"
#include "version.h"
// These macros define the version number for the current version.
// NOTE these macros are used by the SCons build script so their names
// cannot be changed without changing the SCons build script.
#define MAJOR_VERSION 3
#define MINOR_VERSION 18
#define BUILD_NUMBER 0
#define PATCH_LEVEL 0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1
// Define SONAME to have the SCons build the put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the SCons build script.
#define SONAME ""
#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif
#define SX(x) #x
#define S(x) SX(x)
#if PATCH_LEVEL > 0
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \
S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \
CANDIDATE_STRING
#endif
namespace v8 {
namespace internal {
int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;
// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
const char* is_simulator = " SIMULATOR";
#else
const char* is_simulator = "";
#endif // USE_SIMULATOR
if (GetPatch() > 0) {
OS::SNPrintF(str, "%d.%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
is_simulator);
} else {
OS::SNPrintF(str, "%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), candidate,
is_simulator);
}
}
// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
if (soname_ == NULL || *soname_ == '\0') {
// Generate generic SONAME if no specific SONAME is defined.
const char* candidate = IsCandidate() ? "-candidate" : "";
if (GetPatch() > 0) {
OS::SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
} else {
OS::SNPrintF(str, "libv8-%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), candidate);
}
} else {
// Use specific SONAME.
OS::SNPrintF(str, "%s", soname_);
}
}
} } // namespace v8::internal
<|endoftext|> |
<commit_before>#include "vg_set.hpp"
#include <vg/io/stream.hpp>
#include "source_sink_overlay.hpp"
#include <vg/io/stream.hpp>
#include <vg/io/vpkg.hpp>
#include "io/save_handle_graph.hpp"
#include "algorithms/topological_sort.hpp"
namespace vg {
// sets of MutablePathMutableHandleGraphs on disk
void VGset::transform(std::function<void(MutableHandleGraph*)> lambda) {
// TODO: add a way to cache graphs here for multiple scans
for (auto& name : filenames) {
// load
unique_ptr<MutableHandleGraph> g;
get_input_file(name, [&](istream& in) {
// Note: I would have liked to just load a MutableHandleGraph here but the resulting pointer
// is broken (tested: VG and PackedGraph)
g = vg::io::VPKG::load_one<MutablePathMutableHandleGraph>(in);
});
// legacy:
VG* vg_g = dynamic_cast<VG*>(g.get());
if (vg_g != nullptr) {
vg_g->name = name;
}
// apply
lambda(g.get());
// write to the same file
vg::io::save_handle_graph(g.get(), name);
}
}
void VGset::for_each(std::function<void(HandleGraph*)> lambda) {
// TODO: add a way to cache graphs here for multiple scans
for (auto& name : filenames) {
// load
unique_ptr<HandleGraph> g;
get_input_file(name, [&](istream& in) {
g = vg::io::VPKG::load_one<HandleGraph>(in);
});
// legacy:
VG* vg_g = dynamic_cast<VG*>(g.get());
if (vg_g != nullptr) {
vg_g->name = name;
}
// apply
lambda(g.get());
}
}
id_t VGset::max_node_id(void) {
id_t max_id = 0;
for_each([&](HandleGraph* graph) {
max_id = max(graph->max_node_id(), max_id);
});
return max_id;
}
int64_t VGset::merge_id_space(void) {
int64_t max_node_id = 0;
// TODO: for now, only vg::VG actually implements increment_node_ids,
// despite it being in the interface.
auto lambda = [&max_node_id](MutableHandleGraph* g) {
int64_t delta = max_node_id - g->min_node_id();
if (delta >= 0) {
g->increment_node_ids(delta + 1);
}
max_node_id = g->max_node_id();
};
transform(lambda);
return max_node_id;
}
void VGset::to_xg(xg::XG& index) {
// Send a predicate to match nothing
to_xg(index, [](const string& ignored) {
return false;
});
}
void VGset::to_xg(xg::XG& index, const function<bool(const string&)>& paths_to_remove, map<string, Path>* removed_paths) {
// We make multiple passes through the input graphs, loading each and going through its nodes/edges/paths.
// TODO: This is going to go load all the graphs multiple times, even if there's only one graph!
// TODO: streaming HandleGraph API?
// TODO: push-driven XG build?
// TODO: XG::from_path_handle_graphs?
// We need to recostruct full removed paths from fragmentary paths encountered in each chunk.
// This maps from path name to all the Mappings in the path in the order we encountered them
auto for_each_sequence = [&](const std::function<void(const std::string& seq, const nid_t& node_id)>& lambda) {
for_each([&](HandleGraph* graph) {
// For each graph in the set
// Compute a topological order. The XG is much more efficient if the nodes are stored in topological order.
// TODO: Compute this only once and not each time we want to visit all the nodes during XG construction?
for (const handle_t& h : algorithms::topological_order(graph)) {
// For each node in the graph, tell the XG about it.
// Assume it is locally forward.
#ifdef debug
cerr << "Yield node " << graph->get_id(h) << " sequence " << graph->get_sequence(h) << endl;
#endif
lambda(graph->get_sequence(h), graph->get_id(h));
}
});
};
auto for_each_edge = [&](const std::function<void(const nid_t& from, const bool& from_rev, const nid_t& to, const bool& to_rev)>& lambda) {
for_each([&](HandleGraph* graph) {
// For each graph in the set
graph->for_each_edge([&](const edge_t& e) {
// For each edge in the graph, tell the XG about it
#ifdef debug
cerr << "Yield edge " << graph->get_id(e.first) << " " << graph->get_is_reverse(e.first)
<< " " << graph->get_id(e.second) << " " << graph->get_is_reverse(e.second) << endl;
#endif
lambda(graph->get_id(e.first), graph->get_is_reverse(e.first), graph->get_id(e.second), graph->get_is_reverse(e.second));
});
});
};
// We no longer need to reconstitute paths ourselves; we require that each
// input file has all the parts of its paths.
auto for_each_path_element = [&](const std::function<void(const std::string& path_name,
const nid_t& node_id, const bool& is_rev,
const std::string& cigar,
bool is_empty, bool is_circular)>& lambda) {
for_each([&](HandleGraph* graph) {
// Look at each graph and see if it has path support
// TODO: do we need a different for_each to push this down to the loader?
PathHandleGraph* path_graph = dynamic_cast<PathHandleGraph*>(graph);
if (path_graph != nullptr) {
// The graph we loaded actually can have paths, so it can have visits
path_graph->for_each_path_handle([&](const path_handle_t& p) {
// For each path
// Get its metadata
string path_name = path_graph->get_path_name(p);
bool is_circular = path_graph->get_is_circular(p);
if(paths_to_remove(path_name)) {
// We want to filter out this path
if (removed_paths != nullptr) {
// When we filter out a path, we need to send our caller a Protobuf version of it.
Path proto_path;
proto_path.set_name(path_name);
proto_path.set_is_circular(is_circular);
size_t rank = 1;
path_graph->for_each_step_in_path(p, [&](const step_handle_t& s) {
handle_t stepped_on = path_graph->get_handle_of_step(s);
Mapping* mapping = proto_path.add_mapping();
mapping->mutable_position()->set_node_id(path_graph->get_id(stepped_on));
mapping->mutable_position()->set_is_reverse(path_graph->get_is_reverse(stepped_on));
mapping->set_rank(rank++);
});
removed_paths->emplace(std::move(path_name), std::move(proto_path));
}
} else {
// We want to leave this path in
// Assume it is empty
bool is_empty = true;
path_graph->for_each_step_in_path(p, [&](const step_handle_t& s) {
// For each visit on the path
handle_t stepped_on = path_graph->get_handle_of_step(s);
// The path can't be empty
is_empty = false;
// Tell the XG about it
#ifdef debug
cerr << "Yield path " << path_name << " visit to "
<< path_graph->get_id(stepped_on) << " " << path_graph->get_is_reverse(stepped_on) << endl;
#endif
lambda(path_name, path_graph->get_id(stepped_on), path_graph->get_is_reverse(stepped_on), "", is_empty, is_circular);
});
if (is_empty) {
// If the path is empty, tell the XG that.
// It still could be circular.
#ifdef debug
cerr << "Yield empty path " << path_name << endl;
#endif
lambda(path_name, 0, false, "", is_empty, is_circular);
}
}
});
}
});
};
// Now build the xg graph, looping over all our graphs in our set whenever we want anything.
index.from_enumerators(for_each_sequence, for_each_edge, for_each_path_element, false);
}
void VGset::for_each_kmer_parallel(size_t kmer_size, const function<void(const kmer_t&)>& lambda) {
for_each([&lambda, kmer_size, this](HandleGraph* g) {
// legacy
VG* vg_g = dynamic_cast<VG*>(g);
if (vg_g != nullptr) {
vg_g->show_progress = show_progress & progress_bars;
vg_g->preload_progress("processing kmers of " + vg_g->name);
}
//g->for_each_kmer_parallel(kmer_size, path_only, edge_max, lambda, stride, allow_dups, allow_negatives);
for_each_kmer(*g, kmer_size, lambda);
});
}
void VGset::write_gcsa_kmers_ascii(ostream& out, int kmer_size,
id_t head_id, id_t tail_id) {
if (filenames.size() > 1 && (head_id == 0 || tail_id == 0)) {
// Detect head and tail IDs in advance if we have multiple graphs
id_t max_id = max_node_id(); // expensive, as we'll stream through all the files
head_id = max_id + 1;
tail_id = max_id + 2;
}
// When we're sure we know what this kmer instance looks like, we'll write
// it out exactly once. We need the start_end_id actually used in order to
// go to the correct place when we don't go anywhere (i.e. at the far end of
// the start/end node.
auto write_kmer = [&head_id, &tail_id](const kmer_t& kp){
#pragma omp critical (cout)
cout << kp << endl;
};
for_each([&](HandleGraph* g) {
// Make an overlay for each graph, without modifying it. Break into tip-less cycle components.
// Make sure to use a consistent head and tail ID across all graphs in the set.
SourceSinkOverlay overlay(g, kmer_size, head_id, tail_id);
// Read back the head and tail IDs in case we have only one graph and we just detected them now.
head_id = overlay.get_id(overlay.get_source_handle());
tail_id = overlay.get_id(overlay.get_sink_handle());
// Now get the kmers in the graph that pretends to have single head and tail nodes
for_each_kmer(overlay, kmer_size, write_kmer, head_id, tail_id);
});
}
// writes to a specific output stream
void VGset::write_gcsa_kmers_binary(ostream& out, int kmer_size, size_t& size_limit,
id_t head_id, id_t tail_id) {
if (filenames.size() > 1 && (head_id == 0 || tail_id == 0)) {
// Detect head and tail IDs in advance if we have multiple graphs
id_t max_id = max_node_id(); // expensive, as we'll stream through all the files
head_id = max_id + 1;
tail_id = max_id + 2;
}
size_t total_size = 0;
for_each([&](HandleGraph* g) {
// Make an overlay for each graph, without modifying it. Break into tip-less cycle components.
// Make sure to use a consistent head and tail ID across all graphs in the set.
SourceSinkOverlay overlay(g, kmer_size, head_id, tail_id);
// Read back the head and tail IDs in case we have only one graph and we just detected them now.
head_id = overlay.get_id(overlay.get_source_handle());
tail_id = overlay.get_id(overlay.get_sink_handle());
size_t current_bytes = size_limit - total_size;
write_gcsa_kmers(overlay, kmer_size, out, current_bytes, head_id, tail_id);
total_size += current_bytes;
});
size_limit = total_size;
}
// writes to a set of temp files and returns their names
vector<string> VGset::write_gcsa_kmers_binary(int kmer_size, size_t& size_limit,
id_t head_id, id_t tail_id) {
if (filenames.size() > 1 && (head_id == 0 || tail_id == 0)) {
// Detect head and tail IDs in advance if we have multiple graphs
id_t max_id = max_node_id(); // expensive, as we'll stream through all the files
head_id = max_id + 1;
tail_id = max_id + 2;
}
vector<string> tmpnames;
size_t total_size = 0;
for_each([&](HandleGraph* g) {
// Make an overlay for each graph, without modifying it. Break into tip-less cycle components.
// Make sure to use a consistent head and tail ID across all graphs in the set.
SourceSinkOverlay overlay(g, kmer_size, head_id, tail_id);
// Read back the head and tail IDs in case we have only one graph and we just detected them now.
head_id = overlay.get_id(overlay.get_source_handle());
tail_id = overlay.get_id(overlay.get_sink_handle());
size_t current_bytes = size_limit - total_size;
tmpnames.push_back(write_gcsa_kmers_to_tmpfile(overlay, kmer_size, current_bytes, head_id, tail_id));
total_size += current_bytes;
});
size_limit = total_size;
return tmpnames;
}
}
<commit_msg>Go back to ID-order xg files in hopes that that fixes vg map accuracy on Cactus graphs<commit_after>#include "vg_set.hpp"
#include <vg/io/stream.hpp>
#include "source_sink_overlay.hpp"
#include <vg/io/stream.hpp>
#include <vg/io/vpkg.hpp>
#include "io/save_handle_graph.hpp"
namespace vg {
// sets of MutablePathMutableHandleGraphs on disk
void VGset::transform(std::function<void(MutableHandleGraph*)> lambda) {
// TODO: add a way to cache graphs here for multiple scans
for (auto& name : filenames) {
// load
unique_ptr<MutableHandleGraph> g;
get_input_file(name, [&](istream& in) {
// Note: I would have liked to just load a MutableHandleGraph here but the resulting pointer
// is broken (tested: VG and PackedGraph)
g = vg::io::VPKG::load_one<MutablePathMutableHandleGraph>(in);
});
// legacy:
VG* vg_g = dynamic_cast<VG*>(g.get());
if (vg_g != nullptr) {
vg_g->name = name;
}
// apply
lambda(g.get());
// write to the same file
vg::io::save_handle_graph(g.get(), name);
}
}
void VGset::for_each(std::function<void(HandleGraph*)> lambda) {
// TODO: add a way to cache graphs here for multiple scans
for (auto& name : filenames) {
// load
unique_ptr<HandleGraph> g;
get_input_file(name, [&](istream& in) {
g = vg::io::VPKG::load_one<HandleGraph>(in);
});
// legacy:
VG* vg_g = dynamic_cast<VG*>(g.get());
if (vg_g != nullptr) {
vg_g->name = name;
}
// apply
lambda(g.get());
}
}
id_t VGset::max_node_id(void) {
id_t max_id = 0;
for_each([&](HandleGraph* graph) {
max_id = max(graph->max_node_id(), max_id);
});
return max_id;
}
int64_t VGset::merge_id_space(void) {
int64_t max_node_id = 0;
// TODO: for now, only vg::VG actually implements increment_node_ids,
// despite it being in the interface.
auto lambda = [&max_node_id](MutableHandleGraph* g) {
int64_t delta = max_node_id - g->min_node_id();
if (delta >= 0) {
g->increment_node_ids(delta + 1);
}
max_node_id = g->max_node_id();
};
transform(lambda);
return max_node_id;
}
void VGset::to_xg(xg::XG& index) {
// Send a predicate to match nothing
to_xg(index, [](const string& ignored) {
return false;
});
}
void VGset::to_xg(xg::XG& index, const function<bool(const string&)>& paths_to_remove, map<string, Path>* removed_paths) {
// We make multiple passes through the input graphs, loading each and going through its nodes/edges/paths.
// TODO: This is going to go load all the graphs multiple times, even if there's only one graph!
// TODO: streaming HandleGraph API?
// TODO: push-driven XG build?
// TODO: XG::from_path_handle_graphs?
// We need to recostruct full removed paths from fragmentary paths encountered in each chunk.
// This maps from path name to all the Mappings in the path in the order we encountered them
auto for_each_sequence = [&](const std::function<void(const std::string& seq, const nid_t& node_id)>& lambda) {
for_each([&](HandleGraph* graph) {
// For each graph in the set
// ID-sort its handles. This is the order that we have historically
// used, and may be required for e.g. vg map to work correctly.
// TODO: Compute this only once and not each time we want to visit
// all the nodes during XG construction?
vector<handle_t> order;
// TODO: reserve if counting handles will be efficient. Can we know?
graph->for_each_handle([&](const handle_t& h) {
order.push_back(h);
});
std::sort(order.begin(), order.end(), [&](const handle_t& a, const handle_t& b) {
// Return true if a must come first
// We know everything is locally forward already.
return graph->get_id(a) < graph->get_id(b);
});
for (const handle_t& h : order) {
// For each node in the graph, tell the XG about it.
// Assume it is locally forward.
#ifdef debug
cerr << "Yield node " << graph->get_id(h) << " sequence " << graph->get_sequence(h) << endl;
#endif
lambda(graph->get_sequence(h), graph->get_id(h));
}
});
};
auto for_each_edge = [&](const std::function<void(const nid_t& from, const bool& from_rev, const nid_t& to, const bool& to_rev)>& lambda) {
for_each([&](HandleGraph* graph) {
// For each graph in the set
graph->for_each_edge([&](const edge_t& e) {
// For each edge in the graph, tell the XG about it
#ifdef debug
cerr << "Yield edge " << graph->get_id(e.first) << " " << graph->get_is_reverse(e.first)
<< " " << graph->get_id(e.second) << " " << graph->get_is_reverse(e.second) << endl;
#endif
lambda(graph->get_id(e.first), graph->get_is_reverse(e.first), graph->get_id(e.second), graph->get_is_reverse(e.second));
});
});
};
// We no longer need to reconstitute paths ourselves; we require that each
// input file has all the parts of its paths.
auto for_each_path_element = [&](const std::function<void(const std::string& path_name,
const nid_t& node_id, const bool& is_rev,
const std::string& cigar,
bool is_empty, bool is_circular)>& lambda) {
for_each([&](HandleGraph* graph) {
// Look at each graph and see if it has path support
// TODO: do we need a different for_each to push this down to the loader?
PathHandleGraph* path_graph = dynamic_cast<PathHandleGraph*>(graph);
if (path_graph != nullptr) {
// The graph we loaded actually can have paths, so it can have visits
path_graph->for_each_path_handle([&](const path_handle_t& p) {
// For each path
// Get its metadata
string path_name = path_graph->get_path_name(p);
bool is_circular = path_graph->get_is_circular(p);
if(paths_to_remove(path_name)) {
// We want to filter out this path
if (removed_paths != nullptr) {
// When we filter out a path, we need to send our caller a Protobuf version of it.
Path proto_path;
proto_path.set_name(path_name);
proto_path.set_is_circular(is_circular);
size_t rank = 1;
path_graph->for_each_step_in_path(p, [&](const step_handle_t& s) {
handle_t stepped_on = path_graph->get_handle_of_step(s);
Mapping* mapping = proto_path.add_mapping();
mapping->mutable_position()->set_node_id(path_graph->get_id(stepped_on));
mapping->mutable_position()->set_is_reverse(path_graph->get_is_reverse(stepped_on));
mapping->set_rank(rank++);
});
removed_paths->emplace(std::move(path_name), std::move(proto_path));
}
} else {
// We want to leave this path in
// Assume it is empty
bool is_empty = true;
path_graph->for_each_step_in_path(p, [&](const step_handle_t& s) {
// For each visit on the path
handle_t stepped_on = path_graph->get_handle_of_step(s);
// The path can't be empty
is_empty = false;
// Tell the XG about it
#ifdef debug
cerr << "Yield path " << path_name << " visit to "
<< path_graph->get_id(stepped_on) << " " << path_graph->get_is_reverse(stepped_on) << endl;
#endif
lambda(path_name, path_graph->get_id(stepped_on), path_graph->get_is_reverse(stepped_on), "", is_empty, is_circular);
});
if (is_empty) {
// If the path is empty, tell the XG that.
// It still could be circular.
#ifdef debug
cerr << "Yield empty path " << path_name << endl;
#endif
lambda(path_name, 0, false, "", is_empty, is_circular);
}
}
});
}
});
};
// Now build the xg graph, looping over all our graphs in our set whenever we want anything.
index.from_enumerators(for_each_sequence, for_each_edge, for_each_path_element, false);
}
void VGset::for_each_kmer_parallel(size_t kmer_size, const function<void(const kmer_t&)>& lambda) {
for_each([&lambda, kmer_size, this](HandleGraph* g) {
// legacy
VG* vg_g = dynamic_cast<VG*>(g);
if (vg_g != nullptr) {
vg_g->show_progress = show_progress & progress_bars;
vg_g->preload_progress("processing kmers of " + vg_g->name);
}
//g->for_each_kmer_parallel(kmer_size, path_only, edge_max, lambda, stride, allow_dups, allow_negatives);
for_each_kmer(*g, kmer_size, lambda);
});
}
void VGset::write_gcsa_kmers_ascii(ostream& out, int kmer_size,
id_t head_id, id_t tail_id) {
if (filenames.size() > 1 && (head_id == 0 || tail_id == 0)) {
// Detect head and tail IDs in advance if we have multiple graphs
id_t max_id = max_node_id(); // expensive, as we'll stream through all the files
head_id = max_id + 1;
tail_id = max_id + 2;
}
// When we're sure we know what this kmer instance looks like, we'll write
// it out exactly once. We need the start_end_id actually used in order to
// go to the correct place when we don't go anywhere (i.e. at the far end of
// the start/end node.
auto write_kmer = [&head_id, &tail_id](const kmer_t& kp){
#pragma omp critical (cout)
cout << kp << endl;
};
for_each([&](HandleGraph* g) {
// Make an overlay for each graph, without modifying it. Break into tip-less cycle components.
// Make sure to use a consistent head and tail ID across all graphs in the set.
SourceSinkOverlay overlay(g, kmer_size, head_id, tail_id);
// Read back the head and tail IDs in case we have only one graph and we just detected them now.
head_id = overlay.get_id(overlay.get_source_handle());
tail_id = overlay.get_id(overlay.get_sink_handle());
// Now get the kmers in the graph that pretends to have single head and tail nodes
for_each_kmer(overlay, kmer_size, write_kmer, head_id, tail_id);
});
}
// writes to a specific output stream
void VGset::write_gcsa_kmers_binary(ostream& out, int kmer_size, size_t& size_limit,
id_t head_id, id_t tail_id) {
if (filenames.size() > 1 && (head_id == 0 || tail_id == 0)) {
// Detect head and tail IDs in advance if we have multiple graphs
id_t max_id = max_node_id(); // expensive, as we'll stream through all the files
head_id = max_id + 1;
tail_id = max_id + 2;
}
size_t total_size = 0;
for_each([&](HandleGraph* g) {
// Make an overlay for each graph, without modifying it. Break into tip-less cycle components.
// Make sure to use a consistent head and tail ID across all graphs in the set.
SourceSinkOverlay overlay(g, kmer_size, head_id, tail_id);
// Read back the head and tail IDs in case we have only one graph and we just detected them now.
head_id = overlay.get_id(overlay.get_source_handle());
tail_id = overlay.get_id(overlay.get_sink_handle());
size_t current_bytes = size_limit - total_size;
write_gcsa_kmers(overlay, kmer_size, out, current_bytes, head_id, tail_id);
total_size += current_bytes;
});
size_limit = total_size;
}
// writes to a set of temp files and returns their names
vector<string> VGset::write_gcsa_kmers_binary(int kmer_size, size_t& size_limit,
id_t head_id, id_t tail_id) {
if (filenames.size() > 1 && (head_id == 0 || tail_id == 0)) {
// Detect head and tail IDs in advance if we have multiple graphs
id_t max_id = max_node_id(); // expensive, as we'll stream through all the files
head_id = max_id + 1;
tail_id = max_id + 2;
}
vector<string> tmpnames;
size_t total_size = 0;
for_each([&](HandleGraph* g) {
// Make an overlay for each graph, without modifying it. Break into tip-less cycle components.
// Make sure to use a consistent head and tail ID across all graphs in the set.
SourceSinkOverlay overlay(g, kmer_size, head_id, tail_id);
// Read back the head and tail IDs in case we have only one graph and we just detected them now.
head_id = overlay.get_id(overlay.get_source_handle());
tail_id = overlay.get_id(overlay.get_sink_handle());
size_t current_bytes = size_limit - total_size;
tmpnames.push_back(write_gcsa_kmers_to_tmpfile(overlay, kmer_size, current_bytes, head_id, tail_id));
total_size += current_bytes;
});
size_limit = total_size;
return tmpnames;
}
}
<|endoftext|> |
<commit_before>#include "client.h"
CLIENT::CLIENT (char *IP)
{
struct sockaddr_in dest_addr;
name_verified = false;
sockfd = socket (AF_INET, SOCK_STREAM, 0);
if(sockfd == -1){
perror ("socket");
exit (EXIT_FAILURE); // v. pthread_exit
}
dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(PORT);
dest_addr.sin_addr.s_addr = inet_addr(IP);
memset(&(dest_addr.sin_zero), 0, 8);
if (connect(sockfd, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr)) == -1){
if(write (STDERR_FILENO, "Couldn't connect to the server\n", 31) != 31){
perror ("write");
exit (EXIT_FAILURE);
}
if(close(sockfd) == -1){
perror ("close");
exit (EXIT_FAILURE); // v. pthread_exit
}
}
}
CLIENT::~CLIENT ()
{
}
void CLIENT::Play ()
{
server = exchangeCIandName ();
std::thread (writeLoop, this).detach();
std::thread (readLoop, this).detach();
}
SERVER CLIENT::exchangeCIandName ()
{
std::string server_pk;
std::string server_nonce;
ssize_t br;
char buf[64];
char responce;
server_pk = recvPK ();
server_nonce = recvNonce ();
sendPK();
sendNonce();
while(!name_verified){
if(write (STDOUT_FILENO, "Please select a username: ", 26) != 26){
perror ("write");
exit (EXIT_FAILURE);
}
memset (buf, 0, 64);
if((br = read (STDIN_FILENO, buf, 64)) == -1){
perror ("read");
exit (EXIT_FAILURE);
}
if(!br){} //EOF
if(write (sockfd, buf, sizeof(buf)) != sizeof(buf)){
perror ("write");
exit (EXIT_FAILURE);
}
if(read (sockfd, &responce, 1) != 1){
perror ("read");
exit (EXIT_FAILURE);
}
if(responce == 'Y')
name_verified = true;
}
CRYPTO cryptinfo (server_pk, server_nonce);
SERVER server (cryptinfo);
return server;
}
void CLIENT::sendPK ()
{
if(write (sockfd, cryptinfo.getPK().c_str(), crypto_box_PUBLICKEYBYTES ) != crypto_box_PUBLICKEYBYTES){
perror ("write");
exit (EXIT_FAILURE);
}
}
void CLIENT::sendNonce ()
{
if(write (sockfd, cryptinfo.getNonce().c_str(), crypto_box_NONCEBYTES) != crypto_box_NONCEBYTES){
perror ("write");
exit (EXIT_FAILURE);
}
}
std::string CLIENT::recvPK ()
{
std::string server_pk;
char buf[crypto_box_PUBLICKEYBYTES];
memset (buf, 0, crypto_box_PUBLICKEYBYTES);
if(read (sockfd, buf, crypto_box_PUBLICKEYBYTES) != crypto_box_PUBLICKEYBYTES){
perror ("read");
exit (EXIT_FAILURE);
}
server_pk = buf;
return server_pk;
}
std::string CLIENT::recvNonce ()
{
std::string server_nonce;
char buf[crypto_box_NONCEBYTES];
memset (buf, 0, crypto_box_NONCEBYTES);
if(read (sockfd, buf, crypto_box_NONCEBYTES) != crypto_box_NONCEBYTES){
perror ("read");
exit (EXIT_FAILURE);
}
server_nonce = buf;
return server_nonce;
}
int CLIENT::getSFD ()
{
return sockfd;
}
void readLoop (CLIENT *client_p)
{
char buf[1024];
ssize_t br;
while(1){
memset (buf, 0, 1024);
if((br = read (client_p->getSFD(), buf, 1024)) == -1){
perror ("read");
exit (EXIT_FAILURE);
}
if(!br)
return;
if(write(STDOUT_FILENO, buf, br) != br){
perror ("write");
exit (EXIT_FAILURE);
}
}
}
void writeLoop (CLIENT *client_p)
{
char buf[1024];
ssize_t br;
while(1){
memset (buf, 0, 1024);
if((br = read (STDIN_FILENO, buf, 1024)) == -1){
perror ("read");
exit (EXIT_FAILURE);
}
if(!br){
//EOF
close (client_p->getSFD());
return;
}
if(write (client_p->getSFD(), buf, br) != br){
perror ("write");
exit (EXIT_FAILURE);
}
}
}<commit_msg>completed client Play () interface<commit_after>#include "client.h"
CLIENT::CLIENT (char *IP)
{
struct sockaddr_in dest_addr;
name_verified = false;
sockfd = socket (AF_INET, SOCK_STREAM, 0);
if(sockfd == -1){
perror ("socket");
exit (EXIT_FAILURE); // v. pthread_exit
}
dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(PORT);
dest_addr.sin_addr.s_addr = inet_addr(IP);
memset(&(dest_addr.sin_zero), 0, 8);
if (connect(sockfd, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr)) == -1){
if(write (STDERR_FILENO, "Couldn't connect to the server\n", 31) != 31){
perror ("write");
exit (EXIT_FAILURE);
}
if(close(sockfd) == -1){
perror ("close");
exit (EXIT_FAILURE); // v. pthread_exit
}
}
}
CLIENT::~CLIENT ()
{
}
void CLIENT::Play ()
{
server = exchangeCIandName ();
std::thread (writeLoop, this).detach();
std::thread (readLoop, this).detach();
while(true){ sleep(5); }
}
SERVER CLIENT::exchangeCIandName ()
{
std::string server_pk;
std::string server_nonce;
ssize_t br;
char buf[64];
char responce;
server_pk = recvPK ();
server_nonce = recvNonce ();
sendPK();
sendNonce();
while(!name_verified){
if(write (STDOUT_FILENO, "Please select a username: ", 26) != 26){
perror ("write");
exit (EXIT_FAILURE);
}
memset (buf, 0, 64);
if((br = read (STDIN_FILENO, buf, 64)) == -1){
perror ("read");
exit (EXIT_FAILURE);
}
if(!br){} //EOF
if(write (sockfd, buf, sizeof(buf)) != sizeof(buf)){
perror ("write");
exit (EXIT_FAILURE);
}
if(read (sockfd, &responce, 1) != 1){
perror ("read");
exit (EXIT_FAILURE);
}
if(responce == 'Y')
name_verified = true;
}
CRYPTO cryptinfo (server_pk, server_nonce);
SERVER server (cryptinfo);
return server;
}
void CLIENT::sendPK ()
{
if(write (sockfd, cryptinfo.getPK().c_str(), crypto_box_PUBLICKEYBYTES ) != crypto_box_PUBLICKEYBYTES){
perror ("write");
exit (EXIT_FAILURE);
}
}
void CLIENT::sendNonce ()
{
if(write (sockfd, cryptinfo.getNonce().c_str(), crypto_box_NONCEBYTES) != crypto_box_NONCEBYTES){
perror ("write");
exit (EXIT_FAILURE);
}
}
std::string CLIENT::recvPK ()
{
std::string server_pk;
char buf[crypto_box_PUBLICKEYBYTES];
memset (buf, 0, crypto_box_PUBLICKEYBYTES);
if(read (sockfd, buf, crypto_box_PUBLICKEYBYTES) != crypto_box_PUBLICKEYBYTES){
perror ("read");
exit (EXIT_FAILURE);
}
server_pk = buf;
return server_pk;
}
std::string CLIENT::recvNonce ()
{
std::string server_nonce;
char buf[crypto_box_NONCEBYTES];
memset (buf, 0, crypto_box_NONCEBYTES);
if(read (sockfd, buf, crypto_box_NONCEBYTES) != crypto_box_NONCEBYTES){
perror ("read");
exit (EXIT_FAILURE);
}
server_nonce = buf;
return server_nonce;
}
int CLIENT::getSFD ()
{
return sockfd;
}
void readLoop (CLIENT *client_p)
{
char buf[1024];
ssize_t br;
while(1){
memset (buf, 0, 1024);
if((br = read (client_p->getSFD(), buf, 1024)) == -1){
perror ("read");
exit (EXIT_FAILURE);
}
if(!br)
return;
if(write(STDOUT_FILENO, buf, br) != br){
perror ("write");
exit (EXIT_FAILURE);
}
}
}
void writeLoop (CLIENT *client_p)
{
char buf[1024];
ssize_t br;
while(1){
memset (buf, 0, 1024);
if((br = read (STDIN_FILENO, buf, 1024)) == -1){
perror ("read");
exit (EXIT_FAILURE);
}
if(!br){
//EOF
close (client_p->getSFD());
return;
}
if(write (client_p->getSFD(), buf, br) != br){
perror ("write");
exit (EXIT_FAILURE);
}
}
}<|endoftext|> |
<commit_before>// -*- c++ -*-
/********************************************************************
* AUTHORS: Vijay Ganesh
*
* BEGIN DATE: November, 2005
*
* LICENSE: Please view LICENSE file in the home dir of this Program
********************************************************************/
#include "STP.h"
namespace BEEV {
//Acceps a query, calls the SAT solver and generates Valid/InValid.
//if returned 0 then input is INVALID if returned 1 then input is
//VALID if returned 2 then UNDECIDED
SOLVER_RETURN_TYPE STP::TopLevelSTPAux(const ASTNode& inputasserts_and_query)
{
ASTNode inputToSAT = inputasserts_and_query;
ASTNode orig_input = inputToSAT;
bm->ASTNodeStats("input asserts and query: ", inputToSAT);
ASTNode simplified_solved_InputToSAT = inputToSAT;
//round of substitution, solving, and simplification. ensures that
//DAG is minimized as much as possibly, and ideally should
//garuntee that all liketerms in BVPLUSes have been combined.
bm->SimplifyWrites_InPlace_Flag = false;
bm->Begin_RemoveWrites = false;
bm->start_abstracting = false;
bm->TermsAlreadySeenMap_Clear();
do
{
inputToSAT = simplified_solved_InputToSAT;
if(bm->UserFlags.optimize_flag)
{
bm->GetRunTimes()->start(RunTimes::CreateSubstitutionMap);
simplified_solved_InputToSAT =
arrayTransformer->
CreateSubstitutionMap(simplified_solved_InputToSAT);
bm->GetRunTimes()->stop(RunTimes::CreateSubstitutionMap);
//printf("##################################################\n");
bm->ASTNodeStats("after pure substitution: ",
simplified_solved_InputToSAT);
simplified_solved_InputToSAT =
simp->SimplifyFormula_TopLevel(simplified_solved_InputToSAT,
false);
bm->ASTNodeStats("after simplification: ",
simplified_solved_InputToSAT);
}
if(bm->UserFlags.wordlevel_solve_flag)
{
simplified_solved_InputToSAT =
bvsolver->TopLevelBVSolve(simplified_solved_InputToSAT);
bm->ASTNodeStats("after solving: ", simplified_solved_InputToSAT);
}
}
while (inputToSAT != simplified_solved_InputToSAT);
bm->ASTNodeStats("Before SimplifyWrites_Inplace begins: ",
simplified_solved_InputToSAT);
bm->SimplifyWrites_InPlace_Flag = true;
bm->Begin_RemoveWrites = false;
bm->start_abstracting = false;
bm->TermsAlreadySeenMap_Clear();
do
{
inputToSAT = simplified_solved_InputToSAT;
if(bm->UserFlags.optimize_flag)
{
bm->GetRunTimes()->start(RunTimes::CreateSubstitutionMap);
simplified_solved_InputToSAT =
arrayTransformer->
CreateSubstitutionMap(simplified_solved_InputToSAT);
bm->GetRunTimes()->stop(RunTimes::CreateSubstitutionMap);
bm->ASTNodeStats("after pure substitution: ",
simplified_solved_InputToSAT);
simplified_solved_InputToSAT =
simp->SimplifyFormula_TopLevel(simplified_solved_InputToSAT,
false);
bm->ASTNodeStats("after simplification: ",
simplified_solved_InputToSAT);
}
if(bm->UserFlags.wordlevel_solve_flag)
{
simplified_solved_InputToSAT =
bvsolver->TopLevelBVSolve(simplified_solved_InputToSAT);
bm->ASTNodeStats("after solving: ", simplified_solved_InputToSAT);
}
} while (inputToSAT != simplified_solved_InputToSAT);
bm->ASTNodeStats("After SimplifyWrites_Inplace: ",
simplified_solved_InputToSAT);
bm->start_abstracting =
(bm->UserFlags.arraywrite_refinement_flag) ? true : false;
bm->SimplifyWrites_InPlace_Flag = false;
bm->Begin_RemoveWrites = (bm->start_abstracting) ? false : true;
if (bm->start_abstracting)
{
bm->ASTNodeStats("before abstraction round begins: ",
simplified_solved_InputToSAT);
}
bm->TermsAlreadySeenMap_Clear();
if (bm->start_abstracting)
{
bm->ASTNodeStats("After abstraction: ", simplified_solved_InputToSAT);
}
bm->start_abstracting = false;
bm->SimplifyWrites_InPlace_Flag = false;
bm->Begin_RemoveWrites = false;
simplified_solved_InputToSAT =
arrayTransformer->TransformFormula_TopLevel(simplified_solved_InputToSAT);
bm->ASTNodeStats("after transformation: ", simplified_solved_InputToSAT);
bm->TermsAlreadySeenMap_Clear();
SOLVER_RETURN_TYPE res;
//solver instantiated here
#ifdef CORE
MINISAT::Solver newS;
#endif
#ifdef CRYPTOMINISAT
MINISAT::Solver newS;
#endif
#ifdef SIMP
MINISAT::SimpSolver newS;
#endif
#ifdef UNSOUND
MINISAT::UnsoundSimpSolver newS;
#endif
if (bm->UserFlags.arrayread_refinement_flag)
{
bm->counterexample_checking_during_refinement = true;
}
res =
Ctr_Example->CallSAT_ResultCheck(newS,
simplified_solved_InputToSAT,
orig_input);
if (SOLVER_UNDECIDED != res)
{
CountersAndStats("print_func_stats", bm);
return res;
}
// res = SATBased_AllFiniteLoops_Refinement(newS, orig_input);
// if (SOLVER_UNDECIDED != res)
// {
// CountersAndStats("print_func_stats");
// return res;
// }
res =
Ctr_Example->SATBased_ArrayReadRefinement(newS,
simplified_solved_InputToSAT,
orig_input);
if (SOLVER_UNDECIDED != res)
{
CountersAndStats("print_func_stats", bm);
return res;
}
res =
Ctr_Example->SATBased_ArrayWriteRefinement(newS, orig_input);
if (SOLVER_UNDECIDED != res)
{
CountersAndStats("print_func_stats", bm);
return res;
}
res =
Ctr_Example->SATBased_ArrayReadRefinement(newS,
simplified_solved_InputToSAT,
orig_input);
if (SOLVER_UNDECIDED != res)
{
CountersAndStats("print_func_stats", bm);
return res;
}
FatalError("TopLevelSTPAux: reached the end without proper conclusion:"
"either a divide by zero in the input or a bug in STP");
//bogus return to make the compiler shut up
return SOLVER_ERROR;
} //End of TopLevelSTPAux
// void STP::ClearAllTables(void)
// {
// // //Clear STPManager caches
// // //Clear ArrayTransformer caches
// // //Clear Simplifier caches
// // //Clear BVSolver caches
// // //Clear AbsRefine_CounterExample caches
// // //clear all tables before calling toplevelsat
// // //_ASTNode_to_SATVar.clear();
// // //_SATVar_to_AST.clear();
// // // for (ASTtoBitvectorMap::iterator it = _ASTNode_to_Bitvector.begin(),
// // // itend = _ASTNode_to_Bitvector.end(); it != itend; it++)
// // // {
// // // (it->second)->clear();
// // // delete (it->second);
// // // }
// // // _ASTNode_to_Bitvector.clear();
// // NodeLetVarMap.clear();
// // NodeLetVarMap1.clear();
// // PLPrintNodeSet.clear();
// // AlreadyPrintedSet.clear();
// // //ReferenceCount->clear();
// // //_arrayread_ite.clear();
// // //_introduced_symbols.clear();
// // //CounterExampleMap.clear();
// // //ComputeFormulaMap.clear();
// // StatInfoSet.clear();
// // _asserts.clear();
// // // for (ASTNodeToVecMap::iterator iset =
// // // _arrayname_readindices.begin(), iset_end =
// // // _arrayname_readindices.end(); iset != iset_end; iset++) {
// // // iset->second.clear(); }
// // // _arrayname_readindices.clear();
// // _interior_unique_table.clear();
// // _symbol_unique_table->clear();
// // _bvconst_unique_table.clear();
// }
// void STP::ClearAllCaches(void)
// {
// // //clear all tables before calling toplevelsat
// // //_ASTNode_to_SATVar.clear();
// // //_SATVar_to_AST.clear();
// // // for (ASTtoBitvectorMap::iterator it = _ASTNode_to_Bitvector.begin(),
// // // itend = _ASTNode_to_Bitvector.end(); it != itend; it++)
// // // {
// // // (it->second)->clear();
// // // delete (it->second);
// // // }
// // // _ASTNode_to_Bitvector.clear();
// // NodeLetVarMap.clear();
// // NodeLetVarMap1.clear();
// // PLPrintNodeSet.clear();
// // AlreadyPrintedSet.clear();
// // // SimplifyMap->clear();
// // // SimplifyNegMap->clear();
// // // ReferenceCount->clear();
// // // SolverMap.clear();
// // //AlwaysTrueFormMap.clear();
// // //_arrayread_ite.clear();
// // //_arrayread_symbol.clear();
// // //_introduced_symbols.clear();
// // //CounterExampleMap.clear();
// // //ComputeFormulaMap.clear();
// // StatInfoSet.clear();
// // // for (ASTNodeToVecMap::iterator iset = _arrayname_readindices.begin(), iset_end = _arrayname_readindices.end(); iset != iset_end; iset++)
// // // {
// // // iset->second.clear();
// // // }
// // // _arrayname_readindices.clear();
// // //_interior_unique_table.clear();
// // //_symbol_unique_table.clear();
// // //_bvconst_unique_table.clear();
// }
}; //end of namespace
<commit_msg>removed some deadcode relating to previous versions of cleartable and clearcache functions<commit_after>// -*- c++ -*-
/********************************************************************
* AUTHORS: Vijay Ganesh
*
* BEGIN DATE: November, 2005
*
* LICENSE: Please view LICENSE file in the home dir of this Program
********************************************************************/
#include "STP.h"
namespace BEEV {
//Acceps a query, calls the SAT solver and generates Valid/InValid.
//if returned 0 then input is INVALID if returned 1 then input is
//VALID if returned 2 then UNDECIDED
SOLVER_RETURN_TYPE STP::TopLevelSTPAux(const ASTNode& inputasserts_and_query)
{
ASTNode inputToSAT = inputasserts_and_query;
ASTNode orig_input = inputToSAT;
bm->ASTNodeStats("input asserts and query: ", inputToSAT);
ASTNode simplified_solved_InputToSAT = inputToSAT;
//round of substitution, solving, and simplification. ensures that
//DAG is minimized as much as possibly, and ideally should
//garuntee that all liketerms in BVPLUSes have been combined.
bm->SimplifyWrites_InPlace_Flag = false;
bm->Begin_RemoveWrites = false;
bm->start_abstracting = false;
bm->TermsAlreadySeenMap_Clear();
do
{
inputToSAT = simplified_solved_InputToSAT;
if(bm->UserFlags.optimize_flag)
{
bm->GetRunTimes()->start(RunTimes::CreateSubstitutionMap);
simplified_solved_InputToSAT =
arrayTransformer->
CreateSubstitutionMap(simplified_solved_InputToSAT);
bm->GetRunTimes()->stop(RunTimes::CreateSubstitutionMap);
//printf("##################################################\n");
bm->ASTNodeStats("after pure substitution: ",
simplified_solved_InputToSAT);
simplified_solved_InputToSAT =
simp->SimplifyFormula_TopLevel(simplified_solved_InputToSAT,
false);
bm->ASTNodeStats("after simplification: ",
simplified_solved_InputToSAT);
}
if(bm->UserFlags.wordlevel_solve_flag)
{
simplified_solved_InputToSAT =
bvsolver->TopLevelBVSolve(simplified_solved_InputToSAT);
bm->ASTNodeStats("after solving: ", simplified_solved_InputToSAT);
}
}
while (inputToSAT != simplified_solved_InputToSAT);
bm->ASTNodeStats("Before SimplifyWrites_Inplace begins: ",
simplified_solved_InputToSAT);
bm->SimplifyWrites_InPlace_Flag = true;
bm->Begin_RemoveWrites = false;
bm->start_abstracting = false;
bm->TermsAlreadySeenMap_Clear();
do
{
inputToSAT = simplified_solved_InputToSAT;
if(bm->UserFlags.optimize_flag)
{
bm->GetRunTimes()->start(RunTimes::CreateSubstitutionMap);
simplified_solved_InputToSAT =
arrayTransformer->
CreateSubstitutionMap(simplified_solved_InputToSAT);
bm->GetRunTimes()->stop(RunTimes::CreateSubstitutionMap);
bm->ASTNodeStats("after pure substitution: ",
simplified_solved_InputToSAT);
simplified_solved_InputToSAT =
simp->SimplifyFormula_TopLevel(simplified_solved_InputToSAT,
false);
bm->ASTNodeStats("after simplification: ",
simplified_solved_InputToSAT);
}
if(bm->UserFlags.wordlevel_solve_flag)
{
simplified_solved_InputToSAT =
bvsolver->TopLevelBVSolve(simplified_solved_InputToSAT);
bm->ASTNodeStats("after solving: ", simplified_solved_InputToSAT);
}
} while (inputToSAT != simplified_solved_InputToSAT);
bm->ASTNodeStats("After SimplifyWrites_Inplace: ",
simplified_solved_InputToSAT);
bm->start_abstracting =
(bm->UserFlags.arraywrite_refinement_flag) ? true : false;
bm->SimplifyWrites_InPlace_Flag = false;
bm->Begin_RemoveWrites = (bm->start_abstracting) ? false : true;
if (bm->start_abstracting)
{
bm->ASTNodeStats("before abstraction round begins: ",
simplified_solved_InputToSAT);
}
bm->TermsAlreadySeenMap_Clear();
if (bm->start_abstracting)
{
bm->ASTNodeStats("After abstraction: ", simplified_solved_InputToSAT);
}
bm->start_abstracting = false;
bm->SimplifyWrites_InPlace_Flag = false;
bm->Begin_RemoveWrites = false;
simplified_solved_InputToSAT =
arrayTransformer->TransformFormula_TopLevel(simplified_solved_InputToSAT);
bm->ASTNodeStats("after transformation: ", simplified_solved_InputToSAT);
bm->TermsAlreadySeenMap_Clear();
SOLVER_RETURN_TYPE res;
//solver instantiated here
#ifdef CORE
MINISAT::Solver newS;
#endif
#ifdef CRYPTOMINISAT
MINISAT::Solver newS;
#endif
#ifdef SIMP
MINISAT::SimpSolver newS;
#endif
#ifdef UNSOUND
MINISAT::UnsoundSimpSolver newS;
#endif
if (bm->UserFlags.arrayread_refinement_flag)
{
bm->counterexample_checking_during_refinement = true;
}
res =
Ctr_Example->CallSAT_ResultCheck(newS,
simplified_solved_InputToSAT,
orig_input);
if (SOLVER_UNDECIDED != res)
{
CountersAndStats("print_func_stats", bm);
return res;
}
// res = SATBased_AllFiniteLoops_Refinement(newS, orig_input);
// if (SOLVER_UNDECIDED != res)
// {
// CountersAndStats("print_func_stats");
// return res;
// }
res =
Ctr_Example->SATBased_ArrayReadRefinement(newS,
simplified_solved_InputToSAT,
orig_input);
if (SOLVER_UNDECIDED != res)
{
CountersAndStats("print_func_stats", bm);
return res;
}
res =
Ctr_Example->SATBased_ArrayWriteRefinement(newS, orig_input);
if (SOLVER_UNDECIDED != res)
{
CountersAndStats("print_func_stats", bm);
return res;
}
res =
Ctr_Example->SATBased_ArrayReadRefinement(newS,
simplified_solved_InputToSAT,
orig_input);
if (SOLVER_UNDECIDED != res)
{
CountersAndStats("print_func_stats", bm);
return res;
}
FatalError("TopLevelSTPAux: reached the end without proper conclusion:"
"either a divide by zero in the input or a bug in STP");
//bogus return to make the compiler shut up
return SOLVER_ERROR;
} //End of TopLevelSTPAux
}; //end of namespace
<|endoftext|> |
<commit_before>#include "common.h"
#include "watcher.h"
#include <stdlib.h>
#include <stdio.h>
#include <Psapi.h>
#pragma comment (lib, "psapi.lib")
namespace NodeJudger {
#define EXCEPTION_WX86_BREAKPOINT 0x4000001F
#define MAX_TIME_LIMIT_DELAY 200
const bool __WATCHER_PRINT_DEBUG = (GetEnvironmentVar("JUDGE_DEBUG") == "true");
inline __int64 GetRunTime_(HANDLE process)
{
_FILETIME create_time, exit_time, kernel_time, user_time;
__int64* ut;
if(GetProcessTimes(process, &create_time, &exit_time, &kernel_time, &user_time))
{
ut = reinterpret_cast<__int64*>(&user_time);
return (__int64)((*ut) / 10000);
}
return -1;
}
__int64 GetRunMemo_(HANDLE process)
{
PROCESS_MEMORY_COUNTERS memo_counter;
memo_counter.cb = sizeof(PROCESS_MEMORY_COUNTERS);
if(GetProcessMemoryInfo(process, &memo_counter, sizeof(PROCESS_MEMORY_COUNTERS)))
{
return memo_counter.PagefileUsage / 1024;
}
return -1;
}
void ExitAndSetError(HANDLE process, CodeState& code_state, StateEnum state_enum, const char* code = NULL)
{
DWORD process_id = GetProcessId(process);
if(process_id) DebugActiveProcessStop(process_id);
// refer to https://msdn.microsoft.com/en-us/library/windows/desktop/ms686714(v=vs.85).aspx
//
// TerminateProcess is asynchronous; it initiates termination and returns immediately. If you
// need to be sure the process has terminated, call the WaitForSingleObject function with a
// handle to the process.
TerminateProcess(process, 4);
WaitForSingleObject(process, 2000);
code_state.state = state_enum;
if(code && strlen(code) != 0)
{
strcpy(code_state.error_code, code);
}
}
void SetRuntimeErrorCode_(CodeState& code_state, DWORD code)
{
switch(code)
{
case EXCEPTION_ACCESS_VIOLATION:
{
strcpy(code_state.error_code, "ACCESS_VIOLATION");
break;
}
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
{
strcpy(code_state.error_code, "ARRAY_BOUNDS_EXCEEDED");
break;
}
case EXCEPTION_FLT_DENORMAL_OPERAND:
{
strcpy(code_state.error_code, "FLOAT_DENORMAL_OPERAND");
break;
}
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
{
strcpy(code_state.error_code, "FLOAT_DIVIDE_BY_ZERO");
break;
}
case EXCEPTION_FLT_OVERFLOW:
{
strcpy(code_state.error_code, "FLOAT_OVERFLOW");
break;
}
case EXCEPTION_FLT_UNDERFLOW:
{
strcpy(code_state.error_code, "FLOAT_UNDERFLOW");
break;
}
case EXCEPTION_INT_DIVIDE_BY_ZERO:
{
strcpy(code_state.error_code, "INTEGER_DIVIDE_BY_ZERO");
break;
}
case EXCEPTION_INT_OVERFLOW:
{
strcpy(code_state.error_code, "INTEGER_OVERFLOW");
break;
}
case EXCEPTION_STACK_OVERFLOW:
{
strcpy(code_state.error_code, "STACK_OVERFLOW");
break;
}
default:
{
char temp[32];
sprintf(temp, "OTHER_ERRORS_0x%.8X", code);
strcpy(code_state.error_code, temp);
break;
}
}
}
bool WatchProcess(const HANDLE process,
const __int64 time_limit,
const __size memo_limit,
CodeState& code_state)
{
__int64 run_time = 0;
__size run_memo = 0;
// refer to https://msdn.microsoft.com/en-us/library/windows/desktop/ms679308(v=vs.85).aspx
//
// Describes a debugging event.
//
// typedef struct _DEBUG_EVENT {
// DWORD dwDebugEventCode;
// DWORD dwProcessId;
// DWORD dwThreadId;
// union {
// EXCEPTION_DEBUG_INFO Exception;
// CREATE_THREAD_DEBUG_INFO CreateThread;
// CREATE_PROCESS_DEBUG_INFO CreateProcessInfo;
// EXIT_THREAD_DEBUG_INFO ExitThread;
// EXIT_PROCESS_DEBUG_INFO ExitProcess;
// LOAD_DLL_DEBUG_INFO LoadDll;
// UNLOAD_DLL_DEBUG_INFO UnloadDll;
// OUTPUT_DEBUG_STRING_INFO DebugString;
// RIP_INFO RipInfo;
// } u;
// } DEBUG_EVENT, *LPDEBUG_EVENT;
DEBUG_EVENT dbe;
while(true)
{
// refer to https://msdn.microsoft.com/en-us/library/windows/desktop/ms681423(v=vs.85).aspx
//
// Waits for a debugging event to occur in a process being debugged.
//
// If the function succeeds, the return value is nonzero.
// If the function fails, the return value is zero.To get extended error information, call GetLastError.
BOOL flag = WaitForDebugEvent(&dbe, (DWORD)time_limit + MAX_TIME_LIMIT_DELAY - run_time);
if(!flag)
{
std::string error = "Cannot wait for debug event: " + GetLastErrorAsString();
code_state.exe_time = time_limit + MAX_TIME_LIMIT_DELAY;
code_state.exe_memory = GetRunMemo_(process);
ExitAndSetError(process, code_state, TIME_LIMIT_EXCEEDED_2, error.c_str());
return false;
}
// refer to http://www.debuginfo.com/examples/src/DebugEvents.cpp
//
// close some handles inside dbe
switch(dbe.dwDebugEventCode)
{
case CREATE_PROCESS_DEBUG_EVENT:
if(__WATCHER_PRINT_DEBUG)
{
printf("Event: Process creation\n");
printf(" CREATE_PROCESS_DEBUG_INFO members:\n");
printf(" hFile: %08p\n", dbe.u.CreateProcessInfo.hFile);
printf(" hProcess: %08p\n", dbe.u.CreateProcessInfo.hProcess);
printf(" hThread %08p\n", dbe.u.CreateProcessInfo.hThread);
}
// With this event, the debugger receives the following handles:
// CREATE_PROCESS_DEBUG_INFO.hProcess - debuggee process handle
// CREATE_PROCESS_DEBUG_INFO.hThread - handle to the initial thread of the debuggee process
// CREATE_PROCESS_DEBUG_INFO.hFile - handle to the executable file that was
// used to create the debuggee process (.EXE file)
//
// hProcess and hThread handles will be closed by the operating system
// when the debugger calls ContinueDebugEvent after receiving
// EXIT_PROCESS_DEBUG_EVENT for the given process
//
// hFile handle should be closed by the debugger, when the handle
// is no longer needed
SAFE_CLOSE_HANDLE(dbe.u.CreateProcessInfo.hFile);
break;
case CREATE_THREAD_DEBUG_EVENT:
// With this event, the debugger receives the following handle:
// CREATE_THREAD_DEBUG_INFO.hThread - handle to the thread that has been created
//
// This handle will be closed by the operating system
// when the debugger calls ContinueDebugEvent after receiving
// EXIT_THREAD_DEBUG_EVENT for the given thread
break;
case LOAD_DLL_DEBUG_EVENT:
{
std::string dll_name = GetDLLNameFromDebug(dbe.u.LoadDll);
if(__WATCHER_PRINT_DEBUG)
{
printf("Event: DLL loaded\n");
printf(" LOAD_DLL_DEBUG_INFO members:\n");
printf(" hFile: %08p\n", dbe.u.LoadDll.hFile);
printf(" lpBaseOfDll: %08p\n", dbe.u.LoadDll.lpBaseOfDll);
printf(" DLLName: %s\n", dll_name.c_str());
}
// With this event, the debugger receives the following handle:
// LOAD_DLL_DEBUG_INFO.hFile - handle to the DLL file
//
// This handle should be closed by the debugger, when the handle
// is no longer needed
SAFE_CLOSE_HANDLE(dbe.u.LoadDll.hFile);
// And what's more
// users are not allowed to load DLL
if(dll_name.find("\\ntdll.dll") == std::string::npos &&
dll_name.find("\\kernel32.dll") == std::string::npos &&
dll_name.find("\\KernelBase.dll") == std::string::npos &&
dll_name.find("\\msvcrt.dll") == std::string::npos &&
dll_name.find("\\wow64.dll") == std::string::npos &&
dll_name.find("\\wow64win.dll") == std::string::npos &&
dll_name.find("\\wow64cpu.dll") == std::string::npos &&
dll_name.find("\\user32.dll") == std::string::npos)
{
std::string error = "Code is up to load DLL.";
code_state.exe_time = -1;
code_state.exe_memory = -1;
ExitAndSetError(process, code_state, DANGEROUS_CODE, error.c_str());
return false;
}
}
default: break;
}
// get the run time
run_time = GetRunTime_(process);
if(-1 == run_time)
{
std::string error = "Cannot get running time: " + GetLastErrorAsString();
code_state.exe_time = -1;
code_state.exe_memory = GetRunMemo_(process);
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
ExitAndSetError(process, code_state, SYSTEM_ERROR, error.c_str());
return false;
}
// get the run memory
run_memo = GetRunMemo_(process);
if(-1 == run_memo)
{
std::string error = "Cannot get occupied memory: " + GetLastErrorAsString();
code_state.exe_time = run_time;
code_state.exe_memory = -1;
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
ExitAndSetError(process, code_state, SYSTEM_ERROR, error.c_str());
return false;
}
code_state.exe_time = run_time;
code_state.exe_memory = run_memo;
if(run_time > time_limit)
{
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
ExitAndSetError(process, code_state, TIME_LIMIT_EXCEEDED_1);
return false;
}
if(run_memo > memo_limit)
{
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
ExitAndSetError(process, code_state, MEMORY_LIMIT_EXCEEDED);
return false;
}
// do some reaction via each DEBUG_EVENT
switch(dbe.dwDebugEventCode)
{
case EXIT_PROCESS_DEBUG_EVENT:
code_state.state = FINISHED;
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
return true;
case EXCEPTION_DEBUG_EVENT:
if(dbe.u.Exception.ExceptionRecord.ExceptionCode != EXCEPTION_BREAKPOINT &&
dbe.u.Exception.ExceptionRecord.ExceptionCode != EXCEPTION_WX86_BREAKPOINT)
{
SetRuntimeErrorCode_(code_state, dbe.u.Exception.ExceptionRecord.ExceptionCode);
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_EXCEPTION_NOT_HANDLED);
ExitAndSetError(process, code_state, RUNTIME_ERROR);
return false;
}
break;
default: break;
}
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
code_state.state = CONTINUE;
}
}
};<commit_msg>feat: use max memory<commit_after>#include "common.h"
#include "watcher.h"
#include <stdlib.h>
#include <stdio.h>
#include <Psapi.h>
#pragma comment (lib, "psapi.lib")
namespace NodeJudger {
#define EXCEPTION_WX86_BREAKPOINT 0x4000001F
#define MAX_TIME_LIMIT_DELAY 200
const bool __WATCHER_PRINT_DEBUG = (GetEnvironmentVar("JUDGE_DEBUG") == "true");
#define MAX(a, b) ((a) > (b) ? (a) : (b)
inline __int64 GetRunTime_(HANDLE process)
{
_FILETIME create_time, exit_time, kernel_time, user_time;
__int64* ut;
if(GetProcessTimes(process, &create_time, &exit_time, &kernel_time, &user_time))
{
ut = reinterpret_cast<__int64*>(&user_time);
return (__int64)((*ut) / 10000);
}
return -1;
}
__int64 GetRunMemo_(HANDLE process)
{
PROCESS_MEMORY_COUNTERS memo_counter;
memo_counter.cb = sizeof(PROCESS_MEMORY_COUNTERS);
if(GetProcessMemoryInfo(process, &memo_counter, sizeof(PROCESS_MEMORY_COUNTERS)))
{
return memo_counter.PagefileUsage / 1024;
}
return -1;
}
void ExitAndSetError(HANDLE process, CodeState& code_state, StateEnum state_enum, const char* code = NULL)
{
DWORD process_id = GetProcessId(process);
if(process_id) DebugActiveProcessStop(process_id);
// refer to https://msdn.microsoft.com/en-us/library/windows/desktop/ms686714(v=vs.85).aspx
//
// TerminateProcess is asynchronous; it initiates termination and returns immediately. If you
// need to be sure the process has terminated, call the WaitForSingleObject function with a
// handle to the process.
TerminateProcess(process, 4);
WaitForSingleObject(process, 2000);
code_state.state = state_enum;
if(code && strlen(code) != 0)
{
strcpy(code_state.error_code, code);
}
}
void SetRuntimeErrorCode_(CodeState& code_state, DWORD code)
{
switch(code)
{
case EXCEPTION_ACCESS_VIOLATION:
{
strcpy(code_state.error_code, "ACCESS_VIOLATION");
break;
}
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
{
strcpy(code_state.error_code, "ARRAY_BOUNDS_EXCEEDED");
break;
}
case EXCEPTION_FLT_DENORMAL_OPERAND:
{
strcpy(code_state.error_code, "FLOAT_DENORMAL_OPERAND");
break;
}
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
{
strcpy(code_state.error_code, "FLOAT_DIVIDE_BY_ZERO");
break;
}
case EXCEPTION_FLT_OVERFLOW:
{
strcpy(code_state.error_code, "FLOAT_OVERFLOW");
break;
}
case EXCEPTION_FLT_UNDERFLOW:
{
strcpy(code_state.error_code, "FLOAT_UNDERFLOW");
break;
}
case EXCEPTION_INT_DIVIDE_BY_ZERO:
{
strcpy(code_state.error_code, "INTEGER_DIVIDE_BY_ZERO");
break;
}
case EXCEPTION_INT_OVERFLOW:
{
strcpy(code_state.error_code, "INTEGER_OVERFLOW");
break;
}
case EXCEPTION_STACK_OVERFLOW:
{
strcpy(code_state.error_code, "STACK_OVERFLOW");
break;
}
default:
{
char temp[32];
sprintf(temp, "OTHER_ERRORS_0x%.8X", code);
strcpy(code_state.error_code, temp);
break;
}
}
}
bool WatchProcess(const HANDLE process,
const __int64 time_limit,
const __size memo_limit,
CodeState& code_state)
{
__int64 run_time = 0;
__size run_memo = 0;
// refer to https://msdn.microsoft.com/en-us/library/windows/desktop/ms679308(v=vs.85).aspx
//
// Describes a debugging event.
//
// typedef struct _DEBUG_EVENT {
// DWORD dwDebugEventCode;
// DWORD dwProcessId;
// DWORD dwThreadId;
// union {
// EXCEPTION_DEBUG_INFO Exception;
// CREATE_THREAD_DEBUG_INFO CreateThread;
// CREATE_PROCESS_DEBUG_INFO CreateProcessInfo;
// EXIT_THREAD_DEBUG_INFO ExitThread;
// EXIT_PROCESS_DEBUG_INFO ExitProcess;
// LOAD_DLL_DEBUG_INFO LoadDll;
// UNLOAD_DLL_DEBUG_INFO UnloadDll;
// OUTPUT_DEBUG_STRING_INFO DebugString;
// RIP_INFO RipInfo;
// } u;
// } DEBUG_EVENT, *LPDEBUG_EVENT;
DEBUG_EVENT dbe;
while(true)
{
// refer to https://msdn.microsoft.com/en-us/library/windows/desktop/ms681423(v=vs.85).aspx
//
// Waits for a debugging event to occur in a process being debugged.
//
// If the function succeeds, the return value is nonzero.
// If the function fails, the return value is zero.To get extended error information, call GetLastError.
BOOL flag = WaitForDebugEvent(&dbe, (DWORD)time_limit + MAX_TIME_LIMIT_DELAY - run_time);
if(!flag)
{
std::string error = "Cannot wait for debug event: " + GetLastErrorAsString();
code_state.exe_time = time_limit + MAX_TIME_LIMIT_DELAY;
code_state.exe_memory = MAX(GetRunMemo_(process), code_state.exe_memory);
ExitAndSetError(process, code_state, TIME_LIMIT_EXCEEDED_2, error.c_str());
return false;
}
// refer to http://www.debuginfo.com/examples/src/DebugEvents.cpp
//
// close some handles inside dbe
switch(dbe.dwDebugEventCode)
{
case CREATE_PROCESS_DEBUG_EVENT:
if(__WATCHER_PRINT_DEBUG)
{
printf("Event: Process creation\n");
printf(" CREATE_PROCESS_DEBUG_INFO members:\n");
printf(" hFile: %08p\n", dbe.u.CreateProcessInfo.hFile);
printf(" hProcess: %08p\n", dbe.u.CreateProcessInfo.hProcess);
printf(" hThread %08p\n", dbe.u.CreateProcessInfo.hThread);
}
// With this event, the debugger receives the following handles:
// CREATE_PROCESS_DEBUG_INFO.hProcess - debuggee process handle
// CREATE_PROCESS_DEBUG_INFO.hThread - handle to the initial thread of the debuggee process
// CREATE_PROCESS_DEBUG_INFO.hFile - handle to the executable file that was
// used to create the debuggee process (.EXE file)
//
// hProcess and hThread handles will be closed by the operating system
// when the debugger calls ContinueDebugEvent after receiving
// EXIT_PROCESS_DEBUG_EVENT for the given process
//
// hFile handle should be closed by the debugger, when the handle
// is no longer needed
SAFE_CLOSE_HANDLE(dbe.u.CreateProcessInfo.hFile);
break;
case CREATE_THREAD_DEBUG_EVENT:
// With this event, the debugger receives the following handle:
// CREATE_THREAD_DEBUG_INFO.hThread - handle to the thread that has been created
//
// This handle will be closed by the operating system
// when the debugger calls ContinueDebugEvent after receiving
// EXIT_THREAD_DEBUG_EVENT for the given thread
break;
case LOAD_DLL_DEBUG_EVENT:
{
std::string dll_name = GetDLLNameFromDebug(dbe.u.LoadDll);
if(__WATCHER_PRINT_DEBUG)
{
printf("Event: DLL loaded\n");
printf(" LOAD_DLL_DEBUG_INFO members:\n");
printf(" hFile: %08p\n", dbe.u.LoadDll.hFile);
printf(" lpBaseOfDll: %08p\n", dbe.u.LoadDll.lpBaseOfDll);
printf(" DLLName: %s\n", dll_name.c_str());
}
// With this event, the debugger receives the following handle:
// LOAD_DLL_DEBUG_INFO.hFile - handle to the DLL file
//
// This handle should be closed by the debugger, when the handle
// is no longer needed
SAFE_CLOSE_HANDLE(dbe.u.LoadDll.hFile);
// And what's more
// users are not allowed to load DLL
if(dll_name.find("\\ntdll.dll") == std::string::npos &&
dll_name.find("\\kernel32.dll") == std::string::npos &&
dll_name.find("\\KernelBase.dll") == std::string::npos &&
dll_name.find("\\msvcrt.dll") == std::string::npos &&
dll_name.find("\\wow64.dll") == std::string::npos &&
dll_name.find("\\wow64win.dll") == std::string::npos &&
dll_name.find("\\wow64cpu.dll") == std::string::npos &&
dll_name.find("\\user32.dll") == std::string::npos)
{
std::string error = "Code is up to load DLL.";
code_state.exe_time = 0;
code_state.exe_memory = 0;
ExitAndSetError(process, code_state, DANGEROUS_CODE, error.c_str());
return false;
}
}
default: break;
}
// get the run time
run_time = GetRunTime_(process);
if(-1 == run_time)
{
std::string error = "Cannot get running time: " + GetLastErrorAsString();
code_state.exe_time = 0;
code_state.exe_memory = MAX(GetRunMemo_(process), code_state.exe_memory);
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
ExitAndSetError(process, code_state, SYSTEM_ERROR, error.c_str());
return false;
}
// get the run memory
run_memo = GetRunMemo_(process);
if(-1 == run_memo)
{
std::string error = "Cannot get occupied memory: " + GetLastErrorAsString();
code_state.exe_time = run_time;
code_state.exe_memory = 0;
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
ExitAndSetError(process, code_state, SYSTEM_ERROR, error.c_str());
return false;
}
code_state.exe_time = run_time;
code_state.exe_memory = MAX(code_state.exe_memory, run_memo);
if(run_time > time_limit)
{
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
ExitAndSetError(process, code_state, TIME_LIMIT_EXCEEDED_1);
return false;
}
if(run_memo > memo_limit)
{
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
ExitAndSetError(process, code_state, MEMORY_LIMIT_EXCEEDED);
return false;
}
// do some reaction via each DEBUG_EVENT
switch(dbe.dwDebugEventCode)
{
case EXIT_PROCESS_DEBUG_EVENT:
code_state.state = FINISHED;
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
return true;
case EXCEPTION_DEBUG_EVENT:
if(dbe.u.Exception.ExceptionRecord.ExceptionCode != EXCEPTION_BREAKPOINT &&
dbe.u.Exception.ExceptionRecord.ExceptionCode != EXCEPTION_WX86_BREAKPOINT)
{
SetRuntimeErrorCode_(code_state, dbe.u.Exception.ExceptionRecord.ExceptionCode);
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_EXCEPTION_NOT_HANDLED);
ExitAndSetError(process, code_state, RUNTIME_ERROR);
return false;
}
break;
default: break;
}
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
code_state.state = CONTINUE;
}
}
};<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011, Ben Noordhuis <[email protected]>
*
* 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 <stdlib.h>
#include "v8.h"
#include "node.h"
using namespace v8;
using namespace node;
namespace {
typedef struct proxy_container {
Persistent<Object> target;
Persistent<Object> proxy;
Persistent<Array> callbacks;
} proxy_container;
Persistent<ObjectTemplate> proxyClass;
bool IsDead(Handle<Object> proxy) {
assert(proxy->InternalFieldCount() == 1);
proxy_container *cont = reinterpret_cast<proxy_container*>(
proxy->GetPointerFromInternalField(0));
assert(cont != NULL);
return cont->target.IsEmpty();
}
Handle<Object> Unwrap(Handle<Object> proxy) {
assert(!IsDead(proxy));
proxy_container *cont = reinterpret_cast<proxy_container*>(
proxy->GetPointerFromInternalField(0));
assert(cont != NULL);
return cont->target;
}
Handle<Array> GetCallbacks(Handle<Object> proxy) {
proxy_container *cont = reinterpret_cast<proxy_container*>(
proxy->GetPointerFromInternalField(0));
assert(cont != NULL);
return cont->callbacks;
}
#define UNWRAP \
HandleScope scope; \
Handle<Object> obj; \
const bool dead = IsDead(info.This()); \
if (!dead) obj = Unwrap(info.This()); \
Handle<Value> WeakNamedPropertyGetter(Local<String> property,
const AccessorInfo& info) {
UNWRAP
return dead ? Local<Value>() : obj->Get(property);
}
Handle<Value> WeakNamedPropertySetter(Local<String> property,
Local<Value> value,
const AccessorInfo& info) {
UNWRAP
if (!dead) obj->Set(property, value);
return value;
}
Handle<Integer> WeakNamedPropertyQuery(Local<String> property,
const AccessorInfo& info) {
return HandleScope().Close(Integer::New(None));
}
Handle<Boolean> WeakNamedPropertyDeleter(Local<String> property,
const AccessorInfo& info) {
UNWRAP
return Boolean::New(!dead && obj->Delete(property));
}
Handle<Value> WeakIndexedPropertyGetter(uint32_t index,
const AccessorInfo& info) {
UNWRAP
return dead ? Local<Value>() : obj->Get(index);
}
Handle<Value> WeakIndexedPropertySetter(uint32_t index,
Local<Value> value,
const AccessorInfo& info) {
UNWRAP
if (!dead) obj->Set(index, value);
return value;
}
Handle<Integer> WeakIndexedPropertyQuery(uint32_t index,
const AccessorInfo& info) {
return HandleScope().Close(Integer::New(None));
}
Handle<Boolean> WeakIndexedPropertyDeleter(uint32_t index,
const AccessorInfo& info) {
UNWRAP
return Boolean::New(!dead && obj->Delete(index));
}
Handle<Array> WeakPropertyEnumerator(const AccessorInfo& info) {
UNWRAP
return HandleScope().Close(dead ? Array::New(0) : obj->GetPropertyNames());
}
void AddCallback(Handle<Object> proxy, Handle<Function> callback) {
Handle<Array> callbacks = GetCallbacks(proxy);
callbacks->Set(Integer::New(callbacks->Length()), callback);
}
void TargetCallback(Persistent<Value> target, void* arg) {
HandleScope scope;
assert(target.IsNearDeath());
proxy_container *cont = reinterpret_cast<proxy_container*>(arg);
// invoke any listening callbacks
uint32_t len = cont->callbacks->Length();
Handle<Value> argv[1];
argv[0] = target;
for (uint32_t i=0; i<len; i++) {
Handle<Function> cb = Handle<Function>::Cast(
cont->callbacks->Get(Integer::New(i)));
TryCatch try_catch;
cb->Call(target->ToObject(), 1, argv);
if (try_catch.HasCaught()) {
FatalException(try_catch);
}
}
if (target.IsNearDeath()) {
cont->target.Dispose();
cont->target.Clear();
cont->proxy.Dispose();
cont->proxy.Clear();
}
}
void ProxyCallback(Persistent<Value> proxy, void* arg) {
assert(proxy.IsNearDeath());
proxy_container *cont = reinterpret_cast<proxy_container*>(arg);
// Clear the Persistent handle to the "proxy" object, no longer needed.
assert(!cont->proxy.IsEmpty());
cont->proxy.Dispose();
cont->proxy.Clear();
assert(cont->proxy.IsEmpty());
// If there are no callbacks, then clear the other handles as well
if (cont->callbacks->Length() == 0) {
cont->target.Dispose();
cont->target.Clear();
cont->callbacks.Dispose();
cont->callbacks.Clear();
assert(cont->proxy.IsEmpty());
assert(cont->target.IsEmpty());
assert(cont->callbacks.IsEmpty());
free(cont);
}
}
Handle<Value> Create(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsObject()) {
Local<String> message = String::New("Object expected");
return ThrowException(Exception::TypeError(message));
}
proxy_container *cont = (proxy_container *)
malloc(sizeof(proxy_container));
cont->target = Persistent<Object>::New(args[0]->ToObject());
cont->proxy = Persistent<Object>::New(proxyClass->NewInstance());
cont->callbacks = Persistent<Array>::New(Array::New());
cont->proxy->SetPointerInInternalField(0, cont);
cont->target.MakeWeak(cont, TargetCallback);
cont->proxy.MakeWeak(cont, ProxyCallback);
if (args.Length() >= 2) {
AddCallback(cont->proxy, Handle<Function>::Cast(args[1]));
}
return cont->proxy;
}
Handle<Value> Get(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsObject()
|| args[0]->ToObject()->InternalFieldCount() != 1) {
Local<String> message = String::New("Weakref instance expected");
return ThrowException(Exception::TypeError(message));
}
Local<Object> proxy = args[0]->ToObject();
assert(proxy->InternalFieldCount() == 1);
const bool dead = IsDead(proxy);
if (dead) return Undefined();
Handle<Object> obj = Unwrap(proxy);
return scope.Close(obj);
}
Handle<Value> IsDead(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsObject()
|| args[0]->ToObject()->InternalFieldCount() != 1) {
Local<String> message = String::New("Weakref instance expected");
return ThrowException(Exception::TypeError(message));
}
Local<Object> proxy = args[0]->ToObject();
assert(proxy->InternalFieldCount() == 1);
const bool dead = IsDead(proxy);
return Boolean::New(dead);
}
Handle<Value> AddCallback(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsObject()
|| args[0]->ToObject()->InternalFieldCount() != 1) {
Local<String> message = String::New("Weakref instance expected");
return ThrowException(Exception::TypeError(message));
}
Local<Object> proxy = args[0]->ToObject();
assert(proxy->InternalFieldCount() == 1);
AddCallback(proxy, Handle<Function>::Cast(args[1]));
return Undefined();
}
Handle<Value> Callbacks(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsObject()
|| args[0]->ToObject()->InternalFieldCount() != 1) {
Local<String> message = String::New("Weakref instance expected");
return ThrowException(Exception::TypeError(message));
}
Local<Object> proxy = args[0]->ToObject();
assert(proxy->InternalFieldCount() == 1);
return scope.Close(GetCallbacks(proxy));
}
void Initialize(Handle<Object> target) {
HandleScope scope;
proxyClass = Persistent<ObjectTemplate>::New(ObjectTemplate::New());
proxyClass->SetNamedPropertyHandler(WeakNamedPropertyGetter,
WeakNamedPropertySetter,
WeakNamedPropertyQuery,
WeakNamedPropertyDeleter,
WeakPropertyEnumerator);
proxyClass->SetIndexedPropertyHandler(WeakIndexedPropertyGetter,
WeakIndexedPropertySetter,
WeakIndexedPropertyQuery,
WeakIndexedPropertyDeleter,
WeakPropertyEnumerator);
proxyClass->SetInternalFieldCount(1);
NODE_SET_METHOD(target, "get", Get);
NODE_SET_METHOD(target, "create", Create);
NODE_SET_METHOD(target, "isDead", IsDead);
NODE_SET_METHOD(target, "callbacks", Callbacks);
NODE_SET_METHOD(target, "addCallback", AddCallback);
}
} // anonymous namespace
NODE_MODULE(weakref, Initialize);
<commit_msg>Properly free the underlying struct.<commit_after>/*
* Copyright (c) 2011, Ben Noordhuis <[email protected]>
*
* 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 <stdlib.h>
#include "v8.h"
#include "node.h"
using namespace v8;
using namespace node;
namespace {
typedef struct proxy_container {
Persistent<Object> target;
Persistent<Array> callbacks;
} proxy_container;
Persistent<ObjectTemplate> proxyClass;
bool IsDead(Handle<Object> proxy) {
assert(proxy->InternalFieldCount() == 1);
proxy_container *cont = reinterpret_cast<proxy_container*>(
proxy->GetPointerFromInternalField(0));
assert(cont != NULL);
return cont->target.IsEmpty();
}
Handle<Object> Unwrap(Handle<Object> proxy) {
assert(!IsDead(proxy));
proxy_container *cont = reinterpret_cast<proxy_container*>(
proxy->GetPointerFromInternalField(0));
assert(cont != NULL);
return cont->target;
}
Handle<Array> GetCallbacks(Handle<Object> proxy) {
proxy_container *cont = reinterpret_cast<proxy_container*>(
proxy->GetPointerFromInternalField(0));
assert(cont != NULL);
return cont->callbacks;
}
#define UNWRAP \
HandleScope scope; \
Handle<Object> obj; \
const bool dead = IsDead(info.This()); \
if (!dead) obj = Unwrap(info.This()); \
Handle<Value> WeakNamedPropertyGetter(Local<String> property,
const AccessorInfo& info) {
UNWRAP
return dead ? Local<Value>() : obj->Get(property);
}
Handle<Value> WeakNamedPropertySetter(Local<String> property,
Local<Value> value,
const AccessorInfo& info) {
UNWRAP
if (!dead) obj->Set(property, value);
return value;
}
Handle<Integer> WeakNamedPropertyQuery(Local<String> property,
const AccessorInfo& info) {
return HandleScope().Close(Integer::New(None));
}
Handle<Boolean> WeakNamedPropertyDeleter(Local<String> property,
const AccessorInfo& info) {
UNWRAP
return Boolean::New(!dead && obj->Delete(property));
}
Handle<Value> WeakIndexedPropertyGetter(uint32_t index,
const AccessorInfo& info) {
UNWRAP
return dead ? Local<Value>() : obj->Get(index);
}
Handle<Value> WeakIndexedPropertySetter(uint32_t index,
Local<Value> value,
const AccessorInfo& info) {
UNWRAP
if (!dead) obj->Set(index, value);
return value;
}
Handle<Integer> WeakIndexedPropertyQuery(uint32_t index,
const AccessorInfo& info) {
return HandleScope().Close(Integer::New(None));
}
Handle<Boolean> WeakIndexedPropertyDeleter(uint32_t index,
const AccessorInfo& info) {
UNWRAP
return Boolean::New(!dead && obj->Delete(index));
}
Handle<Array> WeakPropertyEnumerator(const AccessorInfo& info) {
UNWRAP
return HandleScope().Close(dead ? Array::New(0) : obj->GetPropertyNames());
}
void AddCallback(Handle<Object> proxy, Handle<Function> callback) {
Handle<Array> callbacks = GetCallbacks(proxy);
callbacks->Set(Integer::New(callbacks->Length()), callback);
}
void TargetCallback(Persistent<Value> target, void* arg) {
HandleScope scope;
assert(target.IsNearDeath());
proxy_container *cont = reinterpret_cast<proxy_container*>(arg);
// invoke any listening callbacks
uint32_t len = cont->callbacks->Length();
Handle<Value> argv[1];
argv[0] = target;
for (uint32_t i=0; i<len; i++) {
Handle<Function> cb = Handle<Function>::Cast(
cont->callbacks->Get(Integer::New(i)));
TryCatch try_catch;
cb->Call(target->ToObject(), 1, argv);
if (try_catch.HasCaught()) {
FatalException(try_catch);
}
}
if (target.IsNearDeath()) {
cont->target.Dispose();
cont->target.Clear();
free(cont);
}
}
Handle<Value> Create(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsObject()) {
Local<String> message = String::New("Object expected");
return ThrowException(Exception::TypeError(message));
}
proxy_container *cont = (proxy_container *)
malloc(sizeof(proxy_container));
cont->target = Persistent<Object>::New(args[0]->ToObject());
cont->callbacks = Persistent<Array>::New(Array::New());
Local<Object> proxy = proxyClass->NewInstance();
proxy->SetPointerInInternalField(0, cont);
cont->target.MakeWeak(cont, TargetCallback);
if (args.Length() >= 2) {
AddCallback(proxy, Handle<Function>::Cast(args[1]));
}
return proxy;
}
Handle<Value> Get(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsObject()
|| args[0]->ToObject()->InternalFieldCount() != 1) {
Local<String> message = String::New("Weakref instance expected");
return ThrowException(Exception::TypeError(message));
}
Local<Object> proxy = args[0]->ToObject();
assert(proxy->InternalFieldCount() == 1);
const bool dead = IsDead(proxy);
if (dead) return Undefined();
Handle<Object> obj = Unwrap(proxy);
return scope.Close(obj);
}
Handle<Value> IsDead(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsObject()
|| args[0]->ToObject()->InternalFieldCount() != 1) {
Local<String> message = String::New("Weakref instance expected");
return ThrowException(Exception::TypeError(message));
}
Local<Object> proxy = args[0]->ToObject();
assert(proxy->InternalFieldCount() == 1);
const bool dead = IsDead(proxy);
return Boolean::New(dead);
}
Handle<Value> AddCallback(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsObject()
|| args[0]->ToObject()->InternalFieldCount() != 1) {
Local<String> message = String::New("Weakref instance expected");
return ThrowException(Exception::TypeError(message));
}
Local<Object> proxy = args[0]->ToObject();
assert(proxy->InternalFieldCount() == 1);
AddCallback(proxy, Handle<Function>::Cast(args[1]));
return Undefined();
}
Handle<Value> Callbacks(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsObject()
|| args[0]->ToObject()->InternalFieldCount() != 1) {
Local<String> message = String::New("Weakref instance expected");
return ThrowException(Exception::TypeError(message));
}
Local<Object> proxy = args[0]->ToObject();
assert(proxy->InternalFieldCount() == 1);
return scope.Close(GetCallbacks(proxy));
}
void Initialize(Handle<Object> target) {
HandleScope scope;
proxyClass = Persistent<ObjectTemplate>::New(ObjectTemplate::New());
proxyClass->SetNamedPropertyHandler(WeakNamedPropertyGetter,
WeakNamedPropertySetter,
WeakNamedPropertyQuery,
WeakNamedPropertyDeleter,
WeakPropertyEnumerator);
proxyClass->SetIndexedPropertyHandler(WeakIndexedPropertyGetter,
WeakIndexedPropertySetter,
WeakIndexedPropertyQuery,
WeakIndexedPropertyDeleter,
WeakPropertyEnumerator);
proxyClass->SetInternalFieldCount(1);
NODE_SET_METHOD(target, "get", Get);
NODE_SET_METHOD(target, "create", Create);
NODE_SET_METHOD(target, "isDead", IsDead);
NODE_SET_METHOD(target, "callbacks", Callbacks);
NODE_SET_METHOD(target, "addCallback", AddCallback);
}
} // anonymous namespace
NODE_MODULE(weakref, Initialize);
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.