text
stringlengths 54
60.6k
|
|---|
<commit_before>#include <map>
#include "assert.hpp"
#include "TimingGraph.hpp"
NodeId TimingGraph::add_node(const TimingNode& new_node) {
//Type
TN_Type new_node_type = new_node.type();
node_types_.push_back(new_node.type());
//Domain
node_clock_domains_.push_back(new_node.clock_domain());
//Logical block
node_logical_blocks_.push_back(new_node.logical_block());
//Clock source
node_is_clock_source_.push_back(new_node.is_clock_source());
//Save primary outputs as we build the graph
if(new_node_type == TN_Type::OUTPAD_SINK ||
new_node_type == TN_Type::FF_SINK) {
primary_outputs_.push_back(node_types_.size() - 1);
}
//Out edges
std::vector<EdgeId> out_edges = std::vector<EdgeId>();
out_edges.reserve(new_node.num_out_edges());
for(int i = 0; i < new_node.num_out_edges(); i++) {
EdgeId edge_id = new_node.out_edge_id(i);
out_edges.emplace_back(edge_id);
}
node_out_edges_.push_back(std::move(out_edges));
//In edges
// these get filled in later, after all nodes have been added
std::vector<EdgeId> in_edges = std::vector<EdgeId>();
node_in_edges_.push_back(std::move(in_edges));
//Verify sizes
ASSERT(node_types_.size() == node_clock_domains_.size());
ASSERT(node_types_.size() == node_out_edges_.size());
ASSERT(node_types_.size() == node_in_edges_.size());
//Return the ID of the added node
return node_types_.size() - 1;
}
EdgeId TimingGraph::add_edge(const TimingEdge& new_edge) {
edge_sink_nodes_.push_back(new_edge.to_node_id());
edge_src_nodes_.push_back(new_edge.from_node_id());
edge_delays_.push_back(new_edge.delay());
ASSERT(edge_sink_nodes_.size() == edge_src_nodes_.size());
ASSERT(edge_sink_nodes_.size() == edge_delays_.size());
//Return the edge id of the added edge
return edge_delays_.size() - 1;
}
void TimingGraph::fill_back_edges() {
//Add reverse/back links for all edges in the timing graph
for(int i = 0; i < num_nodes(); i++) {
for(EdgeId edge_id : node_out_edges_[i]) {
NodeId sink_node = edge_sink_node(edge_id);
//edge_id drives the sink so it is an in edge
node_in_edges_[sink_node].push_back(edge_id);
}
}
}
void TimingGraph::add_launch_capture_edges() {
//We represent the dependancies between the clock and data paths
//As edges in the graph from FF_CLOCK pins to FF_SOURCES (launch path)
//and FF_SINKS (capture path)
//
//We use the information about the logical blocks associated with each
//timing node to infer these edges. That is, we look for FF_SINKs and FF_SOURCEs
//that share the same logical block as an FF_CLOCK.
//
//TODO: Currently this just works for VPR's timing graph where only one FF_CLOCK exists
// per basic logic block. This will need to be generalized.
//Build a map from logical block id to the tnodes we care about
std::map<BlockId,std::vector<NodeId>> logical_block_FF_clocks;
std::map<BlockId,std::vector<NodeId>> logical_block_FF_sources;
std::map<BlockId,std::vector<NodeId>> logical_block_FF_sinks;
for(NodeId node_id = 0; node_id < num_nodes(); node_id++) {
if(node_type(node_id) == TN_Type::FF_CLOCK) {
logical_block_FF_clocks[node_logical_block(node_id)].push_back(node_id);
} else if (node_type(node_id) == TN_Type::FF_SOURCE) {
logical_block_FF_sources[node_logical_block(node_id)].push_back(node_id);
} else if (node_type(node_id) == TN_Type::FF_SINK) {
logical_block_FF_sinks[node_logical_block(node_id)].push_back(node_id);
}
}
//Loop through each FF_CLOCK and add edges to FF_SINKs and FF_SOURCEs
for(const auto clock_kv : logical_block_FF_clocks) {
BlockId logical_block_id = clock_kv.first;
VERIFY(clock_kv.second.size() == 1);
NodeId ff_clock_node_id = clock_kv.second[0];
//Check for FF_SOURCEs associated with this FF_CLOCK pin
auto src_iter = logical_block_FF_sources.find(logical_block_id);
if(src_iter != logical_block_FF_sources.end()) {
//Go through each assoicated source and add an edge to it
for(NodeId ff_src_node_id : src_iter->second) {
//TODO: remove TimingEdge class
EdgeId edge_id = add_edge(TimingEdge(Time(0.), ff_clock_node_id, ff_src_node_id));
node_out_edges_[ff_clock_node_id].push_back(edge_id);
}
}
//Check for FF_SINKs associated with this FF_CLOCK pin
auto sink_iter = logical_block_FF_sinks.find(logical_block_id);
if(sink_iter != logical_block_FF_sinks.end()) {
//Go through each assoicated sink and add an edge to it
for(NodeId ff_sink_node_id : sink_iter->second) {
//TODO: remove TimingEdge class
EdgeId edge_id = add_edge(TimingEdge(Time(0.), ff_clock_node_id, ff_sink_node_id));
node_out_edges_[ff_clock_node_id].push_back(edge_id);
}
}
}
}
void TimingGraph::levelize() {
//Levelizes the timing graph
//This over-writes any previous levelization if it exists
//Clear the previous levelization
node_levels_.clear();
primary_outputs_.clear();
//Allocate space for the first level
node_levels_.resize(1);
//Copy the number of input edges per-node
//These will be decremented to know when a node is done
//
//Also initialize the first level (nodes with no fanin)
std::vector<int> node_fanin_remaining(num_nodes());
for(NodeId node_id = 0; node_id < num_nodes(); node_id++) {
int node_fanin = num_node_in_edges(node_id);
node_fanin_remaining[node_id] = node_fanin;
if(node_fanin == 0) {
//Add a primary input
node_levels_[0].push_back(node_id);
}
}
//Walk the graph from primary inputs (no fanin) to generate a topological sort
//
//We inspect the output edges of each node and decrement the fanin count of the
//target node. Once the fanin count for a node reaches zero it can be added
//to the level.
int level_id = 0;
bool inserted_node_in_level = true;
while(inserted_node_in_level) { //If nothing was inserted we are finished
inserted_node_in_level = false;
for(const NodeId node_id : node_levels_[level_id]) {
//Inspect the fanout
for(int edge_idx = 0; edge_idx < num_node_out_edges(node_id); edge_idx++) {
EdgeId edge_id = node_out_edge(node_id, edge_idx);
NodeId sink_node = edge_sink_node(edge_id);
//Decrement the fanin count
ASSERT(node_fanin_remaining[sink_node] > 0);
node_fanin_remaining[sink_node]--;
//Add to the next level if all fanin has been seen
if(node_fanin_remaining[sink_node] == 0) {
//Ensure there is space by allocating the next level if required
node_levels_.resize(level_id+2);
//Add the node
node_levels_[level_id+1].push_back(sink_node);
inserted_node_in_level = true;
}
}
//Also track the primary outputs
if(num_node_out_edges(node_id) == 0) {
primary_outputs_.push_back(node_id);
}
}
level_id++;
}
}
void TimingGraph::contiguize_level_edges() {
//Make all edges in a level be contiguous in memory
std::cout << "Re-allocating edges so levels are in contiguous memory" << std::endl;
//Collect levels for edges
std::vector<std::vector<EdgeId>> edge_levels;
for(int level_idx = 0; level_idx < num_levels(); level_idx++) {
edge_levels.push_back(std::vector<EdgeId>());
for(auto node_id : node_levels_[level_idx]) {
for(int i = 0; i < num_node_out_edges(node_id); i++) {
EdgeId edge_id = node_out_edge(node_id, i);
edge_levels[level_idx].push_back(edge_id);
}
}
}
//Save a map from old edge_id to new edge_id, will be used to update node refs
std::map<EdgeId,EdgeId> old_edge_to_new_edge;
int cnt = 0;
for(std::vector<EdgeId>& edge_level : edge_levels) {
for(EdgeId orig_edge_id : edge_level) {
old_edge_to_new_edge[orig_edge_id] = cnt;
cnt++;
}
}
/*
* Re-allocate edges to be contiguous in memory
*/
//Save the old values while we write the new ones
std::vector<NodeId> old_edge_sink_nodes_;
std::vector<NodeId> old_edge_src_nodes_;
#ifdef TIME_MEM_ALIGN
std::vector<Time, aligned_allocator<Time, TIME_MEM_ALIGN>> old_edge_delays_;
#else
std::vector<Time> old_edge_delays_;
#endif
//Swap them
std::swap(old_edge_sink_nodes_, edge_sink_nodes_);
std::swap(old_edge_src_nodes_, edge_src_nodes_);
std::swap(old_edge_delays_, edge_delays_);
//Update values
for(auto& edge_level : edge_levels) {
for(auto& orig_edge_id : edge_level) {
//Write edges in the new contiguous order
edge_sink_nodes_.push_back(old_edge_sink_nodes_[orig_edge_id]);
edge_src_nodes_.push_back(old_edge_src_nodes_[orig_edge_id]);
edge_delays_.push_back(old_edge_delays_[orig_edge_id]);
}
}
/*
* Update edge refs in nodes
*/
for(int i = 0; i < num_nodes(); i++) {
for(size_t j = 0; j < node_out_edges_[i].size(); j++) {
EdgeId old_edge_id = node_out_edges_[i][j];
node_out_edges_[i][j] = old_edge_to_new_edge[old_edge_id];
}
for(size_t j = 0; j < node_in_edges_[i].size(); j++) {
EdgeId old_edge_id = node_in_edges_[i][j];
node_in_edges_[i][j] = old_edge_to_new_edge[old_edge_id];
}
}
}
std::map<NodeId,NodeId> TimingGraph::contiguize_level_nodes() {
//Make all nodes in a level be contiguous in memory
std::cout << "Re-allocating nodes so levels are in contiguous memory" << std::endl;
/*
* Build a map of the old and new node ids to update edges
* and node levels later
*/
std::map<NodeId,NodeId> old_node_to_new_node;
int cnt = 0;
for(int level_idx = 0; level_idx < num_levels(); level_idx++) {
for(NodeId node_id : node_levels_[level_idx]) {
old_node_to_new_node[node_id] = cnt;
cnt++;
}
}
/*
* Re-allocate nodes so levels are in contiguous memory
*/
std::vector<TN_Type> old_node_types;
std::vector<DomainId> old_node_clock_domains;
std::vector<std::vector<EdgeId>> old_node_out_edges;
std::vector<std::vector<EdgeId>> old_node_in_edges;
//Swap the values
std::swap(old_node_types, node_types_);
std::swap(old_node_clock_domains, node_clock_domains_);
std::swap(old_node_out_edges, node_out_edges_);
std::swap(old_node_in_edges, node_in_edges_);
//Update the values
for(int level_idx = 0; level_idx < num_levels(); level_idx++) {
for(NodeId old_node_id : node_levels_[level_idx]) {
node_types_.push_back(old_node_types[old_node_id]);
node_clock_domains_.push_back(old_node_clock_domains[old_node_id]);
node_out_edges_.push_back(old_node_out_edges[old_node_id]);
node_in_edges_.push_back(old_node_in_edges[old_node_id]);
}
}
/*
* Update old references to node_ids with thier new values
*/
//The node levels
for(int level_idx = 0; level_idx < num_levels(); level_idx++) {
for(size_t i = 0; i < node_levels_[level_idx].size(); i++) {
NodeId old_node_id = node_levels_[level_idx][i];
node_levels_[level_idx][i] = old_node_to_new_node[old_node_id];
}
}
//The primary outputs
for(size_t i = 0; i < primary_outputs_.size(); i++) {
NodeId old_node_id = primary_outputs_[i];
primary_outputs_[i] = old_node_to_new_node[old_node_id];
}
//The Edges
for(int i = 0; i < num_edges(); i++) {
NodeId old_sink_node = edge_sink_nodes_[i];
NodeId old_src_node = edge_src_nodes_[i];
edge_sink_nodes_[i] = old_node_to_new_node[old_sink_node];
edge_src_nodes_[i] = old_node_to_new_node[old_src_node];
}
return old_node_to_new_node;
}
<commit_msg>Whitespace cleanup<commit_after>#include <map>
#include "assert.hpp"
#include "TimingGraph.hpp"
NodeId TimingGraph::add_node(const TimingNode& new_node) {
//Type
TN_Type new_node_type = new_node.type();
node_types_.push_back(new_node.type());
//Domain
node_clock_domains_.push_back(new_node.clock_domain());
//Logical block
node_logical_blocks_.push_back(new_node.logical_block());
//Clock source
node_is_clock_source_.push_back(new_node.is_clock_source());
//Save primary outputs as we build the graph
if(new_node_type == TN_Type::OUTPAD_SINK ||
new_node_type == TN_Type::FF_SINK) {
primary_outputs_.push_back(node_types_.size() - 1);
}
//Out edges
std::vector<EdgeId> out_edges = std::vector<EdgeId>();
out_edges.reserve(new_node.num_out_edges());
for(int i = 0; i < new_node.num_out_edges(); i++) {
EdgeId edge_id = new_node.out_edge_id(i);
out_edges.emplace_back(edge_id);
}
node_out_edges_.push_back(std::move(out_edges));
//In edges
// these get filled in later, after all nodes have been added
std::vector<EdgeId> in_edges = std::vector<EdgeId>();
node_in_edges_.push_back(std::move(in_edges));
//Verify sizes
ASSERT(node_types_.size() == node_clock_domains_.size());
ASSERT(node_types_.size() == node_out_edges_.size());
ASSERT(node_types_.size() == node_in_edges_.size());
//Return the ID of the added node
return node_types_.size() - 1;
}
EdgeId TimingGraph::add_edge(const TimingEdge& new_edge) {
edge_sink_nodes_.push_back(new_edge.to_node_id());
edge_src_nodes_.push_back(new_edge.from_node_id());
edge_delays_.push_back(new_edge.delay());
ASSERT(edge_sink_nodes_.size() == edge_src_nodes_.size());
ASSERT(edge_sink_nodes_.size() == edge_delays_.size());
//Return the edge id of the added edge
return edge_delays_.size() - 1;
}
void TimingGraph::fill_back_edges() {
//Add reverse/back links for all edges in the timing graph
for(int i = 0; i < num_nodes(); i++) {
for(EdgeId edge_id : node_out_edges_[i]) {
NodeId sink_node = edge_sink_node(edge_id);
//edge_id drives the sink so it is an in edge
node_in_edges_[sink_node].push_back(edge_id);
}
}
}
void TimingGraph::add_launch_capture_edges() {
//We represent the dependancies between the clock and data paths
//As edges in the graph from FF_CLOCK pins to FF_SOURCES (launch path)
//and FF_SINKS (capture path)
//
//We use the information about the logical blocks associated with each
//timing node to infer these edges. That is, we look for FF_SINKs and FF_SOURCEs
//that share the same logical block as an FF_CLOCK.
//
//TODO: Currently this just works for VPR's timing graph where only one FF_CLOCK exists
// per basic logic block. This will need to be generalized.
//Build a map from logical block id to the tnodes we care about
std::map<BlockId,std::vector<NodeId>> logical_block_FF_clocks;
std::map<BlockId,std::vector<NodeId>> logical_block_FF_sources;
std::map<BlockId,std::vector<NodeId>> logical_block_FF_sinks;
for(NodeId node_id = 0; node_id < num_nodes(); node_id++) {
if(node_type(node_id) == TN_Type::FF_CLOCK) {
logical_block_FF_clocks[node_logical_block(node_id)].push_back(node_id);
} else if (node_type(node_id) == TN_Type::FF_SOURCE) {
logical_block_FF_sources[node_logical_block(node_id)].push_back(node_id);
} else if (node_type(node_id) == TN_Type::FF_SINK) {
logical_block_FF_sinks[node_logical_block(node_id)].push_back(node_id);
}
}
//Loop through each FF_CLOCK and add edges to FF_SINKs and FF_SOURCEs
for(const auto clock_kv : logical_block_FF_clocks) {
BlockId logical_block_id = clock_kv.first;
VERIFY(clock_kv.second.size() == 1);
NodeId ff_clock_node_id = clock_kv.second[0];
//Check for FF_SOURCEs associated with this FF_CLOCK pin
auto src_iter = logical_block_FF_sources.find(logical_block_id);
if(src_iter != logical_block_FF_sources.end()) {
//Go through each assoicated source and add an edge to it
for(NodeId ff_src_node_id : src_iter->second) {
//TODO: remove TimingEdge class
EdgeId edge_id = add_edge(TimingEdge(Time(0.), ff_clock_node_id, ff_src_node_id));
node_out_edges_[ff_clock_node_id].push_back(edge_id);
}
}
//Check for FF_SINKs associated with this FF_CLOCK pin
auto sink_iter = logical_block_FF_sinks.find(logical_block_id);
if(sink_iter != logical_block_FF_sinks.end()) {
//Go through each assoicated sink and add an edge to it
for(NodeId ff_sink_node_id : sink_iter->second) {
//TODO: remove TimingEdge class
EdgeId edge_id = add_edge(TimingEdge(Time(0.), ff_clock_node_id, ff_sink_node_id));
node_out_edges_[ff_clock_node_id].push_back(edge_id);
}
}
}
}
void TimingGraph::levelize() {
//Levelizes the timing graph
//This over-writes any previous levelization if it exists
//Clear the previous levelization
node_levels_.clear();
primary_outputs_.clear();
//Allocate space for the first level
node_levels_.resize(1);
//Copy the number of input edges per-node
//These will be decremented to know when a node is done
//
//Also initialize the first level (nodes with no fanin)
std::vector<int> node_fanin_remaining(num_nodes());
for(NodeId node_id = 0; node_id < num_nodes(); node_id++) {
int node_fanin = num_node_in_edges(node_id);
node_fanin_remaining[node_id] = node_fanin;
if(node_fanin == 0) {
//Add a primary input
node_levels_[0].push_back(node_id);
}
}
//Walk the graph from primary inputs (no fanin) to generate a topological sort
//
//We inspect the output edges of each node and decrement the fanin count of the
//target node. Once the fanin count for a node reaches zero it can be added
//to the level.
int level_id = 0;
bool inserted_node_in_level = true;
while(inserted_node_in_level) { //If nothing was inserted we are finished
inserted_node_in_level = false;
for(const NodeId node_id : node_levels_[level_id]) {
//Inspect the fanout
for(int edge_idx = 0; edge_idx < num_node_out_edges(node_id); edge_idx++) {
EdgeId edge_id = node_out_edge(node_id, edge_idx);
NodeId sink_node = edge_sink_node(edge_id);
//Decrement the fanin count
ASSERT(node_fanin_remaining[sink_node] > 0);
node_fanin_remaining[sink_node]--;
//Add to the next level if all fanin has been seen
if(node_fanin_remaining[sink_node] == 0) {
//Ensure there is space by allocating the next level if required
node_levels_.resize(level_id+2);
//Add the node
node_levels_[level_id+1].push_back(sink_node);
inserted_node_in_level = true;
}
}
//Also track the primary outputs
if(num_node_out_edges(node_id) == 0) {
primary_outputs_.push_back(node_id);
}
}
level_id++;
}
}
void TimingGraph::contiguize_level_edges() {
//Make all edges in a level be contiguous in memory
std::cout << "Re-allocating edges so levels are in contiguous memory" << std::endl;
//Collect levels for edges
std::vector<std::vector<EdgeId>> edge_levels;
for(int level_idx = 0; level_idx < num_levels(); level_idx++) {
edge_levels.push_back(std::vector<EdgeId>());
for(auto node_id : node_levels_[level_idx]) {
for(int i = 0; i < num_node_out_edges(node_id); i++) {
EdgeId edge_id = node_out_edge(node_id, i);
edge_levels[level_idx].push_back(edge_id);
}
}
}
//Save a map from old edge_id to new edge_id, will be used to update node refs
std::map<EdgeId,EdgeId> old_edge_to_new_edge;
int cnt = 0;
for(std::vector<EdgeId>& edge_level : edge_levels) {
for(EdgeId orig_edge_id : edge_level) {
old_edge_to_new_edge[orig_edge_id] = cnt;
cnt++;
}
}
/*
* Re-allocate edges to be contiguous in memory
*/
//Save the old values while we write the new ones
std::vector<NodeId> old_edge_sink_nodes_;
std::vector<NodeId> old_edge_src_nodes_;
#ifdef TIME_MEM_ALIGN
std::vector<Time, aligned_allocator<Time, TIME_MEM_ALIGN>> old_edge_delays_;
#else
std::vector<Time> old_edge_delays_;
#endif
//Swap them
std::swap(old_edge_sink_nodes_, edge_sink_nodes_);
std::swap(old_edge_src_nodes_, edge_src_nodes_);
std::swap(old_edge_delays_, edge_delays_);
//Update values
for(auto& edge_level : edge_levels) {
for(auto& orig_edge_id : edge_level) {
//Write edges in the new contiguous order
edge_sink_nodes_.push_back(old_edge_sink_nodes_[orig_edge_id]);
edge_src_nodes_.push_back(old_edge_src_nodes_[orig_edge_id]);
edge_delays_.push_back(old_edge_delays_[orig_edge_id]);
}
}
/*
* Update edge refs in nodes
*/
for(int i = 0; i < num_nodes(); i++) {
for(size_t j = 0; j < node_out_edges_[i].size(); j++) {
EdgeId old_edge_id = node_out_edges_[i][j];
node_out_edges_[i][j] = old_edge_to_new_edge[old_edge_id];
}
for(size_t j = 0; j < node_in_edges_[i].size(); j++) {
EdgeId old_edge_id = node_in_edges_[i][j];
node_in_edges_[i][j] = old_edge_to_new_edge[old_edge_id];
}
}
}
std::map<NodeId,NodeId> TimingGraph::contiguize_level_nodes() {
//Make all nodes in a level be contiguous in memory
std::cout << "Re-allocating nodes so levels are in contiguous memory" << std::endl;
/*
* Build a map of the old and new node ids to update edges
* and node levels later
*/
std::map<NodeId,NodeId> old_node_to_new_node;
int cnt = 0;
for(int level_idx = 0; level_idx < num_levels(); level_idx++) {
for(NodeId node_id : node_levels_[level_idx]) {
old_node_to_new_node[node_id] = cnt;
cnt++;
}
}
/*
* Re-allocate nodes so levels are in contiguous memory
*/
std::vector<TN_Type> old_node_types;
std::vector<DomainId> old_node_clock_domains;
std::vector<std::vector<EdgeId>> old_node_out_edges;
std::vector<std::vector<EdgeId>> old_node_in_edges;
//Swap the values
std::swap(old_node_types, node_types_);
std::swap(old_node_clock_domains, node_clock_domains_);
std::swap(old_node_out_edges, node_out_edges_);
std::swap(old_node_in_edges, node_in_edges_);
//Update the values
for(int level_idx = 0; level_idx < num_levels(); level_idx++) {
for(NodeId old_node_id : node_levels_[level_idx]) {
node_types_.push_back(old_node_types[old_node_id]);
node_clock_domains_.push_back(old_node_clock_domains[old_node_id]);
node_out_edges_.push_back(old_node_out_edges[old_node_id]);
node_in_edges_.push_back(old_node_in_edges[old_node_id]);
}
}
/*
* Update old references to node_ids with thier new values
*/
//The node levels
for(int level_idx = 0; level_idx < num_levels(); level_idx++) {
for(size_t i = 0; i < node_levels_[level_idx].size(); i++) {
NodeId old_node_id = node_levels_[level_idx][i];
node_levels_[level_idx][i] = old_node_to_new_node[old_node_id];
}
}
//The primary outputs
for(size_t i = 0; i < primary_outputs_.size(); i++) {
NodeId old_node_id = primary_outputs_[i];
primary_outputs_[i] = old_node_to_new_node[old_node_id];
}
//The Edges
for(int i = 0; i < num_edges(); i++) {
NodeId old_sink_node = edge_sink_nodes_[i];
NodeId old_src_node = edge_src_nodes_[i];
edge_sink_nodes_[i] = old_node_to_new_node[old_sink_node];
edge_src_nodes_[i] = old_node_to_new_node[old_src_node];
}
return old_node_to_new_node;
}
<|endoftext|>
|
<commit_before><commit_msg><= for extra safely I suppose<commit_after><|endoftext|>
|
<commit_before>#include <iostream>
#include <armadillo>
using namespace std;
using namespace arma;
// EstructruraCapaRed especifica la cantidad de neuronas en cada capa.
// Por ejemplo, si la red tiene 2 neuronas en la primera capa,
// 3 en la capa oculta y 1 en la capa de salida,
// EstructuraCapasRed para esa red será [2 3 1].
using EstructuraCapasRed = vec;
pair<vector<mat>, double> entrenarMulticapa(const EstructuraCapasRed& estructura,
const mat& datos,
int nEpocas,
double tasaAprendizaje,
double toleranciaError);
double errorPrueba(const vec& pesos,
const mat& patrones,
const vec& salidaDeseada);
int main()
{
arma_rng::set_seed_random();
mat datos;
datos.load("XOR_trn.csv");
return 0;
}
namespace ic {
vec sigmoid(const vec& v, double b)
{
vec result(v.n_elem);
for (unsigned int i = 0; i < v.n_elem; ++i)
result(i) = 2 / (1 + exp(-b * v(i))) - 1;
return result;
}
}
pair<vec, double> epocaMulticapa(const mat& patronesExt,
const mat& salidaDeseada,
double tasaAprendizaje,
const vector<mat>& pesos)
{
//Entrenamiento
vector<mat> nuevosPesos = pesos;
const int nCapas = nuevosPesos.size();
for (unsigned int n = 0; n < patronesExt.n_rows; ++n) {
// Calcular las salidas para cada capa
// También vamos a meter la entrada a la red en la estructura de salidas.
// Esto es necesario para el cálculo de ajuste de pesos.
vector<vec> ySalidas;
ySalidas.push_back(patronesExt.row(n));
for (int i = 1; i <= nCapas; ++i) {
vec v = pesos[i - 1] * ySalidas[i - 1]; // FIXME: Esto va a explotar luego de la
// primer capa, porque no le estamos metiendo el sesgo
ySalidas[i] = ic::sigmoid(v, 1); // TODO: ver qué valor le pasamos como parámetro
// a la sigmoidea
}
}
// Validacion
int errores = 0;
for (unsigned int i = 0; i < patronesExt.n_rows; ++i) {
double z = dot(patronesExt.row(i), pesos);
// int y = ic::sign(z);
// if (y != salidaDeseada(i))
// ++errores;
}
double tasaError = static_cast<double>(errores) / patronesExt.n_rows * 100;
return {nuevosPesos, tasaError};
} // fin funcion Epoca
double errorPrueba(const vec& pesos,
const mat& patrones,
const vec& salidaDeseada)
{
// Se extiende la matriz de patrones con la entrada correspondiente al umbral
const mat patronesExt = join_horiz(ones(patrones.n_rows) * (-1), patrones);
int errores = 0;
for (unsigned int i = 0; i < patronesExt.n_rows; ++i) {
double z = dot(patronesExt.row(i), pesos);
// int y = ic::sign(z);
// if (y != salidaDeseada(i))
// ++errores;
}
double tasaError = static_cast<double>(errores) / patronesExt.n_rows * 100;
return tasaError;
}
pair<vector<mat>, double> entrenarMulticapa(const EstructuraCapasRed& estructura,
const mat& datos,
int nEpocas,
double tasaAprendizaje,
double toleranciaError)
{
const int nSalidas = estructura(estructura.n_elem - 1);
const int nEntradas = datos.n_cols - nSalidas;
const int nCapas = estructura.n_elem;
// Vamos a tener tantas columnas en salidaDeseada
// como neuronas en la capa de salida
const mat salidaDeseada = datos.tail_cols(nSalidas);
// Extender la matriz de patrones con la entrada correspondiente al umbral
const mat patronesExt = join_horiz(ones(datos.n_rows) * (-1), datos.head_cols(nEntradas));
// Inicializar pesos y tasa de error
vector<mat> pesos;
// La primer matriz matriz de pesos tiene tantas filas como neuronas en la primer capa
// y tantas columnas como entradas.
pesos.push_back(randu<mat>(estructura(0), nEntradas));
for (int i = 1; i < nCapas; ++i) {
// Las siguientes matrices de pesos tienen tantas filas como neuronas en dicha capa
// y tantas columnas como entradas a esa capa, que van a ser las salidas de
// la capa anterior.
// Las salidas de la capa anterior es igual al nro de neuronas en la capa anterior.
pesos.push_back(randu<mat>(estructura(i), estructura(i - 1)));
}
double tasaError = 0;
// Ciclo de las epocas
for (int epoca = 1; epoca <= nEpocas; ++epoca) {
// Ciclo para una época
tie(pesos, tasaError) = epocaMulticapa(patronesExt,
salidaDeseada,
tasaAprendizaje,
pesos);
if (tasaError < toleranciaError)
break;
}
// Fin ciclo (epocas)
return {pesos, tasaError};
}
<commit_msg>Guia 1 - xor_multicapa: Cambiar ic::sigmoid para que haga el cálculo sobre todo el vector a la vez<commit_after>#include <iostream>
#include <armadillo>
using namespace std;
using namespace arma;
// EstructruraCapaRed especifica la cantidad de neuronas en cada capa.
// Por ejemplo, si la red tiene 2 neuronas en la primera capa,
// 3 en la capa oculta y 1 en la capa de salida,
// EstructuraCapasRed para esa red será [2 3 1].
using EstructuraCapasRed = vec;
pair<vector<mat>, double> entrenarMulticapa(const EstructuraCapasRed& estructura,
const mat& datos,
int nEpocas,
double tasaAprendizaje,
double toleranciaError);
double errorPrueba(const vec& pesos,
const mat& patrones,
const vec& salidaDeseada);
int main()
{
arma_rng::set_seed_random();
mat datos;
datos.load("XOR_trn.csv");
return 0;
}
namespace ic {
vec sigmoid(const vec& v, double b)
{
return 2 / (1 + exp(-b * v)) - 1;
}
}
pair<vec, double> epocaMulticapa(const mat& patronesExt,
const mat& salidaDeseada,
double tasaAprendizaje,
const vector<mat>& pesos)
{
//Entrenamiento
vector<mat> nuevosPesos = pesos;
const int nCapas = nuevosPesos.size();
for (unsigned int n = 0; n < patronesExt.n_rows; ++n) {
// Calcular las salidas para cada capa
// También vamos a meter la entrada a la red en la estructura de salidas.
// Esto es necesario para el cálculo de ajuste de pesos.
vector<vec> ySalidas;
ySalidas.push_back(patronesExt.row(n));
for (int i = 1; i <= nCapas; ++i) {
vec v = pesos[i - 1] * ySalidas[i - 1]; // FIXME: Esto va a explotar luego de la
// primer capa, porque no le estamos metiendo el sesgo
ySalidas[i] = ic::sigmoid(v, 1); // TODO: ver qué valor le pasamos como parámetro
// a la sigmoidea
}
}
// Validacion
int errores = 0;
for (unsigned int i = 0; i < patronesExt.n_rows; ++i) {
double z = dot(patronesExt.row(i), pesos);
// int y = ic::sign(z);
// if (y != salidaDeseada(i))
// ++errores;
}
double tasaError = static_cast<double>(errores) / patronesExt.n_rows * 100;
return {nuevosPesos, tasaError};
} // fin funcion Epoca
double errorPrueba(const vec& pesos,
const mat& patrones,
const vec& salidaDeseada)
{
// Se extiende la matriz de patrones con la entrada correspondiente al umbral
const mat patronesExt = join_horiz(ones(patrones.n_rows) * (-1), patrones);
int errores = 0;
for (unsigned int i = 0; i < patronesExt.n_rows; ++i) {
double z = dot(patronesExt.row(i), pesos);
// int y = ic::sign(z);
// if (y != salidaDeseada(i))
// ++errores;
}
double tasaError = static_cast<double>(errores) / patronesExt.n_rows * 100;
return tasaError;
}
pair<vector<mat>, double> entrenarMulticapa(const EstructuraCapasRed& estructura,
const mat& datos,
int nEpocas,
double tasaAprendizaje,
double toleranciaError)
{
const int nSalidas = estructura(estructura.n_elem - 1);
const int nEntradas = datos.n_cols - nSalidas;
const int nCapas = estructura.n_elem;
// Vamos a tener tantas columnas en salidaDeseada
// como neuronas en la capa de salida
const mat salidaDeseada = datos.tail_cols(nSalidas);
// Extender la matriz de patrones con la entrada correspondiente al umbral
const mat patronesExt = join_horiz(ones(datos.n_rows) * (-1), datos.head_cols(nEntradas));
// Inicializar pesos y tasa de error
vector<mat> pesos;
// La primer matriz matriz de pesos tiene tantas filas como neuronas en la primer capa
// y tantas columnas como entradas.
pesos.push_back(randu<mat>(estructura(0), nEntradas));
for (int i = 1; i < nCapas; ++i) {
// Las siguientes matrices de pesos tienen tantas filas como neuronas en dicha capa
// y tantas columnas como entradas a esa capa, que van a ser las salidas de
// la capa anterior.
// Las salidas de la capa anterior es igual al nro de neuronas en la capa anterior.
pesos.push_back(randu<mat>(estructura(i), estructura(i - 1)));
}
double tasaError = 0;
// Ciclo de las epocas
for (int epoca = 1; epoca <= nEpocas; ++epoca) {
// Ciclo para una época
tie(pesos, tasaError) = epocaMulticapa(patronesExt,
salidaDeseada,
tasaAprendizaje,
pesos);
if (tasaError < toleranciaError)
break;
}
// Fin ciclo (epocas)
return {pesos, tasaError};
}
<|endoftext|>
|
<commit_before>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2011,2012 Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "conf.hh"
#include "dparse.h"
#include "helper.hh"
#include "history.hh"
#include <cstring>
#ifndef DROI
#include <glib.h>
#else
#endif
extern "C" {
extern D_ParserTables parser_tables_conf;
}
extern Conf* conf_obj;
#define RETURN_ERROR_VOID(s) { \
set_exitvalue(on_error); \
log.pop(); \
status=false; \
errormsg=s; \
return; \
}
#define RETURN_ERROR_VERDICT(s) { \
set_exitvalue(on_error); \
log.pop(); \
status=false; \
errormsg=s; \
return Verdict::ERROR; \
}
void Conf::load(std::string& name,std::string& content)
{
D_Parser *p = new_D_Parser(&parser_tables_conf, 512);
p->loc.pathname = name.c_str();
char *s;
Conf* tmp=conf_obj;
log.push("conf_load");
log.debug("Conf::load %s",name.c_str());
conf_obj=this;
s=readfile(name.c_str());
std::string ss(s);
ss=ss+"\n"+content;
if ((name!="" && s==NULL))
RETURN_ERROR_VOID("Loading \"" + name + "\" failed.");
if (ss=="")
RETURN_ERROR_VOID("Empthy configuration");
bool ret=dparse(p,(char*)ss.c_str(),std::strlen(ss.c_str()));
ret=p->syntax_errors==0 && ret;
if (!ret)
RETURN_ERROR_VOID("Parsing \"" + name + "\" failed.");
free(s);
free_D_Parser(p);
conf_obj=tmp;
if ((heuristic=HeuristicFactory::create(log, heuristic_name, heuristic_param)) == NULL)
RETURN_ERROR_VOID("Creating heuristic \"" + heuristic_name + "\" failed.");
if (heuristic->status==false)
RETURN_ERROR_VOID("Error in heuristic \"" + heuristic_name + "\":" +
heuristic->errormsg);
if ((model=Model::create(log, model_name, model_param)) == NULL) {
RETURN_ERROR_VOID("Creating model loader \"" +
filetype(model_name)
+ "\" failed.");
}
Coverage* coverage = CoverageFactory::create(log,coverage_name,coverage_param);
if (coverage == NULL)
RETURN_ERROR_VOID("Creating coverage \"" + coverage_name + "\" failed.");
if (!coverage->status)
RETURN_ERROR_VOID("Coverage error on \"" + coverage_name + "\":" + coverage->errormsg);
if (!model->status || !model->init() || !model->reset())
RETURN_ERROR_VOID("Model error: " + model->stringify());
heuristic->set_coverage(coverage);
heuristic->set_model(model);
coverage->set_model(model);
adapter = AdapterFactory::create(log, adapter_name, adapter_param);
if (adapter && !adapter->status) {
status=false;
errormsg=adapter->errormsg;
return;
}
/* handle history */
for(unsigned i=0;i<history.size();i++) {
std::string name,param;
split(*history[i],name,param);
History* h=HistoryFactory::create(log, name, param);
if (h) {
h->set_coverage(coverage,model);
if (!h->status) {
RETURN_ERROR_VOID(h->errormsg);
}
} else {
RETURN_ERROR_VOID("Creating history \""+ *history[i] + "\" failed");
}
}
if (adapter == NULL)
RETURN_ERROR_VOID("Creating adapter \"" + adapter_name + "\" failed.");
adapter->set_actions(&model->getActionNames());
if (!coverage->status)
RETURN_ERROR_VOID("Coverage error: " + coverage->stringify());
if (!adapter->status)
RETURN_ERROR_VOID("Adapter error: " + adapter->stringify());
log.pop();
}
#include <sstream>
std::string Conf::stringify() {
std::ostringstream t(std::ios::out | std::ios::binary);
if (!status) {
return errormsg;
}
t << "model = \"" << removehash(model_name) << capsulate(model->stringify()) << std::endl;
t << "heuristic = \"" << heuristic_name << "\"" << std::endl;
t << "coverage = \"" << coverage_name << "\"" << std::endl;
t << "adapter = \"" << removehash(adapter_name) << ":"
<< removehash(adapter_param)
<< capsulate(adapter->stringify()) << std::endl;
/* TODO: stringify end conditions */
return t.str();
}
Verdict::Verdict Conf::execute(bool interactive) {
Policy policy;
log.push("conf_execute");
if (!status) {
errormsg = "cannot start executing test due to earlier errors: " + errormsg;
return Verdict::ERROR;
}
if (!adapter->init())
RETURN_ERROR_VERDICT("Initialising adapter failed: " + adapter->stringify());
// Validate and finish existing end_conditions
{
bool end_by_coverage = false;
for (unsigned int i = 0; i < end_conditions.size(); i++) {
End_condition* e = end_conditions[i];
if (e->status == false)
RETURN_ERROR_VERDICT("Error in end condition: " + e->stringify());
if (e->counter == End_condition::STATETAG) {
// avoid string comparisons, fetch the index of the tag
e->param_long = find(model->getSPNames(), *(e->param));
}
if (e->counter == End_condition::COVERAGE) {
end_by_coverage = true;
}
if (e->counter == End_condition::DURATION) {
end_time = e->param_time;
}
}
// Add default end conditions (if coverage is reached, test is passed)
if (!end_by_coverage) {
end_conditions.push_back(
new End_condition(Verdict::PASS, End_condition::COVERAGE, new std::string("1.0")));
}
}
Test_engine engine(*heuristic,*adapter,log,policy,end_conditions);
if (interactive) {
engine.interactive();
} else {
Verdict::Verdict v = engine.run(end_time);
switch (v) {
case Verdict::FAIL: {
set_exitvalue(on_fail);
// Test failed. Continue according to the on_error
// configuration. In addition to the following it could at
// somepoint specify a shell command (for instance, package and
// send log files, etc.)
if (on_fail == "interactive")
engine.interactive();
break;
}
case Verdict::PASS: {
// Test passed
set_exitvalue(on_pass);
break;
}
case Verdict::INCONCLUSIVE: {
set_exitvalue(on_inconc);
break;
}
case Verdict::ERROR: {
RETURN_ERROR_VERDICT(engine.verdict_msg() + ": " + engine.reason_msg());
break;
}
default: {
// unknown verdict?
}
}
}
log.pop();
status = true;
errormsg = engine.verdict_msg() + ": " + engine.reason_msg();
return engine.verdict();
}
void Conf::set_exitvalue(std::string& s)
{
std::string cmd;
std::string value;
split(s,cmd,value);
exit_status=atoi(value.c_str());
}
void Conf::set_observe_sleep(std::string &s)
{
Adapter::sleeptime=atoi(s.c_str());
}
<commit_msg>Fix core-dumping on configuration file read error<commit_after>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2011,2012 Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "conf.hh"
#include "dparse.h"
#include "helper.hh"
#include "history.hh"
#include <cstring>
#ifndef DROI
#include <glib.h>
#else
#endif
extern "C" {
extern D_ParserTables parser_tables_conf;
}
extern Conf* conf_obj;
#define RETURN_ERROR_VOID(s) { \
set_exitvalue(on_error); \
log.pop(); \
status=false; \
errormsg=s; \
return; \
}
#define RETURN_ERROR_VERDICT(s) { \
set_exitvalue(on_error); \
log.pop(); \
status=false; \
errormsg=s; \
return Verdict::ERROR; \
}
void Conf::load(std::string& name,std::string& content)
{
D_Parser *p = new_D_Parser(&parser_tables_conf, 512);
p->loc.pathname = name.c_str();
char *s;
log.push("conf_load");
log.debug("Conf::load %s",name.c_str());
s=readfile(name.c_str());
if (s==NULL) {
status=false;
errormsg=std::string("Can't read configuration file \"")+name+"\"";
log.pop();
return;
}
Conf* tmp=conf_obj;
conf_obj=this;
std::string ss(s);
ss=ss+"\n"+content;
if ((name!="" && s==NULL))
RETURN_ERROR_VOID("Loading \"" + name + "\" failed.");
if (ss=="")
RETURN_ERROR_VOID("Empthy configuration");
bool ret=dparse(p,(char*)ss.c_str(),std::strlen(ss.c_str()));
ret=p->syntax_errors==0 && ret;
if (!ret)
RETURN_ERROR_VOID("Parsing \"" + name + "\" failed.");
free(s);
free_D_Parser(p);
conf_obj=tmp;
if ((heuristic=HeuristicFactory::create(log, heuristic_name, heuristic_param)) == NULL)
RETURN_ERROR_VOID("Creating heuristic \"" + heuristic_name + "\" failed.");
if (heuristic->status==false)
RETURN_ERROR_VOID("Error in heuristic \"" + heuristic_name + "\":" +
heuristic->errormsg);
if ((model=Model::create(log, model_name, model_param)) == NULL) {
RETURN_ERROR_VOID("Creating model loader \"" +
filetype(model_name)
+ "\" failed.");
}
Coverage* coverage = CoverageFactory::create(log,coverage_name,coverage_param);
if (coverage == NULL)
RETURN_ERROR_VOID("Creating coverage \"" + coverage_name + "\" failed.");
if (!coverage->status)
RETURN_ERROR_VOID("Coverage error on \"" + coverage_name + "\":" + coverage->errormsg);
if (!model->status || !model->init() || !model->reset())
RETURN_ERROR_VOID("Model error: " + model->stringify());
heuristic->set_coverage(coverage);
heuristic->set_model(model);
coverage->set_model(model);
adapter = AdapterFactory::create(log, adapter_name, adapter_param);
if (adapter && !adapter->status) {
status=false;
errormsg=adapter->errormsg;
return;
}
/* handle history */
for(unsigned i=0;i<history.size();i++) {
std::string name,param;
split(*history[i],name,param);
History* h=HistoryFactory::create(log, name, param);
if (h) {
h->set_coverage(coverage,model);
if (!h->status) {
RETURN_ERROR_VOID(h->errormsg);
}
} else {
RETURN_ERROR_VOID("Creating history \""+ *history[i] + "\" failed");
}
}
if (adapter == NULL)
RETURN_ERROR_VOID("Creating adapter \"" + adapter_name + "\" failed.");
adapter->set_actions(&model->getActionNames());
if (!coverage->status)
RETURN_ERROR_VOID("Coverage error: " + coverage->stringify());
if (!adapter->status)
RETURN_ERROR_VOID("Adapter error: " + adapter->stringify());
log.pop();
}
#include <sstream>
std::string Conf::stringify() {
std::ostringstream t(std::ios::out | std::ios::binary);
if (!status) {
return errormsg;
}
t << "model = \"" << removehash(model_name) << capsulate(model->stringify()) << std::endl;
t << "heuristic = \"" << heuristic_name << "\"" << std::endl;
t << "coverage = \"" << coverage_name << "\"" << std::endl;
t << "adapter = \"" << removehash(adapter_name) << ":"
<< removehash(adapter_param)
<< capsulate(adapter->stringify()) << std::endl;
/* TODO: stringify end conditions */
return t.str();
}
Verdict::Verdict Conf::execute(bool interactive) {
Policy policy;
log.push("conf_execute");
if (!status) {
errormsg = "cannot start executing test due to earlier errors: " + errormsg;
return Verdict::ERROR;
}
if (!adapter->init())
RETURN_ERROR_VERDICT("Initialising adapter failed: " + adapter->stringify());
// Validate and finish existing end_conditions
{
bool end_by_coverage = false;
for (unsigned int i = 0; i < end_conditions.size(); i++) {
End_condition* e = end_conditions[i];
if (e->status == false)
RETURN_ERROR_VERDICT("Error in end condition: " + e->stringify());
if (e->counter == End_condition::STATETAG) {
// avoid string comparisons, fetch the index of the tag
e->param_long = find(model->getSPNames(), *(e->param));
}
if (e->counter == End_condition::COVERAGE) {
end_by_coverage = true;
}
if (e->counter == End_condition::DURATION) {
end_time = e->param_time;
}
}
// Add default end conditions (if coverage is reached, test is passed)
if (!end_by_coverage) {
end_conditions.push_back(
new End_condition(Verdict::PASS, End_condition::COVERAGE, new std::string("1.0")));
}
}
Test_engine engine(*heuristic,*adapter,log,policy,end_conditions);
if (interactive) {
engine.interactive();
} else {
Verdict::Verdict v = engine.run(end_time);
switch (v) {
case Verdict::FAIL: {
set_exitvalue(on_fail);
// Test failed. Continue according to the on_error
// configuration. In addition to the following it could at
// somepoint specify a shell command (for instance, package and
// send log files, etc.)
if (on_fail == "interactive")
engine.interactive();
break;
}
case Verdict::PASS: {
// Test passed
set_exitvalue(on_pass);
break;
}
case Verdict::INCONCLUSIVE: {
set_exitvalue(on_inconc);
break;
}
case Verdict::ERROR: {
RETURN_ERROR_VERDICT(engine.verdict_msg() + ": " + engine.reason_msg());
break;
}
default: {
// unknown verdict?
}
}
}
log.pop();
status = true;
errormsg = engine.verdict_msg() + ": " + engine.reason_msg();
return engine.verdict();
}
void Conf::set_exitvalue(std::string& s)
{
std::string cmd;
std::string value;
split(s,cmd,value);
exit_status=atoi(value.c_str());
}
void Conf::set_observe_sleep(std::string &s)
{
Adapter::sleeptime=atoi(s.c_str());
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestSpiderPlotActor.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// This tests the spider plot capabilities in VTK.
#include "vtkSpiderPlotActor.h"
#include "vtkFloatArray.h"
#include "vtkDataObject.h"
#include "vtkFieldData.h"
#include "vtkMath.h"
#include "vtkTextProperty.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkPolyData.h"
#include "vtkPoints.h"
#include "vtkIdList.h"
#include "vtkProperty2D.h"
#include "vtkLegendBoxActor.h"
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
//----------------------------------------------------------------------------
int TestSpiderPlotActor( int argc, char * argv [] )
{
int numTuples = 12;
vtkFloatArray *bitter = vtkFloatArray::New();
bitter->SetNumberOfTuples(numTuples);
vtkFloatArray *crispy = vtkFloatArray::New();
crispy->SetNumberOfTuples(numTuples);
vtkFloatArray *crunchy = vtkFloatArray::New();
crunchy->SetNumberOfTuples(numTuples);
vtkFloatArray *salty = vtkFloatArray::New();
salty->SetNumberOfTuples(numTuples);
vtkFloatArray *oily = vtkFloatArray::New();
oily->SetNumberOfTuples(numTuples);
for (int i=0; i<numTuples; i++)
{
bitter->SetTuple1(i, vtkMath::Random(1,10));
crispy->SetTuple1(i, vtkMath::Random(-1,1));
crunchy->SetTuple1(i, vtkMath::Random(1,100));
salty->SetTuple1(i, vtkMath::Random(0,10));
oily->SetTuple1(i, vtkMath::Random(5,25));
}
vtkDataObject *dobj = vtkDataObject::New();
dobj->GetFieldData()->AddArray(bitter);
dobj->GetFieldData()->AddArray(crispy);
dobj->GetFieldData()->AddArray(crunchy);
dobj->GetFieldData()->AddArray(salty);
dobj->GetFieldData()->AddArray(oily);
vtkSpiderPlotActor *actor = vtkSpiderPlotActor::New();
actor->SetInput(dobj);
actor->SetTitle("Spider Plot");
actor->SetIndependentVariablesToColumns();
actor->GetPositionCoordinate()->SetValue(0.05,0.1,0.0);
actor->GetPosition2Coordinate()->SetValue(0.95,0.85,0.0);
actor->GetProperty()->SetColor(1,0,0);
actor->SetAxisLabel(0,"Bitter");
actor->SetAxisRange(0,1,10);
actor->SetAxisLabel(1,"Crispy");
actor->SetAxisRange(1,-1,1);
actor->SetAxisLabel(2,"Crunchy");
actor->SetAxisRange(2,1,100);
actor->SetAxisLabel(3,"Salty");
actor->SetAxisRange(3,0,10);
actor->SetAxisLabel(4,"Oily");
actor->SetAxisRange(4,5,25);
actor->GetLegendActor()->SetNumberOfEntries(numTuples);
for (int i=0; i<numTuples; i++)
{
double red=vtkMath::Random(0,255);
double green=vtkMath::Random(0,255);
double blue=vtkMath::Random(0,255);
actor->SetPlotColor(i,red,green,blue);
}
actor->LegendVisibilityOn();
// Set text colors (same as actor for backward compat with test)
actor->GetTitleTextProperty()->SetColor(1,1,0);
actor->GetLabelTextProperty()->SetColor(1,0,0);
// Create the RenderWindow, Renderer and both Actors
vtkRenderer *ren1 = vtkRenderer::New();
vtkRenderWindow *renWin = vtkRenderWindow::New();
renWin->AddRenderer(ren1);
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow(renWin);
ren1->AddActor(actor);
ren1->SetBackground(0,0,0);
renWin->SetSize(500,200);
// render the image
renWin->Render();
int retVal = vtkRegressionTestImage( renWin );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
bitter->Delete();
crispy->Delete();
crunchy->Delete();
salty->Delete();
oily->Delete();
dobj->Delete();
actor->Delete();
ren1->Delete();
renWin->Delete();
iren->Delete();
return !retVal;
}
<commit_msg>BUG: Use correct range for color components in test code. New image corresponds to new test code. Old test code was using incorrect values for color components, colors have changed in the expected output image.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestSpiderPlotActor.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// This tests the spider plot capabilities in VTK.
#include "vtkSpiderPlotActor.h"
#include "vtkFloatArray.h"
#include "vtkDataObject.h"
#include "vtkFieldData.h"
#include "vtkMath.h"
#include "vtkTextProperty.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkPolyData.h"
#include "vtkPoints.h"
#include "vtkIdList.h"
#include "vtkProperty2D.h"
#include "vtkLegendBoxActor.h"
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
//----------------------------------------------------------------------------
int TestSpiderPlotActor( int argc, char * argv [] )
{
int numTuples = 12;
vtkFloatArray *bitter = vtkFloatArray::New();
bitter->SetNumberOfTuples(numTuples);
vtkFloatArray *crispy = vtkFloatArray::New();
crispy->SetNumberOfTuples(numTuples);
vtkFloatArray *crunchy = vtkFloatArray::New();
crunchy->SetNumberOfTuples(numTuples);
vtkFloatArray *salty = vtkFloatArray::New();
salty->SetNumberOfTuples(numTuples);
vtkFloatArray *oily = vtkFloatArray::New();
oily->SetNumberOfTuples(numTuples);
for (int i=0; i<numTuples; i++)
{
bitter->SetTuple1(i, vtkMath::Random(1,10));
crispy->SetTuple1(i, vtkMath::Random(-1,1));
crunchy->SetTuple1(i, vtkMath::Random(1,100));
salty->SetTuple1(i, vtkMath::Random(0,10));
oily->SetTuple1(i, vtkMath::Random(5,25));
}
vtkDataObject *dobj = vtkDataObject::New();
dobj->GetFieldData()->AddArray(bitter);
dobj->GetFieldData()->AddArray(crispy);
dobj->GetFieldData()->AddArray(crunchy);
dobj->GetFieldData()->AddArray(salty);
dobj->GetFieldData()->AddArray(oily);
vtkSpiderPlotActor *actor = vtkSpiderPlotActor::New();
actor->SetInput(dobj);
actor->SetTitle("Spider Plot");
actor->SetIndependentVariablesToColumns();
actor->GetPositionCoordinate()->SetValue(0.05,0.1,0.0);
actor->GetPosition2Coordinate()->SetValue(0.95,0.85,0.0);
actor->GetProperty()->SetColor(1,0,0);
actor->SetAxisLabel(0,"Bitter");
actor->SetAxisRange(0,1,10);
actor->SetAxisLabel(1,"Crispy");
actor->SetAxisRange(1,-1,1);
actor->SetAxisLabel(2,"Crunchy");
actor->SetAxisRange(2,1,100);
actor->SetAxisLabel(3,"Salty");
actor->SetAxisRange(3,0,10);
actor->SetAxisLabel(4,"Oily");
actor->SetAxisRange(4,5,25);
actor->GetLegendActor()->SetNumberOfEntries(numTuples);
for (int i=0; i<numTuples; i++)
{
double red=vtkMath::Random(0,1);
double green=vtkMath::Random(0,1);
double blue=vtkMath::Random(0,1);
actor->SetPlotColor(i,red,green,blue);
}
actor->LegendVisibilityOn();
// Set text colors (same as actor for backward compat with test)
actor->GetTitleTextProperty()->SetColor(1,1,0);
actor->GetLabelTextProperty()->SetColor(1,0,0);
// Create the RenderWindow, Renderer and both Actors
vtkRenderer *ren1 = vtkRenderer::New();
vtkRenderWindow *renWin = vtkRenderWindow::New();
renWin->AddRenderer(ren1);
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow(renWin);
ren1->AddActor(actor);
ren1->SetBackground(0,0,0);
renWin->SetSize(500,200);
// render the image
renWin->Render();
int retVal = vtkRegressionTestImage( renWin );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
bitter->Delete();
crispy->Delete();
crunchy->Delete();
salty->Delete();
oily->Delete();
dobj->Delete();
actor->Delete();
ren1->Delete();
renWin->Delete();
iren->Delete();
return !retVal;
}
<|endoftext|>
|
<commit_before>//===--- Errors.cpp - Error reporting utilities ---------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Utilities for reporting errors to stderr, system console, and crash logs.
//
//===----------------------------------------------------------------------===//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <pthread.h>
#include <stdarg.h>
#include "swift/Runtime/Debug.h"
#include "swift/Runtime/Mutex.h"
#include "swift/Basic/Demangle.h"
#include <cxxabi.h>
#if !defined(__CYGWIN__) && !defined(__ANDROID__)
// execinfo.h is not available on Android. Checks in this file ensure that
// fatalError behaves as expected, but without stack traces.
#include <execinfo.h>
#endif
#ifdef __APPLE__
#include <asl.h>
#endif
namespace FatalErrorFlags {
enum: uint32_t {
ReportBacktrace = 1 << 0
};
} // end namespace FatalErrorFlags
#if !defined(__CYGWIN__) && !defined(__ANDROID__)
LLVM_ATTRIBUTE_ALWAYS_INLINE
static bool
isIdentifier(char c)
{
return isalnum(c) || c == '_' || c == '$';
}
static bool
demangledLinePrefix(std::string line, std::string prefix,
std::string &out,
bool (*demangle)(std::string, std::string &))
{
int symbolStart = -1;
int symbolEnd = -1;
for (size_t i = 0; i < line.size(); i++) {
char c = line[i];
bool hasBegun = symbolStart != -1;
bool isIdentifierChar = isIdentifier(c);
bool isEndOfSymbol = hasBegun && !isIdentifierChar;
bool isEndOfLine = i == line.size() - 1;
if (isEndOfLine || isEndOfSymbol) {
symbolEnd = i;
break;
}
bool canFindPrefix = (line.size() - 2) - i > prefix.size();
if (!hasBegun && canFindPrefix && !isIdentifierChar &&
line.substr(i + 1, prefix.size()) == prefix) {
symbolStart = i + 1;
continue;
}
}
if (symbolStart == -1 || symbolEnd == -1) {
out = line;
return false;
} else {
auto symbol = line.substr(symbolStart, symbolEnd - symbolStart);
std::string demangled;
bool success = demangle(symbol, demangled);
if (success) {
line.replace(symbolStart, symbolEnd - symbolStart, demangled);
}
out = line;
return success;
}
}
static std::string
demangledLine(std::string line) {
std::string res;
bool success = false;
auto cppPrefix = "_Z"; // not sure how to check for DARWIN's __Z here.
success = demangledLinePrefix(line, cppPrefix, res,
[](std::string symbol, std::string &out) {
int status;
auto demangled = abi::__cxa_demangle(symbol.c_str(), 0, 0, &status);
if (demangled == NULL || status != 0) {
out = symbol;
return false;
} else {
out = demangled;
free(demangled);
return true;
}
});
if (success) return res;
success = demangledLinePrefix(line, "_T", res,
[](std::string symbol, std::string &out) {
out = swift::Demangle::demangleSymbolAsString(symbol);
return true;
});
if (success) return res;
return line;
}
const int STACK_DEPTH = 128;
static char **
reportBacktrace(int *count)
{
void **addrs = (void **)malloc(sizeof(void *) * STACK_DEPTH);
if (addrs == NULL) {
if (count) *count = 0;
return NULL;
}
int symbolCount = backtrace(addrs, STACK_DEPTH);
if (count) *count = symbolCount;
char **symbols = backtrace_symbols(addrs, symbolCount);
free(addrs);
if (symbols == NULL) {
if (count) *count = 0;
return NULL;
}
return symbols;
}
#endif
#ifdef SWIFT_HAVE_CRASHREPORTERCLIENT
#include <malloc/malloc.h>
// Instead of linking to CrashReporterClient.a (because it complicates the
// build system), define the only symbol from that static archive ourselves.
//
// The layout of this struct is CrashReporter ABI, so there are no ABI concerns
// here.
extern "C" {
CRASH_REPORTER_CLIENT_HIDDEN
struct crashreporter_annotations_t gCRAnnotations
__attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION))) = {
CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0, 0};
}
// Report a message to any forthcoming crash log.
static void
reportOnCrash(uint32_t flags, const char *message)
{
// We must use an "unsafe" mutex in this pathway since the normal "safe"
// mutex calls fatalError when an error is detected and fatalError ends up
// calling us. In other words we could get infinite recursion if the
// mutex errors.
static swift::StaticUnsafeMutex crashlogLock();
crashlogLock.lock();
char *oldMessage = (char *)CRGetCrashLogMessage();
char *newMessage;
if (oldMessage) {
asprintf(&newMessage, "%s%s", oldMessage, message);
if (malloc_size(oldMessage)) free(oldMessage);
} else {
newMessage = strdup(message);
}
CRSetCrashLogMessage(newMessage);
crashlogLock.unlock();
}
#else
static void
reportOnCrash(uint32_t flags, const char *message)
{
// empty
}
#endif
// Report a message to system console and stderr.
static void
reportNow(uint32_t flags, const char *message)
{
write(STDERR_FILENO, message, strlen(message));
#ifdef __APPLE__
asl_log(NULL, NULL, ASL_LEVEL_ERR, "%s", message);
#endif
#if !defined(__CYGWIN__) && !defined(__ANDROID__)
if (flags & FatalErrorFlags::ReportBacktrace) {
fputs("Current stack trace:\n", stderr);
int count = 0;
char **trace = reportBacktrace(&count);
for (int i = 0; i < count; i++) {
fprintf(stderr, "%s\n", demangledLine(trace[i]).c_str());
}
free(trace);
}
#endif
}
/// Report a fatal error to system console, stderr, and crash logs.
/// Does not crash by itself.
void swift::swift_reportError(uint32_t flags,
const char *message) {
reportNow(flags, message);
reportOnCrash(flags, message);
}
// Report a fatal error to system console, stderr, and crash logs, then abort.
LLVM_ATTRIBUTE_NORETURN
void
swift::fatalError(uint32_t flags, const char *format, ...)
{
va_list args;
va_start(args, format);
char *log;
vasprintf(&log, format, args);
swift_reportError(flags, log);
abort();
}
// Crash when a deleted method is called by accident.
SWIFT_RUNTIME_EXPORT
LLVM_ATTRIBUTE_NORETURN
extern "C" void
swift_deletedMethodError() {
swift::fatalError(/* flags = */ 0,
"fatal error: call of deleted method\n");
}
<commit_msg>Resolve ambiguity in mutex declaration<commit_after>//===--- Errors.cpp - Error reporting utilities ---------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Utilities for reporting errors to stderr, system console, and crash logs.
//
//===----------------------------------------------------------------------===//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <pthread.h>
#include <stdarg.h>
#include "swift/Runtime/Debug.h"
#include "swift/Runtime/Mutex.h"
#include "swift/Basic/Demangle.h"
#include <cxxabi.h>
#if !defined(__CYGWIN__) && !defined(__ANDROID__)
// execinfo.h is not available on Android. Checks in this file ensure that
// fatalError behaves as expected, but without stack traces.
#include <execinfo.h>
#endif
#ifdef __APPLE__
#include <asl.h>
#endif
namespace FatalErrorFlags {
enum: uint32_t {
ReportBacktrace = 1 << 0
};
} // end namespace FatalErrorFlags
#if !defined(__CYGWIN__) && !defined(__ANDROID__)
LLVM_ATTRIBUTE_ALWAYS_INLINE
static bool
isIdentifier(char c)
{
return isalnum(c) || c == '_' || c == '$';
}
static bool
demangledLinePrefix(std::string line, std::string prefix,
std::string &out,
bool (*demangle)(std::string, std::string &))
{
int symbolStart = -1;
int symbolEnd = -1;
for (size_t i = 0; i < line.size(); i++) {
char c = line[i];
bool hasBegun = symbolStart != -1;
bool isIdentifierChar = isIdentifier(c);
bool isEndOfSymbol = hasBegun && !isIdentifierChar;
bool isEndOfLine = i == line.size() - 1;
if (isEndOfLine || isEndOfSymbol) {
symbolEnd = i;
break;
}
bool canFindPrefix = (line.size() - 2) - i > prefix.size();
if (!hasBegun && canFindPrefix && !isIdentifierChar &&
line.substr(i + 1, prefix.size()) == prefix) {
symbolStart = i + 1;
continue;
}
}
if (symbolStart == -1 || symbolEnd == -1) {
out = line;
return false;
} else {
auto symbol = line.substr(symbolStart, symbolEnd - symbolStart);
std::string demangled;
bool success = demangle(symbol, demangled);
if (success) {
line.replace(symbolStart, symbolEnd - symbolStart, demangled);
}
out = line;
return success;
}
}
static std::string
demangledLine(std::string line) {
std::string res;
bool success = false;
auto cppPrefix = "_Z"; // not sure how to check for DARWIN's __Z here.
success = demangledLinePrefix(line, cppPrefix, res,
[](std::string symbol, std::string &out) {
int status;
auto demangled = abi::__cxa_demangle(symbol.c_str(), 0, 0, &status);
if (demangled == NULL || status != 0) {
out = symbol;
return false;
} else {
out = demangled;
free(demangled);
return true;
}
});
if (success) return res;
success = demangledLinePrefix(line, "_T", res,
[](std::string symbol, std::string &out) {
out = swift::Demangle::demangleSymbolAsString(symbol);
return true;
});
if (success) return res;
return line;
}
const int STACK_DEPTH = 128;
static char **
reportBacktrace(int *count)
{
void **addrs = (void **)malloc(sizeof(void *) * STACK_DEPTH);
if (addrs == NULL) {
if (count) *count = 0;
return NULL;
}
int symbolCount = backtrace(addrs, STACK_DEPTH);
if (count) *count = symbolCount;
char **symbols = backtrace_symbols(addrs, symbolCount);
free(addrs);
if (symbols == NULL) {
if (count) *count = 0;
return NULL;
}
return symbols;
}
#endif
#ifdef SWIFT_HAVE_CRASHREPORTERCLIENT
#include <malloc/malloc.h>
// Instead of linking to CrashReporterClient.a (because it complicates the
// build system), define the only symbol from that static archive ourselves.
//
// The layout of this struct is CrashReporter ABI, so there are no ABI concerns
// here.
extern "C" {
CRASH_REPORTER_CLIENT_HIDDEN
struct crashreporter_annotations_t gCRAnnotations
__attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION))) = {
CRASHREPORTER_ANNOTATIONS_VERSION, 0, 0, 0, 0, 0, 0, 0};
}
// Report a message to any forthcoming crash log.
static void
reportOnCrash(uint32_t flags, const char *message)
{
// We must use an "unsafe" mutex in this pathway since the normal "safe"
// mutex calls fatalError when an error is detected and fatalError ends up
// calling us. In other words we could get infinite recursion if the
// mutex errors.
static swift::StaticUnsafeMutex crashlogLock;
crashlogLock.lock();
char *oldMessage = (char *)CRGetCrashLogMessage();
char *newMessage;
if (oldMessage) {
asprintf(&newMessage, "%s%s", oldMessage, message);
if (malloc_size(oldMessage)) free(oldMessage);
} else {
newMessage = strdup(message);
}
CRSetCrashLogMessage(newMessage);
crashlogLock.unlock();
}
#else
static void
reportOnCrash(uint32_t flags, const char *message)
{
// empty
}
#endif
// Report a message to system console and stderr.
static void
reportNow(uint32_t flags, const char *message)
{
write(STDERR_FILENO, message, strlen(message));
#ifdef __APPLE__
asl_log(NULL, NULL, ASL_LEVEL_ERR, "%s", message);
#endif
#if !defined(__CYGWIN__) && !defined(__ANDROID__)
if (flags & FatalErrorFlags::ReportBacktrace) {
fputs("Current stack trace:\n", stderr);
int count = 0;
char **trace = reportBacktrace(&count);
for (int i = 0; i < count; i++) {
fprintf(stderr, "%s\n", demangledLine(trace[i]).c_str());
}
free(trace);
}
#endif
}
/// Report a fatal error to system console, stderr, and crash logs.
/// Does not crash by itself.
void swift::swift_reportError(uint32_t flags,
const char *message) {
reportNow(flags, message);
reportOnCrash(flags, message);
}
// Report a fatal error to system console, stderr, and crash logs, then abort.
LLVM_ATTRIBUTE_NORETURN
void
swift::fatalError(uint32_t flags, const char *format, ...)
{
va_list args;
va_start(args, format);
char *log;
vasprintf(&log, format, args);
swift_reportError(flags, log);
abort();
}
// Crash when a deleted method is called by accident.
SWIFT_RUNTIME_EXPORT
LLVM_ATTRIBUTE_NORETURN
extern "C" void
swift_deletedMethodError() {
swift::fatalError(/* flags = */ 0,
"fatal error: call of deleted method\n");
}
<|endoftext|>
|
<commit_before>//===-- ipcd.cpp ----------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implements IPCD interface, communicates with ipcd via control socket
//
//===----------------------------------------------------------------------===//
#include "ipcd.h"
#include "debug.h"
#include "real.h"
#include "rename_fd.h"
#include "magic_socket_nums.h"
#include "lock.h"
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
static int ipcd_socket = 0;
static int mypid = 0;
// Must match that used by server,
// currently defined in ipcd/clients.go
const char *SOCK_PATH = "/tmp/ipcd.sock";
const char *IPCD_BIN_PATH = "/bin/ipcd";
const useconds_t SLEEP_AFTER_IPCD_START_INTERVAL = 10 * 1000; // 10ms?
SimpleLock &getConnectLock() {
static SimpleLock ConnectLock;
return ConnectLock;
}
bool we_are_ipcd;
void check_if_we_are_ipcd() {
// man 3 program_invocation_name
extern char *program_invocation_short_name;
assert(program_invocation_short_name);
ipclog("program_invocation_short_name: %s\n", program_invocation_short_name);
we_are_ipcd = strcmp("ipcd", program_invocation_short_name) == 0;
}
void start_ipcd() {
int d = daemon(0, 0);
if (d == -1) {
perror("Failed to daemonize");
exit(1);
}
execl(IPCD_BIN_PATH, IPCD_BIN_PATH, (char *)NULL);
perror("Failed to exec ipcd");
exit(1);
}
void fork_ipcd() {
switch (__real_fork()) {
case -1:
break;
case 0:
// Child
start_ipcd();
assert(0 && "Exec failed?");
break;
default:
// Wait for ipcd to start :P
ipclog("Starting ipcd...\n");
}
}
void connect_to_ipcd() {
int s, len;
struct sockaddr_un remote;
if ((s = __real_socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)) == -1) {
perror("socket");
exit(1);
}
bool rename_success = rename_fd(s, MAGIC_SOCKET_FD, /* cloexec */ true);
assert(rename_success);
s = MAGIC_SOCKET_FD;
remote.sun_family = AF_UNIX;
strcpy(remote.sun_path, SOCK_PATH);
len = strlen(remote.sun_path) + sizeof(remote.sun_family);
if (__real_connect(s, (struct sockaddr *)&remote, len) == -1) {
// XXX: Super kludge!
// If we can't connect to daemon, assume it hasn't been
// started yet and attempt to run it ourselves.
// This code is terrible, and is likely to break
// badly in many situations, but works for now.
if (errno == ENOENT || errno == ECONNREFUSED) {
fork_ipcd();
int attempts = 0;
const int MAX_ATTEMPTS = 10;
while (attempts < MAX_ATTEMPTS) {
usleep(SLEEP_AFTER_IPCD_START_INTERVAL);
if (__real_connect(s, (struct sockaddr *)&remote, len) != -1)
break;
++attempts;
}
if (attempts == MAX_ATTEMPTS) {
perror("Unable to connect to ipcd after attempting to start it");
exit(1);
}
} else {
// Race with socket creation and permissions, maybe?
ipclog("Connect failed, attempting a few more times...\n");
int attempts = 0;
const int MAX_ATTEMPTS = 10;
while (attempts < MAX_ATTEMPTS) {
usleep(SLEEP_AFTER_IPCD_START_INTERVAL);
if (__real_connect(s, (struct sockaddr *)&remote, len) != -1)
break;
++attempts;
}
if (attempts == MAX_ATTEMPTS) {
perror("Connect to ipcd socket");
ipclog("Error connecting to ipcd?\n");
exit(1);
}
}
}
ipclog("Connected to IPCD, fd=%d\n", s);
mypid = getpid();
ipcd_socket = s;
}
void __ipcd_init() {
assert(ipcd_socket == 0);
check_if_we_are_ipcd();
if (ipcd_enabled())
connect_to_ipcd();
}
void __attribute__((destructor)) ipcd_dtor() {
ipclog("ipcd_dtor()!\n");
if (ipcd_socket == 0) {
ipclog("Exiting without establishing connection to ipcd...\n");
return;
}
assert(ipcd_socket != 0);
assert(mypid != 0);
// TODO: REMOVEALL is goodness, but we don't presently
// correctly associate PID's with endpoints they own in ipcd.
// Partially due to the mechanism for REREGISTER being
// performed 'eagerly' before the child PID is known,
// and partially due to a need to update ipcd's datastructures.
// This needs to be done eventually anyway, to provide
// access control restrictions on who can unregister,
// optimize, etc. a given endpoint.
// For now, explicitly unregister all endpoints we know we own.
// XXX: This is done in ipcopt.cpp since this code
// doesn't have access to our state table, just ipcd.
// Return instead of REMOVEALL to avoid
// duplicate UNREGISTER.
return;
char buf[100];
int len = sprintf(buf, "REMOVEALL %d\n", mypid);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
ipclog("Error sending ipcd REMOVEALL command in dtor: %s\n",
strerror(errno));
return;
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
const char *match = "200 REMOVED ";
size_t matchlen = strlen(match);
if (size_t(err) < matchlen) {
ipclog("Error receiving response from ipcd in dtor: %s\n", strerror(errno));
return;
}
bool success = (strncmp(buf, "200 REMOVED ", matchlen) == 0);
if (!success) {
ipclog("Failure, response=%s\n", buf);
}
if (success)
ipclog("Successfully unregistered all fd's\n");
else
ipclog("Failed to remove all fd's\n");
}
void connect_if_needed() {
if (mypid == getpid())
return;
ipclog("Reconnecting to ipcd in child...\n");
__real_close(ipcd_socket);
connect_to_ipcd();
}
endpoint ipcd_register_socket(int fd) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "REGISTER %d %d\n", getpid(), fd);
assert(len > 5);
assert(ipcd_socket);
// ipclog("REGISTER %d -->\n", fd);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
// ipclog("REGISTER %d <--\n", fd);
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
buf[err] = 0;
int id;
int n = sscanf(buf, "200 ID %d\n", &id);
assert(n == 1);
// ipclog("Registered and got endpoint id=%d\n", id);
return id;
}
bool ipcd_localize(endpoint local, endpoint remote) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "LOCALIZE %d %d\n", local, remote);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
return strncmp(buf, "200 OK\n", err) == 0;
}
// GETLOCALFD
int ipcd_getlocalfd(endpoint local) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "GETLOCALFD %d\n", local);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
int fd;
{
// Lots of magic
const size_t CONTROLLEN = CMSG_LEN(sizeof(int));
struct iovec iov[1];
struct msghdr msg;
struct cmsghdr *cmsg;
char cmsg_buf[CONTROLLEN];
cmsg = (struct cmsghdr *)cmsg_buf;
memset(&msg, 0, sizeof(msg));
iov[0].iov_base = buf;
iov[0].iov_len = sizeof(buf);
msg.msg_iov = iov;
msg.msg_iovlen = 1;
msg.msg_control = cmsg;
msg.msg_controllen = CONTROLLEN;
int ret = __real_recvmsg(ipcd_socket, &msg, MSG_NOSIGNAL);
if (ret <= 0) {
perror("recvmsg");
exit(1);
}
// TODO: Understand and fix mismatch between
// CONTROLLEN and msg.msg_controllen after recvmsg()!
memcpy(&fd, CMSG_DATA(cmsg), sizeof(int));
ipclog("received local fd %d for endpoint %d\n", fd, local);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
bool success = strncmp(buf, "200 OK\n", err) == 0;
assert(success);
return fd;
}
// UNREGISTER
bool ipcd_unregister_socket(endpoint ep) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "UNREGISTER %d\n", ep);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
return strncmp(buf, "200 OK\n", err) == 0;
}
// REREGISTER
bool ipcd_reregister_socket(endpoint ep, int fd) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "REREGISTER %d %d %d\n", ep, getpid(), fd);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
return strncmp(buf, "200 OK\n", err) == 0;
}
endpoint ipcd_endpoint_kludge(endpoint local) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "ENDPOINT_KLUDGE %d\n", local);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
buf[err] = 0;
int id;
ipclog("endpoint_kludge(%d) = %s\n", local, buf);
int n = sscanf(buf, "200 PAIR %d\n", &id);
if (n == 1) {
return id;
}
return EP_INVALID;
}
endpoint ipcd_crc_kludge(endpoint local, uint32_t s_crc, uint32_t r_crc,
bool last) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "THRESH_CRC_KLUDGE %d %d %d %d\n", local, s_crc, r_crc,
last ? 1 : 0);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
buf[err] = 0;
int id;
ipclog("crc_kludge(%d, %d, %d) = %s\n", local, s_crc, r_crc, buf);
int n = sscanf(buf, "200 PAIR %d\n", &id);
if (n == 1) {
return id;
}
return EP_INVALID;
}
bool ipcd_is_protected(int fd) {
return fd == ipcd_socket;
}
bool ipcd_enabled() {
static bool disabled = getenv("IPCD_DISABLE") || we_are_ipcd;
return !disabled;
}
<commit_msg>libipc: Be sure lock is released if assert fails or we exit.<commit_after>//===-- ipcd.cpp ----------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implements IPCD interface, communicates with ipcd via control socket
//
//===----------------------------------------------------------------------===//
#include "ipcd.h"
#include "debug.h"
#include "real.h"
#include "rename_fd.h"
#include "magic_socket_nums.h"
#include "lock.h"
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
static int ipcd_socket = 0;
static int mypid = 0;
// Must match that used by server,
// currently defined in ipcd/clients.go
const char *SOCK_PATH = "/tmp/ipcd.sock";
const char *IPCD_BIN_PATH = "/bin/ipcd";
const useconds_t SLEEP_AFTER_IPCD_START_INTERVAL = 10 * 1000; // 10ms?
SimpleLock &getConnectLock() {
static SimpleLock ConnectLock;
return ConnectLock;
}
#define ASSERT_WITH_LOCK(expr) \
((expr) ? __ASSERT_VOID_CAST(0) \
: unlock_and_assert_fail(__STRING(expr), __FILE__, __LINE__, \
__ASSERT_FUNCTION))
void unlock_and_assert_fail(const char *assertion, const char *file,
unsigned int line, const char *function) {
getConnectLock().Unlock();
__assert_fail(assertion, file, line, function);
}
bool we_are_ipcd;
void check_if_we_are_ipcd() {
// man 3 program_invocation_name
extern char *program_invocation_short_name;
assert(program_invocation_short_name);
ipclog("program_invocation_short_name: %s\n", program_invocation_short_name);
we_are_ipcd = strcmp("ipcd", program_invocation_short_name) == 0;
}
void start_ipcd() {
int d = daemon(0, 0);
if (d == -1) {
perror("Failed to daemonize");
exit(1);
}
execl(IPCD_BIN_PATH, IPCD_BIN_PATH, (char *)NULL);
perror("Failed to exec ipcd");
exit(1);
}
void fork_ipcd() {
switch (__real_fork()) {
case -1:
break;
case 0:
// Child
start_ipcd();
assert(0 && "Exec failed?");
break;
default:
// Wait for ipcd to start :P
ipclog("Starting ipcd...\n");
}
}
void connect_to_ipcd() {
int s, len;
struct sockaddr_un remote;
if ((s = __real_socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)) == -1) {
perror("socket");
exit(1);
}
bool rename_success = rename_fd(s, MAGIC_SOCKET_FD, /* cloexec */ true);
assert(rename_success);
s = MAGIC_SOCKET_FD;
remote.sun_family = AF_UNIX;
strcpy(remote.sun_path, SOCK_PATH);
len = strlen(remote.sun_path) + sizeof(remote.sun_family);
if (__real_connect(s, (struct sockaddr *)&remote, len) == -1) {
// XXX: Super kludge!
// If we can't connect to daemon, assume it hasn't been
// started yet and attempt to run it ourselves.
// This code is terrible, and is likely to break
// badly in many situations, but works for now.
if (errno == ENOENT || errno == ECONNREFUSED) {
fork_ipcd();
int attempts = 0;
const int MAX_ATTEMPTS = 10;
while (attempts < MAX_ATTEMPTS) {
usleep(SLEEP_AFTER_IPCD_START_INTERVAL);
if (__real_connect(s, (struct sockaddr *)&remote, len) != -1)
break;
++attempts;
}
if (attempts == MAX_ATTEMPTS) {
perror("Unable to connect to ipcd after attempting to start it");
exit(1);
}
} else {
// Race with socket creation and permissions, maybe?
ipclog("Connect failed, attempting a few more times...\n");
int attempts = 0;
const int MAX_ATTEMPTS = 10;
while (attempts < MAX_ATTEMPTS) {
usleep(SLEEP_AFTER_IPCD_START_INTERVAL);
if (__real_connect(s, (struct sockaddr *)&remote, len) != -1)
break;
++attempts;
}
if (attempts == MAX_ATTEMPTS) {
perror("Connect to ipcd socket");
ipclog("Error connecting to ipcd?\n");
exit(1);
}
}
}
ipclog("Connected to IPCD, fd=%d\n", s);
mypid = getpid();
ipcd_socket = s;
}
void __ipcd_init() {
assert(ipcd_socket == 0);
check_if_we_are_ipcd();
if (ipcd_enabled())
connect_to_ipcd();
}
void __attribute__((destructor)) ipcd_dtor() {
ipclog("ipcd_dtor()!\n");
if (ipcd_socket == 0) {
ipclog("Exiting without establishing connection to ipcd...\n");
return;
}
assert(ipcd_socket != 0);
assert(mypid != 0);
// TODO: REMOVEALL is goodness, but we don't presently
// correctly associate PID's with endpoints they own in ipcd.
// Partially due to the mechanism for REREGISTER being
// performed 'eagerly' before the child PID is known,
// and partially due to a need to update ipcd's datastructures.
// This needs to be done eventually anyway, to provide
// access control restrictions on who can unregister,
// optimize, etc. a given endpoint.
// For now, explicitly unregister all endpoints we know we own.
// XXX: This is done in ipcopt.cpp since this code
// doesn't have access to our state table, just ipcd.
// Return instead of REMOVEALL to avoid
// duplicate UNREGISTER.
return;
char buf[100];
int len = sprintf(buf, "REMOVEALL %d\n", mypid);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
ipclog("Error sending ipcd REMOVEALL command in dtor: %s\n",
strerror(errno));
return;
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
const char *match = "200 REMOVED ";
size_t matchlen = strlen(match);
if (size_t(err) < matchlen) {
ipclog("Error receiving response from ipcd in dtor: %s\n", strerror(errno));
return;
}
bool success = (strncmp(buf, "200 REMOVED ", matchlen) == 0);
if (!success) {
ipclog("Failure, response=%s\n", buf);
}
if (success)
ipclog("Successfully unregistered all fd's\n");
else
ipclog("Failed to remove all fd's\n");
}
void connect_if_needed() {
if (mypid == getpid())
return;
ipclog("Reconnecting to ipcd in child...\n");
__real_close(ipcd_socket);
connect_to_ipcd();
}
endpoint ipcd_register_socket(int fd) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "REGISTER %d %d\n", getpid(), fd);
ASSERT_WITH_LOCK(len > 5);
ASSERT_WITH_LOCK(ipcd_socket);
// ipclog("REGISTER %d -->\n", fd);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
ASSERT_WITH_LOCK(0);
}
// ipclog("REGISTER %d <--\n", fd);
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
ASSERT_WITH_LOCK(err > 5);
buf[err] = 0;
int id;
int n = sscanf(buf, "200 ID %d\n", &id);
ASSERT_WITH_LOCK(n == 1);
// ipclog("Registered and got endpoint id=%d\n", id);
return id;
}
bool ipcd_localize(endpoint local, endpoint remote) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "LOCALIZE %d %d\n", local, remote);
ASSERT_WITH_LOCK(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
ASSERT_WITH_LOCK(0);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
ASSERT_WITH_LOCK(err > 5);
return strncmp(buf, "200 OK\n", err) == 0;
}
// GETLOCALFD
int ipcd_getlocalfd(endpoint local) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "GETLOCALFD %d\n", local);
ASSERT_WITH_LOCK(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
ASSERT_WITH_LOCK(0);
}
int fd;
{
// Lots of magic
const size_t CONTROLLEN = CMSG_LEN(sizeof(int));
struct iovec iov[1];
struct msghdr msg;
struct cmsghdr *cmsg;
char cmsg_buf[CONTROLLEN];
cmsg = (struct cmsghdr *)cmsg_buf;
memset(&msg, 0, sizeof(msg));
iov[0].iov_base = buf;
iov[0].iov_len = sizeof(buf);
msg.msg_iov = iov;
msg.msg_iovlen = 1;
msg.msg_control = cmsg;
msg.msg_controllen = CONTROLLEN;
int ret = __real_recvmsg(ipcd_socket, &msg, MSG_NOSIGNAL);
if (ret <= 0) {
perror("recvmsg");
ASSERT_WITH_LOCK(0);
}
// TODO: Understand and fix mismatch between
// CONTROLLEN and msg.msg_controllen after recvmsg()!
memcpy(&fd, CMSG_DATA(cmsg), sizeof(int));
ipclog("received local fd %d for endpoint %d\n", fd, local);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
ASSERT_WITH_LOCK(err > 5);
bool success = strncmp(buf, "200 OK\n", err) == 0;
ASSERT_WITH_LOCK(success);
return fd;
}
// UNREGISTER
bool ipcd_unregister_socket(endpoint ep) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "UNREGISTER %d\n", ep);
ASSERT_WITH_LOCK(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
ASSERT_WITH_LOCK(0);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
ASSERT_WITH_LOCK(err > 5);
return strncmp(buf, "200 OK\n", err) == 0;
}
// REREGISTER
bool ipcd_reregister_socket(endpoint ep, int fd) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "REREGISTER %d %d %d\n", ep, getpid(), fd);
ASSERT_WITH_LOCK(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
ASSERT_WITH_LOCK(0);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
ASSERT_WITH_LOCK(err > 5);
return strncmp(buf, "200 OK\n", err) == 0;
}
endpoint ipcd_endpoint_kludge(endpoint local) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "ENDPOINT_KLUDGE %d\n", local);
ASSERT_WITH_LOCK(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
ASSERT_WITH_LOCK(0);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
ASSERT_WITH_LOCK(err > 5);
buf[err] = 0;
int id;
ipclog("endpoint_kludge(%d) = %s\n", local, buf);
int n = sscanf(buf, "200 PAIR %d\n", &id);
if (n == 1) {
return id;
}
return EP_INVALID;
}
endpoint ipcd_crc_kludge(endpoint local, uint32_t s_crc, uint32_t r_crc,
bool last) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "THRESH_CRC_KLUDGE %d %d %d %d\n", local, s_crc, r_crc,
last ? 1 : 0);
ASSERT_WITH_LOCK(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
ASSERT_WITH_LOCK(0);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
ASSERT_WITH_LOCK(err > 5);
buf[err] = 0;
int id;
ipclog("crc_kludge(%d, %d, %d) = %s\n", local, s_crc, r_crc, buf);
int n = sscanf(buf, "200 PAIR %d\n", &id);
if (n == 1) {
return id;
}
return EP_INVALID;
}
bool ipcd_is_protected(int fd) {
return fd == ipcd_socket;
}
bool ipcd_enabled() {
static bool disabled = getenv("IPCD_DISABLE") || we_are_ipcd;
return !disabled;
}
<|endoftext|>
|
<commit_before>//===-- ipcd.cpp ----------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implements IPCD interface, communicates with ipcd via control socket
//
//===----------------------------------------------------------------------===//
#include "ipcd.h"
#include "debug.h"
// XXX: Shouldn't need to include this for _real_*
#include "socket_inline.h"
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stropts.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
static int ipcd_socket = 0;
static int mypid = 0;
// Must match that used by server,
// currently defined in ipcd/clients.go
const char *SOCK_PATH = "/tmp/ipcd.sock";
const char *IPCD_BIN_PATH = "/bin/ipcd";
const char *PRELOAD_PATH = "/etc/ld.so.preload";
const char *PRELOAD_TMP = "/tmp/preload.cfg";
void connect_to_ipcd() {
int s, t, len;
struct sockaddr_un remote;
if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
remote.sun_family = AF_UNIX;
strcpy(remote.sun_path, SOCK_PATH);
len = strlen(remote.sun_path) + sizeof(remote.sun_family);
if (connect(s, (struct sockaddr *)&remote, len) == -1) {
if (errno == ENOENT || errno == ECONNREFUSED) {
rename(PRELOAD_PATH, PRELOAD_TMP);
switch (fork()) {
case -1:
break;
case 0:
// Child
execl(IPCD_BIN_PATH, IPCD_BIN_PATH, 0);
perror("Failed to exec ipcd");
assert(0 && "Exec failed?");
break;
default:
// Wait for ipcd to start :P
ipclog("Starting ipcd...\n");
sleep(1);
}
rename(PRELOAD_TMP, PRELOAD_PATH);
if (connect(s, (struct sockaddr *)&remote, len) == -1) {
perror("connect-after-fork");
exit(1);
}
} else {
perror("connect");
ipclog("Error connecting to ipcd?\n");
exit(1);
}
}
ipclog("Connected to IPCD, fd=%d\n", s);
mypid = getpid();
ipcd_socket = s;
}
void __attribute__((constructor)) ipcd_init() {
assert(ipcd_socket == 0);
connect_to_ipcd();
}
void __attribute__((destructor)) ipcd_dtor() {
if (ipcd_socket == 0) {
ipclog("Exiting without establishing connection to ipcd...\n");
return;
}
assert(ipcd_socket != 0);
assert(mypid != 0);
char buf[100];
int len = sprintf(buf, "REMOVEALL %d\n", mypid);
assert(len > 5);
int err = __real_write(ipcd_socket, buf, len);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_read(ipcd_socket, buf, 50);
assert(err > 5);
const char *match = "200 REMOVED ";
size_t matchlen = strlen(match);
if (err < matchlen) {
perror("read");
exit(1);
}
bool success = (strncmp(buf, "200 REMOVED ", matchlen) == 0);
if (!success) {
ipclog("Failure, response=%s\n", buf);
}
assert(success && "Unable to unregister all fd's");
}
static volatile int connect_lock = 0;
void ipcd_lock() {
while (__sync_lock_test_and_set(&connect_lock, 1)) {
// wait
};
}
void ipcd_unlock() { __sync_lock_release(&connect_lock); }
struct IPCLock {
IPCLock() { ipcd_lock(); }
~IPCLock() { ipcd_unlock(); }
};
void connect_if_needed() {
if (mypid == getpid())
return;
ipclog("Reconnecting to ipcd in child...\n");
close(ipcd_socket);
connect_to_ipcd();
}
endpoint ipcd_register_socket(int fd) {
IPCLock();
connect_if_needed();
char buf[100];
int len = sprintf(buf, "REGISTER %d %d\n", getpid(), fd);
assert(len > 5);
assert(ipcd_socket);
// ipclog("REGISTER %d -->\n", fd);
int err = __real_write(ipcd_socket, buf, len);
if (err < 0) {
perror("write");
exit(1);
}
// ipclog("REGISTER %d <--\n", fd);
err = __real_read(ipcd_socket, buf, 50);
assert(err > 5);
buf[err] = 0;
int id;
int n = sscanf(buf, "200 ID %d\n", &id);
assert(n == 1);
// ipclog("Registered and got endpoint id=%d\n", id);
return id;
}
bool ipcd_localize(endpoint local, endpoint remote) {
IPCLock();
connect_if_needed();
char buf[100];
int len = sprintf(buf, "LOCALIZE %d %d\n", local, remote);
assert(len > 5);
int err = __real_write(ipcd_socket, buf, len);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_read(ipcd_socket, buf, 50);
assert(err > 5);
return strncmp(buf, "200 OK\n", err) == 0;
}
// GETLOCALFD
int ipcd_getlocalfd(endpoint local) {
IPCLock();
connect_if_needed();
char buf[100];
int len = sprintf(buf, "GETLOCALFD %d\n", local);
assert(len > 5);
int err = __real_write(ipcd_socket, buf, len);
if (err < 0) {
perror("write");
exit(1);
}
int fd;
{
// Lots of magic
const size_t CONTROLLEN = CMSG_LEN(sizeof(int));
struct iovec iov[1];
struct msghdr msg;
struct cmsghdr *cmsg;
char cmsg_buf[CONTROLLEN];
cmsg = (struct cmsghdr *)cmsg_buf;
memset(&msg, 0, sizeof(msg));
iov[0].iov_base = buf;
iov[0].iov_len = sizeof(buf);
msg.msg_iov = iov;
msg.msg_iovlen = 1;
msg.msg_control = cmsg;
msg.msg_controllen = CONTROLLEN;
int ret = recvmsg(ipcd_socket, &msg, 0);
if (ret <= 0) {
perror("recvmsg");
exit(1);
}
// TODO: Understand and fix mismatch between
// CONTROLLEN and msg.msg_controllen after recvmsg()!
fd = *(int *)CMSG_DATA(cmsg);
ipclog("received local fd %d for endpoint %d\n", fd, local);
}
err = __real_read(ipcd_socket, buf, 50);
assert(err > 5);
bool success = strncmp(buf, "200 OK\n", err) == 0;
assert(success);
return fd;
}
// UNREGISTER
bool ipcd_unregister_socket(endpoint ep) {
IPCLock();
connect_if_needed();
char buf[100];
int len = sprintf(buf, "UNREGISTER %d\n", ep);
assert(len > 5);
int err = __real_write(ipcd_socket, buf, len);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_read(ipcd_socket, buf, 50);
assert(err > 5);
return strncmp(buf, "200 OK\n", err) == 0;
}
<commit_msg>Add note ensuring readers are aware of how bad autostarting ipcd is :/<commit_after>//===-- ipcd.cpp ----------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implements IPCD interface, communicates with ipcd via control socket
//
//===----------------------------------------------------------------------===//
#include "ipcd.h"
#include "debug.h"
// XXX: Shouldn't need to include this for _real_*
#include "socket_inline.h"
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stropts.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
static int ipcd_socket = 0;
static int mypid = 0;
// Must match that used by server,
// currently defined in ipcd/clients.go
const char *SOCK_PATH = "/tmp/ipcd.sock";
const char *IPCD_BIN_PATH = "/bin/ipcd";
const char *PRELOAD_PATH = "/etc/ld.so.preload";
const char *PRELOAD_TMP = "/tmp/preload.cfg";
void connect_to_ipcd() {
int s, t, len;
struct sockaddr_un remote;
if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
remote.sun_family = AF_UNIX;
strcpy(remote.sun_path, SOCK_PATH);
len = strlen(remote.sun_path) + sizeof(remote.sun_family);
if (connect(s, (struct sockaddr *)&remote, len) == -1) {
// XXX: Super kludge!
// If we can't connect to daemon, assume it hasn't been
// started yet and attempt to run it ourselves.
// This code is terrible, and is likely to break
// badly in many situations, but works for now.
if (errno == ENOENT || errno == ECONNREFUSED) {
rename(PRELOAD_PATH, PRELOAD_TMP);
switch (fork()) {
case -1:
break;
case 0:
// Child
execl(IPCD_BIN_PATH, IPCD_BIN_PATH, 0);
perror("Failed to exec ipcd");
assert(0 && "Exec failed?");
break;
default:
// Wait for ipcd to start :P
ipclog("Starting ipcd...\n");
sleep(1);
}
rename(PRELOAD_TMP, PRELOAD_PATH);
if (connect(s, (struct sockaddr *)&remote, len) == -1) {
perror("connect-after-fork");
exit(1);
}
} else {
perror("connect");
ipclog("Error connecting to ipcd?\n");
exit(1);
}
}
ipclog("Connected to IPCD, fd=%d\n", s);
mypid = getpid();
ipcd_socket = s;
}
void __attribute__((constructor)) ipcd_init() {
assert(ipcd_socket == 0);
connect_to_ipcd();
}
void __attribute__((destructor)) ipcd_dtor() {
if (ipcd_socket == 0) {
ipclog("Exiting without establishing connection to ipcd...\n");
return;
}
assert(ipcd_socket != 0);
assert(mypid != 0);
char buf[100];
int len = sprintf(buf, "REMOVEALL %d\n", mypid);
assert(len > 5);
int err = __real_write(ipcd_socket, buf, len);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_read(ipcd_socket, buf, 50);
assert(err > 5);
const char *match = "200 REMOVED ";
size_t matchlen = strlen(match);
if (err < matchlen) {
perror("read");
exit(1);
}
bool success = (strncmp(buf, "200 REMOVED ", matchlen) == 0);
if (!success) {
ipclog("Failure, response=%s\n", buf);
}
assert(success && "Unable to unregister all fd's");
}
static volatile int connect_lock = 0;
void ipcd_lock() {
while (__sync_lock_test_and_set(&connect_lock, 1)) {
// wait
};
}
void ipcd_unlock() { __sync_lock_release(&connect_lock); }
struct IPCLock {
IPCLock() { ipcd_lock(); }
~IPCLock() { ipcd_unlock(); }
};
void connect_if_needed() {
if (mypid == getpid())
return;
ipclog("Reconnecting to ipcd in child...\n");
close(ipcd_socket);
connect_to_ipcd();
}
endpoint ipcd_register_socket(int fd) {
IPCLock();
connect_if_needed();
char buf[100];
int len = sprintf(buf, "REGISTER %d %d\n", getpid(), fd);
assert(len > 5);
assert(ipcd_socket);
// ipclog("REGISTER %d -->\n", fd);
int err = __real_write(ipcd_socket, buf, len);
if (err < 0) {
perror("write");
exit(1);
}
// ipclog("REGISTER %d <--\n", fd);
err = __real_read(ipcd_socket, buf, 50);
assert(err > 5);
buf[err] = 0;
int id;
int n = sscanf(buf, "200 ID %d\n", &id);
assert(n == 1);
// ipclog("Registered and got endpoint id=%d\n", id);
return id;
}
bool ipcd_localize(endpoint local, endpoint remote) {
IPCLock();
connect_if_needed();
char buf[100];
int len = sprintf(buf, "LOCALIZE %d %d\n", local, remote);
assert(len > 5);
int err = __real_write(ipcd_socket, buf, len);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_read(ipcd_socket, buf, 50);
assert(err > 5);
return strncmp(buf, "200 OK\n", err) == 0;
}
// GETLOCALFD
int ipcd_getlocalfd(endpoint local) {
IPCLock();
connect_if_needed();
char buf[100];
int len = sprintf(buf, "GETLOCALFD %d\n", local);
assert(len > 5);
int err = __real_write(ipcd_socket, buf, len);
if (err < 0) {
perror("write");
exit(1);
}
int fd;
{
// Lots of magic
const size_t CONTROLLEN = CMSG_LEN(sizeof(int));
struct iovec iov[1];
struct msghdr msg;
struct cmsghdr *cmsg;
char cmsg_buf[CONTROLLEN];
cmsg = (struct cmsghdr *)cmsg_buf;
memset(&msg, 0, sizeof(msg));
iov[0].iov_base = buf;
iov[0].iov_len = sizeof(buf);
msg.msg_iov = iov;
msg.msg_iovlen = 1;
msg.msg_control = cmsg;
msg.msg_controllen = CONTROLLEN;
int ret = recvmsg(ipcd_socket, &msg, 0);
if (ret <= 0) {
perror("recvmsg");
exit(1);
}
// TODO: Understand and fix mismatch between
// CONTROLLEN and msg.msg_controllen after recvmsg()!
fd = *(int *)CMSG_DATA(cmsg);
ipclog("received local fd %d for endpoint %d\n", fd, local);
}
err = __real_read(ipcd_socket, buf, 50);
assert(err > 5);
bool success = strncmp(buf, "200 OK\n", err) == 0;
assert(success);
return fd;
}
// UNREGISTER
bool ipcd_unregister_socket(endpoint ep) {
IPCLock();
connect_if_needed();
char buf[100];
int len = sprintf(buf, "UNREGISTER %d\n", ep);
assert(len > 5);
int err = __real_write(ipcd_socket, buf, len);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_read(ipcd_socket, buf, 50);
assert(err > 5);
return strncmp(buf, "200 OK\n", err) == 0;
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <magrathea.h>
#include <terrain.h>
#include <game.h>
#include <dynotree.h>
#include <heightmap.h>
#include <images.h>
#include <smallFern.h>
#include <heightmap.h>
#include <cmath>
#include <texture.h>
#include <stdlib.h>
GLuint texture = 0;
/// Constructs a new region at the given position
/// @param x The x coordinate of the origin
/// @param y The y coordinate of the origin
/// @param parent The game that this region is in.
Terrain::Terrain(glm::vec3 pos,Game* parent) : Object(pos,parent)
{
initialiseTriangles();
freeze();
shaderID = game->shaderManager->newShader("terrain",VERTEX_SHADER|GEOMETRY_SHADER|FRAGMENT_SHADER|TESSELATION_SHADER);
makeTexture();
texture = textureFromTGA("assets/grass.tga",true);
}
/// Constructs the triangles
void Terrain::initialiseTriangles()
{
clearTriangleData((NUMBER_OF_PATCHES+1)*(NUMBER_OF_PATCHES+1)*6,2);
for (int i= 0;i<NUMBER_OF_PATCHES+1;i++)
for (int j = 0;j<NUMBER_OF_PATCHES+1;j++)
{
addPoint((i*NUMBER_OF_PATCHES+j)*6,
glm::vec3(i*PATCH_SIZE,
0,
j*PATCH_SIZE),
glm::vec3(1,0,0),
1,1,1);
addPoint((i*NUMBER_OF_PATCHES+j)*6+1,
glm::vec3(i*PATCH_SIZE,
0,
j*PATCH_SIZE+PATCH_SIZE),
glm::vec3(1,0,0),
1,1,1);
addPoint((i*NUMBER_OF_PATCHES+j)*6+2,
glm::vec3(i*PATCH_SIZE+PATCH_SIZE,
0,
j*PATCH_SIZE+PATCH_SIZE),
glm::vec3(1,0,0),
1,1,1);
addPoint((i*NUMBER_OF_PATCHES+j)*6+3,
glm::vec3(i*PATCH_SIZE+PATCH_SIZE,
0,
j*PATCH_SIZE+PATCH_SIZE),
glm::vec3(1,0,0),
1,1,1);
addPoint((i*NUMBER_OF_PATCHES+j)*6+4,
glm::vec3(i*PATCH_SIZE+PATCH_SIZE,
0,
j*PATCH_SIZE),
glm::vec3(1,0,0),
1,1,1);
addPoint((i*NUMBER_OF_PATCHES+j)*6+5,
glm::vec3(i*PATCH_SIZE,
0,
j*PATCH_SIZE),
glm::vec3(1,0,0),
1,1,1);
}
pushTriangleData();
}
void Terrain::Render()
{
heightmapTexture->load();
texture->load();
game->shaderManager->loadShader(shaderID);
// Load our transformation matrix etc
game->shaderManager->getCurrentShader()->setObjectData(objectBO);
// Select this object's texture
glBindVertexArray(VAO);
glPatchParameteri(GL_PATCH_VERTICES,3);
glDrawArrays(GL_PATCHES,0,6*NUMBER_OF_PATCHES*NUMBER_OF_PATCHES);
}
void Terrain::makeTexture()
{
int width = 2049;
int height = 2049;
float* heights = getHeightmapData(width,height);
heightmapTexture = new Texture(HEIGHTMAP_TEXTURE,width,height);
heightmapTexture->loadBumpData(heights);
heightmapTexture->load();
heightmapTexture->toTGA("heightmap.tga");
}
<commit_msg>Removed broken dependecies<commit_after>#include <stdio.h>
#include <magrathea.h>
#include <terrain.h>
#include <game.h>
#include <heightmap.h>
#include <images.h>
#include <heightmap.h>
#include <cmath>
#include <texture.h>
#include <stdlib.h>
GLuint texture = 0;
/// Constructs a new region at the given position
/// @param x The x coordinate of the origin
/// @param y The y coordinate of the origin
/// @param parent The game that this region is in.
Terrain::Terrain(glm::vec3 pos,Game* parent) : Object(pos,parent)
{
initialiseTriangles();
freeze();
shaderID = game->shaderManager->newShader("terrain",VERTEX_SHADER|GEOMETRY_SHADER|FRAGMENT_SHADER|TESSELATION_SHADER);
makeTexture();
texture = textureFromTGA("assets/grass.tga",true);
}
/// Constructs the triangles
void Terrain::initialiseTriangles()
{
clearTriangleData((NUMBER_OF_PATCHES+1)*(NUMBER_OF_PATCHES+1)*6,2);
for (int i= 0;i<NUMBER_OF_PATCHES+1;i++)
for (int j = 0;j<NUMBER_OF_PATCHES+1;j++)
{
addPoint((i*NUMBER_OF_PATCHES+j)*6,
glm::vec3(i*PATCH_SIZE,
0,
j*PATCH_SIZE),
glm::vec3(1,0,0),
1,1,1);
addPoint((i*NUMBER_OF_PATCHES+j)*6+1,
glm::vec3(i*PATCH_SIZE,
0,
j*PATCH_SIZE+PATCH_SIZE),
glm::vec3(1,0,0),
1,1,1);
addPoint((i*NUMBER_OF_PATCHES+j)*6+2,
glm::vec3(i*PATCH_SIZE+PATCH_SIZE,
0,
j*PATCH_SIZE+PATCH_SIZE),
glm::vec3(1,0,0),
1,1,1);
addPoint((i*NUMBER_OF_PATCHES+j)*6+3,
glm::vec3(i*PATCH_SIZE+PATCH_SIZE,
0,
j*PATCH_SIZE+PATCH_SIZE),
glm::vec3(1,0,0),
1,1,1);
addPoint((i*NUMBER_OF_PATCHES+j)*6+4,
glm::vec3(i*PATCH_SIZE+PATCH_SIZE,
0,
j*PATCH_SIZE),
glm::vec3(1,0,0),
1,1,1);
addPoint((i*NUMBER_OF_PATCHES+j)*6+5,
glm::vec3(i*PATCH_SIZE,
0,
j*PATCH_SIZE),
glm::vec3(1,0,0),
1,1,1);
}
pushTriangleData();
}
void Terrain::Render()
{
heightmapTexture->load();
texture->load();
game->shaderManager->loadShader(shaderID);
// Load our transformation matrix etc
game->shaderManager->getCurrentShader()->setObjectData(objectBO);
// Select this object's texture
glBindVertexArray(VAO);
glPatchParameteri(GL_PATCH_VERTICES,3);
glDrawArrays(GL_PATCHES,0,6*NUMBER_OF_PATCHES*NUMBER_OF_PATCHES);
}
void Terrain::makeTexture()
{
int width = 2049;
int height = 2049;
float* heights = getHeightmapData(width,height);
heightmapTexture = new Texture(HEIGHTMAP_TEXTURE,width,height);
heightmapTexture->loadBumpData(heights);
heightmapTexture->load();
heightmapTexture->toTGA("heightmap.tga");
}
<|endoftext|>
|
<commit_before>/**
* @file Cognition.cpp
*
* @author <a href="mailto:mellmann@informatik.hu-berlin.de">Heinrich Mellmann</a>
* Implementation of the class Cognition
*/
#include "Cognition.h"
#include <PlatformInterface/Platform.h>
// tools
#include "Tools/Debug/Trace.h"
/////////////////////////////////////
// Modules
/////////////////////////////////////
// infrastructure
#include "Modules/Infrastructure/IO/Sensor.h"
#include "Modules/Infrastructure/IO/Actuator.h"
#include "Modules/Infrastructure/ButtonEventMonitor/ButtonEventMonitor.h"
#include "Cognition/Modules/Infrastructure/WifiModeSetter/WifiModeSetter.h"
#include "Modules/Infrastructure/BatteryAlert/BatteryAlert.h"
#include "Modules/Infrastructure/GameController/GameController.h"
#include "Modules/Infrastructure/Debug/FrameRateCheck.h"
#include "Modules/Infrastructure/Debug/DebugExecutor.h"
#include "Modules/Infrastructure/Debug/Debug.h"
#include "Modules/Infrastructure/LEDSetter/LEDSetter.h"
#include "Modules/Infrastructure/UltraSoundControl/UltraSoundControl.h"
#include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiver.h"
#include "Modules/Infrastructure/TeamCommunicator/TeamCommSender.h"
#include "Modules/Infrastructure/TeamCommunicator/SimpleNetworkTimeProtocol.h"
#include "Modules/Infrastructure/Debug/CameraDebug.h"
#include "Modules/Infrastructure/Camera/CameraInfoSetter.h"
#include "Modules/Infrastructure/Camera/AdaptiveAutoExposure.h"
#include "Modules/Infrastructure/GameLogger/GameLogger.h"
// perception
#include "Modules/SelfAwareness/CameraMatrixFinder/CameraMatrixFinder.h"
#include "Modules/SelfAwareness/KinematicChainProvider/KinematicChainProvider.h"
#include "Modules/SelfAwareness/ArtificialHorizonCalculator/ArtificialHorizonCalculator.h"
#include "Modules/SelfAwareness/BodyContourProvider/BodyContourProvider.h"
#include "Modules/SelfAwareness/CameraMatrixCorrectorV2/CameraMatrixCorrectorV2.h"
#include "Modules/SelfAwareness/CameraMatrixCorrectorV3/CameraMatrixCorrectorV3.h"
#include "Modules/VisualCortex/HistogramProvider.h"
#include "Modules/VisualCortex/FieldColorClassifier.h"
#include "Modules/VisualCortex/ScanGrid/ScanGridProvider.h"
#include "Modules/VisualCortex/ScanGrid/ScanGridEdgelDetector.h"
#include "Modules/VisualCortex/ScanLineEdgelDetector/ScanLineEdgelDetector.h"
#include "Modules/VisualCortex/FieldDetector/FieldDetector.h"
#include "Modules/VisualCortex/FieldDetector/IntegralFieldDetector.h"
#include "Modules/VisualCortex/LineDetector/LineGraphProvider.h"
#include "Modules/VisualCortex/GoalDetector/GoalFeatureDetector.h"
#include "Modules/VisualCortex/GoalDetector/GoalFeatureDetectorV2.h"
#include "Modules/VisualCortex/GoalDetector/GoalDetector.h"
#include "Modules/VisualCortex/GoalDetector/GoalDetectorV2.h"
#include "Modules/VisualCortex/GoalDetector/GoalCrossBarDetector.h"
#include "Modules/VisualCortex/BallDetector/RedBallDetector.h"
#include "Modules/VisualCortex/BallDetector/CNNBallDetector.h"
#include "Modules/VisualCortex/BallDetector/MultiPassBallDetector.h"
#include "Modules/VisualCortex/IntegralImageProvider.h"
#include "Modules/VisualCortex/ObstacleDetector/NoGreenObstacleDetector.h"
#include "Modules/SelfAwareness/FakeCameraMatrixFinder/FakeCameraMatrixFinder.h"
#include "Modules/VisualCortex/FakeBallDetector/FakeBallDetector.h"
#include "Modules/Perception/VirtualVisionProcessor/VirtualVisionProcessor.h"
#include "Modules/Perception/PerceptionsVisualizer/PerceptionsVisualizer.h"
#include "Modules/Perception/WhistleDetector/WhistleDetectorV1.h"
#include "Modules/Perception/WhistleDetector/WhistleDetectorV2.h"
#include "Modules/VisualCortex/LineDetector/RansacLineDetector.h"
#include "Modules/VisualCortex/LineDetector/RansacLineDetectorOnGraphs.h"
#include "Modules/VisualCortex/LineDetector/LineAugmenter.h"
#include "Modules/Modeling/CompassProvider/CompassProvider.h"
// modeling
#include "Modules/Modeling/BodyStateProvider/BodyStateProvider.h"
#include "Modules/Modeling/FieldCompass/FieldCompass.h"
#include "Modules/Modeling/ObstacleLocator/UltraSoundObstacleLocator.h"
#include "Modules/Modeling/ObstacleLocator/UltrasonicObstacleLocator2020.h"
#include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiveEmulator.h"
#include "Modules/Modeling/TeamMessageStatistics/TeamMessageStatisticsModule.h"
#include "Modules/Modeling/TeamMessageStatistics/TeamMessagePlayersStateModule.h"
#include "Modules/Modeling/SoccerStrategyProvider/SoccerStrategyProvider.h"
#include "Modules/Modeling/PotentialFieldProvider/PotentialFieldProvider.h"
#include "Modules/Modeling/SelfLocator/GPS_SelfLocator/GPS_SelfLocator.h"
#include "Modules/Modeling/SelfLocator/MonteCarloSelfLocator/MonteCarloSelfLocator.h"
#include "Modules/Modeling/SelfLocator/OdometrySelfLocator/OdometrySelfLocator.h"
#include "Modules/Modeling/GoalModel/DummyActiveGoalLocator/DummyActiveGoalLocator.h"
#include "Modules/Modeling/GoalModel/WholeGoalLocator/WholeGoalLocator.h"
// role decisions
#include "Modules/Modeling/RoleDecision/RolesProvider.h"
#include "Modules/Modeling/RoleDecision/Dynamic/RoleDecisionDynamic.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionStatic.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionForce.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionPotentialField.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionFormation.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionDynamicGoalie.h"
#include "Modules/Modeling/RoleDecision/Assignment/RoleDecisionAssignmentStatic.h"
#include "Modules/Modeling/RoleDecision/Assignment/RoleDecisionAssignmentDistance.h"
// the old striker decision (dynamic)
#include "Modules/Modeling/RoleDecision/Dynamic/SimpleRoleDecision.h"
#include "Modules/Modeling/RoleDecision/Dynamic/StableRoleDecision.h"
#include "Modules/Modeling/RoleDecision/Dynamic/CleanRoleDecision.h"
#include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocatorMedian.h"
#include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocatorCanopyCluster.h"
#include "Modules/Modeling/BallLocator/MultiKalmanBallLocator/MultiKalmanBallLocator.h"
#include "Modules/Modeling/StaticDebugModelProvider/StaticDebugModelProvider.h"
#include "Modules/Modeling/ObstacleLocator/MultiUnifiedObstacleLocator.h"
#include "Modules/Modeling/Simulation/SimulationTest.h"
#include "Modules/Modeling/Simulation/Simulation.h"
#include "Modules/Modeling/Simulation/KickDirectionSimulator.h"
#include "Modules/Modeling/SelfLocator/SituationPriorProvider/SituationPriorProvider.h"
// behavior
#include "Modules/Behavior/BasicTestBehavior/BasicTestBehavior.h"
#include "Modules/Behavior/XABSLBehaviorControl/XABSLBehaviorControl.h"
#include "Modules/Behavior/PathPlanner/PathPlanner.h"
#include "Modules/Behavior/PathPlanner/PathPlanner2018.h"
using namespace std;
Cognition::Cognition()
: ModuleManagerWithDebug("")
{
}
Cognition::~Cognition()
{
}
#define REGISTER_MODULE(module) \
std::cout << "[Cognition] Register " << #module << std::endl;\
registerModule<module>(std::string(#module))
void Cognition::init(naoth::ProcessInterface& platformInterface, const naoth::PlatformBase& platform)
{
std::cout << "[Cognition] Cognition register start" << std::endl;
// register input module
ModuleCreator<Sensor>* sensor = registerModule<Sensor>(std::string("Sensor"), true);
sensor->getModuleT()->init(platformInterface, platform);
/*
* to register a module use
* REGISTER_MODULE(ModuleClassName);
*
* Remark: to enable the module don't forget
* to set the value in modules.cfg
*/
// -- BEGIN REGISTER MODULES --
// infrastructure
REGISTER_MODULE(ButtonEventMonitor);
REGISTER_MODULE(WifiModeSetter);
REGISTER_MODULE(TeamCommReceiver);
REGISTER_MODULE(SimpleNetworkTimeProtocol);
REGISTER_MODULE(GameController);
REGISTER_MODULE(BatteryAlert);
REGISTER_MODULE(LEDSetter);
REGISTER_MODULE(UltraSoundControl);
REGISTER_MODULE(CameraDebug);
REGISTER_MODULE(CameraInfoSetter);
REGISTER_MODULE(AdaptiveAutoExposure);
REGISTER_MODULE(WhistleDetectorV1);
REGISTER_MODULE(WhistleDetectorV2);
// perception
REGISTER_MODULE(CameraMatrixFinder);
REGISTER_MODULE(KinematicChainProvider);
REGISTER_MODULE(ArtificialHorizonCalculator);
REGISTER_MODULE(BodyContourProvider);
REGISTER_MODULE(CameraMatrixCorrectorV2);
REGISTER_MODULE(HistogramProvider);
REGISTER_MODULE(IntegralImageProvider);
REGISTER_MODULE(FieldColorClassifier);
REGISTER_MODULE(IntegralFieldDetector);
REGISTER_MODULE(ScanGridProvider);
REGISTER_MODULE(ScanGridEdgelDetector);
REGISTER_MODULE(ScanLineEdgelDetector);
REGISTER_MODULE(FieldDetector);
REGISTER_MODULE(LineGraphProvider);
REGISTER_MODULE(GoalFeatureDetector);
REGISTER_MODULE(GoalFeatureDetectorV2);
REGISTER_MODULE(GoalDetector);
REGISTER_MODULE(GoalDetectorV2);
REGISTER_MODULE(GoalCrossBarDetector);
REGISTER_MODULE(NoGreenObstacleDetector);
REGISTER_MODULE(RedBallDetector);
REGISTER_MODULE(CNNBallDetector);
REGISTER_MODULE(MultiPassBallDetector);
REGISTER_MODULE(FakeCameraMatrixFinder);
REGISTER_MODULE(FakeBallDetector);
REGISTER_MODULE(VirtualVisionProcessor);
REGISTER_MODULE(PerceptionsVisualizer);
REGISTER_MODULE(RansacLineDetector);
REGISTER_MODULE(RansacLineDetectorOnGraphs);
REGISTER_MODULE(LineAugmenter);
REGISTER_MODULE(CompassProvider);
// modeling
REGISTER_MODULE(SituationPriorProvider);
REGISTER_MODULE(BodyStateProvider);
REGISTER_MODULE(FieldCompass);
REGISTER_MODULE(UltraSoundObstacleLocator);
REGISTER_MODULE(UltrasonicObstacleLocator2020);
REGISTER_MODULE(TeamCommReceiveEmulator);
REGISTER_MODULE(TeamMessageStatisticsModule);
REGISTER_MODULE(TeamMessagePlayersStateModule);
REGISTER_MODULE(SoccerStrategyProvider);
REGISTER_MODULE(PotentialFieldProvider);
REGISTER_MODULE(GPS_SelfLocator);
REGISTER_MODULE(MonteCarloSelfLocator);
REGISTER_MODULE(OdometrySelfLocator);
REGISTER_MODULE(WholeGoalLocator);
REGISTER_MODULE(DummyActiveGoalLocator);
REGISTER_MODULE(MultiKalmanBallLocator);
REGISTER_MODULE(TeamBallLocatorMedian);
REGISTER_MODULE(TeamBallLocatorCanopyCluster);
REGISTER_MODULE(MultiUnifiedObstacleLocator);
/*
* BEGIN ROLE DECISIONS
*/
REGISTER_MODULE(RolesProvider);
// first set the position of the roles
REGISTER_MODULE(RoleDecisionPositionStatic);
REGISTER_MODULE(RoleDecisionPositionForce);
REGISTER_MODULE(RoleDecisionPositionPotentialField);
REGISTER_MODULE(RoleDecisionPositionFormation);
REGISTER_MODULE(RoleDecisionPositionDynamicGoalie);
// then decide which player should have which role
REGISTER_MODULE(RoleDecisionAssignmentStatic);
REGISTER_MODULE(RoleDecisionAssignmentDistance);
// finally, determine the dynamic role (striker, supporter, ...)
REGISTER_MODULE(RoleDecisionDynamic);
// old striker decisions
REGISTER_MODULE(SimpleRoleDecision);
REGISTER_MODULE(StableRoleDecision);
REGISTER_MODULE(CleanRoleDecision);
/*
* END ROLE DECISIONS
*/
REGISTER_MODULE(KickDirectionSimulator);
REGISTER_MODULE(Simulation);
REGISTER_MODULE(StaticDebugModelProvider);
// behavior
REGISTER_MODULE(BasicTestBehavior);
REGISTER_MODULE(XABSLBehaviorControl);
REGISTER_MODULE(PathPlanner);
REGISTER_MODULE(PathPlanner2018);
REGISTER_MODULE(CameraMatrixCorrectorV3);
REGISTER_MODULE(TeamCommSender);
// debug
REGISTER_MODULE(GameLogger);
REGISTER_MODULE(Debug);
REGISTER_MODULE(FrameRateCheck);
REGISTER_MODULE(DebugExecutor);
// -- END REGISTER MODULES --
// register output module
ModuleCreator<Actuator>* actuator = registerModule<Actuator>(std::string("Actuator"), true);
actuator->getModuleT()->init(platformInterface, platform);
// use the configuration in order to set whether a module is activated or not
const naoth::Configuration& config = Platform::getInstance().theConfiguration;
list<string>::const_iterator name = getExecutionList().begin();
for(;name != getExecutionList().end(); ++name)
{
bool active = false;
if(config.hasKey("modules", *name)) {
active = config.getBool("modules", *name);
}
if(active) {
std::cout << "[Cognition] activating module " << *name << std::endl;
}
setModuleEnabled(*name, active);
}//end for
// auto-generate the execution list
//calculateExecutionList();
std::cout << "[Cognition] register end" << std::endl;
stopwatch.start();
}//end init
void Cognition::call()
{
// BEGIN cognition frame rate measuring
stopwatch.stop();
stopwatch.start();
PLOT("Cognition.Cycle", stopwatch.lastValue);
// END cognition frame rate measuring
STOPWATCH_START("Cognition.Execute");
// execute all modules
list<AbstractModuleCreator*>::const_iterator iter;
for (iter = getModuleExecutionList().begin(); iter != getModuleExecutionList().end(); ++iter)
{
AbstractModuleCreator* module = *iter;
if (module != NULL && module->isEnabled())
{
std::string name(module->getModule()->getName());
GT_TRACE("executing " << name);
module->execute();
}
}
STOPWATCH_STOP("Cognition.Execute");
// HACK: reset all the debug stuff before executing the modules
STOPWATCH_START("Cognition.Debug.Init");
getDebugDrawings().reset();
getDebugImageDrawings().reset();
getDebugImageDrawingsTop().reset();
getDebugDrawings3D().reset();
STOPWATCH_STOP("Cognition.Debug.Init");
}//end call
<commit_msg>fix a compile error<commit_after>/**
* @file Cognition.cpp
*
* @author <a href="mailto:mellmann@informatik.hu-berlin.de">Heinrich Mellmann</a>
* Implementation of the class Cognition
*/
#include "Cognition.h"
#include <PlatformInterface/Platform.h>
// tools
#include "Tools/Debug/Trace.h"
/////////////////////////////////////
// Modules
/////////////////////////////////////
// infrastructure
#include "Modules/Infrastructure/IO/Sensor.h"
#include "Modules/Infrastructure/IO/Actuator.h"
#include "Modules/Infrastructure/ButtonEventMonitor/ButtonEventMonitor.h"
#include "Cognition/Modules/Infrastructure/WifiModeSetter/WifiModeSetter.h"
#include "Modules/Infrastructure/BatteryAlert/BatteryAlert.h"
#include "Modules/Infrastructure/GameController/GameController.h"
#include "Modules/Infrastructure/Debug/FrameRateCheck.h"
#include "Modules/Infrastructure/Debug/DebugExecutor.h"
#include "Modules/Infrastructure/Debug/Debug.h"
#include "Modules/Infrastructure/LEDSetter/LEDSetter.h"
#include "Modules/Infrastructure/UltraSoundControl/UltraSoundControl.h"
#include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiver.h"
#include "Modules/Infrastructure/TeamCommunicator/TeamCommSender.h"
#include "Modules/Infrastructure/TeamCommunicator/SimpleNetworkTimeProtocol.h"
#include "Modules/Infrastructure/Debug/CameraDebug.h"
#include "Modules/Infrastructure/Camera/CameraInfoSetter.h"
#include "Modules/Infrastructure/Camera/AdaptiveAutoExposure.h"
#include "Modules/Infrastructure/GameLogger/GameLogger.h"
// perception
#include "Modules/SelfAwareness/CameraMatrixFinder/CameraMatrixFinder.h"
#include "Modules/SelfAwareness/KinematicChainProvider/KinematicChainProvider.h"
#include "Modules/SelfAwareness/ArtificialHorizonCalculator/ArtificialHorizonCalculator.h"
#include "Modules/SelfAwareness/BodyContourProvider/BodyContourProvider.h"
#include "Modules/SelfAwareness/CameraMatrixCorrectorV2/CameraMatrixCorrectorV2.h"
#include "Modules/SelfAwareness/CameraMatrixCorrectorV3/CameraMatrixCorrectorV3.h"
#include "Modules/VisualCortex/HistogramProvider.h"
#include "Modules/VisualCortex/FieldColorClassifier.h"
#include "Modules/VisualCortex/ScanGrid/ScanGridProvider.h"
#include "Modules/VisualCortex/ScanGrid/ScanGridEdgelDetector.h"
#include "Modules/VisualCortex/ScanLineEdgelDetector/ScanLineEdgelDetector.h"
#include "Modules/VisualCortex/FieldDetector/FieldDetector.h"
#include "Modules/VisualCortex/FieldDetector/IntegralFieldDetector.h"
#include "Modules/VisualCortex/LineDetector/LineGraphProvider.h"
#include "Modules/VisualCortex/GoalDetector/GoalFeatureDetector.h"
#include "Modules/VisualCortex/GoalDetector/GoalFeatureDetectorV2.h"
#include "Modules/VisualCortex/GoalDetector/GoalDetector.h"
#include "Modules/VisualCortex/GoalDetector/GoalDetectorV2.h"
#include "Modules/VisualCortex/GoalDetector/GoalCrossBarDetector.h"
#include "Modules/VisualCortex/BallDetector/RedBallDetector.h"
#include "Modules/VisualCortex/BallDetector/CNNBallDetector.h"
#include "Modules/VisualCortex/BallDetector/MultiPassBallDetector.h"
#include "Modules/VisualCortex/IntegralImageProvider.h"
#include "Modules/VisualCortex/ObstacleDetector/NoGreenObstacleDetector.h"
#include "Modules/SelfAwareness/FakeCameraMatrixFinder/FakeCameraMatrixFinder.h"
#include "Modules/VisualCortex/FakeBallDetector/FakeBallDetector.h"
#include "Modules/Perception/VirtualVisionProcessor/VirtualVisionProcessor.h"
#include "Modules/Perception/PerceptionsVisualizer/PerceptionsVisualizer.h"
#include "Modules/Perception/WhistleDetector/WhistleDetectorV1.h"
#include "Modules/Perception/WhistleDetector/WhistleDetectorV2.h"
#include "Modules/VisualCortex/LineDetector/RansacLineDetector.h"
#include "Modules/VisualCortex/LineDetector/RansacLineDetectorOnGraphs.h"
#include "Modules/VisualCortex/LineDetector/LineAugmenter.h"
#include "Modules/Modeling/CompassProvider/CompassProvider.h"
// modeling
#include "Modules/Modeling/BodyStateProvider/BodyStateProvider.h"
#include "Modules/Modeling/FieldCompass/FieldCompass.h"
#include "Modules/Modeling/ObstacleLocator/UltraSoundObstacleLocator.h"
#include "Modules/Modeling/ObstacleLocator/UltrasonicObstacleLocator2020.h"
#include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiveEmulator.h"
#include "Modules/Modeling/TeamMessageStatistics/TeamMessageStatisticsModule.h"
#include "Modules/Modeling/TeamMessageStatistics/TeamMessagePlayersStateModule.h"
#include "Modules/Modeling/SoccerStrategyProvider/SoccerStrategyProvider.h"
#include "Modules/Modeling/PotentialFieldProvider/PotentialFieldProvider.h"
#include "Modules/Modeling/SelfLocator/GPS_SelfLocator/GPS_SelfLocator.h"
#include "Modules/Modeling/SelfLocator/MonteCarloSelfLocator/MonteCarloSelfLocator.h"
#include "Modules/Modeling/SelfLocator/OdometrySelfLocator/OdometrySelfLocator.h"
#include "Modules/Modeling/GoalModel/DummyActiveGoalLocator/DummyActiveGoalLocator.h"
#include "Modules/Modeling/GoalModel/WholeGoalLocator/WholeGoalLocator.h"
// role decisions
#include "Modules/Modeling/RoleDecision/RolesProvider.h"
#include "Modules/Modeling/RoleDecision/Dynamic/RoleDecisionDynamic.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionStatic.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionForce.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionPotentialField.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionFormation.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionDynamicGoalie.h"
#include "Modules/Modeling/RoleDecision/Assignment/RoleDecisionAssignmentStatic.h"
#include "Modules/Modeling/RoleDecision/Assignment/RoleDecisionAssignmentDistance.h"
// the old striker decision (dynamic)
#include "Modules/Modeling/RoleDecision/Dynamic/SimpleRoleDecision.h"
#include "Modules/Modeling/RoleDecision/Dynamic/StableRoleDecision.h"
#include "Modules/Modeling/RoleDecision/Dynamic/CleanRoleDecision.h"
#include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocatorMedian.h"
#include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocatorCanopyCluster.h"
#include "Modules/Modeling/BallLocator/MultiKalmanBallLocator/MultiKalmanBallLocator.h"
#include "Modules/Modeling/StaticDebugModelProvider/StaticDebugModelProvider.h"
#include "Modules/Modeling/ObstacleLocator/MultiUnifiedObstacleLocator.h"
#include "Modules/Modeling/Simulation/Simulation.h"
#include "Modules/Modeling/Simulation/KickDirectionSimulator.h"
#include "Modules/Modeling/SelfLocator/SituationPriorProvider/SituationPriorProvider.h"
// behavior
#include "Modules/Behavior/BasicTestBehavior/BasicTestBehavior.h"
#include "Modules/Behavior/XABSLBehaviorControl/XABSLBehaviorControl.h"
#include "Modules/Behavior/PathPlanner/PathPlanner.h"
#include "Modules/Behavior/PathPlanner/PathPlanner2018.h"
using namespace std;
Cognition::Cognition()
: ModuleManagerWithDebug("")
{
}
Cognition::~Cognition()
{
}
#define REGISTER_MODULE(module) \
std::cout << "[Cognition] Register " << #module << std::endl;\
registerModule<module>(std::string(#module))
void Cognition::init(naoth::ProcessInterface& platformInterface, const naoth::PlatformBase& platform)
{
std::cout << "[Cognition] Cognition register start" << std::endl;
// register input module
ModuleCreator<Sensor>* sensor = registerModule<Sensor>(std::string("Sensor"), true);
sensor->getModuleT()->init(platformInterface, platform);
/*
* to register a module use
* REGISTER_MODULE(ModuleClassName);
*
* Remark: to enable the module don't forget
* to set the value in modules.cfg
*/
// -- BEGIN REGISTER MODULES --
// infrastructure
REGISTER_MODULE(ButtonEventMonitor);
REGISTER_MODULE(WifiModeSetter);
REGISTER_MODULE(TeamCommReceiver);
REGISTER_MODULE(SimpleNetworkTimeProtocol);
REGISTER_MODULE(GameController);
REGISTER_MODULE(BatteryAlert);
REGISTER_MODULE(LEDSetter);
REGISTER_MODULE(UltraSoundControl);
REGISTER_MODULE(CameraDebug);
REGISTER_MODULE(CameraInfoSetter);
REGISTER_MODULE(AdaptiveAutoExposure);
REGISTER_MODULE(WhistleDetectorV1);
REGISTER_MODULE(WhistleDetectorV2);
// perception
REGISTER_MODULE(CameraMatrixFinder);
REGISTER_MODULE(KinematicChainProvider);
REGISTER_MODULE(ArtificialHorizonCalculator);
REGISTER_MODULE(BodyContourProvider);
REGISTER_MODULE(CameraMatrixCorrectorV2);
REGISTER_MODULE(HistogramProvider);
REGISTER_MODULE(IntegralImageProvider);
REGISTER_MODULE(FieldColorClassifier);
REGISTER_MODULE(IntegralFieldDetector);
REGISTER_MODULE(ScanGridProvider);
REGISTER_MODULE(ScanGridEdgelDetector);
REGISTER_MODULE(ScanLineEdgelDetector);
REGISTER_MODULE(FieldDetector);
REGISTER_MODULE(LineGraphProvider);
REGISTER_MODULE(GoalFeatureDetector);
REGISTER_MODULE(GoalFeatureDetectorV2);
REGISTER_MODULE(GoalDetector);
REGISTER_MODULE(GoalDetectorV2);
REGISTER_MODULE(GoalCrossBarDetector);
REGISTER_MODULE(NoGreenObstacleDetector);
REGISTER_MODULE(RedBallDetector);
REGISTER_MODULE(CNNBallDetector);
REGISTER_MODULE(MultiPassBallDetector);
REGISTER_MODULE(FakeCameraMatrixFinder);
REGISTER_MODULE(FakeBallDetector);
REGISTER_MODULE(VirtualVisionProcessor);
REGISTER_MODULE(PerceptionsVisualizer);
REGISTER_MODULE(RansacLineDetector);
REGISTER_MODULE(RansacLineDetectorOnGraphs);
REGISTER_MODULE(LineAugmenter);
REGISTER_MODULE(CompassProvider);
// modeling
REGISTER_MODULE(SituationPriorProvider);
REGISTER_MODULE(BodyStateProvider);
REGISTER_MODULE(FieldCompass);
REGISTER_MODULE(UltraSoundObstacleLocator);
REGISTER_MODULE(UltrasonicObstacleLocator2020);
REGISTER_MODULE(TeamCommReceiveEmulator);
REGISTER_MODULE(TeamMessageStatisticsModule);
REGISTER_MODULE(TeamMessagePlayersStateModule);
REGISTER_MODULE(SoccerStrategyProvider);
REGISTER_MODULE(PotentialFieldProvider);
REGISTER_MODULE(GPS_SelfLocator);
REGISTER_MODULE(MonteCarloSelfLocator);
REGISTER_MODULE(OdometrySelfLocator);
REGISTER_MODULE(WholeGoalLocator);
REGISTER_MODULE(DummyActiveGoalLocator);
REGISTER_MODULE(MultiKalmanBallLocator);
REGISTER_MODULE(TeamBallLocatorMedian);
REGISTER_MODULE(TeamBallLocatorCanopyCluster);
REGISTER_MODULE(MultiUnifiedObstacleLocator);
/*
* BEGIN ROLE DECISIONS
*/
REGISTER_MODULE(RolesProvider);
// first set the position of the roles
REGISTER_MODULE(RoleDecisionPositionStatic);
REGISTER_MODULE(RoleDecisionPositionForce);
REGISTER_MODULE(RoleDecisionPositionPotentialField);
REGISTER_MODULE(RoleDecisionPositionFormation);
REGISTER_MODULE(RoleDecisionPositionDynamicGoalie);
// then decide which player should have which role
REGISTER_MODULE(RoleDecisionAssignmentStatic);
REGISTER_MODULE(RoleDecisionAssignmentDistance);
// finally, determine the dynamic role (striker, supporter, ...)
REGISTER_MODULE(RoleDecisionDynamic);
// old striker decisions
REGISTER_MODULE(SimpleRoleDecision);
REGISTER_MODULE(StableRoleDecision);
REGISTER_MODULE(CleanRoleDecision);
/*
* END ROLE DECISIONS
*/
REGISTER_MODULE(KickDirectionSimulator);
REGISTER_MODULE(Simulation);
REGISTER_MODULE(StaticDebugModelProvider);
// behavior
REGISTER_MODULE(BasicTestBehavior);
REGISTER_MODULE(XABSLBehaviorControl);
REGISTER_MODULE(PathPlanner);
REGISTER_MODULE(PathPlanner2018);
REGISTER_MODULE(CameraMatrixCorrectorV3);
REGISTER_MODULE(TeamCommSender);
// debug
REGISTER_MODULE(GameLogger);
REGISTER_MODULE(Debug);
REGISTER_MODULE(FrameRateCheck);
REGISTER_MODULE(DebugExecutor);
// -- END REGISTER MODULES --
// register output module
ModuleCreator<Actuator>* actuator = registerModule<Actuator>(std::string("Actuator"), true);
actuator->getModuleT()->init(platformInterface, platform);
// use the configuration in order to set whether a module is activated or not
const naoth::Configuration& config = Platform::getInstance().theConfiguration;
list<string>::const_iterator name = getExecutionList().begin();
for(;name != getExecutionList().end(); ++name)
{
bool active = false;
if(config.hasKey("modules", *name)) {
active = config.getBool("modules", *name);
}
if(active) {
std::cout << "[Cognition] activating module " << *name << std::endl;
}
setModuleEnabled(*name, active);
}//end for
// auto-generate the execution list
//calculateExecutionList();
std::cout << "[Cognition] register end" << std::endl;
stopwatch.start();
}//end init
void Cognition::call()
{
// BEGIN cognition frame rate measuring
stopwatch.stop();
stopwatch.start();
PLOT("Cognition.Cycle", stopwatch.lastValue);
// END cognition frame rate measuring
STOPWATCH_START("Cognition.Execute");
// execute all modules
list<AbstractModuleCreator*>::const_iterator iter;
for (iter = getModuleExecutionList().begin(); iter != getModuleExecutionList().end(); ++iter)
{
AbstractModuleCreator* module = *iter;
if (module != NULL && module->isEnabled())
{
std::string name(module->getModule()->getName());
GT_TRACE("executing " << name);
module->execute();
}
}
STOPWATCH_STOP("Cognition.Execute");
// HACK: reset all the debug stuff before executing the modules
STOPWATCH_START("Cognition.Debug.Init");
getDebugDrawings().reset();
getDebugImageDrawings().reset();
getDebugImageDrawingsTop().reset();
getDebugDrawings3D().reset();
STOPWATCH_STOP("Cognition.Debug.Init");
}//end call
<|endoftext|>
|
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/log/log.h>
LOG_SETUP("dense_dot_product_function_test");
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/eval/eval/tensor_function.h>
#include <vespa/eval/eval/operation.h>
#include <vespa/eval/eval/simple_tensor.h>
#include <vespa/eval/eval/simple_tensor_engine.h>
#include <vespa/eval/tensor/default_tensor_engine.h>
#include <vespa/eval/tensor/dense/dense_xw_product_function.h>
#include <vespa/eval/tensor/dense/dense_tensor.h>
#include <vespa/eval/tensor/dense/dense_tensor_view.h>
#include <vespa/eval/eval/test/tensor_model.hpp>
#include <vespa/eval/eval/test/eval_fixture.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/util/stash.h>
using namespace vespalib;
using namespace vespalib::eval;
using namespace vespalib::eval::test;
using namespace vespalib::tensor;
using namespace vespalib::eval::tensor_function;
const TensorEngine &prod_engine = DefaultTensorEngine::ref();
struct MyVecSeq : Sequence {
double operator[](size_t i) const override { return (3.0 + i) * 7.0; }
};
struct MyMatSeq : Sequence {
double operator[](size_t i) const override { return (5.0 + i) * 43.0; }
};
EvalFixture::ParamRepo make_params() {
return EvalFixture::ParamRepo()
.add("y1", spec({y(1)}, MyVecSeq()))
.add("y3", spec({y(3)}, MyVecSeq()))
.add("y3f", spec(float_cells({y(3)}), MyVecSeq()))
.add("y5", spec({y(5)}, MyVecSeq()))
.add("y16", spec({y(16)}, MyVecSeq()))
.add("x1y1", spec({x(1),y(1)}, MyMatSeq()))
.add("y1z1", spec({y(1),z(1)}, MyMatSeq()))
.add("x2y3", spec({x(2),y(3)}, MyMatSeq()))
.add("x2y3f", spec(float_cells({x(2),y(3)}), MyMatSeq()))
.add("y3z2f", spec(float_cells({y(3),z(2)}), MyMatSeq()))
.add("x2z3", spec({x(2),z(3)}, MyMatSeq()))
.add("y3z2", spec({y(3),z(2)}, MyMatSeq()))
.add("x8y5", spec({x(8),y(5)}, MyMatSeq()))
.add("y5z8", spec({y(5),z(8)}, MyMatSeq()))
.add("x5y16", spec({x(5),y(16)}, MyMatSeq()))
.add("y16z5", spec({y(16),z(5)}, MyMatSeq()));
}
EvalFixture::ParamRepo param_repo = make_params();
void verify_optimized(const vespalib::string &expr, size_t vec_size, size_t res_size, bool happy) {
EvalFixture fixture(prod_engine, expr, param_repo, true);
EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo));
auto info = fixture.find_all<DenseXWProductFunction>();
ASSERT_EQUAL(info.size(), 1u);
EXPECT_TRUE(info[0]->result_is_mutable());
EXPECT_EQUAL(info[0]->vectorSize(), vec_size);
EXPECT_EQUAL(info[0]->resultSize(), res_size);
EXPECT_EQUAL(info[0]->matrixHasCommonDimensionInnermost(), happy);
}
void verify_not_optimized(const vespalib::string &expr) {
EvalFixture fixture(prod_engine, expr, param_repo, true);
EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo));
auto info = fixture.find_all<DenseXWProductFunction>();
EXPECT_TRUE(info.empty());
}
TEST("require that xw product gives same results as reference join/reduce") {
// 1 -> 1 happy/unhappy
TEST_DO(verify_optimized("reduce(y1*x1y1,sum,y)", 1, 1, true));
TEST_DO(verify_optimized("reduce(y1*y1z1,sum,y)", 1, 1, false));
// 3 -> 2 happy/unhappy
TEST_DO(verify_optimized("reduce(y3*x2y3,sum,y)", 3, 2, true));
TEST_DO(verify_optimized("reduce(y3*y3z2,sum,y)", 3, 2, false));
// 5 -> 8 happy/unhappy
TEST_DO(verify_optimized("reduce(y5*x8y5,sum,y)", 5, 8, true));
TEST_DO(verify_optimized("reduce(y5*y5z8,sum,y)", 5, 8, false));
// 16 -> 5 happy/unhappy
TEST_DO(verify_optimized("reduce(y16*x5y16,sum,y)", 16, 5, true));
TEST_DO(verify_optimized("reduce(y16*y16z5,sum,y)", 16, 5, false));
}
TEST("require that various variants of xw product can be optimized") {
TEST_DO(verify_optimized("reduce(y3*x2y3,sum,y)", 3, 2, true));
TEST_DO(verify_optimized("reduce(x2y3*y3,sum,y)", 3, 2, true));
TEST_DO(verify_optimized("reduce(join(y3,x2y3,f(x,y)(x*y)),sum,y)", 3, 2, true));
TEST_DO(verify_optimized("reduce(join(x2y3,y3,f(x,y)(x*y)),sum,y)", 3, 2, true));
}
TEST("require that expressions similar to xw product are not optimized") {
TEST_DO(verify_not_optimized("reduce(y3*x2y3,sum,x)"));
TEST_DO(verify_not_optimized("reduce(y3*x2y3,prod,y)"));
TEST_DO(verify_not_optimized("reduce(y3*x2y3,sum)"));
TEST_DO(verify_not_optimized("reduce(join(y3,x2y3,f(x,y)(x+y)),sum,y)"));
// TEST_DO(verify_not_optimized("reduce(join(y3,x2y3,f(x,y)(y*x)),sum,y)"));
TEST_DO(verify_not_optimized("reduce(join(y3,x2y3,f(x,y)(x*x)),sum,y)"));
TEST_DO(verify_not_optimized("reduce(join(y3,x2y3,f(x,y)(y*y)),sum,y)"));
TEST_DO(verify_not_optimized("reduce(join(y3,x2y3,f(x,y)(y*x*1)),sum,y)"));
}
TEST("require that xw products with incompatible dimensions are not optimized") {
TEST_DO(verify_not_optimized("reduce(y3*x2z3,sum,y)"));
TEST_DO(verify_not_optimized("reduce(y3*x2z3,sum,z)"));
}
TEST("require that xw product can be debug dumped") {
EvalFixture fixture(prod_engine, "reduce(y5*x8y5,sum,y)", param_repo, true);
auto info = fixture.find_all<DenseXWProductFunction>();
ASSERT_EQUAL(info.size(), 1u);
EXPECT_TRUE(info[0]->result_is_mutable());
fprintf(stderr, "%s\n", info[0]->as_string().c_str());
}
TEST("require that optimization works for float cells") {
TEST_DO(verify_optimized("reduce(y3f*x2y3,sum,y)", 3, 2, true));
TEST_DO(verify_optimized("reduce(y3*x2y3f,sum,y)", 3, 2, true));
TEST_DO(verify_optimized("reduce(y3f*x2y3f,sum,y)", 3, 2, true));
}
TEST("require that optimization works for float cells with inconvenient dimension nesting") {
TEST_DO(verify_optimized("reduce(y3f*y3z2,sum,y)", 3, 2, false));
TEST_DO(verify_optimized("reduce(y3*y3z2f,sum,y)", 3, 2, false));
TEST_DO(verify_optimized("reduce(y3f*y3z2f,sum,y)", 3, 2, false));
}
TEST_MAIN() { TEST_RUN_ALL(); }
<commit_msg>better coverage of cell type and parameter ordering<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/eval/eval/tensor_function.h>
#include <vespa/eval/eval/operation.h>
#include <vespa/eval/eval/simple_tensor.h>
#include <vespa/eval/eval/simple_tensor_engine.h>
#include <vespa/eval/tensor/default_tensor_engine.h>
#include <vespa/eval/tensor/dense/dense_xw_product_function.h>
#include <vespa/eval/tensor/dense/dense_tensor.h>
#include <vespa/eval/tensor/dense/dense_tensor_view.h>
#include <vespa/eval/eval/test/tensor_model.hpp>
#include <vespa/eval/eval/test/eval_fixture.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/util/stash.h>
using namespace vespalib;
using namespace vespalib::eval;
using namespace vespalib::eval::test;
using namespace vespalib::tensor;
using namespace vespalib::eval::tensor_function;
const TensorEngine &prod_engine = DefaultTensorEngine::ref();
struct First {
bool value;
explicit First(bool value_in) : value(value_in) {}
operator bool() const { return value; }
};
struct MyVecSeq : Sequence {
double operator[](size_t i) const override { return (3.0 + i) * 7.0; }
};
struct MyMatSeq : Sequence {
double operator[](size_t i) const override { return (5.0 + i) * 43.0; }
};
void add_vector(EvalFixture::ParamRepo &repo, const char *d1, size_t s1) {
auto name = make_string("%s%zu", d1, s1);
auto layout = Layout({{d1, s1}});
repo.add(name, spec(layout, MyVecSeq()));
repo.add(name + "f", spec(float_cells(layout), MyVecSeq()));
}
void add_matrix(EvalFixture::ParamRepo &repo, const char *d1, size_t s1, const char *d2, size_t s2) {
auto name = make_string("%s%zu%s%zu", d1, s1, d2, s2);
auto layout = Layout({{d1, s1}, {d2, s2}});
repo.add(name, spec(layout, MyMatSeq()));
repo.add(name + "f", spec(float_cells(layout), MyMatSeq()));
}
EvalFixture::ParamRepo make_params() {
EvalFixture::ParamRepo repo;
add_vector(repo, "y", 1);
add_vector(repo, "y", 3);
add_vector(repo, "y", 5);
add_vector(repo, "y", 16);
add_matrix(repo, "x", 1, "y", 1);
add_matrix(repo, "y", 1, "z", 1);
add_matrix(repo, "x", 2, "y", 3);
add_matrix(repo, "y", 3, "z", 2);
add_matrix(repo, "x", 2, "z", 3);
add_matrix(repo, "x", 8, "y", 5);
add_matrix(repo, "y", 5, "z", 8);
add_matrix(repo, "x", 5, "y", 16);
add_matrix(repo, "y", 16, "z", 5);
return repo;
}
EvalFixture::ParamRepo param_repo = make_params();
void verify_optimized(const vespalib::string &expr, size_t vec_size, size_t res_size, bool happy) {
EvalFixture slow_fixture(prod_engine, expr, param_repo, false);
EvalFixture fixture(prod_engine, expr, param_repo, true);
EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo));
EXPECT_EQUAL(fixture.result(), slow_fixture.result());
auto info = fixture.find_all<DenseXWProductFunction>();
ASSERT_EQUAL(info.size(), 1u);
EXPECT_TRUE(info[0]->result_is_mutable());
EXPECT_EQUAL(info[0]->vectorSize(), vec_size);
EXPECT_EQUAL(info[0]->resultSize(), res_size);
EXPECT_EQUAL(info[0]->matrixHasCommonDimensionInnermost(), happy);
}
vespalib::string make_expr(const vespalib::string &a, const vespalib::string &b, const vespalib::string &common,
bool float_a, bool float_b)
{
return make_string("reduce(%s%s*%s%s,sum,%s)", a.c_str(), float_a ? "f" : "", b.c_str(), float_b ? "f" : "", common.c_str());
}
void verify_optimized_multi(const vespalib::string &a, const vespalib::string &b, const vespalib::string &common,
size_t vec_size, size_t res_size, bool happy, First first = First(true))
{
for (bool float_a: {false, true}) {
for (bool float_b: {false, true}) {
auto expr = make_expr(a, b, common, float_a, float_b);
TEST_STATE(expr.c_str());
TEST_DO(verify_optimized(expr, vec_size, res_size, happy));
}
}
if (first) {
TEST_DO(verify_optimized_multi(b, a, common, vec_size, res_size, happy, First(false)));
}
}
void verify_not_optimized(const vespalib::string &expr) {
EvalFixture slow_fixture(prod_engine, expr, param_repo, false);
EvalFixture fixture(prod_engine, expr, param_repo, true);
EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo));
EXPECT_EQUAL(fixture.result(), slow_fixture.result());
auto info = fixture.find_all<DenseXWProductFunction>();
EXPECT_TRUE(info.empty());
}
TEST("require that xw product gives same results as reference join/reduce") {
// 1 -> 1 happy/unhappy
TEST_DO(verify_optimized_multi("y1", "x1y1", "y", 1, 1, true));
TEST_DO(verify_optimized_multi("y1", "y1z1", "y", 1, 1, false));
// 3 -> 2 happy/unhappy
TEST_DO(verify_optimized_multi("y3", "x2y3", "y", 3, 2, true));
TEST_DO(verify_optimized_multi("y3", "y3z2", "y", 3, 2, false));
// 5 -> 8 happy/unhappy
TEST_DO(verify_optimized_multi("y5", "x8y5", "y", 5, 8, true));
TEST_DO(verify_optimized_multi("y5", "y5z8", "y", 5, 8, false));
// 16 -> 5 happy/unhappy
TEST_DO(verify_optimized_multi("y16", "x5y16", "y", 16, 5, true));
TEST_DO(verify_optimized_multi("y16", "y16z5", "y", 16, 5, false));
}
TEST("require that various variants of xw product can be optimized") {
TEST_DO(verify_optimized("reduce(join(y3,x2y3,f(x,y)(x*y)),sum,y)", 3, 2, true));
TEST_DO(verify_optimized("reduce(join(y3,x2y3,f(x,y)(y*x)),sum,y)", 3, 2, true));
}
TEST("require that expressions similar to xw product are not optimized") {
TEST_DO(verify_not_optimized("reduce(y3*x2y3,sum,x)"));
TEST_DO(verify_not_optimized("reduce(y3*x2y3,prod,y)"));
TEST_DO(verify_not_optimized("reduce(y3*x2y3,sum)"));
TEST_DO(verify_not_optimized("reduce(join(y3,x2y3,f(x,y)(x+y)),sum,y)"));
TEST_DO(verify_not_optimized("reduce(join(y3,x2y3,f(x,y)(x*x)),sum,y)"));
TEST_DO(verify_not_optimized("reduce(join(y3,x2y3,f(x,y)(y*y)),sum,y)"));
TEST_DO(verify_not_optimized("reduce(join(y3,x2y3,f(x,y)(y*x*1)),sum,y)"));
TEST_DO(verify_not_optimized("reduce(y3*x2z3,sum,y)"));
TEST_DO(verify_not_optimized("reduce(y3*x2z3,sum,z)"));
}
TEST("require that xw product can be debug dumped") {
EvalFixture fixture(prod_engine, "reduce(y5*x8y5,sum,y)", param_repo, true);
auto info = fixture.find_all<DenseXWProductFunction>();
ASSERT_EQUAL(info.size(), 1u);
EXPECT_TRUE(info[0]->result_is_mutable());
fprintf(stderr, "%s\n", info[0]->as_string().c_str());
}
TEST_MAIN() { TEST_RUN_ALL(); }
<|endoftext|>
|
<commit_before>// Base header file. Must be first.
#include <Include/PlatformDefinitions.hpp>
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <fstream.h>
#include <iostream.h>
#else
#include <fstream>
#include <iostream>
#endif
#include <util/PlatformUtils.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/XalanOutputStreamPrintWriter.hpp>
#include <PlatformSupport/XalanStdOutputStream.hpp>
#include <DOMSupport/DOMSupportDefault.hpp>
#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPathFactoryDefault.hpp>
#include <XPath/XPathProcessorImpl.hpp>
#include <XalanSourceTree/XalanSourceTreeDOMSupport.hpp>
#include <XalanSourceTree/XalanSourceTreeParserLiaison.hpp>
#include <XSLT/XSLTEngineImpl.hpp>
#include <XSLT/XSLTInit.hpp>
#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTResultTarget.hpp>
#include <XSLT/StylesheetConstructionContextDefault.hpp>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <XSLT/TraceListenerDefault.hpp>
#include <XSLT/XSLTProcessorEnvSupportDefault.hpp>
int
main(
int argc,
const char* argv[])
{
#if !defined(XALAN_NO_NAMESPACES)
using std::auto_ptr;
using std::cerr;
using std::endl;
#endif
// TraceListener flags...
bool traceTemplates = false;
bool traceTemplateChildren = false;
bool traceGenerationEvent = false;
bool traceSelectionEvent = false;
if (argc < 2 || argc > 5)
{
cerr << "Usage: TraceListen [+ 1 or more of following] -TT -TG -TS -TTC" << endl;
return -1;
}
// Set the TraceListener flags...
for (int i = 1; i < argc; i ++)
{
if(!stricmp("-TT", argv[i]))
{
traceTemplates = true;
}
else if(!stricmp("-TG", argv[i]))
{
traceGenerationEvent = true;
}
else if(!stricmp("-TS", argv[i]))
{
traceSelectionEvent = true;
}
else if(!stricmp("-TTC", argv[i]))
{
traceTemplateChildren = true;
}
else
{
cerr << "Usage: TraceListen [+ 1 or more of following] -TT -TG -TS -TTC" << endl;
return -1;
}
}
try
{
// Call the static initializers...
XMLPlatformUtils::Initialize();
{
// Initialize the Xalan XSLT subsystem...
XSLTInit theInit;
// Create some support objects that are necessary for running the processor...
XalanSourceTreeDOMSupport theDOMSupport;
XalanSourceTreeParserLiaison theParserLiaison(theDOMSupport);
// Hook the two together...
theDOMSupport.setParserLiaison(&theParserLiaison);
// Create some more support objects.
XSLTProcessorEnvSupportDefault theXSLTProcessorEnvSupport;
XObjectFactoryDefault theXObjectFactory;
XPathFactoryDefault theXPathFactory;
// Create a processor...
XSLTEngineImpl theProcessor(
theParserLiaison,
theXSLTProcessorEnvSupport,
theDOMSupport,
theXObjectFactory,
theXPathFactory);
// Connect the processor to the support object...
theXSLTProcessorEnvSupport.setProcessor(&theProcessor);
// Create a stylesheet construction context, and a stylesheet
// execution context...
StylesheetConstructionContextDefault theConstructionContext(
theProcessor,
theXSLTProcessorEnvSupport,
theXPathFactory);
StylesheetExecutionContextDefault theExecutionContext(
theProcessor,
theXSLTProcessorEnvSupport,
theDOMSupport,
theXObjectFactory);
// Our input files...The assumption is that the executable will be run
// from same directory as the input files.
const XalanDOMString theXMLFileName("birds.xml");
const XalanDOMString theXSLFileName("birds.xsl");
// Our input sources...
XSLTInputSource theInputSource(c_wstr(theXMLFileName));
XSLTInputSource theStylesheetSource(c_wstr(theXSLFileName));
// Our output target...
const XalanDOMString theOutputFile("birds.out");
XSLTResultTarget theResultTarget(theOutputFile);
// Set up a diagnostic writer to be used by the TraceListener...
XalanStdOutputStream theStdErr(cerr);
XalanOutputStreamPrintWriter diagnosticsWriter(theStdErr);
// Set up the TraceListener...
TraceListenerDefault theTraceListener(
diagnosticsWriter,
traceTemplates,
traceTemplateChildren,
traceGenerationEvent,
traceSelectionEvent);
// Add the TraceListener to the XSLT processor...
theProcessor.setTraceSelects(traceSelectionEvent);
theProcessor.addTraceListener(&theTraceListener);
// Perform the transformation...
theProcessor.process(
theInputSource,
theStylesheetSource,
theResultTarget,
theConstructionContext,
theExecutionContext);
}
// Call the static terminator for Xerces...
XMLPlatformUtils::Terminate();
}
catch(...)
{
cerr << "Exception caught! Exiting..." << endl;
}
return 0;
}
<commit_msg>Removed extraneous using directive.<commit_after>// Base header file. Must be first.
#include <Include/PlatformDefinitions.hpp>
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <fstream.h>
#include <iostream.h>
#else
#include <fstream>
#include <iostream>
#endif
#include <util/PlatformUtils.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/XalanOutputStreamPrintWriter.hpp>
#include <PlatformSupport/XalanStdOutputStream.hpp>
#include <DOMSupport/DOMSupportDefault.hpp>
#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPathFactoryDefault.hpp>
#include <XPath/XPathProcessorImpl.hpp>
#include <XalanSourceTree/XalanSourceTreeDOMSupport.hpp>
#include <XalanSourceTree/XalanSourceTreeParserLiaison.hpp>
#include <XSLT/XSLTEngineImpl.hpp>
#include <XSLT/XSLTInit.hpp>
#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTResultTarget.hpp>
#include <XSLT/StylesheetConstructionContextDefault.hpp>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <XSLT/TraceListenerDefault.hpp>
#include <XSLT/XSLTProcessorEnvSupportDefault.hpp>
int
main(
int argc,
const char* argv[])
{
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::endl;
#endif
// TraceListener flags...
bool traceTemplates = false;
bool traceTemplateChildren = false;
bool traceGenerationEvent = false;
bool traceSelectionEvent = false;
if (argc < 2 || argc > 5)
{
cerr << "Usage: TraceListen [+ 1 or more of following] -TT -TG -TS -TTC" << endl;
return -1;
}
// Set the TraceListener flags...
for (int i = 1; i < argc; i ++)
{
if(!stricmp("-TT", argv[i]))
{
traceTemplates = true;
}
else if(!stricmp("-TG", argv[i]))
{
traceGenerationEvent = true;
}
else if(!stricmp("-TS", argv[i]))
{
traceSelectionEvent = true;
}
else if(!stricmp("-TTC", argv[i]))
{
traceTemplateChildren = true;
}
else
{
cerr << "Usage: TraceListen [+ 1 or more of following] -TT -TG -TS -TTC" << endl;
return -1;
}
}
try
{
// Call the static initializers...
XMLPlatformUtils::Initialize();
{
// Initialize the Xalan XSLT subsystem...
XSLTInit theInit;
// Create some support objects that are necessary for running the processor...
XalanSourceTreeDOMSupport theDOMSupport;
XalanSourceTreeParserLiaison theParserLiaison(theDOMSupport);
// Hook the two together...
theDOMSupport.setParserLiaison(&theParserLiaison);
// Create some more support objects.
XSLTProcessorEnvSupportDefault theXSLTProcessorEnvSupport;
XObjectFactoryDefault theXObjectFactory;
XPathFactoryDefault theXPathFactory;
// Create a processor...
XSLTEngineImpl theProcessor(
theParserLiaison,
theXSLTProcessorEnvSupport,
theDOMSupport,
theXObjectFactory,
theXPathFactory);
// Connect the processor to the support object...
theXSLTProcessorEnvSupport.setProcessor(&theProcessor);
// Create a stylesheet construction context, and a stylesheet
// execution context...
StylesheetConstructionContextDefault theConstructionContext(
theProcessor,
theXSLTProcessorEnvSupport,
theXPathFactory);
StylesheetExecutionContextDefault theExecutionContext(
theProcessor,
theXSLTProcessorEnvSupport,
theDOMSupport,
theXObjectFactory);
// Our input files...The assumption is that the executable will be run
// from same directory as the input files.
const XalanDOMString theXMLFileName("birds.xml");
const XalanDOMString theXSLFileName("birds.xsl");
// Our input sources...
XSLTInputSource theInputSource(c_wstr(theXMLFileName));
XSLTInputSource theStylesheetSource(c_wstr(theXSLFileName));
// Our output target...
const XalanDOMString theOutputFile("birds.out");
XSLTResultTarget theResultTarget(theOutputFile);
// Set up a diagnostic writer to be used by the TraceListener...
XalanStdOutputStream theStdErr(cerr);
XalanOutputStreamPrintWriter diagnosticsWriter(theStdErr);
// Set up the TraceListener...
TraceListenerDefault theTraceListener(
diagnosticsWriter,
traceTemplates,
traceTemplateChildren,
traceGenerationEvent,
traceSelectionEvent);
// Add the TraceListener to the XSLT processor...
theProcessor.setTraceSelects(traceSelectionEvent);
theProcessor.addTraceListener(&theTraceListener);
// Perform the transformation...
theProcessor.process(
theInputSource,
theStylesheetSource,
theResultTarget,
theConstructionContext,
theExecutionContext);
}
// Call the static terminator for Xerces...
XMLPlatformUtils::Terminate();
}
catch(...)
{
cerr << "Exception caught! Exiting..." << endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>/**
* @file platform.cpp
* @brief Purpose: Contains the methods for Platform class.
*
* MIT License
* Copyright (c) 2017 MindScape
*
* https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
*/
#include "../include/platform.hpp"
#include "../engine/include/game.hpp"
using namespace mindscape;
/**
* @brief Platform class constructor
*
* Initializes everything need for the platform.
*
* @param name The object's name.
* @param position Pair of integers representing the x and y position.
* @param priority Priority in object's rendering.
*
* @return void
*/
Platform::Platform(
std::string name,
std::pair<int, int> position,
int priority)
: engine::GameObject(name, position, priority,
{{engine::KeyboardEvent::LEFT, "MOVE_LEFT"},
{engine::KeyboardEvent::RIGHT, "MOVE_RIGHT"}}
) {};
/**
* @brief Event processor method
*
* Process Game Events received.
*
* @param game_event The game event to be received.
*
* @return void
*/
void Platform::on_event(GameEvent game_event) {
platform_movement(game_event);
/*
* First Level Limiter.
* All limiter are in pixels.
*/
first_level_clown(game_event);
/*
* Second Level Limiter
* All limiters are in pixels
*/
second_level_boss(game_event);
}
/**
* @brief Movements platform.
*
* Movements platform based on the girl's movement
*
* @param game_event The game event to be received.
*
* @return void.
*/
void Platform::platform_movement(GameEvent game_event){
std::string event_name = game_event.game_event_name; /**< string. Name of the game_event */
const int movement_platform = 10; /**< int. Movement of the platform (value in pixels) */
if (event_name == "MOVE_LEFT" && !engine::GameObject::on_limit_of_level) {
/* set the right position of the platform based in the game_event */
set_position_x(get_position_x() + movement_platform);
}
else if (event_name == "MOVE_RIGHT" && !engine::GameObject::on_limit_of_level) {
/* set the left position of the platform based in the game_event */
set_position_x(get_position_x() - movement_platform);
}
else {
/* Do nothing */
}
}
/**
* @brief Level limiter.
*
* This method limits the level in right and left position in pixels.
*
* @param game_event The game event to be received.
*
* @return void.
*/
void Platform::first_level_clown(GameEvent game_event){
if (name == "clown_tree") {
const int first_level_inicial_limiter = -1300; /**< Int. Left limit in pixel of the girl can walk */
const int first_level_final_limiter = 13350; /**< Int. Right limit in pixel of the girl can walk */
if (get_position_x() > first_level_final_limiter) {
/* Sets the limit of the map in axis x and don't let the girl pass this limit */
engine::GameObject::on_limit_of_level = true;
set_position_x(first_level_final_limiter);
}
else if (get_position_x() < first_level_inicial_limiter) {
/* Sets the limit of the map in axis x and don't let the girl pass this limit */
engine::GameObject::on_limit_of_level = true;
set_position_x(first_level_inicial_limiter);
}
else {
/* The girl is in between the limits */
engine::GameObject::on_limit_of_level = false;
}
}
else {
/* Do nothing */
}
}
/**
* @brief Level limiter.
*
* This method limits the level in right and left position in pixels.
*
* @param game_event The game event to be received.
*
* @return void.
*/
void Platform::second_level_boss(GameEvent game_event){
if (name == "limiter") {
const int second_level_inicial_limiter = 0; /**< Int. Left limit in pixel of the girl can walk */
const int second_level_final_limiter = 3000; /**< Int. Right limit in pixel of the girl can walk */
if (get_position_x() > second_level_final_limiter) {
/* Sets the limit of the map in axis x and don't let the girl pass this limit */
engine::GameObject::on_limit_of_level = true;
set_position_x(second_level_final_limiter);
}
else if (get_position_x() < second_level_inicial_limiter) {
/* Sets the limit of the map in axis x and don't let the girl pass this limit */
engine::GameObject::on_limit_of_level = true;
set_position_x(second_level_inicial_limiter);
}
else {
/* The girl is in between the limits */
engine::GameObject::on_limit_of_level = false;
}
}
else {
/* Do nothing */
}
}
<commit_msg>[ASSERT] Applies technique in platform.cpp<commit_after>/**
* @file platform.cpp
* @brief Purpose: Contains the methods for Platform class.
*
* MIT License
* Copyright (c) 2017 MindScape
*
* https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
*/
#include "../include/platform.hpp"
#include "../engine/include/game.hpp"
#include <assert.h>
using namespace mindscape;
/**
* @brief Platform class constructor
*
* Initializes everything need for the platform.
*
* @param name The object's name.
* @param position Pair of integers representing the x and y position.
* @param priority Priority in object's rendering.
*
* @return void
*/
Platform::Platform(
std::string name,
std::pair<int, int> position,
int priority)
: engine::GameObject(name, position, priority,
{{engine::KeyboardEvent::LEFT, "MOVE_LEFT"},
{engine::KeyboardEvent::RIGHT, "MOVE_RIGHT"}}
) {};
/**
* @brief Event processor method
*
* Process Game Events received.
*
* @param game_event The game event to be received.
*
* @return void
*/
void Platform::on_event(GameEvent game_event) {
platform_movement(game_event);
/*
* First Level Limiter.
* All limiter are in pixels.
*/
first_level_clown(game_event);
/*
* Second Level Limiter
* All limiters are in pixels
*/
second_level_boss(game_event);
}
/**
* @brief Movements platform.
*
* Movements platform based on the girl's movement
*
* @param game_event The game event to be received.
*
* @return void.
*/
void Platform::platform_movement(GameEvent game_event){
assert(!game_event.game_event_name.empty());
std::string event_name = game_event.game_event_name; /**< string. Name of the game_event */
const int movement_platform = 10; /**< int. Movement of the platform (value in pixels) */
if (event_name == "MOVE_LEFT" && !engine::GameObject::on_limit_of_level) {
/* set the right position of the platform based in the game_event */
set_position_x(get_position_x() + movement_platform);
}
else if (event_name == "MOVE_RIGHT" && !engine::GameObject::on_limit_of_level) {
/* set the left position of the platform based in the game_event */
set_position_x(get_position_x() - movement_platform);
}
else {
/* Do nothing */
}
}
/**
* @brief Level limiter.
*
* This method limits the level in right and left position in pixels.
*
* @param game_event The game event to be received.
*
* @return void.
*/
void Platform::first_level_clown(GameEvent game_event){
if (name == "clown_tree") {
const int first_level_inicial_limiter = -1300; /**< Int. Left limit in pixel of the girl can walk */
const int first_level_final_limiter = 13350; /**< Int. Right limit in pixel of the girl can walk */
if (get_position_x() > first_level_final_limiter) {
/* Sets the limit of the map in axis x and don't let the girl pass this limit */
engine::GameObject::on_limit_of_level = true;
set_position_x(first_level_final_limiter);
}
else if (get_position_x() < first_level_inicial_limiter) {
/* Sets the limit of the map in axis x and don't let the girl pass this limit */
engine::GameObject::on_limit_of_level = true;
set_position_x(first_level_inicial_limiter);
}
else {
/* The girl is in between the limits */
engine::GameObject::on_limit_of_level = false;
}
}
else {
/* Do nothing */
}
}
/**
* @brief Level limiter.
*
* This method limits the level in right and left position in pixels.
*
* @param game_event The game event to be received.
*
* @return void.
*/
void Platform::second_level_boss(GameEvent game_event){
if (name == "limiter") {
const int second_level_inicial_limiter = 0; /**< Int. Left limit in pixel of the girl can walk */
const int second_level_final_limiter = 3000; /**< Int. Right limit in pixel of the girl can walk */
if (get_position_x() > second_level_final_limiter) {
/* Sets the limit of the map in axis x and don't let the girl pass this limit */
engine::GameObject::on_limit_of_level = true;
set_position_x(second_level_final_limiter);
}
else if (get_position_x() < second_level_inicial_limiter) {
/* Sets the limit of the map in axis x and don't let the girl pass this limit */
engine::GameObject::on_limit_of_level = true;
set_position_x(second_level_inicial_limiter);
}
else {
/* The girl is in between the limits */
engine::GameObject::on_limit_of_level = false;
}
}
else {
/* Do nothing */
}
}
<|endoftext|>
|
<commit_before>#include "mainwindow.h"
#include <QActionGroup>
#include <QFileDialog>
#include <QKeyEvent>
#include <QString>
#include "ui_mainwindow.h"
#include "screenwidget.h"
#include "emuthread.h"
#include "gameboy/core.h"
#include "gameboy/keyboard.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
videoScalingGroup(new QActionGroup(this)) {
ui->setupUi(this);
videoScalingGroup->addAction(ui->action1x);
videoScalingGroup->addAction(ui->action2x);
videoScalingGroup->addAction(ui->action4x);
videoScalingGroup->addAction(ui->action6x);
gameboyCore = new gameboy::Core;
keyboard = gameboyCore->getKeyboard();
screenWidget = new ScreenWidget(this);
screenWidget->setFramebuffer(gameboyCore->getFramebuffer());
setCentralWidget(screenWidget);
setScaling(4);
emuThread = new EmuThread(gameboyCore, screenWidget);
screenWidget->doneCurrent();
screenWidget->context()->moveToThread(emuThread);
}
MainWindow::~MainWindow() {
pauseEmulation();
delete emuThread;
delete gameboyCore;
delete ui;
}
void MainWindow::continueEmulation() {
if (!emuThread->isRunning()) {
emuThread->stopped = false;
emuThread->start();
}
}
void MainWindow::pauseEmulation() {
if (emuThread->isRunning()) {
emuThread->stopped = true;
emuThread->wait();
}
}
void MainWindow::loadROM() {
QString fileName = QFileDialog::getOpenFileName(this, "Open ROM", "", "Gameboy ROMs (*.gb)");
if (!fileName.isNull()) {
pauseEmulation();
gameboyCore->reset();
gameboyCore->loadROM(fileName.toStdString());
continueEmulation();
}
}
void MainWindow::setScaling(int scaling) {
screenWidget->resize(160*scaling, 144*scaling);
resize(160*scaling, 144*scaling + ui->menubar->height());
}
void MainWindow::scale1x() {
setScaling(1);
}
void MainWindow::scale2x() {
setScaling(2);
}
void MainWindow::scale4x() {
setScaling(4);
}
void MainWindow::scale6x() {
setScaling(6);
}
void MainWindow::keyPressEvent(QKeyEvent *event) {
switch (event->key()) {
case Qt::Key_Up:
keyboard->up = true;
break;
case Qt::Key_Down:
keyboard->down = true;
break;
case Qt::Key_Left:
keyboard->left = true;
break;
case Qt::Key_Right:
keyboard->right = true;
break;
case Qt::Key_C:
keyboard->select = true;
break;
case Qt::Key_V:
keyboard->start = true;
break;
case Qt::Key_F:
keyboard->a = true;
break;
case Qt::Key_D:
keyboard->b = true;
break;
default: //To make the compiler STFU
break;
}
}
void MainWindow::keyReleaseEvent(QKeyEvent *event) {
switch (event->key()) {
case Qt::Key_Up:
keyboard->up = false;
break;
case Qt::Key_Down:
keyboard->down = false;
break;
case Qt::Key_Left:
keyboard->left = false;
break;
case Qt::Key_Right:
keyboard->right = false;
break;
case Qt::Key_C:
keyboard->select = false;
break;
case Qt::Key_V:
keyboard->start = false;
break;
case Qt::Key_F:
keyboard->a = false;
break;
case Qt::Key_D:
keyboard->b = false;
break;
default: //To make the compiler STFU
break;
}
}
<commit_msg>Command line argument parsing<commit_after>#include "mainwindow.h"
#include <QActionGroup>
#include <QFileDialog>
#include <QKeyEvent>
#include <QString>
#include <QStringList>
#include "ui_mainwindow.h"
#include "screenwidget.h"
#include "emuthread.h"
#include "gameboy/core.h"
#include "gameboy/keyboard.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
videoScalingGroup(new QActionGroup(this)) {
ui->setupUi(this);
videoScalingGroup->addAction(ui->action1x);
videoScalingGroup->addAction(ui->action2x);
videoScalingGroup->addAction(ui->action4x);
videoScalingGroup->addAction(ui->action6x);
gameboyCore = new gameboy::Core;
keyboard = gameboyCore->getKeyboard();
screenWidget = new ScreenWidget(this);
screenWidget->setFramebuffer(gameboyCore->getFramebuffer());
setCentralWidget(screenWidget);
setScaling(4);
emuThread = new EmuThread(gameboyCore, screenWidget);
screenWidget->doneCurrent();
screenWidget->context()->moveToThread(emuThread);
QStringList args = QCoreApplication::arguments();
if (args.size() > 1) {
gameboyCore->loadROM(args.at(1).toStdString());
continueEmulation();
}
}
MainWindow::~MainWindow() {
pauseEmulation();
delete emuThread;
delete gameboyCore;
delete ui;
}
void MainWindow::continueEmulation() {
if (!emuThread->isRunning()) {
emuThread->stopped = false;
emuThread->start();
}
}
void MainWindow::pauseEmulation() {
if (emuThread->isRunning()) {
emuThread->stopped = true;
emuThread->wait();
}
}
void MainWindow::loadROM() {
QString fileName = QFileDialog::getOpenFileName(this, "Open ROM", "", "Gameboy ROMs (*.gb)");
if (!fileName.isNull()) {
pauseEmulation();
gameboyCore->reset();
gameboyCore->loadROM(fileName.toStdString());
continueEmulation();
}
}
void MainWindow::setScaling(int scaling) {
screenWidget->resize(160*scaling, 144*scaling);
resize(160*scaling, 144*scaling + ui->menubar->height());
}
void MainWindow::scale1x() {
setScaling(1);
}
void MainWindow::scale2x() {
setScaling(2);
}
void MainWindow::scale4x() {
setScaling(4);
}
void MainWindow::scale6x() {
setScaling(6);
}
void MainWindow::keyPressEvent(QKeyEvent *event) {
switch (event->key()) {
case Qt::Key_Up:
keyboard->up = true;
break;
case Qt::Key_Down:
keyboard->down = true;
break;
case Qt::Key_Left:
keyboard->left = true;
break;
case Qt::Key_Right:
keyboard->right = true;
break;
case Qt::Key_C:
keyboard->select = true;
break;
case Qt::Key_V:
keyboard->start = true;
break;
case Qt::Key_F:
keyboard->a = true;
break;
case Qt::Key_D:
keyboard->b = true;
break;
default: //To make the compiler STFU
break;
}
}
void MainWindow::keyReleaseEvent(QKeyEvent *event) {
switch (event->key()) {
case Qt::Key_Up:
keyboard->up = false;
break;
case Qt::Key_Down:
keyboard->down = false;
break;
case Qt::Key_Left:
keyboard->left = false;
break;
case Qt::Key_Right:
keyboard->right = false;
break;
case Qt::Key_C:
keyboard->select = false;
break;
case Qt::Key_V:
keyboard->start = false;
break;
case Qt::Key_F:
keyboard->a = false;
break;
case Qt::Key_D:
keyboard->b = false;
break;
default: //To make the compiler STFU
break;
}
}
<|endoftext|>
|
<commit_before>#include "NFComm/NFPluginModule/NFPlatform.h"
#if NF_PLATFORM == NF_PLATFORM_WIN
#endif
#pragma comment( lib, "Dbghelp.lib" )
#ifdef NF_DEBUG_MODE
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DYNAMIC_PLUGIN
#pragma comment( lib, "NFCore_d.lib" )
#pragma comment( lib, "Theron_d.lib" )
#else
#pragma comment( lib, "NFCore_d.lib" )
#pragma comment( lib, "Theron_d.lib" )
#endif
//#pragma comment( lib, "Theron_d.lib" )
#pragma comment( lib, "libglog_static_d.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "NFCore_d.a" )
#pragma comment( lib, "libglog_d.a" )
#pragma comment( lib, "libtherond.a")
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#endif
#else
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DYNAMIC_PLUGIN
#pragma comment( lib, "NFCore.lib" )
#pragma comment( lib, "Theron.lib" )
#else
#pragma comment( lib, "NFCorec.lib" )
#pragma comment( lib, "Theron.lib" )
#endif
//#pragma comment( lib, "Theron.lib" )
#pragma comment( lib, "libglog_static.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "NFCore.a" )
#pragma comment( lib, "libglog.a" )
#pragma comment( lib, "libtherond.a")
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#endif
#endif
<commit_msg>remove glog lib linking<commit_after>#include "NFComm/NFPluginModule/NFPlatform.h"
#if NF_PLATFORM == NF_PLATFORM_WIN
#endif
#pragma comment( lib, "Dbghelp.lib" )
#ifdef NF_DEBUG_MODE
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DYNAMIC_PLUGIN
#pragma comment( lib, "NFCore_d.lib" )
#pragma comment( lib, "Theron_d.lib" )
#else
#pragma comment( lib, "NFCore_d.lib" )
#pragma comment( lib, "Theron_d.lib" )
#endif
//#pragma comment( lib, "Theron_d.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "NFCore_d.a" )
#pragma comment( lib, "libtherond.a")
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#endif
#else
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DYNAMIC_PLUGIN
#pragma comment( lib, "NFCore.lib" )
#pragma comment( lib, "Theron.lib" )
#else
#pragma comment( lib, "NFCorec.lib" )
#pragma comment( lib, "Theron.lib" )
#endif
//#pragma comment( lib, "Theron.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "NFCore.a" )
#pragma comment( lib, "libtherond.a")
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#endif
#endif
<|endoftext|>
|
<commit_before>#pragma once
#include "includes.hpp"
#define TAGLIB_STATIC
#include <taglib/fileref.h>
#include <taglib/tag.h>
#include <taglib/tpropertymap.h>
class playlist : public Component, public FileDragAndDropTarget {
struct playlistModel : public ListBoxModel {
StringArray entries;
int getNumRows() override {
return entries.size();
}
void paintListBoxItem(int rowNumber, Graphics& g,
int width, int height, bool rowIsSelected) override {
if (rowIsSelected)
g.fillAll(Colours::lightblue);
g.setColour(Colours::black);
g.setFont(height * 0.7f);
g.drawText(entries[rowNumber], 5, 0, width, height, Justification::centredLeft, true);
}
};
ListBox box;
playlistModel model;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(playlist);
public:
playlist() : box("playlist-box", nullptr) {
setName("playlist");
box.setModel(&model);
box.setMultipleSelectionEnabled(true);
addAndMakeVisible(box);
}
void resized() override {
box.setBounds(getLocalBounds().reduced(0));
}
bool isInterestedInFileDrag(const StringArray& /*files*/) override {
return true;
}
void fileDragEnter(const StringArray& /*files*/, int /*x*/, int /*y*/) override {
repaint();
}
void fileDragMove (const StringArray& /*files*/, int /*x*/, int /*y*/) override {}
void fileDragExit (const StringArray& /*files*/) override {
repaint();
}
void filesDropped (const StringArray& files, int /*x*/, int /*y*/) override {
for (auto &f : files) {
//TagLib::FileRef file(f.toRawUTF8());
//f = (file.tag()->album() + L" | " + file.tag()->artist() + L" | " + file.tag()->title()).toCString();
}
model.entries.addArray(files);
box.updateContent();
repaint();
}
base::string getSelectedRowString() {
return model.entries[box.getSelectedRow()].toStdString();
}
};
<commit_msg>+ encoding<commit_after>#pragma once
#include "includes.hpp"
#define TAGLIB_STATIC
#include <taglib/fileref.h>
#include <taglib/tag.h>
#include <taglib/tpropertymap.h>
class playlist : public Component, public FileDragAndDropTarget {
struct playlistModel : public ListBoxModel {
StringArray entries;
int getNumRows() override {
return entries.size();
}
void paintListBoxItem(int rowNumber, Graphics& g,
int width, int height, bool rowIsSelected) override {
if (rowIsSelected)
g.fillAll(Colours::lightblue);
g.setColour(Colours::black);
g.setFont(height * 0.7f);
g.drawText(entries[rowNumber], 5, 0, width, height, Justification::centredLeft, true);
}
};
ListBox box;
playlistModel model;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(playlist);
// TODO: system codecs?
bool isFileSupported(const String &fname) {
return fname.endsWith(".mp3")
|| fname.endsWith(".wav")
|| fname.endsWith(".wma")
|| fname.endsWith(".flac")
|| fname.endsWith(".ogg")
|| fname.endsWith(".ape");
}
public:
playlist() : box("playlist-box", nullptr) {
setName("playlist");
box.setModel(&model);
box.setMultipleSelectionEnabled(true);
addAndMakeVisible(box);
}
void resized() override {
box.setBounds(getLocalBounds().reduced(0));
}
bool isInterestedInFileDrag(const StringArray& /*files*/) override {
return true;
}
void fileDragEnter(const StringArray& /*files*/, int /*x*/, int /*y*/) override {
repaint();
}
void fileDragMove (const StringArray& /*files*/, int /*x*/, int /*y*/) override {}
void fileDragExit (const StringArray& /*files*/) override {
repaint();
}
void filesDropped (const StringArray& files, int /*x*/, int /*y*/) override {
for (auto &f : files) {
if (isFileSupported(f)) {
//TagLib::FileRef file(f.toRawUTF8());
//f = (file.tag()->album() + L" | " + file.tag()->artist() + L" | " + file.tag()->title()).toCString();
}
}
model.entries.addArray(files);
box.updateContent();
repaint();
}
base::string getSelectedRowString() {
return model.entries[box.getSelectedRow()].toStdString();
}
};
<|endoftext|>
|
<commit_before>#include "util/assert.h"
#ifdef DEBUG
#include <stdio.h>
void __AssertFail(const char* file, unsigned line)
#ifndef _MSC_VER
throw (__Assert)
#endif
{
static bool yes_all = false;
if (yes_all)
return;
const char* msg =
"\n\
**************************************\n\
Assertion failure:\n\
\tfile %s line %d\n\
Continue (y/a/n) ?\n";
fprintf(stderr, msg, file, line);
for (;;) {
switch (getchar()) {
case 'a': yes_all = true;
case 'y': return;
case EOF:
case 'n': throw __Assert(file, line);
}
}
}
#endif //defined(DEBUG)
<commit_msg>don't need this anymore<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cuisrchdlg.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: kz $ $Date: 2007-05-10 14:36:33 $
*
* 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_svx.hxx"
#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif
// include ---------------------------------------------------------------
#ifndef _SV_WRKWIN_HXX
#include <vcl/wrkwin.hxx>
#endif
#ifndef _SV_MOREBTN_HXX //autogen wg. MoreButton
#include <vcl/morebtn.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen wg. RET_OK
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXSLSTITM_HXX
#include <svtools/slstitm.hxx>
#endif
#ifndef _SFXITEMITER_HXX
#include <svtools/itemiter.hxx>
#endif
#ifndef _SFXSTYLE_HXX
#include <svtools/style.hxx>
#endif
#ifndef _SVT_SEARCHOPT_HXX_
#include <svtools/searchopt.hxx>
#endif
#ifndef _SFXDISPATCH_HXX
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#ifndef _SFXMODULE_HXX
#include <sfx2/module.hxx>
#endif
#ifndef _SFXVIEWSH_HXX //autogen
#include <sfx2/viewsh.hxx>
#endif
#ifndef _BASEDLGS_HXX
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _SVTOOLS_CJKOPTIONS_HXX
#include <svtools/cjkoptions.hxx>
#endif
#ifndef _COM_SUN_STAR_I18N_TRANSLITERATIONMODULES_HPP_
#include <com/sun/star/i18n/TransliterationModules.hpp>
#endif
#define _CUI_SRCHDLG_CXX
#include "cuisrchdlg.hxx"
#include "dialogs.hrc"
#include "svxitems.hrc"
#include "srchdlg.hrc"
#define ITEMID_SETITEM 0
#include <sfx2/srchitem.hxx>
#include "pageitem.hxx"
#include "srchctrl.hxx"
//CHINA001 #include "srchxtra.hxx"
#include "dialmgr.hxx"
#include "dlgutil.hxx"
#ifndef _SVX_OPTJSEARCH_HXX_
#include <optjsearch.hxx>
#endif
#ifndef _SVX_BRSHITEM_HXX //autogen
#include <brshitem.hxx>
#endif
#ifndef _SVX_BACKGRND_HXX //autogen
#include "backgrnd.hxx"
#endif
// class SvxJSearchOptionsDialog -----------------------------------------
SvxJSearchOptionsDialog::SvxJSearchOptionsDialog(
Window *pParent,
const SfxItemSet& rOptionsSet, USHORT /*nUniqueId*/, INT32 nInitialFlags ) :
SfxSingleTabDialog ( pParent, rOptionsSet, RID_SVXPAGE_JSEARCH_OPTIONS ),
nInitialTlFlags( nInitialFlags )
{
pPage = (SvxJSearchOptionsPage *)
SvxJSearchOptionsPage::Create( this, rOptionsSet );
SetTabPage( pPage ); //! implicitly calls pPage->Reset(...)!
pPage->EnableSaveOptions( FALSE );
}
SvxJSearchOptionsDialog::~SvxJSearchOptionsDialog()
{
// pPage will be implicitly destroyed by the
// SfxSingleTabDialog destructor
}
void SvxJSearchOptionsDialog::Activate()
{
pPage->SetTransliterationFlags( nInitialTlFlags );
}
INT32 SvxJSearchOptionsDialog::GetTransliterationFlags() const
{
return pPage->GetTransliterationFlags();
}
void SvxJSearchOptionsDialog::SetTransliterationFlags( INT32 nSettings )
{
pPage->SetTransliterationFlags( nSettings );
}
<commit_msg>INTEGRATION: CWS vgbugs07 (1.9.32); FILE MERGED 2007/06/04 13:26:15 vg 1.9.32.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cuisrchdlg.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2007-06-27 16:58:43 $
*
* 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_svx.hxx"
#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif
// include ---------------------------------------------------------------
#ifndef _SV_WRKWIN_HXX
#include <vcl/wrkwin.hxx>
#endif
#ifndef _SV_MOREBTN_HXX //autogen wg. MoreButton
#include <vcl/morebtn.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen wg. RET_OK
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXSLSTITM_HXX
#include <svtools/slstitm.hxx>
#endif
#ifndef _SFXITEMITER_HXX
#include <svtools/itemiter.hxx>
#endif
#ifndef _SFXSTYLE_HXX
#include <svtools/style.hxx>
#endif
#ifndef _SVT_SEARCHOPT_HXX_
#include <svtools/searchopt.hxx>
#endif
#ifndef _SFXDISPATCH_HXX
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#ifndef _SFXMODULE_HXX
#include <sfx2/module.hxx>
#endif
#ifndef _SFXVIEWSH_HXX //autogen
#include <sfx2/viewsh.hxx>
#endif
#ifndef _BASEDLGS_HXX
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _SVTOOLS_CJKOPTIONS_HXX
#include <svtools/cjkoptions.hxx>
#endif
#ifndef _COM_SUN_STAR_I18N_TRANSLITERATIONMODULES_HPP_
#include <com/sun/star/i18n/TransliterationModules.hpp>
#endif
#define _CUI_SRCHDLG_CXX
#include "cuisrchdlg.hxx"
#include <svx/dialogs.hrc>
#include <svx/svxitems.hrc>
#include "srchdlg.hrc"
#define ITEMID_SETITEM 0
#include <sfx2/srchitem.hxx>
#include <svx/pageitem.hxx>
#include "srchctrl.hxx"
//CHINA001 #include "srchxtra.hxx"
#include <svx/dialmgr.hxx>
#include "dlgutil.hxx"
#ifndef _SVX_OPTJSEARCH_HXX_
#include <optjsearch.hxx>
#endif
#ifndef _SVX_BRSHITEM_HXX //autogen
#include <svx/brshitem.hxx>
#endif
#ifndef _SVX_BACKGRND_HXX //autogen
#include "backgrnd.hxx"
#endif
// class SvxJSearchOptionsDialog -----------------------------------------
SvxJSearchOptionsDialog::SvxJSearchOptionsDialog(
Window *pParent,
const SfxItemSet& rOptionsSet, USHORT /*nUniqueId*/, INT32 nInitialFlags ) :
SfxSingleTabDialog ( pParent, rOptionsSet, RID_SVXPAGE_JSEARCH_OPTIONS ),
nInitialTlFlags( nInitialFlags )
{
pPage = (SvxJSearchOptionsPage *)
SvxJSearchOptionsPage::Create( this, rOptionsSet );
SetTabPage( pPage ); //! implicitly calls pPage->Reset(...)!
pPage->EnableSaveOptions( FALSE );
}
SvxJSearchOptionsDialog::~SvxJSearchOptionsDialog()
{
// pPage will be implicitly destroyed by the
// SfxSingleTabDialog destructor
}
void SvxJSearchOptionsDialog::Activate()
{
pPage->SetTransliterationFlags( nInitialTlFlags );
}
INT32 SvxJSearchOptionsDialog::GetTransliterationFlags() const
{
return pPage->GetTransliterationFlags();
}
void SvxJSearchOptionsDialog::SetTransliterationFlags( INT32 nSettings )
{
pPage->SetTransliterationFlags( nSettings );
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: msashape.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: hr $ $Date: 2007-06-27 18:34:13 $
*
* 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 _MSASHAPE_HXX
#define _MSASHAPE_HXX
#ifndef _MSDFFDEF_HXX
#include <svx/msdffdef.hxx>
#endif
#ifndef _MSDFFIMP_HXX
#include <svx/msdffimp.hxx>
#endif
#define DFF_CUSTOMSHAPE_FLIP_V 1
#define DFF_CUSTOMSHAPE_FLIP_H 2
#define DFF_CUSTOMSHAPE_EXCH 4
class SdrModel;
class SfxItemSet;
struct SvxMSDffVertPair;
struct SvxMSDffCalculationData;
struct SvxMSDffTextRectangles;
class SvxMSDffAdjustmentHandle;
class SvxMSDffCustomShape
{
MSFilterTracer* pTracer;
MSO_SPT eSpType;
sal_Int32 nCoordWidth;
sal_Int32 nCoordHeight;
Rectangle aSnapRect;
double fXScale;
double fYScale;
sal_Int32 nFix16Angle;
sal_Int32 nXRef;
sal_Int32 nYRef;
sal_uInt32 nFlags;
sal_uInt32 nNumElemVert;
sal_uInt32 nNumElemSeg;
sal_uInt32 nColorData;
SvxMSDffVertPair* pVertData;
sal_uInt16* pSegData;
sal_uInt32 nTextRectData;
SvxMSDffTextRectangles* pTextRectData;
sal_uInt32 nCalculationData;
SvxMSDffCalculationData* pCalculationData;
sal_uInt32 nAdjustmentHandles;
SvxMSDffAdjustmentHandle* pAdjustmentHandles;
sal_uInt32 nGluePoints;
SvxMSDffVertPair* pGluePoints;
sal_Bool bIsEmpty : 1;
sal_Bool bVertAlloc : 1;
sal_Bool bSegAlloc : 1;
sal_Bool bCalcAlloc : 1;
sal_Bool bTextRectAlloc : 1;
sal_Bool bTextFlow : 1;
sal_Bool bFilled : 1;
sal_Bool bFlipH : 1;
sal_Bool bFlipV : 1;
sal_Int32 GetAdjustValue( sal_uInt32 nIndex ) const;
sal_Int32 GetAdjustValue( sal_uInt32 nIndex, sal_Int32 nDefault ) const;
sal_Int32 Fix16ToAngle( sal_Int32 nAngle ) const;
Color ImplGetColorData( const Color& rFillColor, sal_uInt32 nIndex );
double ImplGetValue( sal_uInt16 nIndex, sal_uInt32& nGeometryFlags ) const;
Point GetPoint( const SvxMSDffVertPair&, sal_Bool bScale = sal_True ) const;
static void SwapStartAndEndArrow( SdrObject* pObj );
public :
SdrObject* GetObject( SdrModel* pSdrModel, SfxItemSet& rSet, sal_Bool bSetAdjustmentItem );
sal_Bool IsEmpty() const;
Rectangle GetTextRect() const;
static sal_Bool HasGluePointList( const MSO_SPT eShapeType );
static MSO_SPT GetShapeTypeFromSdrObject( const SdrObject* );
SvxMSDffCustomShape( const DffPropertyReader& rPropReader, SvStream&,
DffObjData& rObjDat, Rectangle& rSnapRect, sal_Int32 nFix16Angle, MSFilterTracer* pTracer );
~SvxMSDffCustomShape();
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.12.368); FILE MERGED 2008/04/01 12:49:21 thb 1.12.368.2: #i85898# Stripping all external header guards 2008/03/31 14:22:51 rt 1.12.368.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: msashape.hxx,v $
* $Revision: 1.13 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _MSASHAPE_HXX
#define _MSASHAPE_HXX
#include <svx/msdffdef.hxx>
#include <svx/msdffimp.hxx>
#define DFF_CUSTOMSHAPE_FLIP_V 1
#define DFF_CUSTOMSHAPE_FLIP_H 2
#define DFF_CUSTOMSHAPE_EXCH 4
class SdrModel;
class SfxItemSet;
struct SvxMSDffVertPair;
struct SvxMSDffCalculationData;
struct SvxMSDffTextRectangles;
class SvxMSDffAdjustmentHandle;
class SvxMSDffCustomShape
{
MSFilterTracer* pTracer;
MSO_SPT eSpType;
sal_Int32 nCoordWidth;
sal_Int32 nCoordHeight;
Rectangle aSnapRect;
double fXScale;
double fYScale;
sal_Int32 nFix16Angle;
sal_Int32 nXRef;
sal_Int32 nYRef;
sal_uInt32 nFlags;
sal_uInt32 nNumElemVert;
sal_uInt32 nNumElemSeg;
sal_uInt32 nColorData;
SvxMSDffVertPair* pVertData;
sal_uInt16* pSegData;
sal_uInt32 nTextRectData;
SvxMSDffTextRectangles* pTextRectData;
sal_uInt32 nCalculationData;
SvxMSDffCalculationData* pCalculationData;
sal_uInt32 nAdjustmentHandles;
SvxMSDffAdjustmentHandle* pAdjustmentHandles;
sal_uInt32 nGluePoints;
SvxMSDffVertPair* pGluePoints;
sal_Bool bIsEmpty : 1;
sal_Bool bVertAlloc : 1;
sal_Bool bSegAlloc : 1;
sal_Bool bCalcAlloc : 1;
sal_Bool bTextRectAlloc : 1;
sal_Bool bTextFlow : 1;
sal_Bool bFilled : 1;
sal_Bool bFlipH : 1;
sal_Bool bFlipV : 1;
sal_Int32 GetAdjustValue( sal_uInt32 nIndex ) const;
sal_Int32 GetAdjustValue( sal_uInt32 nIndex, sal_Int32 nDefault ) const;
sal_Int32 Fix16ToAngle( sal_Int32 nAngle ) const;
Color ImplGetColorData( const Color& rFillColor, sal_uInt32 nIndex );
double ImplGetValue( sal_uInt16 nIndex, sal_uInt32& nGeometryFlags ) const;
Point GetPoint( const SvxMSDffVertPair&, sal_Bool bScale = sal_True ) const;
static void SwapStartAndEndArrow( SdrObject* pObj );
public :
SdrObject* GetObject( SdrModel* pSdrModel, SfxItemSet& rSet, sal_Bool bSetAdjustmentItem );
sal_Bool IsEmpty() const;
Rectangle GetTextRect() const;
static sal_Bool HasGluePointList( const MSO_SPT eShapeType );
static MSO_SPT GetShapeTypeFromSdrObject( const SdrObject* );
SvxMSDffCustomShape( const DffPropertyReader& rPropReader, SvStream&,
DffObjData& rObjDat, Rectangle& rSnapRect, sal_Int32 nFix16Angle, MSFilterTracer* pTracer );
~SvxMSDffCustomShape();
};
#endif
<|endoftext|>
|
<commit_before><commit_msg>fdo#70100 Detect single stream excel files with BOF ID 5<commit_after><|endoftext|>
|
<commit_before>#include <iostream>
#include <strstream>
#include <stdarg.h>
#include "KAI/KAI.h"
#include "KAI/Translator/Lexer.h"
using namespace std;
KAI_BEGIN
Lexer::Lexer(const char *in)
: input(in)
{
CreateLines();
AddKeywords();
Run();
}
void Lexer::AddKeywords()
{
keyWords["if"] = Token::If;
keyWords["else"] = Token::Else;
keyWords["for"] = Token::For;
keyWords["true"] = Token::True;
keyWords["false"] = Token::False;
keyWords["return"] = Token::Return;
keyWords["self"] = Token::Self;
keyWords["fun"] = Token::Fun;
keyWords["yield"] = Token::Yield;
keyWords["in"] = Token::In;
keyWords["while"] = Token::While;
keyWords["assert"] = Token::Assert;
}
bool Lexer::Run()
{
offset = 0;
lineNumber = 0;
while (!Failed && NextToken())
;
return Add(Token::None, 0);
}
void Lexer::Print() const
{
//std::copy(tokens.begin(), tokens.end(), ostream_iterator<Token>(std::cout, " "));
for (auto tok : tokens)
std::cout << tok << " ";
std::cout << std::endl;
}
Slice Lexer::Gather(int (*filt)(int))
{
int start = offset;
while (filt(Next()))
;
return Slice(start, offset);
}
bool Lexer::Add(Token::Type type, Slice slice)
{
tokens.push_back(Token(type, *this, lineNumber, slice));
return true;
}
bool Lexer::Add(Token::Type type, int len)
{
Add(type, Slice(offset, offset + len));
while (len--)
Next();
return true;
}
bool Lexer::LexAlpha()
{
Token tok(Token::Ident, *this, lineNumber, Gather(isalnum));
auto kw = keyWords.find(tok.Text());
if (kw != keyWords.end())
tok.type = kw->second;
tokens.push_back(tok);
return true;
}
int IsSpaceChar(int ch)
{
return ch == ' ';
}
bool Lexer::NextToken()
{
auto current = Current();
if (current == 0)
return false;
if (isalpha(current))
return LexAlpha();
if (isdigit(current))
return Add(Token::Int, Gather(isdigit));
switch (current)
{
case '\t': return Add(Token::Tab);
case '\n': return Add(Token::NewLine);
case ';': return Add(Token::Semi);
case '{': return Add(Token::OpenBrace);
case '}': return Add(Token::CloseBrace);
case '(': return Add(Token::OpenParan);
case ')': return Add(Token::CloseParan);
case ':': return Add(Token::Colon);
case ' ': return Add(Token::Whitespace, Gather(IsSpaceChar));
case '@': return Add(Token::Lookup);
case ',': return Add(Token::Comma);
case '*': return Add(Token::Mul);
case '[': return Add(Token::OpenSquareBracket);
case ']': return Add(Token::CloseSquareBracket);
case '=': return AddIfNext('=', Token::Equiv, Token::Assign);
case '!': return AddIfNext('=', Token::NotEquiv, Token::Not);
case '&': return AddIfNext('&', Token::And, Token::BitAnd);
case '|': return AddIfNext('|', Token::Or, Token::BitOr);
case '<': return AddIfNext('=', Token::LessEquiv, Token::Less);
case '>': return AddIfNext('=', Token::GreaterEquiv, Token::Greater);
case '"': return LexString();
case '\'': return LexAlpha();
case '-':
if (Peek() == '-')
{
Next();
return Add(Token::Decrement);
}
if (Peek() == '=')
{
Next();
return Add(Token::MinusAssign);
}
return Add(Token::Minus);
case '.':
if (Peek() == '.')
{
Next();
if (Peek() == '.')
{
Next();
return Add(Token::Replace, 3);
}
return Fail("Two dots");
}
return Add(Token::Dot);
case '+':
if (Peek() == '+')
{
Next();
return Add(Token::Increment);
}
if (Peek() == '=')
{
Next();
return Add(Token::PlusAssign);
}
return Add(Token::Plus);
case '/':
if (Peek() == '/')
{
Next();
int start = offset;
while (Next() != '\n')
;
return Add(Token::Comment, offset - start);
}
return Add(Token::Divide);
}
LexError("Unrecognised %c");
return false;
}
std::string Lexer::CreateError(Token tok, const char *fmt, ...)
{
char buff0[2000];
va_list ap;
va_start(ap, fmt);
vsprintf_s(buff0, fmt, ap);
const char *fmt1 = "%s(%d):[%d]: %s\n";
char buff[2000];
sprintf_s(buff, fmt1, "", tok.lineNumber, tok.slice.Start, buff0);
int beforeContext = 1;
int afterContext = 0;
const Lexer &lex = *tok.lexer;
int start = std::max(0, tok.lineNumber - beforeContext);
int end = std::min((int)lex.lines.size() - 1, tok.lineNumber + afterContext);
strstream err;
err << buff << endl;
for (int n = start; n <= end; ++n)
{
for (auto ch : lex.lines[n])
{
if (ch == '\t')
err << " ";
else
err << ch;
}
if (n == tok.lineNumber)
{
for (int ch = 0; ch < (int)lex.lines[n].size(); ++ch)
{
if (lex.lines[tok.lineNumber][ch] == '\t')
err << " ";
else if (ch == tok.slice.Start)
{
err << '^';
break;
}
}
err << endl;
}
}
err << ends;
return err.str();
}
bool Process::Fail(const std::string &err)
{
Failed = true;
Error = err;
return false;
}
bool Process::Fail(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
char buffer[1000];
vsprintf_s(buffer, fmt, ap);
return Fail(std::string(buffer));
}
char Lexer::Current() const
{
if (lineNumber == (int)lines.size())
return 0;
return Line()[offset];
}
const std::string &Lexer::Line() const
{
return lines[lineNumber];
}
char Lexer::Next()
{
if (EndOfLine())
{
offset = 0;
++lineNumber;
}
else
++offset;
if (lineNumber == (int)lines.size())
return 0;
return Line()[offset];
}
char Lexer::Peek() const
{
if (EndOfLine())
return 0;
return Line()[offset + 1];
}
void Lexer::CreateLines()
{
// ensure we end with a newline.
input.push_back('\n');
size_t lineStart = 0;
for (size_t n = 0; n < input.size(); ++n)
{
if (input[n] == '\n')
{
lines.push_back(input.substr(lineStart, n - lineStart + 1));
lineStart = n + 1;
}
}
}
bool Lexer::EndOfLine() const
{
return offset == (int)Line().size() - 1;
}
bool Lexer::AddIfNext(char ch, Token::Type thenType, Token::Type elseType)
{
if (Peek() == ch)
{
Next();
return Add(thenType, 2);
}
return Add(elseType, 1);
}
bool Lexer::AddTwoCharOp(Token::Type ty)
{
Add(ty, 2);
Next();
return true;
}
bool Lexer::LexString()
{
int start = offset;
Next();
while (!Failed && Current() != '"')
{
if (Current() == '\\')
{
switch (Next())
{
case '"':
case 'n':
case 't':
break;
default:
LexError("Bad escape sequence %c");
return false;
}
}
if (Peek() == 0)
{
Fail("Bad string literal");
return false;
}
Next();
}
Next();
// the +1 and -1 to remove the start and end double quote characters
tokens.push_back(Token(Token::String, *this, lineNumber, Slice(start + 1, offset - 1)));
return true;
}
void Lexer::LexError(const char *text)
{
Fail(CreateError(Token(Token::None, *this, lineNumber, Slice(offset, offset)), text, Current()));
}
KAI_END
<commit_msg>.<commit_after>#include "KAI/KAI.h"
#include <iostream>
#include <strstream>
#include <stdarg.h>
#include "KAI/Translator/Lexer.h"
using namespace std;
KAI_BEGIN
Lexer::Lexer(const char *in)
: input(in)
{
CreateLines();
AddKeywords();
Run();
}
void Lexer::AddKeywords()
{
keyWords["if"] = Token::If;
keyWords["else"] = Token::Else;
keyWords["for"] = Token::For;
keyWords["true"] = Token::True;
keyWords["false"] = Token::False;
keyWords["return"] = Token::Return;
keyWords["self"] = Token::Self;
keyWords["fun"] = Token::Fun;
keyWords["yield"] = Token::Yield;
keyWords["in"] = Token::In;
keyWords["while"] = Token::While;
keyWords["assert"] = Token::Assert;
}
bool Lexer::Run()
{
offset = 0;
lineNumber = 0;
while (!Failed && NextToken())
;
return Add(Token::None, 0);
}
void Lexer::Print() const
{
//std::copy(tokens.begin(), tokens.end(), ostream_iterator<Token>(std::cout, " "));
for (auto tok : tokens)
std::cout << tok << " ";
std::cout << std::endl;
}
Slice Lexer::Gather(int (*filt)(int))
{
int start = offset;
while (filt(Next()))
;
return Slice(start, offset);
}
bool Lexer::Add(Token::Type type, Slice slice)
{
tokens.push_back(Token(type, *this, lineNumber, slice));
return true;
}
bool Lexer::Add(Token::Type type, int len)
{
Add(type, Slice(offset, offset + len));
while (len--)
Next();
return true;
}
bool Lexer::LexAlpha()
{
Token tok(Token::Ident, *this, lineNumber, Gather(isalnum));
auto kw = keyWords.find(tok.Text());
if (kw != keyWords.end())
tok.type = kw->second;
tokens.push_back(tok);
return true;
}
int IsSpaceChar(int ch)
{
return ch == ' ';
}
bool Lexer::NextToken()
{
auto current = Current();
if (current == 0)
return false;
if (isalpha(current))
return LexAlpha();
if (isdigit(current))
return Add(Token::Int, Gather(isdigit));
switch (current)
{
case '\t': return Add(Token::Tab);
case '\n': return Add(Token::NewLine);
case ';': return Add(Token::Semi);
case '{': return Add(Token::OpenBrace);
case '}': return Add(Token::CloseBrace);
case '(': return Add(Token::OpenParan);
case ')': return Add(Token::CloseParan);
case ':': return Add(Token::Colon);
case ' ': return Add(Token::Whitespace, Gather(IsSpaceChar));
case '@': return Add(Token::Lookup);
case ',': return Add(Token::Comma);
case '*': return Add(Token::Mul);
case '[': return Add(Token::OpenSquareBracket);
case ']': return Add(Token::CloseSquareBracket);
case '=': return AddIfNext('=', Token::Equiv, Token::Assign);
case '!': return AddIfNext('=', Token::NotEquiv, Token::Not);
case '&': return AddIfNext('&', Token::And, Token::BitAnd);
case '|': return AddIfNext('|', Token::Or, Token::BitOr);
case '<': return AddIfNext('=', Token::LessEquiv, Token::Less);
case '>': return AddIfNext('=', Token::GreaterEquiv, Token::Greater);
case '"': return LexString();
case '\'': return LexAlpha();
case '-':
if (Peek() == '-')
return AddTwoCharOp(Token::Decrement);
if (Peek() == '=')
return AddTwoCharOp(Token::MinusAssign);
return Add(Token::Minus);
case '.':
if (Peek() == '.')
{
Next();
if (Peek() == '.')
{
Next();
return Add(Token::Replace, 3);
}
return Fail("Two dots doesn't work");
}
return Add(Token::Dot);
case '+':
if (Peek() == '+')
return AddTwoCharOp(Token::Increment);
if (Peek() == '=')
return AddTwoCharOp(Token::PlusAssign);
return Add(Token::Plus);
case '/':
if (Peek() == '/')
{
Next();
int start = offset;
while (Next() != '\n')
;
return Add(Token::Comment, offset - start);
}
return Add(Token::Divide);
}
LexError("Unrecognised %c");
return false;
}
bool Process::Fail(const std::string &err)
{
Failed = true;
Error = err;
return false;
}
bool Process::Fail(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
char buffer[1000];
vsprintf_s(buffer, fmt, ap);
return Fail(std::string(buffer));
}
char Lexer::Current() const
{
if (lineNumber == (int)lines.size())
return 0;
return Line()[offset];
}
const std::string &Lexer::Line() const
{
return lines[lineNumber];
}
char Lexer::Next()
{
if (EndOfLine())
{
offset = 0;
++lineNumber;
}
else
++offset;
if (lineNumber == (int)lines.size())
return 0;
return Line()[offset];
}
char Lexer::Peek() const
{
if (EndOfLine())
return 0;
return Line()[offset + 1];
}
void Lexer::CreateLines()
{
// ensure we end with a newline.
input.push_back('\n');
size_t lineStart = 0;
for (size_t n = 0; n < input.size(); ++n)
{
if (input[n] == '\n')
{
lines.push_back(input.substr(lineStart, n - lineStart + 1));
lineStart = n + 1;
}
}
}
bool Lexer::EndOfLine() const
{
return offset == (int)Line().size() - 1;
}
bool Lexer::AddIfNext(char ch, Token::Type thenType, Token::Type elseType)
{
if (Peek() == ch)
{
Next();
return Add(thenType, 2);
}
return Add(elseType, 1);
}
bool Lexer::AddTwoCharOp(Token::Type ty)
{
Add(ty, 2);
Next();
return true;
}
bool Lexer::LexString()
{
int start = offset;
Next();
while (!Failed && Current() != '"')
{
if (Current() == '\\')
{
switch (Next())
{
case '"':
case 'n':
case 't':
break;
default:
LexError("Bad escape sequence %c");
return false;
}
}
if (Peek() == 0)
{
Fail("Bad string literal");
return false;
}
Next();
}
Next();
// the +1 and -1 to remove the start and end double quote characters
tokens.push_back(Token(Token::String, *this, lineNumber, Slice(start + 1, offset - 1)));
return true;
}
void Lexer::LexError(const char *text)
{
Fail(CreateError(Token(Token::None, *this, lineNumber, Slice(offset, offset)), text, Current()));
}
std::string Lexer::CreateError(Token tok, const char *fmt, ...)
{
char buff0[2000];
va_list ap;
va_start(ap, fmt);
vsprintf_s(buff0, fmt, ap);
const char *fmt1 = "%s(%d):[%d]: %s\n";
char buff[2000];
sprintf_s(buff, fmt1, "", tok.lineNumber, tok.slice.Start, buff0);
int beforeContext = 1;
int afterContext = 0;
const Lexer &lex = *tok.lexer;
int start = std::max(0, tok.lineNumber - beforeContext);
int end = std::min((int)lex.lines.size() - 1, tok.lineNumber + afterContext);
strstream err;
err << buff << endl;
for (int n = start; n <= end; ++n)
{
for (auto ch : lex.lines[n])
{
if (ch == '\t')
err << " ";
else
err << ch;
}
if (n == tok.lineNumber)
{
for (int ch = 0; ch < (int)lex.lines[n].size(); ++ch)
{
if (lex.lines[tok.lineNumber][ch] == '\t')
err << " ";
else if (ch == tok.slice.Start)
{
err << '^';
break;
}
}
err << endl;
}
}
err << ends;
return err.str();
}
KAI_END
<|endoftext|>
|
<commit_before>#include "pakfile.h"
#include <stdexcept>
#include <iterator>
#include <algorithm>
#include <cstring>
namespace scpak
{
void PakFile::load(std::istream &stream)
{
// read header
PakHeader header;
stream.read(reinterpret_cast<char*>(&header), sizeof(header));
if (!header.checkMagic())
throw std::runtime_error("bad pak file");
StreamBinaryReader reader(&stream);
// read content dictionary
for (int i=0; i<header.contentCount; ++i)
{
PakItem item;
item.name = reader.readString();
item.type = reader.readString();
item.offset = reader.readInt32();
item.length = reader.readInt32();
addItem(std::move(item));
}
// read all contents
for (PakItem &item : m_contents)
{
stream.seekg(header.contentOffset + item.offset, std::ios::beg);
item.data.resize(item.length);
stream.read(reinterpret_cast<char*>(item.data.data()), item.length);
item.offset = -1; // we will not be able to access the stream
}
}
void PakFile::save(std::ostream &stream)
{
// we cannot detect the length of the file and where content begins,
// so we have to write the header twice
// write file header for the first time
PakHeader header;
header.contentCount = m_contents.size();
StreamBinaryWriter writer(&stream);
stream.write(reinterpret_cast<char*>(&header), sizeof(header));
// we do not know where the content will locate, so it is also
// necessary to write content dictionary twice
// write content dictionary for the first time
for (const PakItem &item : m_contents)
{
writer.writeString(item.name);
writer.writeString(item.type);
writer.writeInt(item.offset); // should be -1
writer.writeInt(item.length);
}
header.contentOffset = stream.tellp();
// write content items
for (PakItem &item : m_contents)
{
// there are a magic number before every content data in origin Content.pak
// it's DEADBEEF
stream.put(0xDE);
stream.put(0xAD);
stream.put(0xBE);
stream.put(0xEF);
item.offset = static_cast<int>(stream.tellp()) - header.contentOffset;
stream.write(reinterpret_cast<char*>(item.data.data()), item.length);
}
header.fileLength = stream.tellp();
// write the header again
stream.seekp(0, std::ios::beg);
stream.write(reinterpret_cast<char*>(&header), sizeof(header));
// write content dictionary again
for (PakItem &item : m_contents)
{
writer.writeString(item.name);
writer.writeString(item.type);
writer.writeInt(item.offset);
writer.writeInt(item.length);
item.offset = -1; // as items can be modified, it is meaningless to keep a offset
}
}
const std::vector<PakItem>& PakFile::contents() const
{
return m_contents;
}
void PakFile::addItem(const PakItem &item)
{
m_contents.push_back(item);
}
void PakFile::addItem(PakItem &&item)
{
m_contents.push_back(std::move(item));
}
PakItem& PakFile::getItem(std::size_t where)
{
return m_contents.at(where);
}
void PakFile::removeItem(std::size_t where)
{
m_contents.erase(m_contents.begin()+where);
}
}
<commit_msg>fix a typo<commit_after>#include "pakfile.h"
#include <stdexcept>
#include <iterator>
#include <algorithm>
#include <cstring>
namespace scpak
{
void PakFile::load(std::istream &stream)
{
// read header
PakHeader header;
stream.read(reinterpret_cast<char*>(&header), sizeof(header));
if (!header.checkMagic())
throw std::runtime_error("bad pak file");
StreamBinaryReader reader(&stream);
// read content dictionary
for (int i=0; i<header.contentCount; ++i)
{
PakItem item;
item.name = reader.readString();
item.type = reader.readString();
item.offset = reader.readInt32();
item.length = reader.readInt32();
addItem(std::move(item));
}
// read all contents
for (PakItem &item : m_contents)
{
stream.seekg(header.contentOffset + item.offset, std::ios::beg);
item.data.resize(item.length);
stream.read(reinterpret_cast<char*>(item.data.data()), item.length);
item.offset = -1; // we will not be able to access the stream
}
}
void PakFile::save(std::ostream &stream)
{
// we cannot detect the length of the file and where content begins,
// so we have to write the header twice
// write file header for the first time
PakHeader header;
header.contentCount = m_contents.size();
StreamBinaryWriter writer(&stream);
stream.write(reinterpret_cast<char*>(&header), sizeof(header));
// we do not know where the content will locate, so it is also
// necessary to write content dictionary twice
// write content dictionary for the first time
for (const PakItem &item : m_contents)
{
writer.writeString(item.name);
writer.writeString(item.type);
writer.writeInt(item.offset); // should be -1
writer.writeInt(item.length);
}
header.contentOffset = stream.tellp();
// write content items
for (PakItem &item : m_contents)
{
// there is a magic number before every content data in origin Content.pak
// it's DEADBEEF
stream.put(0xDE);
stream.put(0xAD);
stream.put(0xBE);
stream.put(0xEF);
item.offset = static_cast<int>(stream.tellp()) - header.contentOffset;
stream.write(reinterpret_cast<char*>(item.data.data()), item.length);
}
header.fileLength = stream.tellp();
// write the header again
stream.seekp(0, std::ios::beg);
stream.write(reinterpret_cast<char*>(&header), sizeof(header));
// write content dictionary again
for (PakItem &item : m_contents)
{
writer.writeString(item.name);
writer.writeString(item.type);
writer.writeInt(item.offset);
writer.writeInt(item.length);
item.offset = -1; // as items can be modified, it is meaningless to keep a offset
}
}
const std::vector<PakItem>& PakFile::contents() const
{
return m_contents;
}
void PakFile::addItem(const PakItem &item)
{
m_contents.push_back(item);
}
void PakFile::addItem(PakItem &&item)
{
m_contents.push_back(std::move(item));
}
PakItem& PakFile::getItem(std::size_t where)
{
return m_contents.at(where);
}
void PakFile::removeItem(std::size_t where)
{
m_contents.erase(m_contents.begin()+where);
}
}
<|endoftext|>
|
<commit_before>
/*
* From:
* http://stackoverflow.com/questions/6142576/sample-from-multivariate-normal-gaussian-distribution-in-c
*/
#include <iostream>
#include "bpmf.h"
using namespace std;
using namespace Eigen;
/*
We need a functor that can pretend it's const,
but to be a good random number generator
it needs mutable state.
*/
#ifndef __clang__
thread_local
#endif
static std::mt19937 rng;
#ifndef __clang__
thread_local
#endif
static normal_distribution<> nd;
double randn(double) {
return nd(rng);
}
auto
nrandn(int n) -> decltype( VectorXd::NullaryExpr(n, ptr_fun(randn)) )
{
return VectorXd::NullaryExpr(n, ptr_fun(randn));
}
MatrixXd MvNormal_prec(const MatrixXd & Lambda, const VectorXd & mean, int nn = 1)
{
int size = mean.rows(); // Dimensionality (rows)
LLT<MatrixXd> chol(Lambda);
MatrixXd r = MatrixXd::NullaryExpr(size,nn,ptr_fun(randn));
chol.matrixU().solveInPlace(r);
return r.colwise() + mean;
}
/*
Draw nn samples from a size-dimensional normal distribution
with a specified mean and covariance
*/
MatrixXd MvNormal(MatrixXd covar, VectorXd mean, int nn = 1)
{
int size = mean.rows(); // Dimensionality (rows)
MatrixXd normTransform(size,size);
LLT<MatrixXd> cholSolver(covar);
normTransform = cholSolver.matrixL();
auto normSamples = MatrixXd::NullaryExpr(size,nn,ptr_fun(randn));
MatrixXd samples = (normTransform * normSamples).colwise() + mean;
return samples;
}
MatrixXd WishartUnit(int m, int df)
{
MatrixXd c(m,m);
c.setZero();
for ( int i = 0; i < m; i++ ) {
std::gamma_distribution<> gam(0.5*(df - i));
c(i,i) = sqrt(2.0 * gam(rng));
VectorXd r = nrandn(m-i-1).transpose();
c.block(i,i+1,1,m-i-1) = r;
}
MatrixXd ret = c.transpose() * c;
#ifdef TEST_MVNORMAL
cout << "WISHART UNIT {\n" << endl;
cout << " m:\n" << m << endl;
cout << " df:\n" << df << endl;
cout << " ret;\n" << ret << endl;
cout << " c:\n" << c << endl;
cout << "}\n" << ret << endl;
#endif
return ret;
}
MatrixXd Wishart(const MatrixXd &sigma, int df)
{
// Get R, the upper triangular Cholesky factor of SIGMA.
MatrixXd r = sigma.llt().matrixU();
// Get AU, a sample from the unit Wishart distribution.
MatrixXd au = WishartUnit(sigma.cols(), df);
// Construct the matrix A = R' * AU * R.
MatrixXd a = r.transpose() * au * r;
#ifdef TEST_MVNORMAL
cout << "WISHART {\n" << endl;
cout << " sigma::\n" << sigma << endl;
cout << " r:\n" << r << endl;
cout << " au:\n" << au << endl;
cout << " df:\n" << df << endl;
cout << " a:\n" << a << endl;
cout << "}\n" << endl;
#endif
return a;
}
// from julia package Distributions: conjugates/normalwishart.jl
std::pair<VectorXd, MatrixXd> NormalWishart(VectorXd mu, double kappa, MatrixXd T, double nu)
{
MatrixXd Lam = Wishart(T, nu);
MatrixXd mu_o = MvNormal_prec(Lam * kappa, mu);
#ifdef TEST_MVNORMAL
cout << "NORMAL WISHART {\n" << endl;
cout << " mu:\n" << mu << endl;
cout << " kappa:\n" << kappa << endl;
cout << " T:\n" << T << endl;
cout << " nu:\n" << nu << endl;
cout << " mu_o\n" << mu_o << endl;
cout << " Lam\n" << Lam << endl;
cout << "}\n" << endl;
#endif
return std::make_pair(mu_o , Lam);
}
double acc[9] = { .0 };
std::pair<VectorXd, MatrixXd> OldCondNormalWishart(const MatrixXd &U, const VectorXd &mu, const double kappa, const MatrixXd &T, const int nu)
{
int N = U.cols();
auto start = tick();
auto Um = U.rowwise().mean();
// http://stackoverflow.com/questions/15138634/eigen-is-there-an-inbuilt-way-to-calculate-sample-covariance
MatrixXd C = U.colwise() - Um;
MatrixXd S = (C * C.adjoint()) / double(N - 1);
VectorXd mu_c = (kappa*mu + N*Um) / (kappa + N);
double kappa_c = kappa + N;
MatrixXd T_c = ( T + N * S.transpose() + (kappa * N)/(kappa + N) * (mu - Um) * ((mu - Um).transpose())).inverse();
int nu_c = nu + N;
#ifdef TEST_MVNORMAL
cout << "mu_c:\n" << mu_c << endl;
cout << "kappa_c:\n" << kappa_c << endl;
cout << "T_c:\n" << T_c << endl;
cout << "nu_c:\n" << nu_c << endl;
#endif
auto ret = NormalWishart(mu_c, kappa_c, T_c, nu_c);
acc[8] += tick() - start;
return ret;
}
// from bpmf.jl -- verified
std::pair<VectorXd, MatrixXd> CondNormalWishart(const MatrixXd &U, const VectorXd &mu, const double kappa, const MatrixXd &T, const int nu)
{
double t[8];
int N = U.cols();
t[0] = tick();
auto Um = U.rowwise().mean();
t[1] = tick();
acc[0] += t[1] - t[0];
// http://stackoverflow.com/questions/15138634/eigen-is-there-an-inbuilt-way-to-calculate-sample-covariance
auto C = U.colwise() - Um;
MatrixXd S = (C * C.adjoint()) / double(N - 1);
VectorXd mu_c = (kappa*mu + N*Um) / (kappa + N);
double kappa_c = kappa + N;
t[2] = tick();
acc[1] += t[2] - t[1];
t[3] = tick();
acc[2] += t[3] - t[2];
t[4] = tick();
acc[3] += t[4] - t[3];
auto mu_m = (mu - Um);
double kappa_m = (kappa * N)/(kappa + N);
auto X = ( T + N * S + kappa_m * (mu_m * mu_m.transpose()));
t[5] = tick();
acc[4] += t[5] - t[4];
MatrixXd T_c = X.inverse();
t[6] = tick();
acc[5] += t[6] - t[5];
int nu_c = nu + N;
#ifdef TEST_MVNORMAL
cout << "mu_c:\n" << mu_c << endl;
cout << "kappa_c:\n" << kappa_c << endl;
cout << "T_c:\n" << T_c << endl;
cout << "nu_c:\n" << nu_c << endl;
#endif
auto ret = NormalWishart(mu_c, kappa_c, T_c, nu_c);
t[7] = tick();
acc[6] += t[7] - t[6];
acc[7] += t[7] - t[0];
return ret;
}
#if defined(TEST_MVNORMAL) || defined (BENCH_MVNORMAL)
int main()
{
MatrixXd U(32,32 * 1024);
U.setOnes();
VectorXd mu(32);
mu.setZero();
double kappa = 2;
MatrixXd T(32,32);
T.setIdentity(32,32);
T.array() /= 4;
int nu = 3;
VectorXd mu_out;
MatrixXd T_out;
#ifdef BENCH_MVNORMAL
for(int i=0; i<300; ++i) {
tie(mu_out, T_out) = CondNormalWishart(U, mu, kappa, T, nu);
cout << i << "\r" << flush;
}
cout << endl << flush;
for(int i=0; i<7; ++i) {
cout << i << ": " << (int)(100.0 * acc[i] / acc[7]) << endl;
}
cout << "total: " << acc[7] << endl;
for(int i=0; i<300; ++i) {
tie(mu_out, T_out) = OldCondNormalWishart(U, mu, kappa, T, nu);
cout << i << "\r" << flush;
}
cout << endl << flush;
cout << "total: " << acc[8] << endl;
#else
#if 1
cout << "COND NORMAL WISHART\n" << endl;
tie(mu_out, T_out) = CondNormalWishart(U, mu, kappa, T, nu);
cout << "mu_out:\n" << mu_out << endl;
cout << "T_out:\n" << T_out << endl;
cout << "\n-----\n\n";
#endif
#if 0
cout << "NORMAL WISHART\n" << endl;
tie(mu_out, T_out) = NormalWishart(mu, kappa, T, nu);
cout << "mu_out:\n" << mu_out << endl;
cout << "T_out:\n" << T_out << endl;
#endif
#if 0
cout << "MVNORMAL\n" << endl;
MatrixXd out = MvNormal(T, mu, 10);
cout << "mu:\n" << mu << endl;
cout << "T:\n" << T << endl;
cout << "out:\n" << out << endl;
#endif
#endif
}
#endif
<commit_msg>removed timing<commit_after>
/*
* From:
* http://stackoverflow.com/questions/6142576/sample-from-multivariate-normal-gaussian-distribution-in-c
*/
#include <iostream>
#include "bpmf.h"
using namespace std;
using namespace Eigen;
/*
We need a functor that can pretend it's const,
but to be a good random number generator
it needs mutable state.
*/
#ifndef __clang__
thread_local
#endif
static std::mt19937 rng;
#ifndef __clang__
thread_local
#endif
static normal_distribution<> nd;
double randn(double) {
return nd(rng);
}
auto
nrandn(int n) -> decltype( VectorXd::NullaryExpr(n, ptr_fun(randn)) )
{
return VectorXd::NullaryExpr(n, ptr_fun(randn));
}
MatrixXd MvNormal_prec(const MatrixXd & Lambda, const VectorXd & mean, int nn = 1)
{
int size = mean.rows(); // Dimensionality (rows)
LLT<MatrixXd> chol(Lambda);
MatrixXd r = MatrixXd::NullaryExpr(size,nn,ptr_fun(randn));
chol.matrixU().solveInPlace(r);
return r.colwise() + mean;
}
/*
Draw nn samples from a size-dimensional normal distribution
with a specified mean and covariance
*/
MatrixXd MvNormal(MatrixXd covar, VectorXd mean, int nn = 1)
{
int size = mean.rows(); // Dimensionality (rows)
MatrixXd normTransform(size,size);
LLT<MatrixXd> cholSolver(covar);
normTransform = cholSolver.matrixL();
auto normSamples = MatrixXd::NullaryExpr(size,nn,ptr_fun(randn));
MatrixXd samples = (normTransform * normSamples).colwise() + mean;
return samples;
}
MatrixXd WishartUnit(int m, int df)
{
MatrixXd c(m,m);
c.setZero();
for ( int i = 0; i < m; i++ ) {
std::gamma_distribution<> gam(0.5*(df - i));
c(i,i) = sqrt(2.0 * gam(rng));
VectorXd r = nrandn(m-i-1).transpose();
c.block(i,i+1,1,m-i-1) = r;
}
MatrixXd ret = c.transpose() * c;
#ifdef TEST_MVNORMAL
cout << "WISHART UNIT {\n" << endl;
cout << " m:\n" << m << endl;
cout << " df:\n" << df << endl;
cout << " ret;\n" << ret << endl;
cout << " c:\n" << c << endl;
cout << "}\n" << ret << endl;
#endif
return ret;
}
MatrixXd Wishart(const MatrixXd &sigma, int df)
{
// Get R, the upper triangular Cholesky factor of SIGMA.
MatrixXd r = sigma.llt().matrixU();
// Get AU, a sample from the unit Wishart distribution.
MatrixXd au = WishartUnit(sigma.cols(), df);
// Construct the matrix A = R' * AU * R.
MatrixXd a = r.transpose() * au * r;
#ifdef TEST_MVNORMAL
cout << "WISHART {\n" << endl;
cout << " sigma::\n" << sigma << endl;
cout << " r:\n" << r << endl;
cout << " au:\n" << au << endl;
cout << " df:\n" << df << endl;
cout << " a:\n" << a << endl;
cout << "}\n" << endl;
#endif
return a;
}
// from julia package Distributions: conjugates/normalwishart.jl
std::pair<VectorXd, MatrixXd> NormalWishart(VectorXd mu, double kappa, MatrixXd T, double nu)
{
MatrixXd Lam = Wishart(T, nu);
MatrixXd mu_o = MvNormal_prec(Lam * kappa, mu);
#ifdef TEST_MVNORMAL
cout << "NORMAL WISHART {\n" << endl;
cout << " mu:\n" << mu << endl;
cout << " kappa:\n" << kappa << endl;
cout << " T:\n" << T << endl;
cout << " nu:\n" << nu << endl;
cout << " mu_o\n" << mu_o << endl;
cout << " Lam\n" << Lam << endl;
cout << "}\n" << endl;
#endif
return std::make_pair(mu_o , Lam);
}
std::pair<VectorXd, MatrixXd> OldCondNormalWishart(const MatrixXd &U, const VectorXd &mu, const double kappa, const MatrixXd &T, const int nu)
{
int N = U.cols();
auto Um = U.rowwise().mean();
// http://stackoverflow.com/questions/15138634/eigen-is-there-an-inbuilt-way-to-calculate-sample-covariance
MatrixXd C = U.colwise() - Um;
MatrixXd S = (C * C.adjoint()) / double(N - 1);
VectorXd mu_c = (kappa*mu + N*Um) / (kappa + N);
double kappa_c = kappa + N;
MatrixXd T_c = ( T + N * S.transpose() + (kappa * N)/(kappa + N) * (mu - Um) * ((mu - Um).transpose())).inverse();
int nu_c = nu + N;
#ifdef TEST_MVNORMAL
cout << "mu_c:\n" << mu_c << endl;
cout << "kappa_c:\n" << kappa_c << endl;
cout << "T_c:\n" << T_c << endl;
cout << "nu_c:\n" << nu_c << endl;
#endif
return NormalWishart(mu_c, kappa_c, T_c, nu_c);
}
// from bpmf.jl -- verified
std::pair<VectorXd, MatrixXd> CondNormalWishart(const MatrixXd &U, const VectorXd &mu, const double kappa, const MatrixXd &T, const int nu)
{
int N = U.cols();
auto Um = U.rowwise().mean();
// http://stackoverflow.com/questions/15138634/eigen-is-there-an-inbuilt-way-to-calculate-sample-covariance
auto C = U.colwise() - Um;
MatrixXd S = (C * C.adjoint()) / double(N - 1);
VectorXd mu_c = (kappa*mu + N*Um) / (kappa + N);
double kappa_c = kappa + N;
auto mu_m = (mu - Um);
double kappa_m = (kappa * N)/(kappa + N);
auto X = ( T + N * S + kappa_m * (mu_m * mu_m.transpose()));
MatrixXd T_c = X.inverse();
int nu_c = nu + N;
#ifdef TEST_MVNORMAL
cout << "mu_c:\n" << mu_c << endl;
cout << "kappa_c:\n" << kappa_c << endl;
cout << "T_c:\n" << T_c << endl;
cout << "nu_c:\n" << nu_c << endl;
#endif
return NormalWishart(mu_c, kappa_c, T_c, nu_c);
}
#if defined(TEST_MVNORMAL) || defined (BENCH_MVNORMAL)
int main()
{
MatrixXd U(32,32 * 1024);
U.setOnes();
VectorXd mu(32);
mu.setZero();
double kappa = 2;
MatrixXd T(32,32);
T.setIdentity(32,32);
T.array() /= 4;
int nu = 3;
VectorXd mu_out;
MatrixXd T_out;
#ifdef BENCH_MVNORMAL
for(int i=0; i<300; ++i) {
tie(mu_out, T_out) = CondNormalWishart(U, mu, kappa, T, nu);
cout << i << "\r" << flush;
}
cout << endl << flush;
for(int i=0; i<7; ++i) {
cout << i << ": " << (int)(100.0 * acc[i] / acc[7]) << endl;
}
cout << "total: " << acc[7] << endl;
for(int i=0; i<300; ++i) {
tie(mu_out, T_out) = OldCondNormalWishart(U, mu, kappa, T, nu);
cout << i << "\r" << flush;
}
cout << endl << flush;
cout << "total: " << acc[8] << endl;
#else
#if 1
cout << "COND NORMAL WISHART\n" << endl;
tie(mu_out, T_out) = CondNormalWishart(U, mu, kappa, T, nu);
cout << "mu_out:\n" << mu_out << endl;
cout << "T_out:\n" << T_out << endl;
cout << "\n-----\n\n";
#endif
#if 0
cout << "NORMAL WISHART\n" << endl;
tie(mu_out, T_out) = NormalWishart(mu, kappa, T, nu);
cout << "mu_out:\n" << mu_out << endl;
cout << "T_out:\n" << T_out << endl;
#endif
#if 0
cout << "MVNORMAL\n" << endl;
MatrixXd out = MvNormal(T, mu, 10);
cout << "mu:\n" << mu << endl;
cout << "T:\n" << T << endl;
cout << "out:\n" << out << endl;
#endif
#endif
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012, Dennis Hedback
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include <iterator>
#include <set>
#include <string>
#include <vector>
typedef std::set<std::string> Set;
typedef std::vector<std::string> Tuple;
typedef std::set<Tuple> Product;
typedef std::vector<Set> Generator;
typedef std::set<Generator> Quotient;
struct Options
{
bool verbose;
};
static Options opts;
#define VPRINT(x) if (opts.verbose) { std::cerr << x << std::endl; }
Product read_tuples(void)
{
Product prod;
Tuple current_tuple;
std::string current_elem;
for (std::istreambuf_iterator<char> it(std::cin), end; it != end; it++)
{
char c = *it;
if (c == ',' || c == '\n')
{
current_tuple.push_back(current_elem);
current_elem.clear();
if (c == '\n')
{
prod.insert(current_tuple);
current_tuple.clear();
}
}
else
{
current_elem += c;
}
}
return prod;
}
unsigned int product_cardinality(Generator gen)
{
unsigned int cardinality = 1;
for (Generator::iterator it = gen.begin(); it != gen.end(); it++)
cardinality *= (*it).size();
return cardinality;
}
Product cartesian_product(Generator gen)
{
Product prod;
unsigned int counters[gen.size()];
size_t gen_size;
gen_size = gen.size();
for (unsigned int i = 0; i < gen_size; i++)
counters[i] = 0;
for (unsigned int i = 0; i < product_cardinality(gen); i++)
{
Tuple current_tuple;
for (unsigned int j = 0; j < gen_size; j++)
{
Set current_set = gen[j];
unsigned int k = 0;
for (Set::iterator it = current_set.begin(); it != current_set.end(); k++, it++)
if (k == counters[j])
current_tuple.push_back(*it);
}
prod.insert(current_tuple);
for (unsigned int j = 0; j < gen_size; j++)
{
counters[j]++;
if (counters[j] > gen[j].size() - 1)
counters[j] = 0;
else
break;
}
}
return prod;
}
Generator init_generator(size_t size)
{
Generator gen;
for (unsigned int i = 0; i < size; i++)
gen.push_back(Set());
return gen;
}
Generator reference_generator(Product prod)
{
Generator ref_generator;
if (prod.size() > 0)
ref_generator = init_generator((*prod.begin()).size());
for (Product::iterator pi = prod.begin(); pi != prod.end(); pi++)
{
unsigned int i = 0;
for (Tuple::const_iterator ti = (*pi).begin(); ti != (*pi).end(); i++, ti++)
{
ref_generator[i].insert(*ti);
}
}
return ref_generator;
}
bool product_contains(Product prod, Tuple tuple)
{
bool found = false;
for (Product::iterator it = prod.begin(); it != prod.end(); it++)
if ((*it) == tuple)
found = true;
return found;
}
Product difference(Product prod_1, Product prod_2)
{
Product diff;
for (Product::iterator pi_1 = prod_1.begin(); pi_1 != prod_1.end(); pi_1++)
if (!product_contains(prod_2, (*pi_1)))
diff.insert(*pi_1);
return diff;
}
void print_product(Product prod)
{
for (Product::iterator pi = prod.begin(); pi != prod.end(); pi++)
{
for (Tuple::const_iterator ti = (*pi).begin(); ti != (*pi).end(); ti++)
{
std::cout << *ti;
if (++ti != (*pi).end())
std::cout << ',';
ti--;
}
std::cout << std::endl;
}
}
Quotient generating_sets(Product prod)
{
Quotient quot;
Generator ref_generator = reference_generator(prod);
Product ref_product = cartesian_product(ref_generator);
Product diff = difference(ref_product, prod);
for (unsigned int num_generators = 1, inserted = 0; prod.size() > 0; num_generators++)
{
Generator current_generator = init_generator((*prod.begin()).size());
Product to_erase;
for (Product::iterator pi = prod.begin(); pi != prod.end();)
{
Tuple current_tuple = (*pi);
Generator tmp = current_generator;
size_t tup_size = current_tuple.size();
for (unsigned int i = 0; i < tup_size; i++)
{
tmp[i].insert(current_tuple[i]);
}
Product tmp_product = cartesian_product(tmp);
if (difference(tmp_product, diff).size() == product_cardinality(tmp)) {
current_generator = tmp;
prod.erase(pi++);
VPRINT(++inserted << " tuples inserted into " << num_generators << " generators ");
}
else
{
++pi;
}
}
quot.insert(current_generator);
}
return quot;
}
void print_quotient(Quotient quot)
{
for (Quotient::iterator qi = quot.begin(); qi != quot.end(); qi++)
{
for (Generator::const_iterator gi = (*qi).begin(); gi != (*qi).end(); gi++)
{
for (Set::iterator si = (*gi).begin(); si != (*gi).end(); si++)
{
std::cout << *si;
if (++si != (*gi).end())
std::cout << ',';
si--;
}
std::cout << std::endl;
}
std::cout << "%%" << std::endl;
}
}
int main(int argc, char *argv[])
{
opts.verbose = true;
Product prod = read_tuples();
Quotient quot = generating_sets(prod);
print_quotient(quot);
return 0;
}
<commit_msg>Decreased execution time by orders of magnitude<commit_after>/*
* Copyright (c) 2012, Dennis Hedback
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include <iterator>
#include <set>
#include <string>
#include <vector>
typedef std::set<std::string> Set;
typedef std::vector<std::string> Tuple;
typedef std::set<Tuple> Product;
typedef std::vector<Set> Generator;
typedef std::set<Generator> Quotient;
struct Options
{
bool verbose;
};
static Options opts;
#define VPRINT(x) if (opts.verbose) { std::cerr << x << std::endl; }
Product read_tuples(void)
{
Product prod;
Tuple current_tuple;
std::string current_elem;
for (std::istreambuf_iterator<char> it(std::cin), end; it != end; it++)
{
char c = *it;
if (c == ',' || c == '\n')
{
current_tuple.push_back(current_elem);
current_elem.clear();
if (c == '\n')
{
prod.insert(current_tuple);
current_tuple.clear();
}
}
else
{
current_elem += c;
}
}
return prod;
}
unsigned int product_cardinality(Generator gen)
{
unsigned int cardinality = 1;
for (Generator::iterator it = gen.begin(); it != gen.end(); it++)
cardinality *= (*it).size();
return cardinality;
}
Product cartesian_product(Generator gen)
{
Product prod;
unsigned int counters[gen.size()];
size_t gen_size;
gen_size = gen.size();
for (unsigned int i = 0; i < gen_size; i++)
counters[i] = 0;
for (unsigned int i = 0; i < product_cardinality(gen); i++)
{
Tuple current_tuple;
for (unsigned int j = 0; j < gen_size; j++)
{
Set current_set = gen[j];
unsigned int k = 0;
for (Set::iterator it = current_set.begin(); it != current_set.end(); k++, it++)
if (k == counters[j])
current_tuple.push_back(*it);
}
prod.insert(current_tuple);
for (unsigned int j = 0; j < gen_size; j++)
{
counters[j]++;
if (counters[j] > gen[j].size() - 1)
counters[j] = 0;
else
break;
}
}
return prod;
}
Generator init_generator(size_t size)
{
Generator gen;
for (unsigned int i = 0; i < size; i++)
gen.push_back(Set());
return gen;
}
Generator reference_generator(Product prod)
{
Generator ref_generator;
if (prod.size() > 0)
ref_generator = init_generator((*prod.begin()).size());
for (Product::iterator pi = prod.begin(); pi != prod.end(); pi++)
{
unsigned int i = 0;
for (Tuple::const_iterator ti = (*pi).begin(); ti != (*pi).end(); i++, ti++)
{
ref_generator[i].insert(*ti);
}
}
return ref_generator;
}
bool product_contains(Product prod, Tuple tuple)
{
bool found = false;
for (Product::iterator it = prod.begin(); it != prod.end(); it++)
if ((*it) == tuple)
found = true;
return found;
}
Product difference(Product prod_1, Product prod_2)
{
Product diff;
for (Product::iterator pi_1 = prod_1.begin(); pi_1 != prod_1.end(); pi_1++)
if (!product_contains(prod_2, (*pi_1)))
diff.insert(*pi_1);
return diff;
}
void print_product(Product prod)
{
for (Product::iterator pi = prod.begin(); pi != prod.end(); pi++)
{
for (Tuple::const_iterator ti = (*pi).begin(); ti != (*pi).end(); ti++)
{
std::cout << *ti;
if (++ti != (*pi).end())
std::cout << ',';
ti--;
}
std::cout << std::endl;
}
}
Quotient generating_sets(Product prod)
{
Quotient quot;
Product ref_prod = prod;
/*
Generator ref_generator = reference_generator(prod);
Product ref_product = cartesian_product(ref_generator);
Product diff = difference(ref_product, prod);
*/
for (unsigned int num_generators = 1, inserted = 0; prod.size() > 0; num_generators++)
{
Generator current_generator = init_generator((*prod.begin()).size());
Product to_erase;
for (Product::iterator pi = prod.begin(); pi != prod.end();)
{
Tuple current_tuple = (*pi);
Generator tmp = current_generator;
size_t tup_size = current_tuple.size();
for (unsigned int i = 0; i < tup_size; i++)
{
tmp[i].insert(current_tuple[i]);
}
Product tmp_product = cartesian_product(tmp);
for (Product::iterator tmpi = tmp_product.begin(); tmpi != tmp_product.end(); tmpi++)
{
if (!product_contains(ref_prod, *tmpi))
{
++pi;
// FIXME: Go away ugly goto, go away!
goto foo;
}
}
current_generator = tmp;
prod.erase(pi++);
VPRINT(++inserted << " tuples inserted into " << num_generators << " generators ");
foo:
if (1 == 2) break;
}
quot.insert(current_generator);
}
return quot;
}
void print_quotient(Quotient quot)
{
for (Quotient::iterator qi = quot.begin(); qi != quot.end(); qi++)
{
for (Generator::const_iterator gi = (*qi).begin(); gi != (*qi).end(); gi++)
{
for (Set::iterator si = (*gi).begin(); si != (*gi).end(); si++)
{
std::cout << *si;
if (++si != (*gi).end())
std::cout << ',';
si--;
}
std::cout << std::endl;
}
std::cout << "%%" << std::endl;
}
}
int main(int argc, char *argv[])
{
opts.verbose = true;
Product prod = read_tuples();
Quotient quot = generating_sets(prod);
print_quotient(quot);
return 0;
}
<|endoftext|>
|
<commit_before>/*
** Author(s):
** - Pierre Roullon <proullon@aldebaran-robotics.com>
**
** Copyright (C) 2010, 2011, 2012 Aldebararan Robotics
*/
#include <list>
#include <vector>
#include <qic/future.h>
#include <qic/object.h>
#include <qic/value.h>
#include <qi/future.hpp>
#include "future_p.h"
#include "value_p.h"
qiLogCategory("qipy.future");
qi_promise_t* qi_promise_create()
{
qi::Promise<qi::GenericValue> *pr = new qi::Promise<qi::GenericValue>();
return (qi_promise_t *) pr;
}
void qi_promise_destroy(qi_promise_t *pr)
{
qi::Promise<qi::GenericValue> *promise = qi_promise_cpp(pr);
delete promise;
promise = 0;
}
void qi_promise_set_value(qi_promise_t *pr, qi_value_t *value)
{
qi::Promise<qi::GenericValue> *promise = qi_promise_cpp(pr);
//TODO: Take?
promise->setValue(qi_value_cpp(value));
}
void qi_promise_set_error(qi_promise_t *pr, const char *error)
{
qi::Promise<qi::GenericValue>* promise = qi_promise_cpp(pr);
promise->setError(error);
}
qi_future_t* qi_promise_get_future(qi_promise_t *pr)
{
qi::Promise<qi::GenericValue>* promise = qi_promise_cpp(pr);
return qi_cpp_promise_get_future(*promise);
}
void qi_future_destroy(qi_future_t *fu)
{
qi::Future<qi::GenericValue> *fut = qi_future_cpp(fu);
qiLogInfo() << "qi_future_destroy(" << fu << ")";
//TODO: the GenericValue should be somehow destroyed
delete fut;
fut = 0;
}
QIC_API qi_future_t* qi_future_clone(qi_future_t* fu) {
qi::Future<qi::GenericValue>* fut = qi_future_cpp(fu);
qi::Future<qi::GenericValue>* clo = new qi::Future<qi::GenericValue>();
*clo = *fut;
return (qi_future_t *)clo;
}
void qi_future_add_callback(qi_future_t *fu, qi_future_callback_t cb, void *miscdata)
{
qiLogInfo() << "qi_future_add_cb(" << fu << ")";
qi::Future<qi::GenericValue> *fut = qi_future_cpp(fu);
fut->connect(boost::bind<void>(cb, fu, miscdata));
}
void qi_future_wait(qi_future_t *fu, int timeout)
{
qi::Future<qi::GenericValue> *fut = qi_future_cpp(fu);
fut->wait(timeout);
}
int qi_future_has_error(qi_future_t *fu)
{
qi::Future<qi::GenericValue> *fut = qi_future_cpp(fu);
return fut->hasError();
}
int qi_future_is_ready(qi_future_t *fu)
{
qi::Future<qi::GenericValue> *fut = qi_future_cpp(fu);
return fut->isReady();
}
qi_value_t *qi_future_get_value(qi_future_t *fu)
{
qi::Future<qi::GenericValue> *fut = qi_future_cpp(fu);
if (fut->hasError())
return 0;
qi_value_t *val = qi_value_create("");
qi::GenericValue &gv = qi_value_cpp(val);
gv = fut->value();
return val;
}
const char* qi_future_get_error(qi_future_t *fu)
{
qi::Future<qi::GenericValue> *fut = qi_future_cpp(fu);
return strdup(fut->error().c_str());
}
//Syntaxic Sugar
long long qi_future_get_int64(qi_future_t* fut, int *err) {
if (qi_future_has_error(fut)) {
if (err)
*err = 1;
return 0;
}
qi_value_t* val = qi_future_get_value(fut);
long long res;
int ret = qi_value_get_int64(val, &res);
if (err)
*err = ret;
qi_value_destroy(val);
qi_future_destroy(fut);
return res;
}
unsigned long long qi_future_get_uint64(qi_future_t* fut, int *err) {
if (qi_future_has_error(fut)) {
if (err)
*err = 1;
return 0;
}
qi_value_t* val = qi_future_get_value(fut);
unsigned long long res;
int ret = qi_value_get_uint64(val, &res);
if (err)
*err = ret;
qi_value_destroy(val);
qi_future_destroy(fut);
return res;
}
const char* qi_future_get_string(qi_future_t* fut) {
if (qi_future_has_error(fut)) {
return 0;
}
qi_value_t* val = qi_future_get_value(fut);
const char *str;
str = qi_value_get_string(val);
qi_value_destroy(val);
qi_future_destroy(fut);
return str;
}
qi_object_t* qi_future_get_object(qi_future_t* fut) {
if (qi_future_has_error(fut)) {
return 0;
}
qi_value_t* val = qi_future_get_value(fut);
qi_object_t* obj;
obj = qi_value_get_object(val);
qi_value_destroy(val);
qi_future_destroy(fut);
return obj;
}
<commit_msg>c: fix future compilation on windows<commit_after>/*
** Author(s):
** - Pierre Roullon <proullon@aldebaran-robotics.com>
**
** Copyright (C) 2010, 2011, 2012 Aldebararan Robotics
*/
#include <list>
#include <vector>
#include <qic/future.h>
#include <qic/object.h>
#include <qic/value.h>
#include <qi/future.hpp>
#include "future_p.h"
#include "value_p.h"
qiLogCategory("qipy.future");
qi_promise_t* qi_promise_create()
{
qi::Promise<qi::GenericValue> *pr = new qi::Promise<qi::GenericValue>();
return (qi_promise_t *) pr;
}
void qi_promise_destroy(qi_promise_t *pr)
{
qi::Promise<qi::GenericValue> *promise = qi_promise_cpp(pr);
delete promise;
promise = 0;
}
void qi_promise_set_value(qi_promise_t *pr, qi_value_t *value)
{
qi::Promise<qi::GenericValue> *promise = qi_promise_cpp(pr);
//TODO: Take?
promise->setValue(qi_value_cpp(value));
}
void qi_promise_set_error(qi_promise_t *pr, const char *error)
{
qi::Promise<qi::GenericValue>* promise = qi_promise_cpp(pr);
promise->setError(error);
}
qi_future_t* qi_promise_get_future(qi_promise_t *pr)
{
qi::Promise<qi::GenericValue>* promise = qi_promise_cpp(pr);
return qi_cpp_promise_get_future(*promise);
}
void qi_future_destroy(qi_future_t *fu)
{
qi::Future<qi::GenericValue> *fut = qi_future_cpp(fu);
qiLogInfo() << "qi_future_destroy(" << fu << ")";
//TODO: the GenericValue should be somehow destroyed
delete fut;
fut = 0;
}
qi_future_t* qi_future_clone(qi_future_t* fu) {
qi::Future<qi::GenericValue>* fut = qi_future_cpp(fu);
qi::Future<qi::GenericValue>* clo = new qi::Future<qi::GenericValue>();
*clo = *fut;
return (qi_future_t *)clo;
}
void qi_future_add_callback(qi_future_t *fu, qi_future_callback_t cb, void *miscdata)
{
qiLogInfo() << "qi_future_add_cb(" << fu << ")";
qi::Future<qi::GenericValue> *fut = qi_future_cpp(fu);
fut->connect(boost::bind<void>(cb, fu, miscdata));
}
void qi_future_wait(qi_future_t *fu, int timeout)
{
qi::Future<qi::GenericValue> *fut = qi_future_cpp(fu);
fut->wait(timeout);
}
int qi_future_has_error(qi_future_t *fu)
{
qi::Future<qi::GenericValue> *fut = qi_future_cpp(fu);
return fut->hasError();
}
int qi_future_is_ready(qi_future_t *fu)
{
qi::Future<qi::GenericValue> *fut = qi_future_cpp(fu);
return fut->isReady();
}
qi_value_t *qi_future_get_value(qi_future_t *fu)
{
qi::Future<qi::GenericValue> *fut = qi_future_cpp(fu);
if (fut->hasError())
return 0;
qi_value_t *val = qi_value_create("");
qi::GenericValue &gv = qi_value_cpp(val);
gv = fut->value();
return val;
}
const char* qi_future_get_error(qi_future_t *fu)
{
qi::Future<qi::GenericValue> *fut = qi_future_cpp(fu);
return strdup(fut->error().c_str());
}
//Syntaxic Sugar
long long qi_future_get_int64(qi_future_t* fut, int *err) {
if (qi_future_has_error(fut)) {
if (err)
*err = 1;
return 0;
}
qi_value_t* val = qi_future_get_value(fut);
long long res;
int ret = qi_value_get_int64(val, &res);
if (err)
*err = ret;
qi_value_destroy(val);
qi_future_destroy(fut);
return res;
}
unsigned long long qi_future_get_uint64(qi_future_t* fut, int *err) {
if (qi_future_has_error(fut)) {
if (err)
*err = 1;
return 0;
}
qi_value_t* val = qi_future_get_value(fut);
unsigned long long res;
int ret = qi_value_get_uint64(val, &res);
if (err)
*err = ret;
qi_value_destroy(val);
qi_future_destroy(fut);
return res;
}
const char* qi_future_get_string(qi_future_t* fut) {
if (qi_future_has_error(fut)) {
return 0;
}
qi_value_t* val = qi_future_get_value(fut);
const char *str;
str = qi_value_get_string(val);
qi_value_destroy(val);
qi_future_destroy(fut);
return str;
}
qi_object_t* qi_future_get_object(qi_future_t* fut) {
if (qi_future_has_error(fut)) {
return 0;
}
qi_value_t* val = qi_future_get_value(fut);
qi_object_t* obj;
obj = qi_value_get_object(val);
qi_value_destroy(val);
qi_future_destroy(fut);
return obj;
}
<|endoftext|>
|
<commit_before>#include <cstring>
#include "object.h"
#include "objectValue.h"
#include "array.h"
#include "allocator.h"
#include <time.h>
#include "operations.h"
#include "key.h"
#include "path.h"
namespace json {
template<typename Fn>
static RefCntPtr<ObjectValue> applyDiffImpl(const Value &baseObject, const Value &diffObject, Fn mergeFn);
const Value &Object::defaultMerge(const Value &, const Value &v) {
return v;
}
Value Object::recursiveMerge(const Value &b, const Value &d) {
if (b.type() == json::object && d.type() == json::object)
return applyDiff(b,d,recursiveMerge);
else
return d;
}
PValue bindKeyToPValue(const StrViewA &key, const PValue &value) {
if (key.empty()) {
return value->unproxy();
}else if (key == value->getMemberName()) {
return value;
}else {
return new(key) ObjectProxy(key, value->unproxy());
}
}
class ObjectDiff: public ObjectValue {
public:
ObjectDiff(AllocInfo &nfo):ObjectValue(nfo) {}
virtual ValueTypeFlags flags() const override { return valueDiff;}
static RefCntPtr<ObjectDiff> create(std::size_t capacity) {
AllocInfo nfo(capacity);
return new(nfo) ObjectDiff(nfo);
}
};
Object::Object(Value value):base(value)
{
}
Object::Object(): base(AbstractObjectValue::getEmptyObject())
{
}
Object::Object(const StringView<char>& name, const Value & value): base(AbstractObjectValue::getEmptyObject())
{
set(name, value);
}
Object::~Object()
{
//force delection here
ordered = nullptr;
unordered = nullptr;
}
Object::Object(const Object &other):base(other.base) {
ordered = other.commitAsDiffObject();
unordered = ordered != nullptr?ObjectValue::create(ordered->size()):nullptr;
}
Object &Object::operator=(const Object &other) {
clear();
base = other.base;
ordered = other.commitAsDiffObject();
unordered = ordered != nullptr?ObjectValue::create(ordered->size()):nullptr;
return *this;
}
Object &Object::operator=(Object &&other) {
clear();
base = std::move(other.base);
ordered = std::move(other.ordered);
unordered = std::move(other.unordered);
return *this;
}
void Object::set_internal(const Value& v) {
StringView<char> curName = v.getKey();
lastIterSnapshot = Value();
if (unordered == nullptr) {
unordered = ObjectValue::create(8);
}
bool ok = unordered->push_back(v.getHandle());
if (!ok) {
RefCntPtr<ObjectValue> newcont (ObjectValue::create(unordered->size()*2));
optimize();
unordered = newcont;
unordered->push_back(v.getHandle());
}
}
Object & Object::set(const StringView<char>& name, const Value & value)
{
PValue v = value.getHandle();
if (v->flags() & proxy ) {
StringView<char> curName = v->getMemberName();
if (curName == name) {
set_internal(v);
return *this;
} else {
v = v->unproxy();
}
}
v = new(name) ObjectProxy(name, v);
set_internal(v);
return *this;
}
Object & Object::set(const Value & value)
{
set_internal(value.getHandle());
return *this;
}
Object & Object::unset(const StringView<char>& name)
{
return set(name, AbstractValue::getUndefined());
}
const Value Object::operator[](const StringView<char> &name) const {
if (unordered != nullptr) {
std::size_t usz = unordered->size();
if (usz>16 && usz > ordered->size()/2) {
optimize();
usz = 0;
}
for (std::size_t i = usz; i>0; i--) {
const PValue &z = (*unordered)[i-1];
if (z->getMemberName() == name) return z;
}
if (ordered != nullptr) {
const IValue *f = ordered->findSorted(name);
if (f) return f;
}
}
return base[name];
}
ValueRef Object::makeRef(const StringView<char> &name) {
return ValueRef(*this, name);
}
Object &Object::operator()(const StringView<char> &name, const Value &value) {
return set(name, value);
}
static const Value &defaultConflictResolv(const Path &, const Value &, const Value &right) {
return right;
}
void Object::optimize() const {
if (unordered == nullptr || unordered->size() == 0) return;
unordered->sort();
if (ordered == nullptr) {
ordered = ordered->create(unordered->size());
*ordered = *unordered;
ordered->isDiff = true;
} else {
//wild casting here, because applyDiffImpl need Value as argumeny
//however, it returns new ObjectValue
ordered = applyDiffImpl(
Value(PValue::staticCast(ordered)),
Value(PValue::staticCast(unordered)),
defaultMerge);
}
unordered->clear();
}
PValue Object::commit() const {
optimize();
if (ordered == nullptr) {
return base.v;
} else {
return applyDiff(base,commitAsDiff()).getHandle();
}
}
Object2Object Object::object(const StringView<char>& name)
{
return Object2Object((*this)[name],*this,name);
}
Array2Object Object::array(const StringView<char>& name)
{
return Array2Object((*this)[name], *this, name);
}
void Object::clear()
{
base = Value(AbstractObjectValue::getEmptyObject());
revert();
}
bool Object::dirty() const
{
return (ordered != nullptr && !ordered->empty()) || (unordered != nullptr && !unordered->empty());
}
Object & Object::merge(Value object)
{
object.forEach([&](Value v) {
set(v); return true;
});
return *this;
}
void Object::revert() {
ordered = nullptr;
unordered = nullptr;
}
ValueIterator Object::begin() const {
if (!lastIterSnapshot.defined()) lastIterSnapshot = commit();
return lastIterSnapshot.begin();
}
ValueIterator Object::end() const {
return lastIterSnapshot.end();
}
bool Object::createDiff(const Value oldObject, Value newObject, unsigned int recursive) {
if (newObject.type() != json::object || oldObject.type() != json::object) return false;
auto bp = oldObject.begin();
auto dp = newObject.begin();
auto be = oldObject.end();
auto de = newObject.end();
auto merge = [](const Value &old, const Value &nw) {
if (nw.type() & valueDiff) return old.replace(Path::root,nw);
else return nw;
};
while (bp != be && dp != de) {
int cmp = (*bp).getKey().compare((*dp).getKey());
if (cmp < 0) {
set(Value((*bp).getKey(),json::undefined));
++bp;
} else if (cmp > 0){
set(*dp);
++dp;
} else {
if (recursive > 0) {
Object obj;
if (obj.createDiff(*bp,*dp,recursive-1)) {
set(obj.commitAsDiff());
} else {
if (*dp != *bp) set(*dp);
}
} else {
if (*dp != *bp) set(*dp);
}
++dp;
++bp;
}
}
while (bp != be) {
set(Value((*bp).getKey(),json::undefined));
++bp;
}
while (dp != de) {
set(*dp);
++dp;
}
return true;
}
Value Object::commitAsDiff() const {
ObjectValue *obj = commitAsDiffObject();
if (obj == nullptr) return json::object;
else return Value(static_cast<const IValue *>(obj));
}
Value Object::applyDiff(const Value& baseObject, const Value& diffObject) {
if (diffObject.type() != json::object) return baseObject;
if (baseObject.type() != json::object) return applyDiff(json::object, diffObject);
return PValue::staticCast(applyDiffImpl(baseObject,diffObject,defaultMerge));
}
Value Object::applyDiff(const Value &baseObject, const Value &diffObject,
const std::function<Value(const Value &base, const Value &diff)> &mergeFn) {
if (diffObject.type() != json::object) return baseObject;
if (baseObject.type() != json::object) return applyDiff(json::object, diffObject);
return PValue::staticCast(applyDiffImpl(baseObject,diffObject,mergeFn));
}
template<typename Fn>
static RefCntPtr<ObjectValue> applyDiffImpl(const Value &baseObject, const Value &diffObject, Fn mergeFn) {
RefCntPtr<ObjectValue> newobj = ObjectValue::create(baseObject.size()+diffObject.size());
bool createDiff = (baseObject.flags() & valueDiff) != 0;
newobj->isDiff = createDiff;
auto bp = baseObject.begin();
auto dp = diffObject.begin();
auto be = baseObject.end();
auto de = diffObject.end();
auto merge = [&mergeFn](const Value &old, const Value &nw) {
if (nw.type() & valueDiff) return Value(old.getKey(),old.replace(Path::root,nw));
else return Value(old.getKey(),mergeFn(old,nw));
};
auto merge2 = [](const Value &nw) {
if (nw.type() & valueDiff) return Value(nw.getKey(),Value(json::object).replace(Path::root,nw));
else return nw;
};
while (bp != be && dp != de) {
int cmp = (*bp).getKey().compare((*dp).getKey());
if (cmp < 0) {
newobj->push_back((*bp).getHandle());
++bp;
} else if (cmp > 0){
Value v = *dp;
if (v.defined()) {
newobj->push_back(merge2(v).getHandle());
} else if (createDiff) {
newobj->push_back(v.getHandle());
}
++dp;
} else {
Value v = *dp;
if (v.defined()) {
newobj->push_back(merge(*bp,v).getHandle());
} else if (createDiff) {
newobj->push_back(v.getHandle());
}
++dp;
++bp;
}
}
while (bp != be) {
newobj->push_back((*bp).getHandle());
++bp;
}
while (dp != de) {
if ((*dp).defined()) {
newobj->push_back(merge2(*dp).getHandle());
} else if (createDiff) {
newobj->push_back((*dp).getHandle());
}
++dp;
}
return newobj;
}
StringView<PValue> Object::getItems(const Value& v) {
const IValue *pv = v.getHandle();
const ObjectValue *ov = dynamic_cast<const ObjectValue *>(pv->unproxy());
if (ov) return ov->getItems(); else return StringView<PValue>();
}
std::size_t Object::size() const {
return base.size() + (ordered == nullptr?0:ordered->size())+unordered->size();
}
ObjectValue *Object::commitAsDiffObject() const {
optimize();
return ordered;
}
Object::Object(Object &&other)
:base(std::move(other.base))
,ordered(std::move(other.ordered))
,unordered(std::move(other.unordered)) {
}
Value::Value(const StrViewA key, const Value &value) :v(bindKeyToPValue(key, value.getHandle())) {}
}
<commit_msg>fix bug Object::size() can crash if object is empty<commit_after>#include <cstring>
#include "object.h"
#include "objectValue.h"
#include "array.h"
#include "allocator.h"
#include <time.h>
#include "operations.h"
#include "key.h"
#include "path.h"
namespace json {
template<typename Fn>
static RefCntPtr<ObjectValue> applyDiffImpl(const Value &baseObject, const Value &diffObject, Fn mergeFn);
const Value &Object::defaultMerge(const Value &, const Value &v) {
return v;
}
Value Object::recursiveMerge(const Value &b, const Value &d) {
if (b.type() == json::object && d.type() == json::object)
return applyDiff(b,d,recursiveMerge);
else
return d;
}
PValue bindKeyToPValue(const StrViewA &key, const PValue &value) {
if (key.empty()) {
return value->unproxy();
}else if (key == value->getMemberName()) {
return value;
}else {
return new(key) ObjectProxy(key, value->unproxy());
}
}
class ObjectDiff: public ObjectValue {
public:
ObjectDiff(AllocInfo &nfo):ObjectValue(nfo) {}
virtual ValueTypeFlags flags() const override { return valueDiff;}
static RefCntPtr<ObjectDiff> create(std::size_t capacity) {
AllocInfo nfo(capacity);
return new(nfo) ObjectDiff(nfo);
}
};
Object::Object(Value value):base(value)
{
}
Object::Object(): base(AbstractObjectValue::getEmptyObject())
{
}
Object::Object(const StringView<char>& name, const Value & value): base(AbstractObjectValue::getEmptyObject())
{
set(name, value);
}
Object::~Object()
{
//force delection here
ordered = nullptr;
unordered = nullptr;
}
Object::Object(const Object &other):base(other.base) {
ordered = other.commitAsDiffObject();
unordered = ordered != nullptr?ObjectValue::create(ordered->size()):nullptr;
}
Object &Object::operator=(const Object &other) {
clear();
base = other.base;
ordered = other.commitAsDiffObject();
unordered = ordered != nullptr?ObjectValue::create(ordered->size()):nullptr;
return *this;
}
Object &Object::operator=(Object &&other) {
clear();
base = std::move(other.base);
ordered = std::move(other.ordered);
unordered = std::move(other.unordered);
return *this;
}
void Object::set_internal(const Value& v) {
StringView<char> curName = v.getKey();
lastIterSnapshot = Value();
if (unordered == nullptr) {
unordered = ObjectValue::create(8);
}
bool ok = unordered->push_back(v.getHandle());
if (!ok) {
RefCntPtr<ObjectValue> newcont (ObjectValue::create(unordered->size()*2));
optimize();
unordered = newcont;
unordered->push_back(v.getHandle());
}
}
Object & Object::set(const StringView<char>& name, const Value & value)
{
PValue v = value.getHandle();
if (v->flags() & proxy ) {
StringView<char> curName = v->getMemberName();
if (curName == name) {
set_internal(v);
return *this;
} else {
v = v->unproxy();
}
}
v = new(name) ObjectProxy(name, v);
set_internal(v);
return *this;
}
Object & Object::set(const Value & value)
{
set_internal(value.getHandle());
return *this;
}
Object & Object::unset(const StringView<char>& name)
{
return set(name, AbstractValue::getUndefined());
}
const Value Object::operator[](const StringView<char> &name) const {
if (unordered != nullptr) {
std::size_t usz = unordered->size();
if (usz>16 && usz > ordered->size()/2) {
optimize();
usz = 0;
}
for (std::size_t i = usz; i>0; i--) {
const PValue &z = (*unordered)[i-1];
if (z->getMemberName() == name) return z;
}
if (ordered != nullptr) {
const IValue *f = ordered->findSorted(name);
if (f) return f;
}
}
return base[name];
}
ValueRef Object::makeRef(const StringView<char> &name) {
return ValueRef(*this, name);
}
Object &Object::operator()(const StringView<char> &name, const Value &value) {
return set(name, value);
}
static const Value &defaultConflictResolv(const Path &, const Value &, const Value &right) {
return right;
}
void Object::optimize() const {
if (unordered == nullptr || unordered->size() == 0) return;
unordered->sort();
if (ordered == nullptr) {
ordered = ordered->create(unordered->size());
*ordered = *unordered;
ordered->isDiff = true;
} else {
//wild casting here, because applyDiffImpl need Value as argumeny
//however, it returns new ObjectValue
ordered = applyDiffImpl(
Value(PValue::staticCast(ordered)),
Value(PValue::staticCast(unordered)),
defaultMerge);
}
unordered->clear();
}
PValue Object::commit() const {
optimize();
if (ordered == nullptr) {
return base.v;
} else {
return applyDiff(base,commitAsDiff()).getHandle();
}
}
Object2Object Object::object(const StringView<char>& name)
{
return Object2Object((*this)[name],*this,name);
}
Array2Object Object::array(const StringView<char>& name)
{
return Array2Object((*this)[name], *this, name);
}
void Object::clear()
{
base = Value(AbstractObjectValue::getEmptyObject());
revert();
}
bool Object::dirty() const
{
return (ordered != nullptr && !ordered->empty()) || (unordered != nullptr && !unordered->empty());
}
Object & Object::merge(Value object)
{
object.forEach([&](Value v) {
set(v); return true;
});
return *this;
}
void Object::revert() {
ordered = nullptr;
unordered = nullptr;
}
ValueIterator Object::begin() const {
if (!lastIterSnapshot.defined()) lastIterSnapshot = commit();
return lastIterSnapshot.begin();
}
ValueIterator Object::end() const {
return lastIterSnapshot.end();
}
bool Object::createDiff(const Value oldObject, Value newObject, unsigned int recursive) {
if (newObject.type() != json::object || oldObject.type() != json::object) return false;
auto bp = oldObject.begin();
auto dp = newObject.begin();
auto be = oldObject.end();
auto de = newObject.end();
auto merge = [](const Value &old, const Value &nw) {
if (nw.type() & valueDiff) return old.replace(Path::root,nw);
else return nw;
};
while (bp != be && dp != de) {
int cmp = (*bp).getKey().compare((*dp).getKey());
if (cmp < 0) {
set(Value((*bp).getKey(),json::undefined));
++bp;
} else if (cmp > 0){
set(*dp);
++dp;
} else {
if (recursive > 0) {
Object obj;
if (obj.createDiff(*bp,*dp,recursive-1)) {
set(obj.commitAsDiff());
} else {
if (*dp != *bp) set(*dp);
}
} else {
if (*dp != *bp) set(*dp);
}
++dp;
++bp;
}
}
while (bp != be) {
set(Value((*bp).getKey(),json::undefined));
++bp;
}
while (dp != de) {
set(*dp);
++dp;
}
return true;
}
Value Object::commitAsDiff() const {
ObjectValue *obj = commitAsDiffObject();
if (obj == nullptr) return json::object;
else return Value(static_cast<const IValue *>(obj));
}
Value Object::applyDiff(const Value& baseObject, const Value& diffObject) {
if (diffObject.type() != json::object) return baseObject;
if (baseObject.type() != json::object) return applyDiff(json::object, diffObject);
return PValue::staticCast(applyDiffImpl(baseObject,diffObject,defaultMerge));
}
Value Object::applyDiff(const Value &baseObject, const Value &diffObject,
const std::function<Value(const Value &base, const Value &diff)> &mergeFn) {
if (diffObject.type() != json::object) return baseObject;
if (baseObject.type() != json::object) return applyDiff(json::object, diffObject);
return PValue::staticCast(applyDiffImpl(baseObject,diffObject,mergeFn));
}
template<typename Fn>
static RefCntPtr<ObjectValue> applyDiffImpl(const Value &baseObject, const Value &diffObject, Fn mergeFn) {
RefCntPtr<ObjectValue> newobj = ObjectValue::create(baseObject.size()+diffObject.size());
bool createDiff = (baseObject.flags() & valueDiff) != 0;
newobj->isDiff = createDiff;
auto bp = baseObject.begin();
auto dp = diffObject.begin();
auto be = baseObject.end();
auto de = diffObject.end();
auto merge = [&mergeFn](const Value &old, const Value &nw) {
if (nw.type() & valueDiff) return Value(old.getKey(),old.replace(Path::root,nw));
else return Value(old.getKey(),mergeFn(old,nw));
};
auto merge2 = [](const Value &nw) {
if (nw.type() & valueDiff) return Value(nw.getKey(),Value(json::object).replace(Path::root,nw));
else return nw;
};
while (bp != be && dp != de) {
int cmp = (*bp).getKey().compare((*dp).getKey());
if (cmp < 0) {
newobj->push_back((*bp).getHandle());
++bp;
} else if (cmp > 0){
Value v = *dp;
if (v.defined()) {
newobj->push_back(merge2(v).getHandle());
} else if (createDiff) {
newobj->push_back(v.getHandle());
}
++dp;
} else {
Value v = *dp;
if (v.defined()) {
newobj->push_back(merge(*bp,v).getHandle());
} else if (createDiff) {
newobj->push_back(v.getHandle());
}
++dp;
++bp;
}
}
while (bp != be) {
newobj->push_back((*bp).getHandle());
++bp;
}
while (dp != de) {
if ((*dp).defined()) {
newobj->push_back(merge2(*dp).getHandle());
} else if (createDiff) {
newobj->push_back((*dp).getHandle());
}
++dp;
}
return newobj;
}
StringView<PValue> Object::getItems(const Value& v) {
const IValue *pv = v.getHandle();
const ObjectValue *ov = dynamic_cast<const ObjectValue *>(pv->unproxy());
if (ov) return ov->getItems(); else return StringView<PValue>();
}
std::size_t Object::size() const {
return base.size() + (ordered == nullptr?0:ordered->size())+(ordered == nullptr?0:unordered->size());
}
ObjectValue *Object::commitAsDiffObject() const {
optimize();
return ordered;
}
Object::Object(Object &&other)
:base(std::move(other.base))
,ordered(std::move(other.ordered))
,unordered(std::move(other.unordered)) {
}
Value::Value(const StrViewA key, const Value &value) :v(bindKeyToPValue(key, value.getHandle())) {}
}
<|endoftext|>
|
<commit_before>
#ifndef STRINGBUILDER_H
#define STRINGBUILDER_H
#include <cstdlib>
#include <cstring>
namespace wiz {
class StringBuilder //
{
private:
char* buffer_first;
char* buffer;
int len;
int capacity;
private:
char* end() const
{
return buffer_first + capacity;
}
public:
StringBuilder(const int buffer_size, const char* cstr = "", int len = 0) {
buffer = (char*)malloc(sizeof(char) * (buffer_size + 1)); // 1 for '\0'
this->len = len;
capacity = buffer_size;
memcpy(buffer, cstr, this->len);
buffer[this->len] = '\0';
buffer_first = buffer;
}
StringBuilder(const StringBuilder& other)
{
buffer = (char*)malloc(sizeof(char) * (other.capacity + 1)); // 1 for '\0'
this->len = other.len;
capacity = other.capacity;
memcpy(buffer, other.buffer, other.capacity);
buffer[this->len] = '\0';
buffer_first = buffer;
}
StringBuilder& operator=(const StringBuilder& other)
{
if (buffer_first != nullptr) {
free(buffer_first);
}
len = other.len;
capacity = other.capacity;
buffer_first = (char*)malloc(sizeof(char)*(len + 1));
buffer = other.buffer;
for (int i = 0; i <= len; ++i) {
buffer_first[i] = other.buffer_first[i];
}
return *this;
}
StringBuilder& operator=(StringBuilder&& other)
{
buffer_first = other.buffer_first;
buffer = other.buffer;
len = other.len;
capacity = other.capacity;
other.buffer_first = nullptr;
other.buffer = nullptr;
other.len = 0;
return *this;
}
virtual ~StringBuilder()
{
free(buffer_first);
}
StringBuilder& AppendChar(const char ch)
{
char temp[2];
temp[0] = ch; temp[1] = '\0';
return Append(temp, 1);
}
StringBuilder& Append(const char* cstr, const int len)
{
if (buffer + this->len + len < end())
{
memcpy(buffer + this->len, cstr, len);
buffer[this->len + len] = '\0';
this->len = this->len + len;
}
else {
if (buffer_first + this->len + len < end()) {
memmove(buffer_first, buffer, this->len);
memcpy(buffer_first + this->len, cstr, len);
buffer_first[this->len + len] = '\0';
buffer = buffer_first;
this->len = this->len + len;
}
else {
char* new_buffer = (char*)malloc(sizeof(char) * (2 * (this->len + len) + 1));
memcpy(new_buffer, buffer, this->len);
memcpy(new_buffer + this->len, cstr, len);
new_buffer[this->len + len] = '\0';
free(buffer_first);
buffer = new_buffer;
buffer_first = buffer;
this->capacity = 2 * (this->len + len);
this->len = this->len + len;
}
}
return *this;
}
const char* Divide(const int idx) // need to rename!l, chk idx range!
{
buffer[idx] = '\0';
return buffer;
}
const char* Str(int* size = nullptr) const {
if (size) { *size = len; }
return buffer;
}
char* Str(int* size = nullptr) {
if (size) { *size = len; }
return buffer;
}
void Clear()
{
len = 0;
buffer = buffer_first;
buffer[0] = '\0';
}
int Size() { return len; }
StringBuilder& LeftShift(const int offset = 1)
{
if (offset < 1) { return *this; }
if (buffer + offset < end()) {
buffer = buffer + offset;
}
else {
memmove(buffer_first, buffer + offset, len - offset);
buffer = buffer_first;
buffer[len - offset] = '\0';
}
len = len - offset;
return *this;
}
void SetLength(const int len)
{
this->len = len;
}
void SetBuffer(const int idx, const char val)
{
this->buffer[idx] = val;
}
char& operator[](const int idx)
{
return this->buffer[idx];
}
const char& operator[](const int idx) const
{
return this->buffer[idx];
}
};
}
#endif
<commit_msg>Delete STRINGBUILDER.H<commit_after><|endoftext|>
|
<commit_before>// Probabilistic Question-Answering system
// @2017 Sarge Rogatch
// This software is distributed under GNU AGPLv3 license. See file LICENSE in repository root for details.
#include "stdafx.h"
using namespace ProbQA;
using namespace SRPlat;
const uint64_t gPerfCntFreq = []() {
LARGE_INTEGER li;
if (!QueryPerformanceFrequency(&li)) {
printf("Can't get performance counter frequency: error %u.\n", GetLastError());
}
return li.QuadPart;
}();
uint64_t GetPerfCnt() {
LARGE_INTEGER li;
if (!QueryPerformanceCounter(&li)) {
printf("Failed QueryPerformanceCounter(): error %u.\n", GetLastError());
}
return li.QuadPart;
}
//void InfLoop() {
// for(;;) { }
//}
int __cdecl main() {
//std::vector<std::thread> testLoad;
//for (int i = 0; i < 16; i++) {
// testLoad.emplace_back(&InfLoop);
//}
//for (int i = 0; i < 16; i++) {
// testLoad[i].join();
//}
const char* baseName = "Logs\\PqaClient";
if (!CreateDirectoryA("Logs", nullptr)) {
uint32_t le = GetLastError();
if (le != ERROR_ALREADY_EXISTS) {
baseName = "PqaClient";
}
}
SRDefaultLogger::Init(SRString::MakeUnowned(baseName));
FILE *fpProgress = fopen("progress.txt", "wt");
PqaError err;
EngineDefinition ed;
ed._dims._nAnswers = 5;
ed._dims._nQuestions = 1000;
ed._dims._nTargets = 1000;
ed._initAmount = 0.1;
ed._prec._type = TPqaPrecisionType::Double;
IPqaEngine *pEngine = PqaGetEngineFactory().CreateCpuEngine(err, ed);
if (!err.IsOk() || pEngine == nullptr) {
fprintf(stderr, "Failed to instantiate a ProbQA engine.\n");
return int(SRExitCode::UnspecifiedError);
}
SRFastRandom fr;
SREntropyAdapter ea(fr);
constexpr int64_t cnTrainings = 1000 * 1000;
constexpr int64_t cMaxQuizLen = 100;
constexpr int64_t cMaxTrialLen = 30;
constexpr int64_t cnTopRated = 1;
int64_t nCorrect = 0;
int64_t sumQuizLens = 0;
double totCertainty = 0;
uint64_t pcStart = GetPerfCnt();
uint64_t prevQAsked = pEngine->GetTotalQuestionsAsked(err);
if (!err.IsOk()) {
fprintf(stderr, SR_FILE_LINE "Failed to query the total number of questions asked.\n");
return int(SRExitCode::UnspecifiedError);
}
for (int64_t i = 0; i < cnTrainings; i++) {
if (((i & 255) == 0) && (i != 0)) {
const uint64_t totQAsked = pEngine->GetTotalQuestionsAsked(err);
if (!err.IsOk()) {
fprintf(stderr, SR_FILE_LINE "Failed to query the total number of questions asked.\n");
return int(SRExitCode::UnspecifiedError);
}
const double precision = nCorrect * 100.0 / 256;
const double elapsedSec = double(GetPerfCnt() - pcStart) / gPerfCntFreq;
printf("\n*%" PRIu64 ";%.2lf%%*", totQAsked, precision);
fprintf(fpProgress, "%" PRId64 "\t%" PRIu64 "\t%lf\t%lf\t%lf\t%lf\n", i, totQAsked, precision,
double(sumQuizLens)/nCorrect, totCertainty/nCorrect, (totQAsked-prevQAsked)/elapsedSec);
fflush(fpProgress);
nCorrect = 0;
sumQuizLens = 0;
totCertainty = 0;
pcStart = GetPerfCnt();
prevQAsked = totQAsked;
}
const TPqaId guess = ea.Generate<TPqaId>(ed._dims._nTargets);
volatile TPqaId dbgGuess = guess;
const TPqaId iQuiz = pEngine->StartQuiz(err);
if (!err.IsOk() || iQuiz == cInvalidPqaId) {
fprintf(stderr, "Failed to create a quiz.\n");
return int(SRExitCode::UnspecifiedError);
}
int64_t j = 0;
for (; j < cMaxQuizLen; j++) {
const TPqaId iQuestion = pEngine->NextQuestion(err, iQuiz);
if (!err.IsOk() || iQuestion == cInvalidPqaId) {
fprintf(stderr, "Failed to query a next question.\n");
return int(SRExitCode::UnspecifiedError);
}
TPqaId iAnswer;
if (guess < iQuestion - 32) {
iAnswer = 0;
}
else if (iQuestion - 32 <= guess && guess < iQuestion) {
iAnswer = 1;
}
else if (iQuestion == guess) {
iAnswer = 2;
}
else if (iQuestion < guess && guess <= iQuestion + 32) {
iAnswer = 3;
}
else if (guess > iQuestion + 32) {
iAnswer = 4;
}
else {
fprintf(stderr, "Answering logic error.\n");
return int(SRExitCode::UnspecifiedError);
}
err = pEngine->RecordAnswer(iQuiz, iAnswer);
if (!err.IsOk()) {
fprintf(stderr, "Failed to record answer: %s\n", err.ToString(true).ToString().c_str());
return int(SRExitCode::UnspecifiedError);
}
RatedTarget rts[cnTopRated];
const TPqaId nListed = pEngine->ListTopTargets(err, iQuiz, cnTopRated, rts);
if (!err.IsOk() || nListed != cnTopRated) {
fprintf(stderr, "Failed to list top targets.\n");
return int(SRExitCode::UnspecifiedError);
}
//for (TPqaId k = 0; k < cnTopRated; k++) {
// printf(" [%g; %" PRId64 "] ", rts[k]._prob, rts[k]._iTarget);
//}
//printf("\n");
TPqaId posInTop = cInvalidPqaId;
for (TPqaId k = 0; k < cnTopRated; k++) {
if (rts[k]._iTarget == guess) {
posInTop = k;
break;
}
}
if (posInTop != cInvalidPqaId) {
const double certainty = rts[posInTop]._prob * 100;
nCorrect++;
sumQuizLens += j + 1;
totCertainty += certainty;
//printf("[guess=%" PRId64 ",top=%" PRId64 ",after=%" PRId64 "]", int64_t(guess), int64_t(posInTop),
// int64_t(j+1));
printf("[G=%" PRId64 ",A=%" PRId64 ",P=%.2lf%%]", int64_t(guess), int64_t(j + 1), certainty);
break;
}
}
if (j >= cMaxQuizLen) {
printf("-");
}
err = pEngine->RecordQuizTarget(iQuiz, guess);
if (!err.IsOk()) {
fprintf(stderr, "Failed to record quiz target: %s\n", err.ToString(true).ToString().c_str());
return int(SRExitCode::UnspecifiedError);
}
err = pEngine->ReleaseQuiz(iQuiz);
if (!err.IsOk()) {
fprintf(stderr, "Failed to release a quiz: %s\n", err.ToString(true).ToString().c_str());
return int(SRExitCode::UnspecifiedError);
}
}
delete pEngine;
return 0;
}
<commit_msg>Adjusted PqaClient sandbox so to save KBs.<commit_after>// Probabilistic Question-Answering system
// @2017 Sarge Rogatch
// This software is distributed under GNU AGPLv3 license. See file LICENSE in repository root for details.
#include "stdafx.h"
using namespace ProbQA;
using namespace SRPlat;
const uint64_t gPerfCntFreq = []() {
LARGE_INTEGER li;
if (!QueryPerformanceFrequency(&li)) {
printf("Can't get performance counter frequency: error %u.\n", GetLastError());
}
return li.QuadPart;
}();
uint64_t GetPerfCnt() {
LARGE_INTEGER li;
if (!QueryPerformanceCounter(&li)) {
printf("Failed QueryPerformanceCounter(): error %u.\n", GetLastError());
}
return li.QuadPart;
}
//void InfLoop() {
// for(;;) { }
//}
int __cdecl main() {
//std::vector<std::thread> testLoad;
//for (int i = 0; i < 16; i++) {
// testLoad.emplace_back(&InfLoop);
//}
//for (int i = 0; i < 16; i++) {
// testLoad[i].join();
//}
const char* baseName = "Logs\\PqaClient";
if (!CreateDirectoryA("Logs", nullptr)) {
uint32_t le = GetLastError();
if (le != ERROR_ALREADY_EXISTS) {
baseName = "PqaClient";
}
}
SRDefaultLogger::Init(SRString::MakeUnowned(baseName));
if (!CreateDirectoryA("KBs", nullptr)) {
uint32_t le = GetLastError();
if (le != ERROR_ALREADY_EXISTS) {
fprintf(stderr, "Failed to ensure that a directory for KBs exists.\n");
return int(SRExitCode::UnspecifiedError);
}
}
FILE *fpProgress = fopen("progress.txt", "wt");
PqaError err;
EngineDefinition ed;
ed._dims._nAnswers = 5;
ed._dims._nQuestions = 1000;
ed._dims._nTargets = 1000;
ed._initAmount = 0.1;
ed._prec._type = TPqaPrecisionType::Double;
IPqaEngine *pEngine = PqaGetEngineFactory().CreateCpuEngine(err, ed);
if (!err.IsOk() || pEngine == nullptr) {
fprintf(stderr, "Failed to instantiate a ProbQA engine.\n");
return int(SRExitCode::UnspecifiedError);
}
SRFastRandom fr;
SREntropyAdapter ea(fr);
constexpr int64_t cnTrainings = 1000 * 1000;
constexpr int64_t cMaxQuizLen = 100;
constexpr int64_t cMaxTrialLen = 30;
constexpr int64_t cnTopRated = 1;
int64_t nCorrect = 0;
int64_t sumQuizLens = 0;
double totCertainty = 0;
uint64_t pcStart = GetPerfCnt();
uint64_t prevQAsked = pEngine->GetTotalQuestionsAsked(err);
if (!err.IsOk()) {
fprintf(stderr, SR_FILE_LINE "Failed to query the total number of questions asked.\n");
return int(SRExitCode::UnspecifiedError);
}
for (int64_t i = 0; i < cnTrainings; i++) {
if (((i & 255) == 0) && (i != 0)) {
const uint64_t totQAsked = pEngine->GetTotalQuestionsAsked(err);
if (!err.IsOk()) {
fprintf(stderr, SR_FILE_LINE "Failed to query the total number of questions asked.\n");
return int(SRExitCode::UnspecifiedError);
}
const double precision = nCorrect * 100.0 / 256;
const double elapsedSec = double(GetPerfCnt() - pcStart) / gPerfCntFreq;
printf("\n*%" PRIu64 ";%.2lf%%*", totQAsked, precision);
fprintf(fpProgress, "%" PRId64 "\t%" PRIu64 "\t%lf\t%lf\t%lf\t%lf\n", i, totQAsked, precision,
double(sumQuizLens)/nCorrect, totCertainty/nCorrect, (totQAsked-prevQAsked)/elapsedSec);
fflush(fpProgress);
char kbFile[128];
sprintf(kbFile, "KBs\\dichotomy%.6" PRId64 ".kb", i);
err = pEngine->SaveKB(kbFile, false);
if (!err.IsOk()) {
fprintf(stderr, SR_FILE_LINE "Failed to save the KB.\n");
return int(SRExitCode::UnspecifiedError);
}
nCorrect = 0;
sumQuizLens = 0;
totCertainty = 0;
prevQAsked = totQAsked;
pcStart = GetPerfCnt();
}
const TPqaId guess = ea.Generate<TPqaId>(ed._dims._nTargets);
volatile TPqaId dbgGuess = guess;
const TPqaId iQuiz = pEngine->StartQuiz(err);
if (!err.IsOk() || iQuiz == cInvalidPqaId) {
fprintf(stderr, "Failed to create a quiz.\n");
return int(SRExitCode::UnspecifiedError);
}
int64_t j = 0;
for (; j < cMaxQuizLen; j++) {
const TPqaId iQuestion = pEngine->NextQuestion(err, iQuiz);
if (!err.IsOk() || iQuestion == cInvalidPqaId) {
fprintf(stderr, "Failed to query a next question.\n");
return int(SRExitCode::UnspecifiedError);
}
TPqaId iAnswer;
if (guess < iQuestion - 32) {
iAnswer = 0;
}
else if (iQuestion - 32 <= guess && guess < iQuestion) {
iAnswer = 1;
}
else if (iQuestion == guess) {
iAnswer = 2;
}
else if (iQuestion < guess && guess <= iQuestion + 32) {
iAnswer = 3;
}
else if (guess > iQuestion + 32) {
iAnswer = 4;
}
else {
fprintf(stderr, "Answering logic error.\n");
return int(SRExitCode::UnspecifiedError);
}
err = pEngine->RecordAnswer(iQuiz, iAnswer);
if (!err.IsOk()) {
fprintf(stderr, "Failed to record answer: %s\n", err.ToString(true).ToString().c_str());
return int(SRExitCode::UnspecifiedError);
}
RatedTarget rts[cnTopRated];
const TPqaId nListed = pEngine->ListTopTargets(err, iQuiz, cnTopRated, rts);
if (!err.IsOk() || nListed != cnTopRated) {
fprintf(stderr, "Failed to list top targets.\n");
return int(SRExitCode::UnspecifiedError);
}
//for (TPqaId k = 0; k < cnTopRated; k++) {
// printf(" [%g; %" PRId64 "] ", rts[k]._prob, rts[k]._iTarget);
//}
//printf("\n");
TPqaId posInTop = cInvalidPqaId;
for (TPqaId k = 0; k < cnTopRated; k++) {
if (rts[k]._iTarget == guess) {
posInTop = k;
break;
}
}
if (posInTop != cInvalidPqaId) {
const double certainty = rts[posInTop]._prob * 100;
nCorrect++;
sumQuizLens += j + 1;
totCertainty += certainty;
//printf("[guess=%" PRId64 ",top=%" PRId64 ",after=%" PRId64 "]", int64_t(guess), int64_t(posInTop),
// int64_t(j+1));
printf("[G=%" PRId64 ",A=%" PRId64 ",P=%.2lf%%]", int64_t(guess), int64_t(j + 1), certainty);
break;
}
}
if (j >= cMaxQuizLen) {
printf("-");
}
err = pEngine->RecordQuizTarget(iQuiz, guess);
if (!err.IsOk()) {
fprintf(stderr, "Failed to record quiz target: %s\n", err.ToString(true).ToString().c_str());
return int(SRExitCode::UnspecifiedError);
}
err = pEngine->ReleaseQuiz(iQuiz);
if (!err.IsOk()) {
fprintf(stderr, "Failed to release a quiz: %s\n", err.ToString(true).ToString().c_str());
return int(SRExitCode::UnspecifiedError);
}
}
delete pEngine;
return 0;
}
<|endoftext|>
|
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <fcntl.h> // open()
#include <string.h>
#include <signal.h>
#include <sys/errno.h>
#include <sys/stat.h>
#include <kernel/os.hpp>
#include <kernel/syscalls.hpp>
#include <kernel/rtc.hpp>
#include <hw/serial.hpp>
#include <statman>
#include <kprint>
#include <info>
#include <smp>
#if defined (UNITTESTS) && !defined(__MACH__)
#define THROW throw()
#else
#define THROW
#endif
// We can't use the usual "info", as printf isn't available after call to exit
#define SYSINFO(TEXT, ...) kprintf("%13s ] " TEXT "\n", "[ Kernel", ##__VA_ARGS__)
char* __env[1] {nullptr};
char** environ {__env};
extern "C" {
uintptr_t heap_begin;
uintptr_t heap_end;
}
void _exit(int status) {
kprintf("%s",std::string(LINEWIDTH, '=').c_str());
kprint("\n");
SYSINFO("service exited with status %i", status);
default_exit();
}
int execve(const char*,
char* const*,
char* const*)
{
panic("SYSCALL EXECVE NOT SUPPORTED");
return -1;
}
int fork() {
panic("SYSCALL FORK NOT SUPPORTED");
return -1;
}
int fstat(int, struct stat* st) {
debug("SYSCALL FSTAT Dummy, returning OK 0");
st->st_mode = S_IFCHR;
return 0;
}
int getpid() {
debug("SYSCALL GETPID Dummy, returning 1");
return 1;
}
int link(const char*, const char*) {
panic("SYSCALL LINK unsupported");
return -1;
}
int unlink(const char*) {
panic("SYSCALL UNLINK unsupported");
return -1;
}
void* sbrk(ptrdiff_t incr) {
/// NOTE:
/// sbrk gets called really early on, before everything else
if (UNLIKELY(heap_end + incr > OS::heap_max())) {
errno = ENOMEM;
return (void*)-1;
}
auto prev_heap_end = heap_end;
heap_end += incr;
return (void*) prev_heap_end;
}
/*
int stat(const char*, struct stat *st) {
debug("SYSCALL STAT Dummy");
st->st_mode = S_IFCHR;
return 0;
}
*/
clock_t times(struct tms*) {
panic("SYSCALL TIMES Dummy, returning -1");
return -1;
}
int wait(int*) {
debug((char*)"SYSCALL WAIT Dummy, returning -1");
return -1;
}
int gettimeofday(struct timeval* p, void*) {
p->tv_sec = RTC::now();
p->tv_usec = 0;
return 0;
}
int kill(pid_t pid, int sig) THROW {
printf("!!! Kill PID: %i, SIG: %i - %s ", pid, sig, strsignal(sig));
if (sig == 6ul) {
printf("/ ABORT\n");
}
panic("\tKilling a process doesn't make sense in IncludeOS. Panic.");
errno = ESRCH;
return -1;
}
static const size_t CONTEXT_BUFFER_LENGTH = 0x1000;
static char _crash_context_buffer[CONTEXT_BUFFER_LENGTH] __attribute__((aligned(0x1000)));
size_t get_crash_context_length()
{
return CONTEXT_BUFFER_LENGTH;
}
char* get_crash_context_buffer()
{
return _crash_context_buffer;
}
struct alignas(SMP_ALIGN) panic_struct
{
bool reenter = false;
};
static std::array<panic_struct, SMP_MAX_CORES> panic_stuff;
OS::on_panic_func panic_handler = nullptr;
/**
* panic:
* Display reason for kernel panic
* Display last crash context value, if it exists
* Display no-heap backtrace of stack
* Print EOT character to stderr, to signal outside that PANIC occured
* Call on_panic handler function, which determines what to do when
* the kernel panics
* If the handler returns, go to (permanent) sleep
**/
void panic(const char* why)
{
#ifdef ARCH_X86
/// prevent re-entering panic() more than once per CPU
if (PER_CPU(panic_stuff).reenter)
OS::reboot();
PER_CPU(panic_stuff).reenter = true;
/// display informacion ...
SMP::global_lock();
fprintf(stderr, "\n\t**** CPU %u PANIC: ****\n %s\n",
SMP::cpu_id(), why);
// the crash context buffer can help determine cause of crash
int len = strnlen(get_crash_context_buffer(), CONTEXT_BUFFER_LENGTH);
if (len > 0) {
printf("\n\t**** CONTEXT: ****\n %*s\n\n",
len, get_crash_context_buffer());
}
// heap and backtrace info
uintptr_t heap_total = OS::heap_max() - heap_begin;
double total = (heap_end - heap_begin) / (double) heap_total;
fprintf(stderr, "\tHeap is at: %#x / %#x (diff=%#x)\n",
heap_end, OS::heap_max(), OS::heap_max() - heap_end);
fprintf(stderr, "\tHeap usage: %u / %u Kb (%.2f%%)\n",
(uintptr_t) (heap_end - heap_begin) / 1024,
heap_total / 1024,
total * 100.0);
print_backtrace();
fflush(stderr);
SMP::global_unlock();
// call custom on panic handler
if (panic_handler) panic_handler();
if (SMP::cpu_id() == 0) {
SMP::global_lock();
// Signal End-Of-Transmission
fprintf(stderr, "\x04"); fflush(stderr);
SMP::global_unlock();
}
// .. if we return from the panic handler, go to permanent sleep
while (1) asm("cli; hlt");
__builtin_unreachable();
#else
#warning "panic() not implemented for selected arch"
#endif
}
// Shutdown the machine when one of the exit functions are called
void default_exit() {
__arch_poweroff();
__builtin_unreachable();
}
// To keep our sanity, we need a reason for the abort
void abort_ex(const char* why) {
panic(why);
__builtin_unreachable();
}
#if defined(__MACH__)
#if !defined(__MAC_10_12)
typedef int clockid_t;
#endif
#if !defined(CLOCK_REALTIME)
#define CLOCK_REALTIME 0
#endif
#endif
// Basic second-resolution implementation - using CMOS directly for now.
int clock_gettime(clockid_t clk_id, struct timespec* tp) {
if (clk_id == CLOCK_REALTIME) {
tp->tv_sec = RTC::now();
tp->tv_nsec = 0;
return 0;
}
return -1;
}
extern "C" void _init_syscalls();
void _init_syscalls()
{
// make sure that the buffers length is zero so it won't always show up in crashes
_crash_context_buffer[0] = 0;
}
<commit_msg>syscalls: delete obsolete commented-out code<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <fcntl.h> // open()
#include <string.h>
#include <signal.h>
#include <sys/errno.h>
#include <sys/stat.h>
#include <kernel/os.hpp>
#include <kernel/syscalls.hpp>
#include <kernel/rtc.hpp>
#include <hw/serial.hpp>
#include <statman>
#include <kprint>
#include <info>
#include <smp>
#if defined (UNITTESTS) && !defined(__MACH__)
#define THROW throw()
#else
#define THROW
#endif
// We can't use the usual "info", as printf isn't available after call to exit
#define SYSINFO(TEXT, ...) kprintf("%13s ] " TEXT "\n", "[ Kernel", ##__VA_ARGS__)
char* __env[1] {nullptr};
char** environ {__env};
extern "C" {
uintptr_t heap_begin;
uintptr_t heap_end;
}
void _exit(int status) {
kprintf("%s",std::string(LINEWIDTH, '=').c_str());
kprint("\n");
SYSINFO("service exited with status %i", status);
default_exit();
}
int execve(const char*,
char* const*,
char* const*)
{
panic("SYSCALL EXECVE NOT SUPPORTED");
return -1;
}
int fork() {
panic("SYSCALL FORK NOT SUPPORTED");
return -1;
}
int fstat(int, struct stat* st) {
debug("SYSCALL FSTAT Dummy, returning OK 0");
st->st_mode = S_IFCHR;
return 0;
}
int getpid() {
debug("SYSCALL GETPID Dummy, returning 1");
return 1;
}
int link(const char*, const char*) {
panic("SYSCALL LINK unsupported");
return -1;
}
int unlink(const char*) {
panic("SYSCALL UNLINK unsupported");
return -1;
}
void* sbrk(ptrdiff_t incr) {
/// NOTE:
/// sbrk gets called really early on, before everything else
if (UNLIKELY(heap_end + incr > OS::heap_max())) {
errno = ENOMEM;
return (void*)-1;
}
auto prev_heap_end = heap_end;
heap_end += incr;
return (void*) prev_heap_end;
}
clock_t times(struct tms*) {
panic("SYSCALL TIMES Dummy, returning -1");
return -1;
}
int wait(int*) {
debug((char*)"SYSCALL WAIT Dummy, returning -1");
return -1;
}
int gettimeofday(struct timeval* p, void*) {
p->tv_sec = RTC::now();
p->tv_usec = 0;
return 0;
}
int kill(pid_t pid, int sig) THROW {
printf("!!! Kill PID: %i, SIG: %i - %s ", pid, sig, strsignal(sig));
if (sig == 6ul) {
printf("/ ABORT\n");
}
panic("\tKilling a process doesn't make sense in IncludeOS. Panic.");
errno = ESRCH;
return -1;
}
static const size_t CONTEXT_BUFFER_LENGTH = 0x1000;
static char _crash_context_buffer[CONTEXT_BUFFER_LENGTH] __attribute__((aligned(0x1000)));
size_t get_crash_context_length()
{
return CONTEXT_BUFFER_LENGTH;
}
char* get_crash_context_buffer()
{
return _crash_context_buffer;
}
struct alignas(SMP_ALIGN) panic_struct
{
bool reenter = false;
};
static std::array<panic_struct, SMP_MAX_CORES> panic_stuff;
OS::on_panic_func panic_handler = nullptr;
/**
* panic:
* Display reason for kernel panic
* Display last crash context value, if it exists
* Display no-heap backtrace of stack
* Print EOT character to stderr, to signal outside that PANIC occured
* Call on_panic handler function, which determines what to do when
* the kernel panics
* If the handler returns, go to (permanent) sleep
**/
void panic(const char* why)
{
#ifdef ARCH_X86
/// prevent re-entering panic() more than once per CPU
if (PER_CPU(panic_stuff).reenter)
OS::reboot();
PER_CPU(panic_stuff).reenter = true;
/// display informacion ...
SMP::global_lock();
fprintf(stderr, "\n\t**** CPU %u PANIC: ****\n %s\n",
SMP::cpu_id(), why);
// the crash context buffer can help determine cause of crash
int len = strnlen(get_crash_context_buffer(), CONTEXT_BUFFER_LENGTH);
if (len > 0) {
printf("\n\t**** CONTEXT: ****\n %*s\n\n",
len, get_crash_context_buffer());
}
// heap and backtrace info
uintptr_t heap_total = OS::heap_max() - heap_begin;
double total = (heap_end - heap_begin) / (double) heap_total;
fprintf(stderr, "\tHeap is at: %#x / %#x (diff=%#x)\n",
heap_end, OS::heap_max(), OS::heap_max() - heap_end);
fprintf(stderr, "\tHeap usage: %u / %u Kb (%.2f%%)\n",
(uintptr_t) (heap_end - heap_begin) / 1024,
heap_total / 1024,
total * 100.0);
print_backtrace();
fflush(stderr);
SMP::global_unlock();
// call custom on panic handler
if (panic_handler) panic_handler();
if (SMP::cpu_id() == 0) {
SMP::global_lock();
// Signal End-Of-Transmission
fprintf(stderr, "\x04"); fflush(stderr);
SMP::global_unlock();
}
// .. if we return from the panic handler, go to permanent sleep
while (1) asm("cli; hlt");
__builtin_unreachable();
#else
#warning "panic() not implemented for selected arch"
#endif
}
// Shutdown the machine when one of the exit functions are called
void default_exit() {
__arch_poweroff();
__builtin_unreachable();
}
// To keep our sanity, we need a reason for the abort
void abort_ex(const char* why) {
panic(why);
__builtin_unreachable();
}
#if defined(__MACH__)
#if !defined(__MAC_10_12)
typedef int clockid_t;
#endif
#if !defined(CLOCK_REALTIME)
#define CLOCK_REALTIME 0
#endif
#endif
// Basic second-resolution implementation - using CMOS directly for now.
int clock_gettime(clockid_t clk_id, struct timespec* tp) {
if (clk_id == CLOCK_REALTIME) {
tp->tv_sec = RTC::now();
tp->tv_nsec = 0;
return 0;
}
return -1;
}
extern "C" void _init_syscalls();
void _init_syscalls()
{
// make sure that the buffers length is zero so it won't always show up in crashes
_crash_context_buffer[0] = 0;
}
<|endoftext|>
|
<commit_before>//
// calcPWP.cpp
//
//
// Created by Evan McCartney-Melstad on 1/10/15.
//
//
#include "calcPWP.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <thread>
#include <string>
int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) {
//****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE****
std::cout << "Number of threads: " << numThreads << std::endl;
std::streampos size;
std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate);
//ifstream file ("test500k.binary8bitunsigned", ios::in|ios::binary|ios::ate);
if (file.is_open()) {
size = file.tellg(); // Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB!
file.seekg (0, std::ios::beg); // Go back to the beginning of the file
//file.read((char*)readCounts, size); // cast to a char* to give to file.read
//unsigned char* readCounts;
//readCounts = new unsigned char[size];
std::vector<unsigned char> readCounts(size);
file.read((char*) &readCounts[0], size);
file.close();
std::cout << "the entire file content is in memory" << std::endl;
std::cout << "the total size of the file is " << size << std::endl;
std::cout << "the number of elements in the readCounts vector is: " << readCounts.size() << std::endl; // Will give the total size bytes divided by the size of one element--so it gives the number of elements
/* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional
vectors of the forms std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0)) and std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0))
First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a
vector of two-dimensional vectors...
*/
std::vector<std::vector<std::vector<long double>>> pwpThreads(numThreads, std::vector<std::vector<long double>> (numIndividuals, std::vector<long double> (numIndividuals,0) ) ); //pwpThreads[0] is the first 2D array for the first thread, etc...
std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) );
std::cout << "Initialized the 3d vectors" << std::endl;
// Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size/(numIndividuals*2))/numThreads
//unsigned long long int lociPerThread = numLoci / numThreads;
//unsigned long long int lociPerThread = (readCounts.size()-1)/numThreads; // loci starts with 0, so need to subtract 1 from numLoci
unsigned long long int lociPerThread;
if (numLoci == 0) {
lociPerThread = (unsigned long long)(size/(numIndividuals*2))/(unsigned long long)numThreads;
} else {
lociPerThread = (unsigned long long)numLoci/(unsigned long long)numThreads;
}
std::cout << "Initialized lociPerThread with " << numLoci << std::endl;
std::vector<std::thread> threadsVec;
for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) {
std::cout << "Got to the function call. Running thread # " << threadRunning << std::endl;
unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread;
unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0;
std::cout << "Set firstLocus to " << firstLocus << " and finishingLocus to " << finishingLocus << std::endl;
threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));
}
// Wait on threads to finish
for (int i = 0; i < numThreads; ++i) {
threadsVec[i].join();
std::cout << "Joined thread " << i << std::endl;
}
std::cout << "All threads completed running" << std::endl;
// Now aggregate the results of the threads and print final results
std::vector<std::vector<long double>> weightingsSum(numIndividuals, std::vector<long double>(numIndividuals,0));
std::vector<std::vector<long double>> pwpSum(numIndividuals, std::vector<long double>(numIndividuals,0));
for (int tortoise = 0; tortoise < numIndividuals; tortoise++) {
for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
for (int threadVector = 0; threadVector < numThreads; threadVector++) {
weightingsSum[tortoise][comparisonTortoise] += weightingsThreads[threadVector][tortoise][comparisonTortoise];
pwpSum[tortoise][comparisonTortoise] += pwpThreads[threadVector][tortoise][comparisonTortoise];
}
}
}
std::cout << "Finished summing the threads vectors" << std::endl;
// Now print out the final output to the pairwise pi file:
std::ofstream pwpOUT (outFile);
int rowCounter = 0;
if (!pwpOUT) {
std::cerr << "Crap, " << outFile << "didn't open!" << std::endl;
} else {
for (int tortoise=0; tortoise < numIndividuals; tortoise++) {
for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
rowCounter++;
//std::cout << "Made it past the beginning of the last end for loop" << std::endl;
//std::cout << "Tortoise numbers: " << tortoise << " and " << comparisonTortoise << std::endl;
if (weightingsSum[tortoise][comparisonTortoise] > 0) {
//std::cout << weightings[tortoise][comparisonTortoise] << std::endl;
//std::cout << pwp[tortoise][comparisonTortoise] / weightings[tortoise][comparisonTortoise] << std::endl;
std::cout << "Weightings for tortoise " << tortoise << " and comparisonTortoise " << comparisonTortoise << " : " << weightingsSum[tortoise][comparisonTortoise] << std::endl;
std::cout << "PWP for tortoise " << tortoise << " and comparisonTortoise " << comparisonTortoise << " : " << pwpSum[tortoise][comparisonTortoise] << std::endl;
pwpOUT << pwpSum[tortoise][comparisonTortoise] / weightingsSum[tortoise][comparisonTortoise] << std::endl;
} else {
pwpOUT << "NA" << std::endl;
}
}
}
}
} else std::cout << "Unable to open file";
return 0;
}
//int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector<BYTE>& mainReadCountVector, std::vector< std::vector<long double> > & threadPWP, std::vector< std::vector<long double> > & threadWeightings) {
int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings) {
std::cout << "Calculating PWP for the following locus range: " << startingLocus << " to " << endingLocus << std::endl;
for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) {
//std::cout << "Processing locus # " << locus << std::endl;
if (locus % 100000 == 0) {
std::cout << locus << " loci processed through calcPWPfromBinaryFile" << std::endl;
}
int coverages[numIndividuals];
double *majorAlleleFreqs = new double[numIndividuals]; // This will hold the major allele frequencies for that locus for each tortoise
for( int tortoise = 0; tortoise <= (numIndividuals-1); tortoise++ ) {
unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise;
unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1;
coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus
if ( coverages[tortoise] > 0 ) {
//std::cout << "Made it to line 222 for locus " << locus << std::endl;
majorAlleleFreqs[tortoise] = (double)mainReadCountVector[majorIndex] / (double)coverages[tortoise]; // Not necessarily an int, but could be 0 or 1
if (coverages[tortoise] > 1) {
unsigned long long locusWeighting = coverages[tortoise]*(coverages[tortoise]);
threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; // This is an int--discrete number of reads
threadPWP[tortoise][tortoise] += double(locusWeighting) * (2.0 * majorAlleleFreqs[tortoise] * (double(coverages[tortoise]) - double(mainReadCountVector[majorIndex]))) / (double((coverages[tortoise])-1.0));
}
for( int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
if (coverages[comparisonTortoise] > 0) {
double locusWeighting = (double)coverages[tortoise] * (double)coverages[comparisonTortoise];
threadWeightings[tortoise][comparisonTortoise] += locusWeighting;
threadPWP[tortoise][comparisonTortoise] += (double)locusWeighting * (majorAlleleFreqs[tortoise] * (1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * (1.0-majorAlleleFreqs[tortoise]));
}
}
}
}
delete[] majorAlleleFreqs; // Needed to avoid memory leaks
}
std::cout << "Finished thread ending on locus " << endingLocus << std::endl;
return 0;
}
<commit_msg>Minor changes<commit_after>//
// calcPWP.cpp
//
//
// Created by Evan McCartney-Melstad on 1/10/15.
//
//
#include "calcPWP.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <thread>
#include <string>
int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) {
//****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE****
std::cout << "Number of threads: " << numThreads << std::endl;
std::streampos size;
std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate);
//ifstream file ("test500k.binary8bitunsigned", ios::in|ios::binary|ios::ate);
if (file.is_open()) {
size = file.tellg(); // Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB!
file.seekg (0, std::ios::beg); // Go back to the beginning of the file
//file.read((char*)readCounts, size); // cast to a char* to give to file.read
//unsigned char* readCounts;
//readCounts = new unsigned char[size];
std::vector<unsigned char> readCounts(size);
file.read((char*) &readCounts[0], size);
file.close();
std::cout << "the entire file content is in memory" << std::endl;
std::cout << "the total size of the file is " << size << std::endl;
std::cout << "the number of elements in the readCounts vector is: " << readCounts.size() << std::endl; // Will give the total size bytes divided by the size of one element--so it gives the number of elements
/* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional
vectors of the forms std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0)) and std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0))
First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a
vector of two-dimensional vectors...
*/
std::vector<std::vector<std::vector<long double>>> pwpThreads(numThreads, std::vector<std::vector<long double>> (numIndividuals, std::vector<long double> (numIndividuals,0) ) ); //pwpThreads[0] is the first 2D array for the first thread, etc...
std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) );
std::cout << "Initialized the 3d vectors" << std::endl;
// Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size/(numIndividuals*2))/numThreads
//unsigned long long int lociPerThread = numLoci / numThreads;
//unsigned long long int lociPerThread = (readCounts.size()-1)/numThreads; // loci starts with 0, so need to subtract 1 from numLoci
unsigned long long int lociPerThread;
if (numLoci == 0) {
lociPerThread = (unsigned long long)(size/(numIndividuals*2))/(unsigned long long)numThreads;
} else {
lociPerThread = (unsigned long long)numLoci/(unsigned long long)numThreads;
}
std::cout << "Initialized lociPerThread with " << numLoci << std::endl;
std::vector<std::thread> threadsVec;
for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) {
std::cout << "Got to the function call. Running thread # " << threadRunning << std::endl;
unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread;
unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0;
std::cout << "Set firstLocus to " << firstLocus << " and finishingLocus to " << finishingLocus << std::endl;
threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));
}
// Wait on threads to finish
for (int i = 0; i < numThreads; ++i) {
threadsVec[i].join();
std::cout << "Joined thread " << i << std::endl;
}
std::cout << "All threads completed running" << std::endl;
// Now aggregate the results of the threads and print final results
std::vector<std::vector<long double>> weightingsSum(numIndividuals, std::vector<long double>(numIndividuals,0));
std::vector<std::vector<long double>> pwpSum(numIndividuals, std::vector<long double>(numIndividuals,0));
for (int tortoise = 0; tortoise < numIndividuals; tortoise++) {
for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
for (int threadVector = 0; threadVector < numThreads; threadVector++) {
weightingsSum[tortoise][comparisonTortoise] += weightingsThreads[threadVector][tortoise][comparisonTortoise];
pwpSum[tortoise][comparisonTortoise] += pwpThreads[threadVector][tortoise][comparisonTortoise];
}
}
}
std::cout << "Finished summing the threads vectors" << std::endl;
// Now print out the final output to the pairwise pi file:
std::ofstream pwpOUT (outFile);
int rowCounter = 0;
if (!pwpOUT) {
std::cerr << "Crap, " << outFile << "didn't open!" << std::endl;
} else {
for (int tortoise=0; tortoise < numIndividuals; tortoise++) {
for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
rowCounter++;
//std::cout << "Made it past the beginning of the last end for loop" << std::endl;
//std::cout << "Tortoise numbers: " << tortoise << " and " << comparisonTortoise << std::endl;
if (weightingsSum[tortoise][comparisonTortoise] > 0) {
//std::cout << weightings[tortoise][comparisonTortoise] << std::endl;
//std::cout << pwp[tortoise][comparisonTortoise] / weightings[tortoise][comparisonTortoise] << std::endl;
std::cout << "Weightings for tortoise " << tortoise << " and comparisonTortoise " << comparisonTortoise << " : " << weightingsSum[tortoise][comparisonTortoise] << std::endl;
std::cout << "PWP for tortoise " << tortoise << " and comparisonTortoise " << comparisonTortoise << " : " << pwpSum[tortoise][comparisonTortoise] << std::endl;
pwpOUT << pwpSum[tortoise][comparisonTortoise] / weightingsSum[tortoise][comparisonTortoise] << std::endl;
} else {
pwpOUT << "NA" << std::endl;
}
}
}
}
} else std::cout << "Unable to open file";
return 0;
}
//int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector<BYTE>& mainReadCountVector, std::vector< std::vector<long double> > & threadPWP, std::vector< std::vector<long double> > & threadWeightings) {
int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings) {
std::cout << "Calculating PWP for the following locus range: " << startingLocus << " to " << endingLocus << std::endl;
for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) {
//std::cout << "Processing locus # " << locus << std::endl;
if (locus % 100000 == 0) {
std::cout << locus << " loci processed through calcPWPfromBinaryFile" << std::endl;
}
int coverages[numIndividuals];
double *majorAlleleFreqs = new double[numIndividuals]; // This will hold the major allele frequencies for that locus for each tortoise
for( int tortoise = 0; tortoise <= (numIndividuals-1); tortoise++ ) {
unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise;
unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1;
coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus
if ( coverages[tortoise] > 0 ) {
//std::cout << "Made it to line 222 for locus " << locus << std::endl;
majorAlleleFreqs[tortoise] = (double)mainReadCountVector[majorIndex] / (double)coverages[tortoise]; // Not necessarily an int, but could be 0 or 1
if (coverages[tortoise] > 1) {
unsigned long long locusWeighting = coverages[tortoise]*(coverages[tortoise]-1);
//unsigned long long locusWeighting = coverages[tortoise]*(coverages[tortoise]);
threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; // This is an int--discrete number of reads
threadPWP[tortoise][tortoise] += double(locusWeighting) * (2.0 * majorAlleleFreqs[tortoise] * (double(coverages[tortoise]) - double(mainReadCountVector[majorIndex]))) / (double((coverages[tortoise])-1.0));
}
for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) {
if (coverages[comparisonTortoise] > 0) {
double locusWeighting = (double)coverages[tortoise] * (double)coverages[comparisonTortoise];
threadWeightings[tortoise][comparisonTortoise] += locusWeighting;
threadPWP[tortoise][comparisonTortoise] += (double)locusWeighting * (majorAlleleFreqs[tortoise] * (1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * (1.0-majorAlleleFreqs[tortoise]));
}
}
}
}
delete[] majorAlleleFreqs; // Needed to avoid memory leaks
}
std::cout << "Finished thread ending on locus " << endingLocus << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cerrno>
#include <stdexcept>
// ----------------------------------------------------------------------
inline std::string read_file(std::string aFilename)
{
std::string buffer;
int f = open(aFilename.c_str(), O_RDONLY);
if (f >= 0) {
struct stat st;
fstat(f, &st);
buffer.resize(static_cast<std::string::size_type>(st.st_size), ' '); // reserve space
read(f, &*buffer.begin(), static_cast<size_t>(st.st_size));
close(f);
}
else {
throw std::runtime_error(std::string("Cannot open ") + aFilename + ": " + std::strerror(errno));
}
return buffer;
}
// ----------------------------------------------------------------------
inline bool file_exists(std::string aFilename)
{
struct stat buffer;
return stat(aFilename.c_str(), &buffer) == 0;
}
// ----------------------------------------------------------------------
inline std::string read_from_file_descriptor(int fd, size_t chunk_size = 1024)
{
std::string buffer;
std::string::size_type offset = 0;
for (;;) {
buffer.resize(buffer.size() + chunk_size, ' ');
const auto bytes_read = read(fd, (&*buffer.begin()) + offset, chunk_size);
if (bytes_read < 0)
throw std::runtime_error(std::string("Cannot read from file descriptor: ") + std::strerror(errno));
if (static_cast<size_t>(bytes_read) < chunk_size) {
buffer.resize(buffer.size() - chunk_size + static_cast<size_t>(bytes_read));
break;
}
offset += static_cast<size_t>(bytes_read);
}
return buffer;
}
// ----------------------------------------------------------------------
inline std::string read_stdin()
{
return read_from_file_descriptor(0);
}
// ----------------------------------------------------------------------
<commit_msg>porting to gcc 4.9<commit_after>#pragma once
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cerrno>
#include <stdexcept>
// ----------------------------------------------------------------------
inline std::string read_file(std::string aFilename)
{
std::string buffer;
int f = open(aFilename.c_str(), O_RDONLY);
if (f >= 0) {
struct stat st;
fstat(f, &st);
buffer.resize(static_cast<std::string::size_type>(st.st_size), ' '); // reserve space
read(f, &*buffer.begin(), static_cast<size_t>(st.st_size));
close(f);
}
else {
throw std::runtime_error(std::string("Cannot open ") + aFilename + ": " + strerror(errno));
}
return buffer;
}
// ----------------------------------------------------------------------
inline bool file_exists(std::string aFilename)
{
struct stat buffer;
return stat(aFilename.c_str(), &buffer) == 0;
}
// ----------------------------------------------------------------------
inline std::string read_from_file_descriptor(int fd, size_t chunk_size = 1024)
{
std::string buffer;
std::string::size_type offset = 0;
for (;;) {
buffer.resize(buffer.size() + chunk_size, ' ');
const auto bytes_read = read(fd, (&*buffer.begin()) + offset, chunk_size);
if (bytes_read < 0)
throw std::runtime_error(std::string("Cannot read from file descriptor: ") + strerror(errno));
if (static_cast<size_t>(bytes_read) < chunk_size) {
buffer.resize(buffer.size() - chunk_size + static_cast<size_t>(bytes_read));
break;
}
offset += static_cast<size_t>(bytes_read);
}
return buffer;
}
// ----------------------------------------------------------------------
inline std::string read_stdin()
{
return read_from_file_descriptor(0);
}
// ----------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Alisa Dolinsky
*
* 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 "PhantomGunsDemo.h"
#include "TclComponent.h"
void* UTclComponent::handle = nullptr;
_Tcl_CreateInterpProto UTclComponent::_Tcl_CreateInterp = nullptr;
_Tcl_EvalProto UTclComponent::_Tcl_Eval = nullptr;
_Tcl_CreateObjCommandProto UTclComponent::_Tcl_CreateObjCommand = nullptr;
_Tcl_NewObjProto UTclComponent::_Tcl_NewObj = nullptr;
_Tcl_SetVar2ExProto UTclComponent::_Tcl_SetVar2Ex = nullptr;
_Tcl_GetLongFromObjProto UTclComponent::_Tcl_GetLongFromObj = nullptr;
_Tcl_GetDoubleFromObjProto UTclComponent::_Tcl_GetDoubleFromObj = nullptr;
_Tcl_GetStringFromObjProto UTclComponent::_Tcl_GetStringFromObj = nullptr;
// Sets default values for this component's properties
UTclComponent::UTclComponent()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
bWantsBeginPlay = true;
PrimaryComponentTick.bCanEverTick = true;
}
// Called when the game starts
void UTclComponent::BeginPlay()
{
Super::BeginPlay();
if (handle == nullptr) {
auto dllPath = FPaths::Combine(*FPaths::GameDir(), TEXT("ThirdParty/"), TEXT(_TCL_DLL_FNAME_));
if (FPaths::FileExists(dllPath)) {
handle = FPlatformProcess::GetDllHandle(*dllPath);
if (handle == nullptr) { UE_LOG(LogClass, Log, TEXT("Tcl bootstrapping failed")) }
else {
FString procName = "";
procName = "Tcl_CreateInterp";
_Tcl_CreateInterp = (_Tcl_CreateInterpProto)FPlatformProcess::GetDllExport(handle, *procName);
procName = "Tcl_Eval";
_Tcl_Eval = (_Tcl_EvalProto)FPlatformProcess::GetDllExport(handle, *procName);
procName = "Tcl_CreateObjCommand";
_Tcl_CreateObjCommand = (_Tcl_CreateObjCommandProto)FPlatformProcess::GetDllExport(handle, *procName);
procName = "Tcl_NewObj";
_Tcl_NewObj = (_Tcl_NewObjProto)FPlatformProcess::GetDllExport(handle, *procName);
procName = "Tcl_SetVar2Ex";
_Tcl_SetVar2Ex = (_Tcl_SetVar2ExProto)FPlatformProcess::GetDllExport(handle, *procName);
procName = "Tcl_GetLongFromObj";
_Tcl_GetLongFromObj = (_Tcl_GetLongFromObjProto)FPlatformProcess::GetDllExport(handle, *procName);
procName = "Tcl_GetDoubleFromObj";
_Tcl_GetDoubleFromObj = (_Tcl_GetDoubleFromObjProto)FPlatformProcess::GetDllExport(handle, *procName);
procName = "Tcl_GetStringFromObj";
_Tcl_GetStringFromObj = (_Tcl_GetStringFromObjProto)FPlatformProcess::GetDllExport(handle, *procName);
if (_Tcl_CreateInterp == nullptr ||
_Tcl_Eval == nullptr ||
_Tcl_CreateObjCommand == nullptr ||
_Tcl_NewObj == nullptr ||
_Tcl_SetVar2Ex == nullptr ||
_Tcl_GetLongFromObj == nullptr ||
_Tcl_GetDoubleFromObj == nullptr ||
_Tcl_GetStringFromObj == nullptr) {
handle = nullptr;
UE_LOG(LogClass, Log, TEXT("Bootstrapping one or more functions for Tcl failed!"))
}
else {
interpreter = _Tcl_CreateInterp();
UE_LOG(LogClass, Log, TEXT("Bootstrapping Tcl and its functions succeeded!"))
}
}
}
else { UE_LOG(LogClass, Log, TEXT("Cannot find %s for Tcl!"), _TCL_DLL_FNAME_) }
} else { interpreter = _Tcl_CreateInterp(); }
}
void UTclComponent::TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction )
{
Super::TickComponent( DeltaTime, TickType, ThisTickFunction );
}
void UTclComponent::Tcl_FreeInternalRepProc(Tcl_Obj* obj) { }
void UTclComponent::Tcl_DupInternalRepProc(Tcl_Obj* srcPtr, Tcl_Obj* dupPtr) { }
void UTclComponent::Tcl_UpdateStringProc(Tcl_Obj* obj) { }
int UTclComponent::Tcl_SetFromAnyProc(Tcl_Interp* interp, Tcl_Obj* obj) { return 0; }
bool UTclComponent::handleIsMissing() { return handle == nullptr; }
_Tcl_GetLongFromObjProto UTclComponent::get_Tcl_GetLongFromObj() { return _Tcl_GetLongFromObj; }
_Tcl_GetDoubleFromObjProto UTclComponent::get_Tcl_GetDoubleFromObj() { return _Tcl_GetDoubleFromObj; }
_Tcl_GetStringFromObjProto UTclComponent::get_Tcl_GetStringFromObj() { return _Tcl_GetStringFromObj; }
int UTclComponent::define(char* location, ClientData ptr, char* scope, int flags) {
static const Tcl_ObjType type = { "ClientData", &Tcl_FreeInternalRepProc, &Tcl_DupInternalRepProc, &Tcl_UpdateStringProc, &Tcl_SetFromAnyProc };
if (handle == nullptr || interpreter == nullptr) { return _TCL_BOOTSTRAP_FAIL_; }
else {
auto val = _Tcl_NewObj();
val->internalRep.otherValuePtr = ptr;
val->typePtr = &type;
*val = *(_Tcl_SetVar2Ex(interpreter, location, scope, val, flags));
FString loc = location;
if (scope == nullptr) {
UE_LOG(LogClass, Log, TEXT("Defined in %s for Tcl"), *loc)
}
else {
FString scp = scope;
UE_LOG(LogClass, Log, TEXT("Defined in %s(%s) for Tcl"), *loc, *scp)
}
return TCL_OK;
}
}
int UTclComponent::define(char* location, UObject* ptr, char* scope, int flags) {
static const Tcl_ObjType type = { "UObject", &Tcl_FreeInternalRepProc, &Tcl_DupInternalRepProc, &Tcl_UpdateStringProc, &Tcl_SetFromAnyProc };
if (handle == nullptr || interpreter == nullptr) { return _TCL_BOOTSTRAP_FAIL_; }
else {
auto val = _Tcl_NewObj();
val->internalRep.otherValuePtr = (ClientData)ptr;
val->typePtr = &type;
*val = *(_Tcl_SetVar2Ex(interpreter, location, scope, val, flags));
FString loc = location;
if (scope == nullptr) {
UE_LOG(LogClass, Log, TEXT("Defined in %s"), *loc)
}
else {
FString scp = scope;
UE_LOG(LogClass, Log, TEXT("Defined in %s(%s)"), *loc, *scp)
}
return TCL_OK;
}
}
int UTclComponent::eval(const char* code) {
if (handle == nullptr || interpreter == nullptr) { return _TCL_BOOTSTRAP_FAIL_; }
else { return _Tcl_Eval(interpreter, code); }
}
void UTclComponent::Define(FString Location, FString Key, UObject* Object) {
if (Location.IsEmpty()) {
UE_LOG(LogClass, Error, TEXT("Location must be filled if Key is empty!"))
return;
}
if (Key.IsEmpty()) {
define(TCHAR_TO_ANSI(*Location), Object);
}
else {
define(TCHAR_TO_ANSI(*Location), Object, TCHAR_TO_ANSI(*Key));
}
}
void UTclComponent::DefineClass(FString Location, FString Key, UClass* Cls) {
if (Location.IsEmpty()) {
UE_LOG(LogClass, Error, TEXT("Location must be filled if Key is empty!"))
return;
}
if (Key.IsEmpty()) {
define(TCHAR_TO_ANSI(*Location), (ClientData)Cls);
}
else {
define(TCHAR_TO_ANSI(*Location), (ClientData)Cls, TCHAR_TO_ANSI(*Key));
}
}
int32 UTclComponent::Eval(FString Filename, FString Code) {
if(!Filename.IsEmpty()) {
auto fname = FPaths::GameContentDir() + "Scripts/" + Filename;
if(FPaths::FileExists(fname)) {
UE_LOG(LogClass, Log, TEXT("Tcl loaded a script file at path: %s"), *fname)
FFileHelper::LoadFileToString(Code, *fname);
} else {
UE_LOG(LogClass, Error, TEXT("File at path: %s doesn't exist! Executing the Code field"), *fname)
}
}
auto status = eval(TCHAR_TO_ANSI(*Code));
if (status != TCL_OK) { UE_LOG(LogClass, Log, TEXT("Tcl script error!")) }
return status;
}<commit_msg>Added a NIL symbol which is just a nullptr. Often useful.<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Alisa Dolinsky
*
* 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 "PhantomGunsDemo.h"
#include "TclComponent.h"
void* UTclComponent::handle = nullptr;
_Tcl_CreateInterpProto UTclComponent::_Tcl_CreateInterp = nullptr;
_Tcl_EvalProto UTclComponent::_Tcl_Eval = nullptr;
_Tcl_CreateObjCommandProto UTclComponent::_Tcl_CreateObjCommand = nullptr;
_Tcl_NewObjProto UTclComponent::_Tcl_NewObj = nullptr;
_Tcl_SetVar2ExProto UTclComponent::_Tcl_SetVar2Ex = nullptr;
_Tcl_GetLongFromObjProto UTclComponent::_Tcl_GetLongFromObj = nullptr;
_Tcl_GetDoubleFromObjProto UTclComponent::_Tcl_GetDoubleFromObj = nullptr;
_Tcl_GetStringFromObjProto UTclComponent::_Tcl_GetStringFromObj = nullptr;
// Sets default values for this component's properties
UTclComponent::UTclComponent()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
bWantsBeginPlay = true;
PrimaryComponentTick.bCanEverTick = true;
}
// Called when the game starts
void UTclComponent::BeginPlay()
{
Super::BeginPlay();
if (handle == nullptr) {
auto dllPath = FPaths::Combine(*FPaths::GameDir(), TEXT("ThirdParty/"), TEXT(_TCL_DLL_FNAME_));
if (FPaths::FileExists(dllPath)) {
handle = FPlatformProcess::GetDllHandle(*dllPath);
if (handle == nullptr) { UE_LOG(LogClass, Log, TEXT("Tcl bootstrapping failed")) }
else {
FString procName = "";
procName = "Tcl_CreateInterp";
_Tcl_CreateInterp = (_Tcl_CreateInterpProto)FPlatformProcess::GetDllExport(handle, *procName);
procName = "Tcl_Eval";
_Tcl_Eval = (_Tcl_EvalProto)FPlatformProcess::GetDllExport(handle, *procName);
procName = "Tcl_CreateObjCommand";
_Tcl_CreateObjCommand = (_Tcl_CreateObjCommandProto)FPlatformProcess::GetDllExport(handle, *procName);
procName = "Tcl_NewObj";
_Tcl_NewObj = (_Tcl_NewObjProto)FPlatformProcess::GetDllExport(handle, *procName);
procName = "Tcl_SetVar2Ex";
_Tcl_SetVar2Ex = (_Tcl_SetVar2ExProto)FPlatformProcess::GetDllExport(handle, *procName);
procName = "Tcl_GetLongFromObj";
_Tcl_GetLongFromObj = (_Tcl_GetLongFromObjProto)FPlatformProcess::GetDllExport(handle, *procName);
procName = "Tcl_GetDoubleFromObj";
_Tcl_GetDoubleFromObj = (_Tcl_GetDoubleFromObjProto)FPlatformProcess::GetDllExport(handle, *procName);
procName = "Tcl_GetStringFromObj";
_Tcl_GetStringFromObj = (_Tcl_GetStringFromObjProto)FPlatformProcess::GetDllExport(handle, *procName);
if (_Tcl_CreateInterp == nullptr ||
_Tcl_Eval == nullptr ||
_Tcl_CreateObjCommand == nullptr ||
_Tcl_NewObj == nullptr ||
_Tcl_SetVar2Ex == nullptr ||
_Tcl_GetLongFromObj == nullptr ||
_Tcl_GetDoubleFromObj == nullptr ||
_Tcl_GetStringFromObj == nullptr) {
handle = nullptr;
UE_LOG(LogClass, Log, TEXT("Bootstrapping one or more functions for Tcl failed!"))
}
else {
interpreter = _Tcl_CreateInterp();
Define("NIL", "", nullptr);
UE_LOG(LogClass, Log, TEXT("Bootstrapping Tcl and its functions succeeded!"))
}
}
}
else { UE_LOG(LogClass, Log, TEXT("Cannot find %s for Tcl!"), _TCL_DLL_FNAME_) }
} else {
interpreter = _Tcl_CreateInterp();
Define("NIL", "", nullptr);
}
}
void UTclComponent::TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction )
{
Super::TickComponent( DeltaTime, TickType, ThisTickFunction );
}
void UTclComponent::Tcl_FreeInternalRepProc(Tcl_Obj* obj) { }
void UTclComponent::Tcl_DupInternalRepProc(Tcl_Obj* srcPtr, Tcl_Obj* dupPtr) { }
void UTclComponent::Tcl_UpdateStringProc(Tcl_Obj* obj) { }
int UTclComponent::Tcl_SetFromAnyProc(Tcl_Interp* interp, Tcl_Obj* obj) { return 0; }
bool UTclComponent::handleIsMissing() { return handle == nullptr; }
_Tcl_GetLongFromObjProto UTclComponent::get_Tcl_GetLongFromObj() { return _Tcl_GetLongFromObj; }
_Tcl_GetDoubleFromObjProto UTclComponent::get_Tcl_GetDoubleFromObj() { return _Tcl_GetDoubleFromObj; }
_Tcl_GetStringFromObjProto UTclComponent::get_Tcl_GetStringFromObj() { return _Tcl_GetStringFromObj; }
int UTclComponent::define(char* location, ClientData ptr, char* scope, int flags) {
static const Tcl_ObjType type = { "ClientData", &Tcl_FreeInternalRepProc, &Tcl_DupInternalRepProc, &Tcl_UpdateStringProc, &Tcl_SetFromAnyProc };
if (handle == nullptr || interpreter == nullptr) { return _TCL_BOOTSTRAP_FAIL_; }
else {
auto val = _Tcl_NewObj();
val->internalRep.otherValuePtr = ptr;
val->typePtr = &type;
*val = *(_Tcl_SetVar2Ex(interpreter, location, scope, val, flags));
FString loc = location;
if (scope == nullptr) {
UE_LOG(LogClass, Log, TEXT("Defined in %s for Tcl"), *loc)
}
else {
FString scp = scope;
UE_LOG(LogClass, Log, TEXT("Defined in %s(%s) for Tcl"), *loc, *scp)
}
return TCL_OK;
}
}
int UTclComponent::define(char* location, UObject* ptr, char* scope, int flags) {
static const Tcl_ObjType type = { "UObject", &Tcl_FreeInternalRepProc, &Tcl_DupInternalRepProc, &Tcl_UpdateStringProc, &Tcl_SetFromAnyProc };
if (handle == nullptr || interpreter == nullptr) { return _TCL_BOOTSTRAP_FAIL_; }
else {
auto val = _Tcl_NewObj();
val->internalRep.otherValuePtr = (ClientData)ptr;
val->typePtr = &type;
*val = *(_Tcl_SetVar2Ex(interpreter, location, scope, val, flags));
FString loc = location;
if (scope == nullptr) {
UE_LOG(LogClass, Log, TEXT("Defined in %s"), *loc)
}
else {
FString scp = scope;
UE_LOG(LogClass, Log, TEXT("Defined in %s(%s)"), *loc, *scp)
}
return TCL_OK;
}
}
int UTclComponent::eval(const char* code) {
if (handle == nullptr || interpreter == nullptr) { return _TCL_BOOTSTRAP_FAIL_; }
else { return _Tcl_Eval(interpreter, code); }
}
void UTclComponent::Define(FString Location, FString Key, UObject* Object) {
if (Location.IsEmpty()) {
UE_LOG(LogClass, Error, TEXT("Location must be filled if Key is empty!"))
return;
}
if (Key.IsEmpty()) {
define(TCHAR_TO_ANSI(*Location), Object);
}
else {
define(TCHAR_TO_ANSI(*Location), Object, TCHAR_TO_ANSI(*Key));
}
}
void UTclComponent::DefineClass(FString Location, FString Key, UClass* Cls) {
if (Location.IsEmpty()) {
UE_LOG(LogClass, Error, TEXT("Location must be filled if Key is empty!"))
return;
}
if (Key.IsEmpty()) {
define(TCHAR_TO_ANSI(*Location), (ClientData)Cls);
}
else {
define(TCHAR_TO_ANSI(*Location), (ClientData)Cls, TCHAR_TO_ANSI(*Key));
}
}
int32 UTclComponent::Eval(FString Filename, FString Code) {
if(!Filename.IsEmpty()) {
auto fname = FPaths::GameContentDir() + "Scripts/" + Filename;
if(FPaths::FileExists(fname)) {
UE_LOG(LogClass, Log, TEXT("Tcl loaded a script file at path: %s"), *fname)
FFileHelper::LoadFileToString(Code, *fname);
} else {
UE_LOG(LogClass, Error, TEXT("File at path: %s doesn't exist! Executing the Code field"), *fname)
}
}
auto status = eval(TCHAR_TO_ANSI(*Code));
if (status != TCL_OK) { UE_LOG(LogClass, Log, TEXT("Tcl script error!")) }
return status;
}<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2005 by Thorsten Staerk <kde@staerk.de>
* 2007 the ktimetracker developers
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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, write to the
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA.
*
*/
#include "ktimetrackerpart.h"
#include <QMenu>
#include <KAboutData>
#include <KAction>
#include <KComponentData>
#include <KGlobal>
#include <KLocale>
#include <KStandardAction>
#include <KStandardDirs>
#include <KXMLGUIFactory>
#include <KActionCollection>
#include <kdemacros.h>
#include <kparts/genericfactory.h>
#include "mainwindow.h"
#include "ktimetrackerutility.h"
#include "task.h"
#include "preferences.h"
#include "tray.h"
#include "version.h"
#include "ktimetracker.h"
#include "timetrackerwidget.h"
K_PLUGIN_FACTORY(ktimetrackerPartFactory, registerPlugin<ktimetrackerpart>();)
K_EXPORT_PLUGIN( ktimetrackerPartFactory("ktimetracker","ktimetracker") )
ktimetrackerpart::ktimetrackerpart( QWidget *parentWidget, QObject *parent, const QVariantList& )
: KParts::ReadWritePart(parent)
{
KGlobal::locale()->insertCatalog("ktimetracker");
// we need an instance
setComponentData( ktimetrackerPartFactory::componentData() );
mMainWidget = new TimetrackerWidget( parentWidget );
setWidget( mMainWidget );
setXMLFile( "ktimetrackerui.rc" );
makeMenus();
}
ktimetrackerpart::~ktimetrackerpart()
{
}
KAboutData *ktimetrackerpart::createAboutData()
{
const QByteArray& appname=QByteArray("ktimetracker");
const QByteArray& catalogname=QByteArray("ktimetracker");
const KLocalizedString localizedname=ki18n("ktimetracker");
const QByteArray version=QByteArray(KTIMETRACKER_VERSION);
KAboutData* aboutData=new KAboutData( appname, catalogname, localizedname, version);
return aboutData;
}
void ktimetrackerpart::makeMenus()
{
mMainWidget->setupActions( actionCollection() );
KAction *actionKeyBindings;
actionKeyBindings = KStandardAction::keyBindings( this, SLOT( keyBindings() ),
actionCollection() );
// Tool tips must be set after the createGUI.
actionKeyBindings->setToolTip( i18n("Configure key bindings") );
actionKeyBindings->setWhatsThis( i18n("This will let you configure key"
"bindings which are specific to ktimetracker") );
}
void ktimetrackerpart::setStatusBar(const QString & qs)
{
kDebug(5970) << "Entering function";
emit setStatusBarText(qs);
}
bool ktimetrackerpart::openFile(QString icsfile)
{
mMainWidget->openFile(icsfile);
emit setWindowCaption(icsfile);
if ( KTimeTrackerSettings::trayIcon() ) mTray = new TrayIcon( this );
else mTray = new TrayIcon( );
// connections
connect( mMainWidget, SIGNAL( totalTimesChanged( long, long ) ),
this, SLOT( updateTime( long, long ) ) );
connect( mMainWidget, SIGNAL( statusBarTextChangeRequested( QString ) ),
this, SLOT( setStatusBar( QString ) ) );
connect( mMainWidget, SIGNAL( setCaption( const QString& ) ),
this, SIGNAL( setWindowCaption( const QString& ) ) );
connect( mTray, SIGNAL( quitSelected() ), SLOT( quit() ) );
connect( mMainWidget, SIGNAL( timersActive() ), mTray, SLOT( startClock() ) );
connect( mMainWidget, SIGNAL( timersInactive() ), mTray, SLOT( stopClock() ) );
connect( mMainWidget, SIGNAL( tasksChanged( const QList<Task*>& ) ),
mTray, SLOT( updateToolTip( QList<Task*> ) ));
return true;
}
bool ktimetrackerpart::openFile()
{
return openFile(KStandardDirs::locateLocal( "data", QString::fromLatin1( "ktimetracker/ktimetracker.ics" ) ));
}
bool ktimetrackerpart::saveFile()
{
mMainWidget->saveFile();
return true;
}
#include "ktimetrackerpart.moc"
<commit_msg>load catalog with translations for kdatepickerpopup<commit_after>/*
* Copyright (C) 2005 by Thorsten Staerk <kde@staerk.de>
* 2007 the ktimetracker developers
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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, write to the
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA.
*
*/
#include "ktimetrackerpart.h"
#include <QMenu>
#include <KAboutData>
#include <KAction>
#include <KComponentData>
#include <KGlobal>
#include <KLocale>
#include <KStandardAction>
#include <KStandardDirs>
#include <KXMLGUIFactory>
#include <KActionCollection>
#include <kdemacros.h>
#include <kparts/genericfactory.h>
#include "mainwindow.h"
#include "ktimetrackerutility.h"
#include "task.h"
#include "preferences.h"
#include "tray.h"
#include "version.h"
#include "ktimetracker.h"
#include "timetrackerwidget.h"
K_PLUGIN_FACTORY(ktimetrackerPartFactory, registerPlugin<ktimetrackerpart>();)
K_EXPORT_PLUGIN( ktimetrackerPartFactory("ktimetracker","ktimetracker") )
ktimetrackerpart::ktimetrackerpart( QWidget *parentWidget, QObject *parent, const QVariantList& )
: KParts::ReadWritePart(parent)
{
KGlobal::locale()->insertCatalog("ktimetracker");
KGlobal::locale()->insertCatalog("libkdepim");
// we need an instance
setComponentData( ktimetrackerPartFactory::componentData() );
mMainWidget = new TimetrackerWidget( parentWidget );
setWidget( mMainWidget );
setXMLFile( "ktimetrackerui.rc" );
makeMenus();
}
ktimetrackerpart::~ktimetrackerpart()
{
}
KAboutData *ktimetrackerpart::createAboutData()
{
const QByteArray& appname=QByteArray("ktimetracker");
const QByteArray& catalogname=QByteArray("ktimetracker");
const KLocalizedString localizedname=ki18n("ktimetracker");
const QByteArray version=QByteArray(KTIMETRACKER_VERSION);
KAboutData* aboutData=new KAboutData( appname, catalogname, localizedname, version);
return aboutData;
}
void ktimetrackerpart::makeMenus()
{
mMainWidget->setupActions( actionCollection() );
KAction *actionKeyBindings;
actionKeyBindings = KStandardAction::keyBindings( this, SLOT( keyBindings() ),
actionCollection() );
// Tool tips must be set after the createGUI.
actionKeyBindings->setToolTip( i18n("Configure key bindings") );
actionKeyBindings->setWhatsThis( i18n("This will let you configure key"
"bindings which are specific to ktimetracker") );
}
void ktimetrackerpart::setStatusBar(const QString & qs)
{
kDebug(5970) << "Entering function";
emit setStatusBarText(qs);
}
bool ktimetrackerpart::openFile(QString icsfile)
{
mMainWidget->openFile(icsfile);
emit setWindowCaption(icsfile);
if ( KTimeTrackerSettings::trayIcon() ) mTray = new TrayIcon( this );
else mTray = new TrayIcon( );
// connections
connect( mMainWidget, SIGNAL( totalTimesChanged( long, long ) ),
this, SLOT( updateTime( long, long ) ) );
connect( mMainWidget, SIGNAL( statusBarTextChangeRequested( QString ) ),
this, SLOT( setStatusBar( QString ) ) );
connect( mMainWidget, SIGNAL( setCaption( const QString& ) ),
this, SIGNAL( setWindowCaption( const QString& ) ) );
connect( mTray, SIGNAL( quitSelected() ), SLOT( quit() ) );
connect( mMainWidget, SIGNAL( timersActive() ), mTray, SLOT( startClock() ) );
connect( mMainWidget, SIGNAL( timersInactive() ), mTray, SLOT( stopClock() ) );
connect( mMainWidget, SIGNAL( tasksChanged( const QList<Task*>& ) ),
mTray, SLOT( updateToolTip( QList<Task*> ) ));
return true;
}
bool ktimetrackerpart::openFile()
{
return openFile(KStandardDirs::locateLocal( "data", QString::fromLatin1( "ktimetracker/ktimetracker.ics" ) ));
}
bool ktimetrackerpart::saveFile()
{
mMainWidget->saveFile();
return true;
}
#include "ktimetrackerpart.moc"
<|endoftext|>
|
<commit_before>#include <img_processing.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <settings_class.h>
#include <stdlib.h>
#include <ancillary_functions.h>
#include <boost/filesystem.hpp>
#define DEFAULT_RESCALE_Y 100
#define DEFAULT_RESCALE_X 100
// change image to same dimensions
float Img_Processing::compareImages(std::string img1, std::string img2){
int* bucket1 = (int*) calloc(BUCKET_SIZE, sizeof(int));
int* bucket2 = (int*) calloc(BUCKET_SIZE, sizeof(int));
int bytes_to_read = 0;
FILE* img1_loaded;
FILE* img2_loaded;
if(!(img1_loaded = fopen(img1.c_str(), "r"))) std::cerr << "Couldn't open image";
if(!(img2_loaded = fopen(img2.c_str(), "r"))) std::cerr << "Couldn't open image"; // add exception?
bytes_to_read = boost::filesystem::file_size(img1);
Img_Processing::getBuckets(img1_loaded, bucket1, bytes_to_read - 1);
fclose(img1_loaded);
// practice clearing pointers
//Print first 2kb of image 1
/*for(int x = 0; x < BUCKET_SIZE; x++){
printf("%02d ", bucket1[x]);
if(x % 20 == 1 && x > 1) std::cout << "\n";
}*/
std::cout << "\n";
bytes_to_read = boost::filesystem::file_size(img2);
Img_Processing::getBuckets(img2_loaded, bucket2, bytes_to_read);
//Print first 2kb of Image2
/*for(int x = 0; x < BUCKET_SIZE; x++){
printf("%02d ", bucket2[x]);
if(x % 20 == 1 && x > 1) std::cout << "\n";
}*/
// Compare the buckets
int difference = 0;
int sum_diff = 0;
for(int x = 0; x < BUCKET_SIZE; x++){
difference = bucket1[x] - bucket2[x]; // average and compare to original?
if(difference < 0) difference *= -1;
sum_diff += difference;
}
printf("\nDifference between images: %%%.4f", ((float) sum_diff / (bytes_to_read * 256)) * 1000);
fclose(img2_loaded);
return 1.0;
}
void Img_Processing::getBuckets(FILE* img, int* store, int bytes_to_read){
unsigned char* buffer = (unsigned char*) calloc(bytes_to_read, sizeof(char));
fread(buffer, sizeof(char), bytes_to_read, img);
for(int x = 0; x < bytes_to_read; x++){
store[buffer[x]]++;
}
}
float Img_Processing::compareMemoryImg(HBITMAP mem_img1, HBITMAP mem_img2){
Gdiplus::Bitmap img1(mem_img1, NULL);
Gdiplus::Bitmap img2(mem_img2, NULL);
float per_diff = 0;
int rgb_diff[3] = {0};
int temp;
// Gives Resolution of Image
//img1.GetWidth() img1.GetHeight() << ;
img1.SetResolution(DEFAULT_RESCALE_X, DEFAULT_RESCALE_Y);
img2.SetResolution(DEFAULT_RESCALE_X, DEFAULT_RESCALE_Y);
Gdiplus::Color c1;
Gdiplus::Color c2;
for(int x = 0; x < DEFAULT_RESCALE_X; x++){
for(int y = 0; y < DEFAULT_RESCALE_Y; y++){
img1.GetPixel(x, y, &c1);
img2.GetPixel(x, y, &c2);
temp = c1.GetR() - c2.GetR();
if(temp < 0) temp *= -1;
rgb_diff[0] += temp;
temp = c1.GetB() - c2.GetB();
if(temp < 0) temp *= -1;
rgb_diff[1] += temp;
temp = c1.GetG() - c2.GetG();
if(temp < 0) temp *= -1;
rgb_diff[2] += temp;
//printf("Img 1: R: %03d G: %03d B: %03d\tImg 2: R: %03d G: %03d B: %03d\n", c1.GetR(), c1.GetG(), c1.GetB(), c2.GetR(), c2.GetG(), c2.GetB());
}
}
for(int x = 0; x < 3; x++){
per_diff += rgb_diff[x];
}
per_diff = per_diff / (DEFAULT_RESCALE_Y * DEFAULT_RESCALE_X);
return per_diff;
}
struct result_data Img_Processing::compareMemoryImgSel(HBITMAP canvas, HBITMAP img, int x, int y, struct Scaling_Info* si_s){
Gdiplus::Bitmap img1(canvas, NULL);
std::vector<Gdiplus::Bitmap*> img2;
struct result_data rdt;
rdt.difference = NULL;
//************************check canvas is bigger than img*********************************
//****************************************************************************************
float scale_factor_x = img1.GetWidth() / si_s->x_scaler;
float scale_factor_y = img1.GetHeight() / si_s->y_scaler ;
si_s->scaling_ratio = scale_factor_x;
std::cout << "Scale factor " << scale_factor_y << scale_factor_x << " " << "\n";
std::cout << "Snapshot dimensions after scale factor applied: " << img1.GetHeight() << "x" << img1.GetWidth() << "\n";
std::vector<Gdiplus::Bitmap*> newmap;
int count = si_s->num_images;
std::cout << "number of images: " << count << std::endl;
rdt.difference = (float*) calloc(sizeof(float), count);
rdt.threshold = (float*) calloc(sizeof(float), count);
//const CLSID codec = { 0x557cf406, 0x1a04, 0x11d3,{ 0x9a,0x73,0x00,0x00,0xf8,0x1e,0xf3,0x2e } };
//newmap->Save(L"test.png", &codec, NULL);
//exit(1);
/*std::string file_name = "testf.png";
const CLSID codec = { 0x557cf406, 0x1a04, 0x11d3,{ 0x9a,0x73,0x00,0x00,0xf8,0x1e,0xf3,0x2e } };
int size = file_name.length();
wchar_t name[size + 1];
swprintf(name, size + 1, L"%s", file_name.c_str());
int status = (*newmap).Save(name, &codec, NULL);
if(status){
std::cerr << "Error saving image: " << status << "\n";
return 1;
}*/
float per_diff = 0;
int rgb_diff[3] = {0};
int temp;
try{
for(int z = 0; z < count; z++){
per_diff = 0;
for(int x = 0; x < 3; x++) rgb_diff[x] = 0;
img2.push_back(new Gdiplus::Bitmap(si_s->pic_data_array[z].bmp, NULL));
x = si_s->pic_data_array[z].x;
y = si_s->pic_data_array[z].y;
printf("statistics: x: %d y: %d width: %d height: %d scale_factor: %f", x, y, img2.back()->GetHeight(), img2.back()->GetWidth(), scale_factor_x);
newmap.push_back(img1.Clone(x * scale_factor_x, y * scale_factor_y, img2.back()->GetWidth() * scale_factor_x, img2.back()->GetHeight() * scale_factor_y, PixelFormat32bppARGB));
img2.back()->SetResolution(DEFAULT_RESCALE_X * scale_factor_x, DEFAULT_RESCALE_Y * scale_factor_y);
newmap.back()->SetResolution(DEFAULT_RESCALE_X * scale_factor_x, DEFAULT_RESCALE_Y * scale_factor_y);
Gdiplus::Color c1;
Gdiplus::Color c2;
for(int c = 0; c < DEFAULT_RESCALE_X * scale_factor_x; c++){
for(int b = 0; b < DEFAULT_RESCALE_Y * scale_factor_y; b++){
newmap.back()->GetPixel(c, b, &c1);
img2.back()->GetPixel(c, b, &c2);
temp = c1.GetR() - c2.GetR();
if(temp < 0) temp *= -1;
rgb_diff[0] += temp;
temp = c1.GetB() - c2.GetB();
if(temp < 0) temp *= -1;
rgb_diff[1] += temp;
temp = c1.GetG() - c2.GetG();
if(temp < 0) temp *= -1;
rgb_diff[2] += temp;
//printf("Img 1: R: %03d G: %03d B: %03d\tImg 2: R: %03d G: %03d B: %03d\n", c1.GetR(), c1.GetG(), c1.GetB(), c2.GetR(), c2.GetG(), c2.GetB());
}
}
for(int z = 0; z < 3; z++){
per_diff += rgb_diff[z];
}
per_diff = per_diff / ((DEFAULT_RESCALE_Y * scale_factor_y) * (DEFAULT_RESCALE_X * scale_factor_x));
rdt.difference[z] = per_diff;
}
}catch(std::exception &e){
std::cerr << "Error: " << e.what();
exit(1);
}
for(int z = 0; z < img2.size() ; z++)delete img2.at(z);
for(int z = 0; z < newmap.size(); z++) delete newmap.at(z);
img2.clear();
newmap.clear();
return rdt;
}<commit_msg>revised comparing method, now using LockBits<commit_after>#include <img_processing.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
//#include <ancillary_functions.h>
//#include <boost/filesystem.hpp>
#define DEFAULT_RESCALE_Y 100
#define DEFAULT_RESCALE_X 100
// change image to same dimensions
namespace Img_Processing{
float compareImages(std::string img1, std::string img2){
int sum_diff, temp = 0;
float per_diff = 0;
int rgb_diff[3] = {0};
FILE* img1_loaded;
FILE* img2_loaded;
if(!(img1_loaded = fopen(img1.c_str(), "r"))) std::cerr << "Couldn't open image";
if(!(img2_loaded = fopen(img2.c_str(), "r"))) std::cerr << "Couldn't open image"; // add exception?
Gdiplus::Bitmap* img1_bmp = new Gdiplus::Bitmap(std::wstring(img1.begin(), img1.end()).c_str(), NULL);
Gdiplus::Bitmap* img2_bmp = new Gdiplus::Bitmap(std::wstring(img2.begin(), img2.end()).c_str(), NULL);
img1_bmp->SetResolution(DEFAULT_RESCALE_X, DEFAULT_RESCALE_Y);
img2_bmp->SetResolution(DEFAULT_RESCALE_X, DEFAULT_RESCALE_Y);
Gdiplus::Color c1;
Gdiplus::Color c2;
for(int x = 0; x < DEFAULT_RESCALE_X; x++){
for(int y = 0; y < DEFAULT_RESCALE_Y; y++){
img1_bmp->GetPixel(x, y, &c1);
img2_bmp->GetPixel(x, y, &c2);
temp = c1.GetR() - c2.GetR();
if(temp < 0) temp *= -1;
rgb_diff[0] += temp;
temp = c1.GetB() - c2.GetB();
if(temp < 0) temp *= -1;
rgb_diff[1] += temp;
temp = c1.GetG() - c2.GetG();
if(temp < 0) temp *= -1;
rgb_diff[2] += temp;
//printf("Img 1: R: %03d G: %03d B: %03d\tImg 2: R: %03d G: %03d B: %03d\n", c1.GetR(), c1.GetG(), c1.GetB(), c2.GetR(), c2.GetG(), c2.GetB());
}
}
for(int x = 0; x < 3; x++){
per_diff += rgb_diff[x];
}
per_diff = per_diff / (DEFAULT_RESCALE_Y * DEFAULT_RESCALE_X);
// clean up
DeleteObject(img1_bmp);
DeleteObject(img2_bmp);
return per_diff;
}
float compareMemoryImg(HBITMAP mem_img1, HBITMAP mem_img2){
Gdiplus::Bitmap img1(mem_img1, NULL);
Gdiplus::Bitmap img2(mem_img2, NULL);
float per_diff = 0;
int rgb_diff[3] = {0};
int temp;
// Gives Resolution of Image
//img1.GetWidth() img1.GetHeight() << ;
img1.SetResolution(DEFAULT_RESCALE_X, DEFAULT_RESCALE_Y);
img2.SetResolution(DEFAULT_RESCALE_X, DEFAULT_RESCALE_Y);
Gdiplus::Color c1;
Gdiplus::Color c2;
for(int x = 0; x < DEFAULT_RESCALE_X; x++){
for(int y = 0; y < DEFAULT_RESCALE_Y; y++){
img1.GetPixel(x, y, &c1);
img2.GetPixel(x, y, &c2);
temp = c1.GetR() - c2.GetR();
if(temp < 0) temp *= -1;
rgb_diff[0] += temp;
temp = c1.GetB() - c2.GetB();
if(temp < 0) temp *= -1;
rgb_diff[1] += temp;
temp = c1.GetG() - c2.GetG();
if(temp < 0) temp *= -1;
rgb_diff[2] += temp;
//printf("Img 1: R: %03d G: %03d B: %03d\tImg 2: R: %03d G: %03d B: %03d\n", c1.GetR(), c1.GetG(), c1.GetB(), c2.GetR(), c2.GetG(), c2.GetB());
}
}
for(int x = 0; x < 3; x++){
per_diff += rgb_diff[x];
}
per_diff = per_diff / (DEFAULT_RESCALE_Y * DEFAULT_RESCALE_X);
return per_diff;
}
struct result_data compareMemoryImgSel(HBITMAP canvas, HBITMAP img, int x, int y, struct Scaling_Info* si_s){
float per_diff = 0;
int temp = 0;
int rgb_diff[3] = {0};
Gdiplus::Bitmap img1(canvas, NULL);
vector<Gdiplus::Bitmap*> img2;
struct result_data rdt;
rdt.difference = NULL;
//************************check canvas is bigger than img*********************************
//****************************************************************************************
float scale_factor_x = img1.GetWidth() / si_s->x_scaler;
float scale_factor_y = img1.GetHeight() / si_s->y_scaler ;
si_s->scaling_ratio = scale_factor_x;
cout << "Scale factor " << scale_factor_y << scale_factor_x << " " << "\n";
cout << "Snapshot dimensions after scale factor applied: " << img1.GetHeight() << "x" << img1.GetWidth() << "\n";
vector<Gdiplus::Bitmap*> newmap;
int count = si_s->num_images;
cout << "number of images: " << count << std::endl;
rdt.difference = (float*) calloc(sizeof(float), count);
rdt.threshold = (float*) calloc(sizeof(float), count);
try{
for(int z = 0; z < count; z++){
per_diff = 0;
for(int x = 0; x < 3; x++) rgb_diff[x] = 0;
img2.push_back(new Gdiplus::Bitmap(si_s->pic_data_array[z].bmp, NULL));
x = si_s->pic_data_array[z].x;
y = si_s->pic_data_array[z].y;
printf("statistics: x: %d y: %d width: %d height: %d scale_factor: %f", x, y, img2.back()->GetHeight(), img2.back()->GetWidth(), scale_factor_x);
newmap.push_back(img1.Clone(x * scale_factor_x, y * scale_factor_y, img2.back()->GetWidth() * scale_factor_x, img2.back()->GetHeight() * scale_factor_y, PixelFormat32bppARGB));
img2.back()->SetResolution(DEFAULT_RESCALE_X * scale_factor_x, DEFAULT_RESCALE_Y * scale_factor_y);
newmap.back()->SetResolution(DEFAULT_RESCALE_X * scale_factor_x, DEFAULT_RESCALE_Y * scale_factor_y);
Gdiplus::Color c1;
Gdiplus::Color c2;
for(int c = 0; c < DEFAULT_RESCALE_X * scale_factor_x; c++){
for(int b = 0; b < DEFAULT_RESCALE_Y * scale_factor_y; b++){
newmap.back()->GetPixel(c, b, &c1);
img2.back()->GetPixel(c, b, &c2);
temp = c1.GetR() - c2.GetR();
if(temp < 0) temp *= -1;
rgb_diff[0] += temp;
temp = c1.GetB() - c2.GetB();
if(temp < 0) temp *= -1;
rgb_diff[1] += temp;
temp = c1.GetG() - c2.GetG();
if(temp < 0) temp *= -1;
rgb_diff[2] += temp;
//printf("Img 1: R: %03d G: %03d B: %03d\tImg 2: R: %03d G: %03d B: %03d\n", c1.GetR(), c1.GetG(), c1.GetB(), c2.GetR(), c2.GetG(), c2.GetB());
}
}
for(int z = 0; z < 3; z++){
per_diff += rgb_diff[z];
}
per_diff = per_diff / ((DEFAULT_RESCALE_Y * scale_factor_y) * (DEFAULT_RESCALE_X * scale_factor_x));
rdt.difference[z] = per_diff;
}
}catch(std::exception &e){
std::cerr << "Error: " << e.what();
exit(1);
}
for(int z = 0; z < img2.size() ; z++)delete img2.at(z);
for(int z = 0; z < newmap.size(); z++) delete newmap.at(z);
img2.clear();
newmap.clear();
return rdt;
}
void getBuckets(FILE* img, int* store, int bytes_to_read){
unsigned char* buffer = (unsigned char*) calloc(bytes_to_read, sizeof(char));
fread(buffer, sizeof(char), bytes_to_read, img);
for(int x = 0; x < bytes_to_read; x++){
store[buffer[x]]++;
}
free(buffer);
}
/**
* Compares two bitmaps and returns the overall color difference as a decimal where 100% difference would be 1.00 and a match would 0
* @param img1 First image to compare
* @param img2 Second image to compare
* @return the overall difference as a decimal which is <= 1
*/
float compareMemoryImg(Gdiplus::Bitmap* img1, Gdiplus::Bitmap* img2){
// compare bitmaps
float difference, per_diff = 0;
int height, width;
height = img1->GetHeight();
width = img1->GetWidth();
if(height > img2->GetHeight()) height = img2->GetHeight();
if(width > img2->GetWidth()) width = img2->GetWidth();
Gdiplus::BitmapData* bitmapData1 = new Gdiplus::BitmapData;
Gdiplus::BitmapData* bitmapData2 = new Gdiplus::BitmapData;
Gdiplus::Color c1;
Gdiplus::Color c2;
Gdiplus::Rect rect(0,0, width, height);
img1->LockBits(&rect, Gdiplus::ImageLockModeRead, PixelFormat32bppARGB, bitmapData1);
img2->LockBits(&rect, Gdiplus::ImageLockModeRead, PixelFormat32bppARGB, bitmapData2);
int current_pixel_place;
unsigned char* pixels_1 = (unsigned char*) bitmapData1->Scan0;
unsigned char* pixels_2 = (unsigned char*) bitmapData2->Scan0;
for(int x = 0; x < height; x++){
for(int y = 0; y < width; y++){
current_pixel_place = x * bitmapData1->Stride / 4 + y*4;
for(int z = 0; z < 2; z ++)
{
difference = pixels_1[current_pixel_place + z] - pixels_2[current_pixel_place + z];
if(difference < 0) difference *= -1;
per_diff += difference;
}
}
}
img1->UnlockBits(bitmapData1);
img2->UnlockBits(bitmapData2);
delete bitmapData1;
delete bitmapData2;
DeleteObject(bitmapData1);
DeleteObject(bitmapData2);
return (per_diff / (width * height * 765));
}
void cropBitmap(Gdiplus::Bitmap** img, int x, int y, int width, int height){
Gdiplus::Bitmap* temp = (*img)->Clone(x, y, width, height, PixelFormat32bppARGB);
delete *img;
*img = temp;
}
}<|endoftext|>
|
<commit_before>// Copyright (C) 2010 Nikhil Marathe <nsm.nikhil@gmail.com>
#include <string>
#include <vector>
#include <iostream>
#include <v8.h>
#include <node.h>
#include <libface/LibFace.h>
#include <libface/Face.h>
using namespace v8;
using namespace node;
namespace face {
Handle<Value> Faces( const Arguments &args ) {
HandleScope scope;
std::string filename;
if (args.Length() > 0 && args[0]->IsString()) {
Local<String> p = args[0]->ToString();
String::AsciiValue asc(p);
filename = *asc;
}
libface::LibFace detector;
std::vector<libface::Face> faces = detector.detectFaces(filename);
Local<Array> faceArray = Array::New(faces.size());
for(int i = 0, l = faces.size(); i < l; i++) {
Local<Object> coords = Object::New();
coords->Set(String::New("x"), Integer::New(faces[i].getX1()));
coords->Set(String::New("y"), Integer::New(faces[i].getY1()));
coords->Set(String::New("width"), Integer::New(faces[i].getWidth()));
coords->Set(String::New("height"), Integer::New(faces[i].getHeight()));
faceArray->Set(Integer::New(i), coords);
}
return faceArray;
}
void Initialize( Handle<Object> target ) {
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(Faces);
target->Set( String::NewSymbol( "faces" ), t->GetFunction() );
}
}
extern "C"
void init( Handle<Object> target ) {
HandleScope scope;
face::Initialize( target );
}
<commit_msg>Check if image is valid.<commit_after>// Copyright (C) 2010 Nikhil Marathe <nsm.nikhil@gmail.com>
#include <string>
#include <vector>
#include <iostream>
#include <v8.h>
#include <node.h>
#include <opencv2/opencv.hpp>
#include <libface/LibFace.h>
#include <libface/Face.h>
using namespace v8;
using namespace node;
namespace face {
Handle<Value> Faces( const Arguments &args ) {
HandleScope scope;
std::string filename;
if (args.Length() > 0 && args[0]->IsString()) {
Local<String> p = args[0]->ToString();
String::AsciiValue asc(p);
filename = *asc;
}
IplImage *img = cvLoadImage(filename.c_str());
if( !img ) {
return String::New( cvErrorStr( cvGetErrStatus() ) );
}
libface::LibFace detector;
std::vector<libface::Face> faces = detector.detectFaces(filename);
Local<Array> faceArray = Array::New(faces.size());
for(int i = 0, l = faces.size(); i < l; i++) {
Local<Object> coords = Object::New();
coords->Set(String::New("x"), Integer::New(faces[i].getX1()));
coords->Set(String::New("y"), Integer::New(faces[i].getY1()));
coords->Set(String::New("width"), Integer::New(faces[i].getWidth()));
coords->Set(String::New("height"), Integer::New(faces[i].getHeight()));
faceArray->Set(Integer::New(i), coords);
}
return scope.Close(faceArray);
}
void Initialize( Handle<Object> target ) {
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(Faces);
target->Set( String::NewSymbol( "faces" ), t->GetFunction() );
}
}
extern "C"
void init( Handle<Object> target ) {
HandleScope scope;
face::Initialize( target );
}
<|endoftext|>
|
<commit_before>#include <QPdfWriter>
#include <QPrintDialog>
#include <QPainter>
#include <QPrintPreviewWidget>
#include <QPrintPreviewDialog>
#include <QTextBrowser>
#include <QFile>
#include <QTextStream>
#include "engine.hpp"
namespace qtreports {
Engine::Engine( QObject * parent ) :
QObject( parent ),
m_isCompiled( false ) {}
Engine::~Engine() {}
bool Engine::compile( const QString & path ) {
detail::Translator translator;
bool result = translator.parse( path );
if( !result ) {
m_lastError = translator.getLastError();
return false;
}
m_isCompiled = true;
m_compiledPath = path;
m_widget = translator.getWidget();
return true;
}
bool Engine::setParameters( const QMap< QString, QString > & map ) {
//QString or QVariant?
return true;
}
bool Engine::setConnection( const QSqlDatabase & connection ) {
if( connection.isOpen() ) {
m_lastError = "Connection not open";
return false;
}
return true;
}
bool Engine::createPDF( const QString & path ) {
QPdfWriter writer( path );
//Very small, need resize to page size.
m_widget->render( &writer );
return true;
}
bool Engine::createHTML( const QString & path ) {
auto isCopied = QFile::copy( m_compiledPath, path );
if( !isCopied ) {
m_lastError = "Can not create html file";
return false;
}
return true;
/*
auto browser = dynamic_cast< QTextBrowser * >( m_widget.data() );
QFile file( path );
file.open(
QIODevice::OpenModeFlag::WriteOnly |
QIODevice::OpenModeFlag::Text |
QIODevice::OpenModeFlag::Truncate
);
if( !file.isOpen() ) {
m_lastError = "The file can not be opened";
return false;
}
QTextStream stream( &file );
stream << browser->toHtml();
return true;
*/
}
bool Engine::print() {
QPrinter printer;
QPrintPreviewDialog preview( &printer );
connect(
&preview, &QPrintPreviewDialog::paintRequested,
this, &Engine::drawPreview
);
preview.exec();
return true;
}
void Engine::drawPreview( QPrinter * printer ) {
QRectF rect = printer->pageRect();
QPainter painter( printer );
double xscale = rect.width() / m_widget->width();
double yscale = rect.height() / m_widget->height();
double scale = std::min( xscale, yscale );
painter.translate(
0, rect.height() / 2 - scale * m_widget->height() / 2
);
painter.scale( scale, scale );
m_widget->render( &painter );
}
const QString Engine::getLastError() const {
return m_lastError;
}
const QWidgetPtr Engine::getWidget() const {
return m_widget;
}
const bool Engine::isCompiled() const {
return m_isCompiled;
}
}<commit_msg>Delete engine.cpp<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright (C) 2009-2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file libuvalue/ubinary.cc
#include <iostream>
#include <sstream>
#include <libport/debug.hh>
#include <libport/escape.hh>
#include <urbi/ubinary.hh>
#include <boost/algorithm/string/replace.hpp>
GD_CATEGORY(UValue);
namespace urbi
{
UBinary::UBinary()
: type(BINARY_NONE)
, allocated_(true)
{
common.data = 0;
common.size = 0;
}
UBinary::UBinary(const UBinary& b, bool copy)
: type(BINARY_NONE)
, allocated_(copy)
{
common.data = 0;
if (copy)
*this = b;
else
{
// Be safe, do not try to guess which is bigger.
image = b.image;
sound = b.sound;
message = b.message;
type = b.type;
}
}
UBinary::UBinary(const UImage& i, bool copy)
: type(BINARY_IMAGE)
, image(i)
, allocated_(copy)
{
if (copy)
{
image.data = static_cast<unsigned char*> (malloc (image.size));
memcpy(image.data, i.data, image.size);
}
}
UBinary::UBinary(const USound& i, bool copy)
: type(BINARY_SOUND)
, sound(i)
, allocated_(copy)
{
if (copy)
{
sound.data = static_cast<char*> (malloc (sound.size));
memcpy(sound.data, i.data, sound.size);
}
}
void
UBinary::clear()
{
if (allocated_)
free(common.data);
}
UBinary::~UBinary()
{
clear();
}
UBinary& UBinary::operator= (const UBinary& b)
{
if (this == &b)
return *this;
clear();
type = b.type;
message = b.message;
common.size = b.common.size;
switch(type)
{
case BINARY_IMAGE:
image = b.image;
break;
case BINARY_SOUND:
sound = b.sound;
break;
case BINARY_NONE:
case BINARY_UNKNOWN:
break;
}
common.data = malloc(common.size);
memcpy(common.data, b.common.data, b.common.size);
return *this;
}
int
UBinary::parse(const char* message, int pos,
const binaries_type& bins,
binaries_type::const_iterator& binpos, bool copy)
{
std::istringstream is(message + pos);
bool ok = parse(is, bins, binpos, copy);
// tellg() might be -1 if we encountered an error.
int endpos = is.tellg();
if (endpos == -1)
endpos = strlen(message) - pos;
return (ok ? 1:-1) * (pos + endpos);
}
namespace
{
/// Return everything up to the next "\n" or "\n\r" or ";", not included.
/// Leave \a i after that delimiter.
/// Return empty string on errors.
static
std::string
headers_get(std::istringstream& i)
{
std::string res;
int c = 0;
while (!i.eof()
&& (c = i.get()) && c != '\n' && c != ';')
res.append(1, c);
if (i.eof())
GD_ERROR("unexpected end of file while parsing UBinary headers");
else
{
// Skip the delimiter.
if (c == '\n')
{
i.ignore();
if (c == '\r')
i.ignore();
}
else
i.ignore();
}
return res;
}
}
bool
UBinary::parse(std::istringstream& is,
const binaries_type& bins,
binaries_type::const_iterator& binpos, bool copy)
{
// LIBPORT_ECHO("Parsing: {" << is.str() << "}");
if (binpos == bins.end())
{
GD_ERROR("no binary data available");
return false;
}
// Validate size.
size_t psize;
is >> psize;
if (is.fail())
{
GD_FERROR("cannot read bin size: %s (%s)", is.str(), psize);
return false;
}
if (psize != binpos->size)
{
GD_FERROR("bin size inconsistency: %s != %s", psize, binpos->size);
return false;
}
common.size = psize;
if (copy)
{
common.data = malloc(common.size);
memcpy(common.data, binpos->data, common.size);
}
else
{
common.data = binpos->data;
this->allocated_ = false;
}
++binpos;
// Skip spaces.
while (is.peek() == ' ')
is.ignore();
// Get the headers.
message = headers_get(is);
// Analyse the header to decode know UBinary types.
// Header stream.
std::istringstream hs(message);
// Parse the optional type. Don't check hs.fail, since the type
// is optional, in which case t remains empty.
std::string t;
hs >> t;
UImageFormat image_format = parse_image_format(t);
if (image_format != IMAGE_UNKNOWN || t.find("image_")==0)
{
type = BINARY_IMAGE;
image.size = common.size;
// In some cases (jpeg source), image size is not present in headers.
image.width = image.height = 0;
hs >> image.width >> image.height;
image.imageFormat = image_format;
}
else if (t == "raw" || t == "wav")
{
type = BINARY_SOUND;
sound.soundFormat = (t == "raw" ? SOUND_RAW
: t == "wav" ? SOUND_WAV
: SOUND_UNKNOWN);
sound.size = common.size;
hs >> sound.channels
>> sound.rate
>> sound.sampleSize >> sound.sampleFormat;
}
else
{
// GD_FWARN("unknown binary type: %s", t);
type = BINARY_UNKNOWN;
}
return true;
}
void UBinary::buildMessage()
{
message = getMessage();
}
std::string UBinary::getMessage() const
{
switch (type)
{
case BINARY_IMAGE:
return image.headers_();
case BINARY_SOUND:
return sound.headers_();
case BINARY_UNKNOWN:
{
bool warned = false;
std::string res = message;
foreach (char& c, res)
if (c == '\0' || c == '\n' || c == ';')
{
if (!warned++)
GD_FERROR("invalid UBinary header: "
"prohibited `\\n', `\\0' and `;' will be "
"smashed to space: %s",
libport::escape(message));
c = ' ';
}
return res;
}
case BINARY_NONE:
return "";
}
unreachable();
}
std::ostream&
UBinary::print(std::ostream& o) const
{
// Format for the Kernel, which wants ';' as header terminator.
o << "BIN "<< common.size << ' ' << getMessage() << ';';
o.write((char*) common.data, common.size);
return o;
}
std::ostream&
operator<< (std::ostream& o, const UBinary& t)
{
return t.print(o);
}
} // namespace urbi
<commit_msg>UBinary: fix.<commit_after>/*
* Copyright (C) 2009-2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file libuvalue/ubinary.cc
#include <iostream>
#include <sstream>
#include <libport/debug.hh>
#include <libport/escape.hh>
#include <urbi/ubinary.hh>
#include <boost/algorithm/string/replace.hpp>
GD_CATEGORY(UValue);
namespace urbi
{
UBinary::UBinary()
: type(BINARY_NONE)
, allocated_(true)
{
common.data = 0;
common.size = 0;
}
UBinary::UBinary(const UBinary& b, bool copy)
: type(BINARY_NONE)
, allocated_(copy)
{
common.data = 0;
if (copy)
*this = b;
else
{
// Be safe, do not try to guess which is bigger.
image = b.image;
sound = b.sound;
message = b.message;
type = b.type;
}
}
UBinary::UBinary(const UImage& i, bool copy)
: type(BINARY_IMAGE)
, image(i)
, allocated_(copy)
{
if (copy)
{
image.data = static_cast<unsigned char*> (malloc (image.size));
memcpy(image.data, i.data, image.size);
}
}
UBinary::UBinary(const USound& i, bool copy)
: type(BINARY_SOUND)
, sound(i)
, allocated_(copy)
{
if (copy)
{
sound.data = static_cast<char*> (malloc (sound.size));
memcpy(sound.data, i.data, sound.size);
}
}
void
UBinary::clear()
{
if (allocated_)
free(common.data);
}
UBinary::~UBinary()
{
clear();
}
UBinary& UBinary::operator= (const UBinary& b)
{
if (this == &b)
return *this;
clear();
type = b.type;
message = b.message;
common.size = b.common.size;
switch(type)
{
case BINARY_IMAGE:
image = b.image;
break;
case BINARY_SOUND:
sound = b.sound;
break;
case BINARY_NONE:
case BINARY_UNKNOWN:
break;
}
common.data = malloc(common.size);
memcpy(common.data, b.common.data, b.common.size);
return *this;
}
int
UBinary::parse(const char* message, int pos,
const binaries_type& bins,
binaries_type::const_iterator& binpos, bool copy)
{
std::istringstream is(message + pos);
bool ok = parse(is, bins, binpos, copy);
// tellg() might be -1 if we encountered an error.
int endpos = is.tellg();
if (endpos == -1)
endpos = strlen(message) - pos;
return (ok ? 1:-1) * (pos + endpos);
}
namespace
{
/// Return everything up to the next "\n" or "\n\r" or ";", not included.
/// Leave \a i after that delimiter.
/// Return empty string on errors.
static
std::string
headers_get(std::istringstream& i)
{
std::string res;
int c = 0;
while (!i.eof()
&& (c = i.get()) && c != '\n' && c != ';')
res.append(1, c);
if (i.eof())
GD_ERROR("unexpected end of file while parsing UBinary headers");
else
{
// Skip the delimiter.
if (c == '\n')
{
i.ignore();
if (i.peek() == '\r')
i.ignore();
}
else
i.ignore();
}
return res;
}
}
bool
UBinary::parse(std::istringstream& is,
const binaries_type& bins,
binaries_type::const_iterator& binpos, bool copy)
{
// LIBPORT_ECHO("Parsing: {" << is.str() << "}");
if (binpos == bins.end())
{
GD_ERROR("no binary data available");
return false;
}
// Validate size.
size_t psize;
is >> psize;
if (is.fail())
{
GD_FERROR("cannot read bin size: %s (%s)", is.str(), psize);
return false;
}
if (psize != binpos->size)
{
GD_FERROR("bin size inconsistency: %s != %s", psize, binpos->size);
return false;
}
common.size = psize;
if (copy)
{
common.data = malloc(common.size);
memcpy(common.data, binpos->data, common.size);
}
else
{
common.data = binpos->data;
this->allocated_ = false;
}
++binpos;
// Skip spaces.
while (is.peek() == ' ')
is.ignore();
// Get the headers.
message = headers_get(is);
// Analyse the header to decode know UBinary types.
// Header stream.
std::istringstream hs(message);
// Parse the optional type. Don't check hs.fail, since the type
// is optional, in which case t remains empty.
std::string t;
hs >> t;
UImageFormat image_format = parse_image_format(t);
if (image_format != IMAGE_UNKNOWN || t.find("image_")==0)
{
type = BINARY_IMAGE;
image.size = common.size;
// In some cases (jpeg source), image size is not present in headers.
image.width = image.height = 0;
hs >> image.width >> image.height;
image.imageFormat = image_format;
}
else if (t == "raw" || t == "wav")
{
type = BINARY_SOUND;
sound.soundFormat = (t == "raw" ? SOUND_RAW
: t == "wav" ? SOUND_WAV
: SOUND_UNKNOWN);
sound.size = common.size;
hs >> sound.channels
>> sound.rate
>> sound.sampleSize >> sound.sampleFormat;
}
else
{
// GD_FWARN("unknown binary type: %s", t);
type = BINARY_UNKNOWN;
}
return true;
}
void UBinary::buildMessage()
{
message = getMessage();
}
std::string UBinary::getMessage() const
{
switch (type)
{
case BINARY_IMAGE:
return image.headers_();
case BINARY_SOUND:
return sound.headers_();
case BINARY_UNKNOWN:
{
bool warned = false;
std::string res = message;
foreach (char& c, res)
if (c == '\0' || c == '\n' || c == ';')
{
if (!warned++)
GD_FERROR("invalid UBinary header: "
"prohibited `\\n', `\\0' and `;' will be "
"smashed to space: %s",
libport::escape(message));
c = ' ';
}
return res;
}
case BINARY_NONE:
return "";
}
unreachable();
}
std::ostream&
UBinary::print(std::ostream& o) const
{
// Format for the Kernel, which wants ';' as header terminator.
o << "BIN "<< common.size << ' ' << getMessage() << ';';
o.write((char*) common.data, common.size);
return o;
}
std::ostream&
operator<< (std::ostream& o, const UBinary& t)
{
return t.print(o);
}
} // namespace urbi
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2015, Wator Vapor
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 wator nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "wator.hpp"
using namespace Wator;
#include <bitset>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
using namespace boost::property_tree;
/**
* Constructor
**/
V1CortexLayer::V1CortexLayer()
{
memory_.push_back({});
}
V1CortexLayer::~V1CortexLayer()
{
INFO_VAR(this);
}
/**
* update
* @return None.
**/
void V1CortexLayer::update(void)
{
INFO_VAR("finnish V1CortexLayer::update");
}
/**
* round
* @return None.
**/
void V1CortexLayer::round(void)
{
this->forward();
this->update();
INFO_VAR("finnish V1CortexLayer::round");
LayerBase::round();
this->dump();
}
/**
* forward
* @return None.
**/
void V1CortexLayer::forward(void)
{
pinchs_.clear();
blobs_.clear();
for(auto btm:bottom_){
CoulombLayer *coulom = dynamic_cast<CoulombLayer*>(btm);
auto coulomBlob = coulom->getBlob(this);
INFO_VAR(coulomBlob->w_);
INFO_VAR(coulomBlob->h_);
INFO_VAR(coulomBlob->ch_);
// const int size = (coulomBlob->w_/this->w_ )* (coulomBlob->h_ /this->h_)* coulomBlob->ch_;
for (auto top:top_) {
auto pinch = new Blob<bool>(coulomBlob->w_,coulomBlob->h_,coulomBlob->ch_);
for (int ch = 0; ch < coulomBlob->ch_; ch++) {
for (int y = 0; y < coulomBlob->h_; y++) {
for (int x = 0; x < coulomBlob->w_; x++) {
int grid = (y/this->h_) * (coulomBlob->w_/this->w_) + (x/this->w_) ;
int index = ch * coulomBlob->w_ * coulomBlob->h_;
index += grid * this->w_ * this->h_;
index += (y%this->h_)*this->w_ + x%this->w_ ;
TRACE_VAR(index);
TRACE_VAR(x);
TRACE_VAR(y);
int index2 = ch * coulomBlob->w_ * coulomBlob->h_;
index2 += y*coulomBlob->w_ + x;
TRACE_VAR(index2);
if (index >= coulomBlob->size_|| index2 >= coulomBlob->size_) {
/// 无法整除的最后几行,不能的到下一层的完整输出,省略。
TRACE_VAR(this->w_);
TRACE_VAR(this->h_);
TRACE_VAR(grid);
TRACE_VAR(x);
TRACE_VAR(y);
TRACE_VAR(index);
TRACE_VAR(index2);
TRACE_VAR(coulomBlob->w_);
TRACE_VAR(coulomBlob->h_);
TRACE_VAR(coulomBlob->size_);
continue;
}
pinch->data_[index] = coulomBlob->data_[index2];
}
}
}
pinchs_.push_back(pinch);
}
}
INFO_VAR(pinchs_.size());
for(int index = 0; index < pinchs_.size();index++) {
auto &memory = memory_[index];
auto pinch = pinchs_[index];
TRACE_VAR(pinch->size_);
for (int i = 0;i < pinch->size_;i += this->w_*this->h_) {
uint64_t memIndex = 0;
for (int j = 0; j < this->w_*this->h_; j++) {
if (pinch->data_[i + j]) {
memIndex++;
}
memIndex = memIndex <<1;
}
std::bitset<64> memBit(memIndex);
// sparse +- 1/3
//if (memBit.count() < this->sparse_*2/3 || memBit.count() > this->sparse_*6/3) {
if (memBit.count() != this->sparse_) {
continue;
}
TRACE_VAR(memBit);
TRACE_VAR(memIndex);
auto it = memory.find(memIndex);
if (it != memory.end()) {
it->second++;
} else {
memory[memIndex] = 1;
}
}
memory_[index] = memory;
}
INFO_VAR(memory_.size());
for(auto memory :memory_) {
map<uint64_t,vector<uint64_t>> sortByCount;
for (auto it:memory) {
auto memCount = it.second;
auto itSort = sortByCount.find(memCount);
if (sortByCount.end() != itSort) {
itSort->second.push_back(it.first);
} else {
sortByCount[memCount] = {it.first};
}
}
for (auto it:sortByCount) {
auto memCount = it.first;
INFO_VAR(memCount);
for (auto mem:it.second) {
if(9 ==this->w_*this->h_) {
std::bitset<9> memBit(mem);
INFO_VAR(memBit);
}
if(25 ==this->w_*this->h_) {
std::bitset<25> memBit(mem);
INFO_VAR(memBit);
}
}
}
INFO_VAR(memory.size());
INFO_VAR(sortByCount.size());
#if 0
{
uint64_t line = 0b010010010;
std::bitset<9> LineB(line);
INFO_VAR(LineB);
auto it = memory.find(line);
if (memory.end() != it) {
INFO_VAR(it->second);
} else {
INFO_VAR(0);
}
}
{
uint64_t line = 0b000111000;
std::bitset<9> LineB(line);
INFO_VAR(LineB);
auto it = memory.find(line);
if (memory.end() != it) {
INFO_VAR(it->second);
} else {
INFO_VAR(0);
}
}
{
uint64_t line = 0b100010001;
std::bitset<9> LineB(line);
INFO_VAR(LineB);
auto it = memory.find(line);
if (memory.end() != it) {
INFO_VAR(it->second);
} else {
INFO_VAR(0);
}
}
{
uint64_t line = 0b001010100;
std::bitset<9> LineB(line);
INFO_VAR(LineB);
auto it = memory.find(line);
if (memory.end() != it) {
INFO_VAR(it->second);
} else {
INFO_VAR(0);
}
}
#endif
}
INFO_VAR(blobs_.size());
INFO_VAR("finnish V1CortexLayer::forward");
}
/**
* dump to png
* @return None.
**/
void V1CortexLayer::dump(void){
INFO_VAR(blobs_.size());
for (auto blob:blobs_) {
blob->dump();
}
}
<commit_msg>fix coredump<commit_after>/*
Copyright (c) 2015, Wator Vapor
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 wator nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "wator.hpp"
using namespace Wator;
#include <bitset>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
using namespace boost::property_tree;
/**
* Constructor
**/
V1CortexLayer::V1CortexLayer()
{
memory_.push_back({});
}
V1CortexLayer::~V1CortexLayer()
{
INFO_VAR(this);
}
/**
* update
* @return None.
**/
void V1CortexLayer::update(void)
{
INFO_VAR("finnish V1CortexLayer::update");
}
/**
* round
* @return None.
**/
void V1CortexLayer::round(void)
{
this->forward();
this->update();
INFO_VAR("finnish V1CortexLayer::round");
LayerBase::round();
this->dump();
}
/**
* forward
* @return None.
**/
void V1CortexLayer::forward(void)
{
pinchs_.clear();
blobs_.clear();
for(auto btm:bottom_){
CoulombLayer *coulom = dynamic_cast<CoulombLayer*>(btm);
auto coulomBlob = coulom->getBlob(this);
INFO_VAR(coulomBlob->w_);
INFO_VAR(coulomBlob->h_);
INFO_VAR(coulomBlob->ch_);
// const int size = (coulomBlob->w_/this->w_ )* (coulomBlob->h_ /this->h_)* coulomBlob->ch_;
for (auto top:top_) {
auto pinch = new Blob<bool>(coulomBlob->w_,coulomBlob->h_,coulomBlob->ch_);
for (int ch = 0; ch < coulomBlob->ch_; ch++) {
for (int y = 0; y < coulomBlob->h_; y++) {
for (int x = 0; x < coulomBlob->w_; x++) {
int grid = (y/this->h_) * (coulomBlob->w_/this->w_) + (x/this->w_) ;
int index = ch * coulomBlob->w_ * coulomBlob->h_;
index += grid * this->w_ * this->h_;
index += (y%this->h_)*this->w_ + x%this->w_ ;
TRACE_VAR(index);
TRACE_VAR(x);
TRACE_VAR(y);
int index2 = ch * coulomBlob->w_ * coulomBlob->h_;
index2 += y*coulomBlob->w_ + x;
TRACE_VAR(index2);
if (index >= coulomBlob->size_|| index2 >= coulomBlob->size_) {
// 无法整除的最后几行,不能的到下一层的完整输出,省略。
TRACE_VAR(this->w_);
TRACE_VAR(this->h_);
TRACE_VAR(grid);
TRACE_VAR(x);
TRACE_VAR(y);
TRACE_VAR(index);
TRACE_VAR(index2);
TRACE_VAR(coulomBlob->w_);
TRACE_VAR(coulomBlob->h_);
TRACE_VAR(coulomBlob->size_);
continue;
}
pinch->data_[index] = coulomBlob->data_[index2];
}
}
}
pinchs_.push_back(pinch);
}
}
INFO_VAR(pinchs_.size());
for(int index = 0; index < pinchs_.size();index++) {
auto &memory = memory_[index];
auto pinch = pinchs_[index];
TRACE_VAR(pinch->size_);
for (int i = 0;i < pinch->size_;i += this->w_*this->h_) {
uint64_t memIndex = 0;
for (int j = 0; j < this->w_*this->h_; j++) {
auto index = i + j;
// 无法整除的最后几点,不能的到下一层的完整输出,省略。
if (index >= pinch->size_) {
continue;
}
if (pinch->data_[index]) {
memIndex++;
}
memIndex = memIndex <<1;
}
std::bitset<64> memBit(memIndex);
// sparse +- 1/3
//if (memBit.count() < this->sparse_*2/3 || memBit.count() > this->sparse_*6/3) {
if (memBit.count() != this->sparse_) {
continue;
}
TRACE_VAR(memBit);
TRACE_VAR(memIndex);
auto it = memory.find(memIndex);
if (it != memory.end()) {
it->second++;
} else {
memory[memIndex] = 1;
}
}
memory_[index] = memory;
}
INFO_VAR(memory_.size());
for(auto memory :memory_) {
map<uint64_t,vector<uint64_t>> sortByCount;
for (auto it:memory) {
auto memCount = it.second;
auto itSort = sortByCount.find(memCount);
if (sortByCount.end() != itSort) {
itSort->second.push_back(it.first);
} else {
sortByCount[memCount] = {it.first};
}
}
for (auto it:sortByCount) {
auto memCount = it.first;
INFO_VAR(memCount);
for (auto mem:it.second) {
if(9 ==this->w_*this->h_) {
std::bitset<9> memBit(mem);
INFO_VAR(memBit);
}
if(25 ==this->w_*this->h_) {
std::bitset<25> memBit(mem);
INFO_VAR(memBit);
}
}
}
INFO_VAR(memory.size());
INFO_VAR(sortByCount.size());
#if 0
{
uint64_t line = 0b010010010;
std::bitset<9> LineB(line);
INFO_VAR(LineB);
auto it = memory.find(line);
if (memory.end() != it) {
INFO_VAR(it->second);
} else {
INFO_VAR(0);
}
}
{
uint64_t line = 0b000111000;
std::bitset<9> LineB(line);
INFO_VAR(LineB);
auto it = memory.find(line);
if (memory.end() != it) {
INFO_VAR(it->second);
} else {
INFO_VAR(0);
}
}
{
uint64_t line = 0b100010001;
std::bitset<9> LineB(line);
INFO_VAR(LineB);
auto it = memory.find(line);
if (memory.end() != it) {
INFO_VAR(it->second);
} else {
INFO_VAR(0);
}
}
{
uint64_t line = 0b001010100;
std::bitset<9> LineB(line);
INFO_VAR(LineB);
auto it = memory.find(line);
if (memory.end() != it) {
INFO_VAR(it->second);
} else {
INFO_VAR(0);
}
}
#endif
}
INFO_VAR(blobs_.size());
INFO_VAR("finnish V1CortexLayer::forward");
}
/**
* dump to png
* @return None.
**/
void V1CortexLayer::dump(void){
INFO_VAR(blobs_.size());
for (auto blob:blobs_) {
blob->dump();
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2013, 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.
*/
#include "libtorrent/resolver.hpp"
#include <boost/bind.hpp>
#include "libtorrent/debug.hpp"
namespace libtorrent
{
// TODO: 3 the first places to use this resolver is the
// http_connection/http_tracker_connection and udp_tracker_connection.
// make sure to prefer cache on shutdown
resolver::resolver(io_service& ios)
: m_ios(ios)
, m_resolver(ios)
, m_max_size(700)
, m_timeout(seconds(1200))
{}
void resolver::on_lookup(error_code const& ec, tcp::resolver::iterator i
, resolver_interface::callback_t h, std::string hostname)
{
#if defined TORRENT_ASIO_DEBUGGING
complete_async("resolver::on_lookup");
#endif
if (ec)
{
std::vector<address> empty;
h(ec, empty);
return;
}
dns_cache_entry& ce = m_cache[hostname];
ptime now = time_now();
ce.last_seen = now;
ce.addresses.clear();
while (i != tcp::resolver::iterator())
{
ce.addresses.push_back(i->endpoint().address());
++i;
}
h(ec, ce.addresses);
// if m_cache grows too big, weed out the
// oldest entries
if (m_cache.size() > m_max_size)
{
cache_t::iterator oldest = m_cache.begin();
for (cache_t::iterator i = m_cache.begin();
i != m_cache.end(); ++i)
{
cache_t::iterator e = i;
++i;
if (e->second.last_seen < oldest->second.last_seen)
oldest = e;
}
// remove the oldest entry
m_cache.erase(oldest);
}
}
void resolver::async_resolve(std::string const& host, int flags
, resolver_interface::callback_t const& h)
{
cache_t::iterator i = m_cache.find(host);
if (i != m_cache.end())
{
// keep cache entries valid for m_timeout seconds
if ((flags & resolver_interface::prefer_cache)
|| i->second.last_seen + m_timeout >= time_now())
{
error_code ec;
m_ios.post(boost::bind(h, ec, i->second.addresses));
return;
}
}
// the port is ignored
tcp::resolver::query q(host, "80");
#if defined TORRENT_ASIO_DEBUGGING
add_outstanding_async("resolver::on_lookup");
#endif
m_resolver.async_resolve(q, boost::bind(&resolver::on_lookup, this, _1, _2
, h, host));
}
}
<commit_msg>fix bug in hostname resolver<commit_after>/*
Copyright (c) 2013, 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.
*/
#include "libtorrent/resolver.hpp"
#include <boost/bind.hpp>
#include "libtorrent/debug.hpp"
namespace libtorrent
{
// TODO: 3 the first places to use this resolver is the
// http_connection/http_tracker_connection and udp_tracker_connection.
// make sure to prefer cache on shutdown
resolver::resolver(io_service& ios)
: m_ios(ios)
, m_resolver(ios)
, m_max_size(700)
, m_timeout(seconds(1200))
{}
void resolver::on_lookup(error_code const& ec, tcp::resolver::iterator i
, resolver_interface::callback_t h, std::string hostname)
{
#if defined TORRENT_ASIO_DEBUGGING
complete_async("resolver::on_lookup");
#endif
if (ec)
{
std::vector<address> empty;
h(ec, empty);
return;
}
dns_cache_entry& ce = m_cache[hostname];
ptime now = time_now();
ce.last_seen = now;
ce.addresses.clear();
while (i != tcp::resolver::iterator())
{
ce.addresses.push_back(i->endpoint().address());
++i;
}
h(ec, ce.addresses);
// if m_cache grows too big, weed out the
// oldest entries
if (m_cache.size() > m_max_size)
{
cache_t::iterator oldest = m_cache.begin();
for (cache_t::iterator i = m_cache.begin();
i != m_cache.end(); ++i)
{
if (i->second.last_seen < oldest->second.last_seen)
oldest = i;
}
// remove the oldest entry
m_cache.erase(oldest);
}
}
void resolver::async_resolve(std::string const& host, int flags
, resolver_interface::callback_t const& h)
{
cache_t::iterator i = m_cache.find(host);
if (i != m_cache.end())
{
// keep cache entries valid for m_timeout seconds
if ((flags & resolver_interface::prefer_cache)
|| i->second.last_seen + m_timeout >= time_now())
{
error_code ec;
m_ios.post(boost::bind(h, ec, i->second.addresses));
return;
}
}
// the port is ignored
tcp::resolver::query q(host, "80");
#if defined TORRENT_ASIO_DEBUGGING
add_outstanding_async("resolver::on_lookup");
#endif
m_resolver.async_resolve(q, boost::bind(&resolver::on_lookup, this, _1, _2
, h, host));
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2015 Georgia Institute of Technology
*
* 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.
*/
/**
* @file file_loader.hpp
* @ingroup io
* @author Tony Pan <tpan7@gatech.edu>
* @brief contains a generic FileLoader class to perform distributed and concurrent file access.
*
*/
#ifndef FILE_LOADER_HPP_
#define FILE_LOADER_HPP_
#include "bliss-config.hpp"
#if defined(USE_MPI)
#include "mpi.h"
#endif
#if defined(USE_OPENMP)
#include "omp.h"
#endif
#include <string>
#include <cstring> // memcpy, strerror
#include <exception> // ioexception
#include <sstream> // stringstream
#include <memory>
#include <unistd.h> // sysconf
#include <sys/stat.h> // block size.
#include <sys/mman.h> // mmap
#include <fcntl.h> // for open
#include <sys/sysinfo.h> // for meminfo
#include <type_traits>
#include "partition/range.hpp"
#include "partition/partitioner.hpp"
//#include "io/data_block.hpp"
#include "io/io_exception.hpp"
#include "utils/logging.h"
#include "common/sequence.hpp"
#include <mxx/comm.hpp> // for mxx::comm
namespace bliss
{
namespace io
{
struct BaseFile {
};
// TODO: simplify possibly by separating L1 and L2 partitioning.
/**
* @brief Partitions input data into sequences, e.g. blocks or reads.
* @details Iterator template parameter refers to the iterator type that is currently being traversed.
* this applies to the sequence object, and the following methods:
* get_next_record, and find_first_record.
*
* init method can potentially use a different iterator type. this is useful when
* state information is extracted from perhaps a containing block (e.g. L1Block),
* then used with a sub block (e.g. L2Block).
*
* @note there are 2 (non-interchangeable) scenarios when we may need to change the iterator type.
* 1. L1 at process level, L2 at thread level. SeqParser state is calculated at L1.
* 2. L1 at rank 0 of a sub communicator (processes), L2 is broadcast from rank0 of the rest of processes. SeqParser state is calculated at L1.
*
* to handle the first case: approaches are
* 1a. to allow a parser to operate on different iterator types when invoking find_first_record, increment.
* additional template parameter for these functions. SequenceType will need to change.
* API in SequenceIterator, BaseFileParser, FASTQParser, FASTAParser all need to change
* 1b. convert the seq parser from L1 to L2, but copy the state of L1.
* can be shared between threads. additional api for convert only
*
* to handle the second case.
* 2a. convert the seq parser from L1 to L2, communicate (and copy) the state of L1.
* additional api for convert and broadcast. minimal api change. requires L1 to be block (or cyclic with synchronization).
* 2b. create seq parser for L2, and initialize using all processes.
* no api change, but works only when L1 and L2 are block partitioned (or cyclic with synchronization).
* potentially less communication, and Parser does not need to have a broadcast semantic.
*
* 1a is not general, potentially complicated, and a source of potential errors.
* 1b and 2a share common apis.
* 2b requires application to specifically call init at L2. Also, already initialized L1 during data load.
*
* choose 2b and 1b. Sequence Iterator does not call init_for_iterator, mostly for flexibility and compatibility with case 1.
*
* @tparam Iterator The underlying iterator to be traversed to generate a Sequence
*
*/
template <typename Iterator>
class BaseFileParser {
// let another BaseFileParser with some other iterator type be a friend so we can convert.
template <typename Iterator2>
friend class BaseFileParser;
public:
// using SequenceIdType = SeqIdType;
using SequenceType = typename ::bliss::common::Sequence<Iterator, ::bliss::common::SequenceId>;
using SequenceIdType = typename SequenceType::IdType;
/// static constant for end of line. Iterator note this is same for unicode as well
static constexpr unsigned char eol = '\n';
/// static constant for carriage return. note this is same for unicode as well
static constexpr unsigned char cr = '\r';
protected:
/**
* @typedef RangeType
* @brief range object types
*/
using RangeType = bliss::partition::range<size_t>;
/**
* @brief search for first non-EOL character in a iterator, returns the stopping position as an iterator. also records offset.
* @details iter can point to the previous EOL, or a nonEOL character.
* @param[in/out] iter iterator to advance
* @param[in] end position to stop the traversal
* @param[in/out] offset the global offset of the sequence record within the file. used as record id.
* @return iterator at the new position, where the Non EOL char is found, or end.
*/
template <typename IT = Iterator,
typename = typename ::std::enable_if<(::std::is_same<typename ::std::iterator_traits<IT>::value_type, char>::value ||
::std::is_same<typename ::std::iterator_traits<IT>::value_type, unsigned char>::value)
>::type >
inline IT findNonEOL(IT& iter, const IT& end, size_t &offset) const {
while ((iter != end) && ((*iter == eol) || (*iter == cr))) {
++iter;
++offset;
}
return iter;
}
/**
* @brief search for first EOL character in a iterator, returns the stopping position as an iterator. also records offset.
* @details iter can point to a nonEOL char, or an EOL char.
* @param[in/out] iter iterator to advance
* @param[in] end position to stop the traversal
* @param[in/out] offset the global offset of the sequence record within the file. used as record id.
* @return iterator at the new position, where the EOL char is found, or end.
*/
template <typename IT = Iterator,
typename = typename ::std::enable_if<(::std::is_same<typename ::std::iterator_traits<IT>::value_type, char>::value ||
::std::is_same<typename ::std::iterator_traits<IT>::value_type, unsigned char>::value)
>::type >
inline IT findEOL(IT& iter, const IT& end, size_t &offset) const {
while ((iter != end) && ((*iter != eol) && (*iter != cr) ) ) {
++iter;
++offset;
}
return iter;
}
/**
* @brief constructs an IOException object with the relevant debug data.
* @param errType string indicating the source of the error. user choice
* @param start iterator pointing to beginning of the data in question
* @param end iterator pointing to end of the data in question
* @param startOffset offset for the beginning of the data in question
* @param endOffset offset for the end of the data in question
*/
void handleError(const std::string& errType, const Iterator &start, const Iterator &end, const size_t& startOffset, const size_t& endOffset) throw (bliss::io::IOException) {
std::stringstream ss;
//#ifdef USE_MPI
// int rank = 0;
// MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// ss << "rank: " << rank << " ";
//#endif
ss << "ERROR: " << errType << " in " << startOffset << " to " << endOffset << std::endl;
ss << " offending string is \"";
std::ostream_iterator<typename std::iterator_traits<Iterator>::value_type> oit(ss);
std::copy(start, end, oit);
ss << "\".";
throw ::std::logic_error(ss.str());
}
/**
* @brief print out an Warning, for example when there is malformed partial data.
* @param errType string indicating the source of the error. user choice
* @param start iterator pointing to beginning of the data in question
* @param end iterator pointing to end of the data in question
* @param startOffset offset for the beginning of the data in question
* @param endOffset offset for the end of the data in question
*/
void handleWarning(const std::string& errType, const Iterator &start, const Iterator &end, const size_t& startOffset, const size_t& endOffset) {
BL_WARNING("WARNING: " << errType << " in " << startOffset << " to " << endOffset);
}
public:
/// default constructor.
BaseFileParser() {};
/// default destructor
virtual ~BaseFileParser() {};
/// converting constructor.
template <typename Iterator2>
BaseFileParser(BaseFileParser<Iterator2> const & other) {}
/// converting assignment operator that can transform the base iterator type.
template <typename Iterator2>
BaseFileParser<Iterator>& operator=(BaseFileParser<Iterator2> const & other) {
return *this;
}
/**
* @brief given a block/range, find the starting point of the first sequence object (here, just the actual start)
* @note virtual function, for convenience.
* used by getNextL1BlockRange to find exact range for an L1 Partition.
*
* Also can be used to do other initializations.
*
* @param _data
* @param parentRange
* @param inMemRange
* @param searchRange
* @return
*/
virtual std::size_t find_first_record(const Iterator &_data, const RangeType &parentRange, const RangeType &inMemRange, const RangeType &searchRange)
{
//== range checking
if(!parentRange.contains(inMemRange)) {
::std::cout << "parent: " << parentRange << " , in mem: " << inMemRange << ::std::endl;
throw std::invalid_argument("ERROR: Parent Range does not contain inMemRange");
}
// no op, other than to use intersect to make sure that the start is valid and within parent, and in memry ranges.
return RangeType::intersect(searchRange, inMemRange).start;
}
#ifdef USE_MPI
virtual std::size_t find_first_record(const Iterator &_data, const RangeType &parentRange, const RangeType &inMemRange, const RangeType &searchRange, const mxx::comm& comm) {
return find_first_record(_data, parentRange, inMemRange, searchRange);
}
#endif
virtual typename RangeType::ValueType find_overlap_end(const Iterator &_data,
const RangeType &parentRange, const RangeType &inMemRange, typename RangeType::ValueType end, size_t overlap ) {
return std::max(inMemRange.start, std::min(end + overlap, inMemRange.end));
}
/// reset any parser internal state so the parser can be reused on a different data range. overridden in subclass.
virtual void reset() {}
virtual bool should_parse(const RangeType & range) {
return range.size() > 0;
}
#ifdef USE_MPI
virtual bool should_parse(const RangeType & range, const mxx::comm & comm) {
return range.size() > 0;
}
#endif
/// initializes parser for a particular data range. overridden in subclass. returns start of first record. _data points to first element in mem.
virtual std::size_t init_parser(const Iterator &_data, const RangeType &parentRange, const RangeType &inMemRange, const RangeType &searchRange) {
return this->find_first_record(_data, parentRange, inMemRange, searchRange);
}
#ifdef USE_MPI
/// initializes the parser. only useful for FASTA parser for now. Assumes searchRange do NOT overlap between processes. _data points to first element in mem.
virtual std::size_t init_parser(const Iterator &_data, const RangeType &parentRange, const RangeType &inMemRange, const RangeType &searchRange, const mxx::comm& comm)
{
return this->find_first_record(_data, parentRange, inMemRange, searchRange);
};
#endif
/**
* @brief increment to get next sequence object
* @note not virtual because SequenceType is different for each subclass, so the signatures are different. We rely on compiler to enforce the correct one.
* this is in general not an issue as we do not need polymorphic Sequence Parsers - they are specific to file types.
* this is probably better for performance anyways.
*
* Used by FileLoader's getRecordSize to compute an average record size.
*
* @param iter start of a sequence object. this is the beginning of a record, not just DNA sequence
* @param end end of a sequence object. this is the end of a record, not just DNA sequence
* @param offset offset in the file for the start of the record.
* @param seq_offset index in the local (shared) vector of sequence breaks, if there is one (e.g. FASTA). used by FASTA to lookup the nearest complete sequence record info.
* @param output updated sequence object.
* @return next seq id offset.
*/
SequenceType get_next_record(Iterator & iter, const Iterator & end, size_t & offset)
{
Iterator orig_iter = iter;
size_t orig_offset = offset;
size_t dist = std::distance(iter, end);
offset += dist;
iter = end;
return SequenceType(SequenceIdType(orig_offset), dist, 0, 0, orig_iter, end);
}
/**
* @brief get the average record size in the supplied range
* @return return the records size and the internal data size
*/
virtual ::std::pair<size_t, size_t> get_record_size(const Iterator &_data, const RangeType &parentRange, const RangeType &inMemRange, const RangeType &validRange, size_t const count) {
size_t dist = validRange.size();
return ::std::pair<size_t, size_t>(dist,dist);
}
#ifdef USE_MPI
virtual ::std::pair<size_t, size_t> get_record_size(const Iterator &_data, const RangeType &parentRange, const RangeType &inMemRange, const RangeType &validRange, mxx::comm const & comm, size_t const count) {
size_t dist = validRange.size();
return ::std::pair<size_t, size_t>(dist,dist);
}
#endif
};
/// template class' static variable definition (declared and initialized in class)
template <typename Iterator>
constexpr unsigned char bliss::io::BaseFileParser<Iterator >::eol;
template <typename Iterator>
constexpr unsigned char bliss::io::BaseFileParser<Iterator>::cr;
} /* namespace functional */
} /* namespace bliss */
#endif /* FILE_LOADER_HPP_ */
<commit_msg>FIX: gcc 6 compiler error, part2.<commit_after>/*
* Copyright 2015 Georgia Institute of Technology
*
* 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.
*/
/**
* @file file_loader.hpp
* @ingroup io
* @author Tony Pan <tpan7@gatech.edu>
* @brief contains a generic FileLoader class to perform distributed and concurrent file access.
*
*/
#ifndef FILE_LOADER_HPP_
#define FILE_LOADER_HPP_
#include "bliss-config.hpp"
#if defined(USE_MPI)
#include "mpi.h"
#endif
#if defined(USE_OPENMP)
#include "omp.h"
#endif
#include <string>
#include <cstring> // memcpy, strerror
#include <exception> // ioexception
#include <sstream> // stringstream
#include <memory>
#include <unistd.h> // sysconf
#include <sys/stat.h> // block size.
#include <sys/mman.h> // mmap
#include <fcntl.h> // for open
#include <sys/sysinfo.h> // for meminfo
#include <type_traits>
#include "partition/range.hpp"
#include "partition/partitioner.hpp"
//#include "io/data_block.hpp"
#include "io/io_exception.hpp"
#include "utils/logging.h"
#include "common/sequence.hpp"
#include <mxx/comm.hpp> // for mxx::comm
namespace bliss
{
namespace io
{
struct BaseFile {
};
// TODO: simplify possibly by separating L1 and L2 partitioning.
/**
* @brief Partitions input data into sequences, e.g. blocks or reads.
* @details Iterator template parameter refers to the iterator type that is currently being traversed.
* this applies to the sequence object, and the following methods:
* get_next_record, and find_first_record.
*
* init method can potentially use a different iterator type. this is useful when
* state information is extracted from perhaps a containing block (e.g. L1Block),
* then used with a sub block (e.g. L2Block).
*
* @note there are 2 (non-interchangeable) scenarios when we may need to change the iterator type.
* 1. L1 at process level, L2 at thread level. SeqParser state is calculated at L1.
* 2. L1 at rank 0 of a sub communicator (processes), L2 is broadcast from rank0 of the rest of processes. SeqParser state is calculated at L1.
*
* to handle the first case: approaches are
* 1a. to allow a parser to operate on different iterator types when invoking find_first_record, increment.
* additional template parameter for these functions. SequenceType will need to change.
* API in SequenceIterator, BaseFileParser, FASTQParser, FASTAParser all need to change
* 1b. convert the seq parser from L1 to L2, but copy the state of L1.
* can be shared between threads. additional api for convert only
*
* to handle the second case.
* 2a. convert the seq parser from L1 to L2, communicate (and copy) the state of L1.
* additional api for convert and broadcast. minimal api change. requires L1 to be block (or cyclic with synchronization).
* 2b. create seq parser for L2, and initialize using all processes.
* no api change, but works only when L1 and L2 are block partitioned (or cyclic with synchronization).
* potentially less communication, and Parser does not need to have a broadcast semantic.
*
* 1a is not general, potentially complicated, and a source of potential errors.
* 1b and 2a share common apis.
* 2b requires application to specifically call init at L2. Also, already initialized L1 during data load.
*
* choose 2b and 1b. Sequence Iterator does not call init_for_iterator, mostly for flexibility and compatibility with case 1.
*
* @tparam Iterator The underlying iterator to be traversed to generate a Sequence
*
*/
template <typename Iterator>
class BaseFileParser {
// let another BaseFileParser with some other iterator type be a friend so we can convert.
template <typename Iterator2>
friend class BaseFileParser;
public:
// using SequenceIdType = SeqIdType;
using SequenceType = typename ::bliss::common::Sequence<Iterator, ::bliss::common::SequenceId>;
using SequenceIdType = typename SequenceType::IdType;
/// static constant for end of line. Iterator note this is same for unicode as well
static constexpr unsigned char eol = '\n';
/// static constant for carriage return. note this is same for unicode as well
static constexpr unsigned char cr = '\r';
protected:
/**
* @typedef RangeType
* @brief range object types
*/
using RangeType = bliss::partition::range<size_t>;
/**
* @brief search for first non-EOL character in a iterator, returns the stopping position as an iterator. also records offset.
* @details iter can point to the previous EOL, or a nonEOL character.
* @param[in/out] iter iterator to advance
* @param[in] end position to stop the traversal
* @param[in/out] offset the global offset of the sequence record within the file. used as record id.
* @return iterator at the new position, where the Non EOL char is found, or end.
*/
template <typename IT = Iterator,
typename = typename ::std::enable_if<(::std::is_same<typename ::std::iterator_traits<IT>::value_type, char>::value ||
::std::is_same<typename ::std::iterator_traits<IT>::value_type, unsigned char>::value)
>::type >
inline IT findNonEOL(IT& iter, const IT& end, size_t &offset) const {
while ((iter != end) && ((*iter == eol) || (*iter == cr))) {
++iter;
++offset;
}
return iter;
}
/**
* @brief search for first EOL character in a iterator, returns the stopping position as an iterator. also records offset.
* @details iter can point to a nonEOL char, or an EOL char.
* @param[in/out] iter iterator to advance
* @param[in] end position to stop the traversal
* @param[in/out] offset the global offset of the sequence record within the file. used as record id.
* @return iterator at the new position, where the EOL char is found, or end.
*/
template <typename IT = Iterator,
typename = typename ::std::enable_if<(::std::is_same<typename ::std::iterator_traits<IT>::value_type, char>::value ||
::std::is_same<typename ::std::iterator_traits<IT>::value_type, unsigned char>::value)
>::type >
inline IT findEOL(IT& iter, const IT& end, size_t &offset) const {
while ((iter != end) && ((*iter != eol) && (*iter != cr) ) ) {
++iter;
++offset;
}
return iter;
}
/**
* @brief constructs an IOException object with the relevant debug data.
* @param errType string indicating the source of the error. user choice
* @param start iterator pointing to beginning of the data in question
* @param end iterator pointing to end of the data in question
* @param startOffset offset for the beginning of the data in question
* @param endOffset offset for the end of the data in question
*/
void handleError(const std::string& errType, const Iterator &start, const Iterator &end, const size_t& startOffset, const size_t& endOffset) {
std::stringstream ss;
//#ifdef USE_MPI
// int rank = 0;
// MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// ss << "rank: " << rank << " ";
//#endif
ss << "ERROR: " << errType << " in " << startOffset << " to " << endOffset << std::endl;
ss << " offending string is \"";
std::ostream_iterator<typename std::iterator_traits<Iterator>::value_type> oit(ss);
std::copy(start, end, oit);
ss << "\".";
throw ::std::logic_error(ss.str());
}
/**
* @brief print out an Warning, for example when there is malformed partial data.
* @param errType string indicating the source of the error. user choice
* @param start iterator pointing to beginning of the data in question
* @param end iterator pointing to end of the data in question
* @param startOffset offset for the beginning of the data in question
* @param endOffset offset for the end of the data in question
*/
void handleWarning(const std::string& errType, const Iterator &start, const Iterator &end, const size_t& startOffset, const size_t& endOffset) {
BL_WARNING("WARNING: " << errType << " in " << startOffset << " to " << endOffset);
}
public:
/// default constructor.
BaseFileParser() {};
/// default destructor
virtual ~BaseFileParser() {};
/// converting constructor.
template <typename Iterator2>
BaseFileParser(BaseFileParser<Iterator2> const & other) {}
/// converting assignment operator that can transform the base iterator type.
template <typename Iterator2>
BaseFileParser<Iterator>& operator=(BaseFileParser<Iterator2> const & other) {
return *this;
}
/**
* @brief given a block/range, find the starting point of the first sequence object (here, just the actual start)
* @note virtual function, for convenience.
* used by getNextL1BlockRange to find exact range for an L1 Partition.
*
* Also can be used to do other initializations.
*
* @param _data
* @param parentRange
* @param inMemRange
* @param searchRange
* @return
*/
virtual std::size_t find_first_record(const Iterator &_data, const RangeType &parentRange, const RangeType &inMemRange, const RangeType &searchRange)
{
//== range checking
if(!parentRange.contains(inMemRange)) {
::std::cout << "parent: " << parentRange << " , in mem: " << inMemRange << ::std::endl;
throw std::invalid_argument("ERROR: Parent Range does not contain inMemRange");
}
// no op, other than to use intersect to make sure that the start is valid and within parent, and in memry ranges.
return RangeType::intersect(searchRange, inMemRange).start;
}
#ifdef USE_MPI
virtual std::size_t find_first_record(const Iterator &_data, const RangeType &parentRange, const RangeType &inMemRange, const RangeType &searchRange, const mxx::comm& comm) {
return find_first_record(_data, parentRange, inMemRange, searchRange);
}
#endif
virtual typename RangeType::ValueType find_overlap_end(const Iterator &_data,
const RangeType &parentRange, const RangeType &inMemRange, typename RangeType::ValueType end, size_t overlap ) {
return std::max(inMemRange.start, std::min(end + overlap, inMemRange.end));
}
/// reset any parser internal state so the parser can be reused on a different data range. overridden in subclass.
virtual void reset() {}
virtual bool should_parse(const RangeType & range) {
return range.size() > 0;
}
#ifdef USE_MPI
virtual bool should_parse(const RangeType & range, const mxx::comm & comm) {
return range.size() > 0;
}
#endif
/// initializes parser for a particular data range. overridden in subclass. returns start of first record. _data points to first element in mem.
virtual std::size_t init_parser(const Iterator &_data, const RangeType &parentRange, const RangeType &inMemRange, const RangeType &searchRange) {
return this->find_first_record(_data, parentRange, inMemRange, searchRange);
}
#ifdef USE_MPI
/// initializes the parser. only useful for FASTA parser for now. Assumes searchRange do NOT overlap between processes. _data points to first element in mem.
virtual std::size_t init_parser(const Iterator &_data, const RangeType &parentRange, const RangeType &inMemRange, const RangeType &searchRange, const mxx::comm& comm)
{
return this->find_first_record(_data, parentRange, inMemRange, searchRange);
};
#endif
/**
* @brief increment to get next sequence object
* @note not virtual because SequenceType is different for each subclass, so the signatures are different. We rely on compiler to enforce the correct one.
* this is in general not an issue as we do not need polymorphic Sequence Parsers - they are specific to file types.
* this is probably better for performance anyways.
*
* Used by FileLoader's getRecordSize to compute an average record size.
*
* @param iter start of a sequence object. this is the beginning of a record, not just DNA sequence
* @param end end of a sequence object. this is the end of a record, not just DNA sequence
* @param offset offset in the file for the start of the record.
* @param seq_offset index in the local (shared) vector of sequence breaks, if there is one (e.g. FASTA). used by FASTA to lookup the nearest complete sequence record info.
* @param output updated sequence object.
* @return next seq id offset.
*/
SequenceType get_next_record(Iterator & iter, const Iterator & end, size_t & offset)
{
Iterator orig_iter = iter;
size_t orig_offset = offset;
size_t dist = std::distance(iter, end);
offset += dist;
iter = end;
return SequenceType(SequenceIdType(orig_offset), dist, 0, 0, orig_iter, end);
}
/**
* @brief get the average record size in the supplied range
* @return return the records size and the internal data size
*/
virtual ::std::pair<size_t, size_t> get_record_size(const Iterator &_data, const RangeType &parentRange, const RangeType &inMemRange, const RangeType &validRange, size_t const count) {
size_t dist = validRange.size();
return ::std::pair<size_t, size_t>(dist,dist);
}
#ifdef USE_MPI
virtual ::std::pair<size_t, size_t> get_record_size(const Iterator &_data, const RangeType &parentRange, const RangeType &inMemRange, const RangeType &validRange, mxx::comm const & comm, size_t const count) {
size_t dist = validRange.size();
return ::std::pair<size_t, size_t>(dist,dist);
}
#endif
};
/// template class' static variable definition (declared and initialized in class)
template <typename Iterator>
constexpr unsigned char bliss::io::BaseFileParser<Iterator >::eol;
template <typename Iterator>
constexpr unsigned char bliss::io::BaseFileParser<Iterator>::cr;
} /* namespace functional */
} /* namespace bliss */
#endif /* FILE_LOADER_HPP_ */
<|endoftext|>
|
<commit_before><commit_msg>Use more proper types and range-for loops<commit_after><|endoftext|>
|
<commit_before>#include "Halide.h"
using namespace Halide;
int multi_type_test() {
Func f1("f1"), f2("f2"), f3("f3"), f4("f4"), f5("f5"), f6("f6");
Var x, y, z;
f1(x, y, z) = cast<uint8_t>(1);
f2(x, y, z) = cast<uint32_t>(f1(x+1, y, z) + f1(x, y+1, z));
f3(x, y, z) = cast<uint16_t>(f2(x+1, y, z) + f2(x, y+1, z));
f4(x, y, z) = cast<uint16_t>(f3(x+1, y, z) + f3(x, y+1, z));
f5(x, y, z) = cast<uint32_t>(f4(x+1, y, z) + f4(x, y+1, z));
f6(x, y, z) = cast<uint8_t>(f5(x+1, y, z) + f5(x, y+1, z));
f6.compute_root().gpu_tile(x, y, 1, 1);
f5.compute_at(f6, Var::gpu_blocks()).gpu_threads(x, y);
f4.compute_at(f6, Var::gpu_blocks()).gpu_threads(x, y);
f3.compute_at(f6, Var::gpu_blocks()).gpu_threads(x, y);
f2.compute_at(f6, Var::gpu_blocks()).gpu_threads(x, y);
f1.compute_at(f6, Var::gpu_blocks()).gpu_threads(x, y);
const int size_x = 200;
const int size_y = 200;
const int size_z = 4;
Image<uint8_t> out = f6.realize(size_x, size_y, size_z);
uint8_t correct = 32;
for (int z = 0; z < size_z; z++) {
for (int y = 0; y < size_y; y++) {
for (int x = 0; x < size_x; x++) {
if (out(x, y, z) != correct) {
printf("out(%d, %d, %d) = %d instead of %d\n",
x, y, z, out(x, y, z), correct);
return -1;
}
}
}
}
printf("Success!\n");
return 0;
}
int pyramid_test() {
const int levels = 10;
const int size_x = 100;
const int size_y = 100;
Var x, y, z, xo, xi, yo, yi;
std::vector<Func> funcs(levels);
funcs[0](x, y) = 1;
for (int i = 1; i < levels; ++i) {
funcs[i](x, y) = funcs[i-1](2*x, y);
}
funcs[levels-1].compute_root()
.gpu_tile(x, y, 4, 4);
for (int i = levels-2; i >= 0; --i) {
funcs[i].compute_at(funcs[levels-1], Var::gpu_blocks())
.split(x, xo, xi, 1 << (levels - i - 1))
.gpu_threads(xo, y);
}
Image<int> out = funcs[levels-1].realize(size_x, size_y);
int correct = 1;
for (int y = 0; y < size_y; y++) {
for (int x = 0; x < size_x; x++) {
if (out(x, y) != correct) {
printf("out(%d, %d) = %d instead of %d\n",
x, y, out(x, y), correct);
return -1;
}
}
}
printf("Success!\n");
return 0;
}
int inverted_pyramid_test() {
const int levels = 6;
const int size_x = 8*16;
const int size_y = 8*16;
Var x, y, z, yo, yi, xo, xi;
std::vector<Func> funcs(levels);
funcs[0](x, y) = 1;
for (int i = 1; i < levels; ++i) {
funcs[i](x, y) = funcs[i-1](x/2, y);
}
funcs[levels-1].compute_root()
.tile(x, y, xo, yo, xi, yi, 16, 16)
.gpu_tile(xo, yo, 8, 8);
for (int i = levels-2; i >= 0; --i) {
funcs[i].compute_at(funcs[levels-1], Var::gpu_blocks())
.tile(x, y, xo, yo, xi, yi, 16, 16)
.gpu_threads(xo, yo);
}
Image<int> out = funcs[levels-1].realize(size_x, size_y);
int correct = 1;
for (int y = 0; y < size_y; y++) {
for (int x = 0; x < size_x; x++) {
if (out(x, y) != correct) {
printf("out(%d, %d) = %d instead of %d\n",
x, y, out(x, y), correct);
return -1;
}
}
}
printf("Success!\n");
return 0;
}
int dynamic_shared_test() {
if (!get_jit_target_from_environment().has_gpu_feature()) {
printf("Not running test because no gpu target enabled\n");
return 0;
}
Func f1, f2, f3, f4;
Var x, xo, xi;
f1(x) = x;
f2(x) = f1(x) + f1(2*x);
f3(x) = f2(x) + f2(2*x);
f4(x) = f3(x) + f3(2*x);
f4.split(x, xo, xi, 16).gpu_tile(xo, 16);
f3.compute_at(f4, Var::gpu_blocks()).split(x, xo, xi, 16).gpu_threads(xi);
f2.compute_at(f4, Var::gpu_blocks()).split(x, xo, xi, 16).gpu_threads(xi);
f1.compute_at(f4, Var::gpu_blocks()).split(x, xo, xi, 16).gpu_threads(xi);
// The amount of shared memory required varies with x
Image<int> out = f4.realize(500);
for (int x = 0; x < out.width(); x++) {
int correct = 27*x;
if (out(x) != correct) {
printf("out(%d) = %d instead of %d\n",
x, out(x), correct);
return -1;
}
}
printf("Success!\n");
return 0;
}
int main(int argc, char **argv) {
if (!get_jit_target_from_environment().has_gpu_feature()) {
printf("Not running test because no gpu target enabled\n");
return 0;
}
printf("Running multi type test!\n");
if (multi_type_test() != 0) {
return -1;
}
printf("Running pyramid test!\n");
if (pyramid_test() != 0) {
return -1;
}
printf("Running inverted pyramid test!\n");
if (inverted_pyramid_test() != 0) {
return -1;
}
printf("Running dynamic shared test!\n");
if (dynamic_shared_test() != 0) {
return -1;
}
return 0;
}
<commit_msg>Limit shared memory usage to 32k<commit_after>#include "Halide.h"
using namespace Halide;
int multi_type_test() {
Func f1("f1"), f2("f2"), f3("f3"), f4("f4"), f5("f5"), f6("f6");
Var x, y, z;
f1(x, y, z) = cast<uint8_t>(1);
f2(x, y, z) = cast<uint32_t>(f1(x+1, y, z) + f1(x, y+1, z));
f3(x, y, z) = cast<uint16_t>(f2(x+1, y, z) + f2(x, y+1, z));
f4(x, y, z) = cast<uint16_t>(f3(x+1, y, z) + f3(x, y+1, z));
f5(x, y, z) = cast<uint32_t>(f4(x+1, y, z) + f4(x, y+1, z));
f6(x, y, z) = cast<uint8_t>(f5(x+1, y, z) + f5(x, y+1, z));
f6.compute_root().gpu_tile(x, y, 1, 1);
f5.compute_at(f6, Var::gpu_blocks()).gpu_threads(x, y);
f4.compute_at(f6, Var::gpu_blocks()).gpu_threads(x, y);
f3.compute_at(f6, Var::gpu_blocks()).gpu_threads(x, y);
f2.compute_at(f6, Var::gpu_blocks()).gpu_threads(x, y);
f1.compute_at(f6, Var::gpu_blocks()).gpu_threads(x, y);
const int size_x = 200;
const int size_y = 200;
const int size_z = 4;
Image<uint8_t> out = f6.realize(size_x, size_y, size_z);
uint8_t correct = 32;
for (int z = 0; z < size_z; z++) {
for (int y = 0; y < size_y; y++) {
for (int x = 0; x < size_x; x++) {
if (out(x, y, z) != correct) {
printf("out(%d, %d, %d) = %d instead of %d\n",
x, y, z, out(x, y, z), correct);
return -1;
}
}
}
}
printf("Success!\n");
return 0;
}
int pyramid_test() {
const int levels = 10;
const int size_x = 100;
const int size_y = 100;
Var x, y, z, xo, xi, yo, yi;
std::vector<Func> funcs(levels);
funcs[0](x, y) = 1;
for (int i = 1; i < levels; ++i) {
funcs[i](x, y) = funcs[i-1](2*x, y);
}
funcs[levels-1].compute_root()
.gpu_tile(x, y, 3, 4);
for (int i = levels-2; i >= 0; --i) {
funcs[i].compute_at(funcs[levels-1], Var::gpu_blocks())
.split(x, xo, xi, 1 << (levels - i - 1))
.gpu_threads(xo, y);
}
Image<int> out = funcs[levels-1].realize(size_x, size_y);
int correct = 1;
for (int y = 0; y < size_y; y++) {
for (int x = 0; x < size_x; x++) {
if (out(x, y) != correct) {
printf("out(%d, %d) = %d instead of %d\n",
x, y, out(x, y), correct);
return -1;
}
}
}
printf("Success!\n");
return 0;
}
int inverted_pyramid_test() {
const int levels = 6;
const int size_x = 8*16*4;
const int size_y = 8*16*4;
Var x, y, z, yo, yi, yii, xo, xi, xii;
std::vector<Func> funcs(levels);
funcs[0](x, y) = 1;
for (int i = 1; i < levels; ++i) {
funcs[i](x, y) = funcs[i-1](x/2, y);
}
funcs[levels-1].compute_root()
.tile(x, y, xi, yi, 64, 64)
.gpu_blocks(x, y)
.tile(xi, yi, xii, yii, 16, 16)
.gpu_threads(xi, yi);
for (int i = levels-2; i >= 0; --i) {
funcs[i].compute_at(funcs[levels-1], Var::gpu_blocks())
.tile(x, y, xi, yi, 4, 4)
.gpu_threads(xi, yi);
}
funcs[levels-1].bound(x, 0, size_x).bound(y, 0, size_y);
Image<int> out = funcs[levels-1].realize(size_x, size_y);
int correct = 1;
for (int y = 0; y < size_y; y++) {
for (int x = 0; x < size_x; x++) {
if (out(x, y) != correct) {
printf("out(%d, %d) = %d instead of %d\n",
x, y, out(x, y), correct);
return -1;
}
}
}
printf("Success!\n");
return 0;
}
int dynamic_shared_test() {
if (!get_jit_target_from_environment().has_gpu_feature()) {
printf("Not running test because no gpu target enabled\n");
return 0;
}
Func f1, f2, f3, f4;
Var x, xo, xi;
f1(x) = x;
f2(x) = f1(x) + f1(2*x);
f3(x) = f2(x) + f2(2*x);
f4(x) = f3(x) + f3(2*x);
f4.split(x, xo, xi, 16).gpu_tile(xo, 16);
f3.compute_at(f4, Var::gpu_blocks()).split(x, xo, xi, 16).gpu_threads(xi);
f2.compute_at(f4, Var::gpu_blocks()).split(x, xo, xi, 16).gpu_threads(xi);
f1.compute_at(f4, Var::gpu_blocks()).split(x, xo, xi, 16).gpu_threads(xi);
// The amount of shared memory required varies with x
Image<int> out = f4.realize(500);
for (int x = 0; x < out.width(); x++) {
int correct = 27*x;
if (out(x) != correct) {
printf("out(%d) = %d instead of %d\n",
x, out(x), correct);
return -1;
}
}
printf("Success!\n");
return 0;
}
int main(int argc, char **argv) {
if (!get_jit_target_from_environment().has_gpu_feature()) {
printf("Not running test because no gpu target enabled\n");
return 0;
}
printf("Running multi type test!\n");
if (multi_type_test() != 0) {
return -1;
}
printf("Running pyramid test!\n");
if (pyramid_test() != 0) {
return -1;
}
printf("Running inverted pyramid test!\n");
if (inverted_pyramid_test() != 0) {
return -1;
}
printf("Running dynamic shared test!\n");
if (dynamic_shared_test() != 0) {
return -1;
}
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: flypos.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2003-04-17 14:12:31 $
*
* 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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "doc.hxx"
#include "node.hxx"
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _FMTANCHR_HXX //autogen
#include <fmtanchr.hxx>
#endif
#include "flypos.hxx"
#include "frmfmt.hxx"
#include "dcontact.hxx"
#include "dview.hxx"
#include "flyfrm.hxx"
#include "dflyobj.hxx"
#include "ndindex.hxx"
SV_IMPL_OP_PTRARR_SORT( SwPosFlyFrms, SwPosFlyFrmPtr )
SwPosFlyFrm::SwPosFlyFrm( const SwNodeIndex& rIdx, const SwFrmFmt* pFmt,
USHORT nArrPos )
: pNdIdx( (SwNodeIndex*) &rIdx ), pFrmFmt( pFmt )
{
BOOL bFnd = FALSE;
const SwFmtAnchor& rAnchor = pFmt->GetAnchor();
if( FLY_PAGE == rAnchor.GetAnchorId() )
pNdIdx = new SwNodeIndex( rIdx );
else if( pFmt->GetDoc()->GetRootFrm() )
{
SwClientIter aIter( (SwFmt&)*pFmt );
if( RES_FLYFRMFMT == pFmt->Which() )
{
// Schauen, ob es ein SdrObject dafuer gibt
if( aIter.First( TYPE( SwFlyFrm) ) )
nOrdNum = ((SwFlyFrm*)aIter())->GetVirtDrawObj()->GetOrdNum(),
bFnd = TRUE;
}
else if( RES_DRAWFRMFMT == pFmt->Which() )
{
// Schauen, ob es ein SdrObject dafuer gibt
if( aIter.First( TYPE(SwDrawContact) ) )
nOrdNum = ((SwDrawContact*)aIter())->GetMaster()->GetOrdNum(),
bFnd = TRUE;
}
}
if( !bFnd )
{
nOrdNum = pFmt->GetDoc()->GetSpzFrmFmts()->Count();
nOrdNum += nArrPos;
}
}
SwPosFlyFrm::~SwPosFlyFrm()
{
const SwFmtAnchor& rAnchor = pFrmFmt->GetAnchor();
if( FLY_PAGE == rAnchor.GetAnchorId() )
delete pNdIdx;
}
BOOL SwPosFlyFrm::operator==( const SwPosFlyFrm& rPosFly )
{
return FALSE; // FlyFrames koennen auf der gleichen Position stehen
}
BOOL SwPosFlyFrm::operator<( const SwPosFlyFrm& rPosFly )
{
if( pNdIdx->GetIndex() == rPosFly.pNdIdx->GetIndex() )
{
// dann entscheidet die Ordnungsnummer!
return nOrdNum < rPosFly.nOrdNum;
}
return pNdIdx->GetIndex() < rPosFly.pNdIdx->GetIndex();
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.1254); FILE MERGED 2005/09/05 13:40:16 rt 1.2.1254.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: flypos.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 04:13:27 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#include "doc.hxx"
#include "node.hxx"
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _FMTANCHR_HXX //autogen
#include <fmtanchr.hxx>
#endif
#include "flypos.hxx"
#include "frmfmt.hxx"
#include "dcontact.hxx"
#include "dview.hxx"
#include "flyfrm.hxx"
#include "dflyobj.hxx"
#include "ndindex.hxx"
SV_IMPL_OP_PTRARR_SORT( SwPosFlyFrms, SwPosFlyFrmPtr )
SwPosFlyFrm::SwPosFlyFrm( const SwNodeIndex& rIdx, const SwFrmFmt* pFmt,
USHORT nArrPos )
: pNdIdx( (SwNodeIndex*) &rIdx ), pFrmFmt( pFmt )
{
BOOL bFnd = FALSE;
const SwFmtAnchor& rAnchor = pFmt->GetAnchor();
if( FLY_PAGE == rAnchor.GetAnchorId() )
pNdIdx = new SwNodeIndex( rIdx );
else if( pFmt->GetDoc()->GetRootFrm() )
{
SwClientIter aIter( (SwFmt&)*pFmt );
if( RES_FLYFRMFMT == pFmt->Which() )
{
// Schauen, ob es ein SdrObject dafuer gibt
if( aIter.First( TYPE( SwFlyFrm) ) )
nOrdNum = ((SwFlyFrm*)aIter())->GetVirtDrawObj()->GetOrdNum(),
bFnd = TRUE;
}
else if( RES_DRAWFRMFMT == pFmt->Which() )
{
// Schauen, ob es ein SdrObject dafuer gibt
if( aIter.First( TYPE(SwDrawContact) ) )
nOrdNum = ((SwDrawContact*)aIter())->GetMaster()->GetOrdNum(),
bFnd = TRUE;
}
}
if( !bFnd )
{
nOrdNum = pFmt->GetDoc()->GetSpzFrmFmts()->Count();
nOrdNum += nArrPos;
}
}
SwPosFlyFrm::~SwPosFlyFrm()
{
const SwFmtAnchor& rAnchor = pFrmFmt->GetAnchor();
if( FLY_PAGE == rAnchor.GetAnchorId() )
delete pNdIdx;
}
BOOL SwPosFlyFrm::operator==( const SwPosFlyFrm& rPosFly )
{
return FALSE; // FlyFrames koennen auf der gleichen Position stehen
}
BOOL SwPosFlyFrm::operator<( const SwPosFlyFrm& rPosFly )
{
if( pNdIdx->GetIndex() == rPosFly.pNdIdx->GetIndex() )
{
// dann entscheidet die Ordnungsnummer!
return nOrdNum < rPosFly.nOrdNum;
}
return pNdIdx->GetIndex() < rPosFly.pNdIdx->GetIndex();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: swacorr.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-01-11 12:21:09 $
*
* 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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _URLOBJ_HXX //autogen
#include <tools/urlobj.hxx>
#endif
#ifndef _SWACORR_HXX
#include <swacorr.hxx>
#endif
#ifndef _SWBLOCKS_HXX
#include <swblocks.hxx>
#endif
#ifndef _SW_XMLTEXTBLOCKS_HXX
#include "SwXMLTextBlocks.hxx"
#endif
#ifndef _SWSERROR_H
#include <swerror.h>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _EDITSH_HXX
#include <editsh.hxx>
#endif
#include <sot/storage.hxx>
TYPEINIT1( SwAutoCorrect, SvxAutoCorrect );
// - return den Ersetzungstext (nur fuer SWG-Format, alle anderen
// koennen aus der Wortliste herausgeholt werden!)
// rShort ist der Stream-Name - gecryptet!
BOOL SwAutoCorrect::GetLongText( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >& rStg, const String& rFileName, const String& rShort, String& rLong )
{
ULONG nRet;
if (rStg.is())
{
// mba: relative URLs don't make sense here
SwXMLTextBlocks aBlk( rStg, rFileName );
nRet = aBlk.GetText( rShort, rLong );
}
else
ASSERT ( rStg.is(), "Someone passed SwAutoCorrect::GetLongText a dud storage!");
return !IsError( nRet ) && rLong.Len();
}
// - Text mit Attributierung (kann nur der SWG - SWG-Format!)
// rShort ist der Stream-Name - gecryptet!
BOOL SwAutoCorrect::PutText( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >& rStg, const String& rFileName, const String& rShort,
SfxObjectShell& rObjSh, String& rLong )
{
if( !rObjSh.IsA( TYPE(SwDocShell) ) )
return FALSE;
SwDocShell& rDShell = (SwDocShell&)rObjSh;
ULONG nRet = 0;
// mba: relative URLs don't make sense here
SwXMLTextBlocks aBlk( rStg, rFileName );
SwDoc* pDoc = aBlk.GetDoc();
nRet = aBlk.BeginPutDoc( rShort, rShort );
if( !IsError( nRet ) )
{
((SwEditShell*)rDShell.GetWrtShell())->_CopySelToDoc( pDoc );
nRet = aBlk.PutDoc();
aBlk.AddName ( rShort, rShort, FALSE );
if( !IsError( nRet ) )
nRet = aBlk.GetText( rShort, rLong );
}
return !IsError( nRet );
}
SwAutoCorrect::SwAutoCorrect( const SvxAutoCorrect& rACorr )
: SvxAutoCorrect( rACorr )
{
SwEditShell::SetAutoFmtFlags(&GetSwFlags());
}
SwAutoCorrect::~SwAutoCorrect()
{
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.8.386); FILE MERGED 2005/09/05 13:40:33 rt 1.8.386.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: swacorr.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-09-09 04:41:38 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#ifndef _URLOBJ_HXX //autogen
#include <tools/urlobj.hxx>
#endif
#ifndef _SWACORR_HXX
#include <swacorr.hxx>
#endif
#ifndef _SWBLOCKS_HXX
#include <swblocks.hxx>
#endif
#ifndef _SW_XMLTEXTBLOCKS_HXX
#include "SwXMLTextBlocks.hxx"
#endif
#ifndef _SWSERROR_H
#include <swerror.h>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _EDITSH_HXX
#include <editsh.hxx>
#endif
#include <sot/storage.hxx>
TYPEINIT1( SwAutoCorrect, SvxAutoCorrect );
// - return den Ersetzungstext (nur fuer SWG-Format, alle anderen
// koennen aus der Wortliste herausgeholt werden!)
// rShort ist der Stream-Name - gecryptet!
BOOL SwAutoCorrect::GetLongText( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >& rStg, const String& rFileName, const String& rShort, String& rLong )
{
ULONG nRet;
if (rStg.is())
{
// mba: relative URLs don't make sense here
SwXMLTextBlocks aBlk( rStg, rFileName );
nRet = aBlk.GetText( rShort, rLong );
}
else
ASSERT ( rStg.is(), "Someone passed SwAutoCorrect::GetLongText a dud storage!");
return !IsError( nRet ) && rLong.Len();
}
// - Text mit Attributierung (kann nur der SWG - SWG-Format!)
// rShort ist der Stream-Name - gecryptet!
BOOL SwAutoCorrect::PutText( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >& rStg, const String& rFileName, const String& rShort,
SfxObjectShell& rObjSh, String& rLong )
{
if( !rObjSh.IsA( TYPE(SwDocShell) ) )
return FALSE;
SwDocShell& rDShell = (SwDocShell&)rObjSh;
ULONG nRet = 0;
// mba: relative URLs don't make sense here
SwXMLTextBlocks aBlk( rStg, rFileName );
SwDoc* pDoc = aBlk.GetDoc();
nRet = aBlk.BeginPutDoc( rShort, rShort );
if( !IsError( nRet ) )
{
((SwEditShell*)rDShell.GetWrtShell())->_CopySelToDoc( pDoc );
nRet = aBlk.PutDoc();
aBlk.AddName ( rShort, rShort, FALSE );
if( !IsError( nRet ) )
nRet = aBlk.GetText( rShort, rLong );
}
return !IsError( nRet );
}
SwAutoCorrect::SwAutoCorrect( const SvxAutoCorrect& rACorr )
: SvxAutoCorrect( rACorr )
{
SwEditShell::SetAutoFmtFlags(&GetSwFlags());
}
SwAutoCorrect::~SwAutoCorrect()
{
}
<|endoftext|>
|
<commit_before><commit_msg>sw: replace pointless unused position update in SwTxtNode::Update()<commit_after><|endoftext|>
|
<commit_before>#include "twister.h"
const unsigned CYCLE = 0x100;
//Suggest we wrap these arrays inside an fsm or test base class
const unsigned C_TRANS_ = 0xff;
int block_units[][0x10] = {
0x74, 0x63, 0x69, 0x67, 0x72, 0x68, 0x6e, 0x6c, 0x61, 0x67, 0x74, 0x6c, 0x69, 0x73, 0x61, 0x61, 0x6f, 0x6d, 0x6f, 0x72, 0x6e, 0x72, 0x69, 0x6d, 0x6e, 0x6e, 0x65, 0x74, 0x72, 0x6e, 0x6b, 0x73, 0x61, 0x6f, 0x65, 0x69, 0x73, 0x64, 0x6c, 0x65, 0x69, 0x6b, 0x68, 0x68, 0x68, 0x65, 0x72, 0x64, 0x66, 0x74, 0x61, 0x73, 0x6f, 0x69, 0x65, 0x74, 0x69, 0x68, 0x6e, 0x65, 0x62, 0x74, 0x6b, 0x65
};
int triad_units[][0x03] = {
0x31, 0xfe, 0x45, 0x74, 0x68, 0x65, 0x74, 0x68, 0x61, 0x65, 0x74, 0x68, 0x66, 0x6f, 0x72, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x65, 0x68, 0x61, 0x74, 0x68, 0x69, 0x73, 0x1a, 0x36, 0x49, 0x91, 0x43, 0x53
};
const int transition_seq[] = { 0xce, 0xab, 0xdf, 0xcf, 0xee,
0xcf, 0xad, 0xdf, 0xff, 0xce,
0x32, 0x40, 0xd3, 0x27, 0x82,
0xda, 0xee, 0xff, 0xfc, 0xbf,
0x1c, 0x90, 0x13, 0x4a, 0xa5,
0xe0, 0x21, 0x9f, 0xe1, 0xc6,
0xaf, 0x05, 0x81, 0xf0, 0xee,
0xe4, 0x38, 0x1f, 0x60, 0x24,
0x0c, 0x35, 0x51, 0x32, 0xcf,
0x12, 0x9a, 0x30, 0x44, 0x72,
0x51, 0x3c, 0x61, 0x2d, 0x5f,
0x04, 0x1c, 0x52, 0xca, 0xdf,
0x12, 0x0b, 0x30, 0xa0, 0x1e,
0x03, 0x14, 0x09, 0x73, 0x23,
0xf2, 0xca, 0xa2, 0x51, 0xc6,
0x01, 0xdf, 0x41, 0x96, 0xa0,
0x51, 0x19, 0x71, 0x23, 0x47,
0xcb, 0xbd, 0xba, 0xac, 0xdf,
0xdf, 0xde, 0xcd, 0xfd, 0xca };
int ENTRY_LINK__ = 0x05;
int ENTRY_LINK__TEST = 0x09;
int ENTRY_C_REF_ECM = 0x10;
int ENTRY_C_REF_ECM_TEST = 0x03;
int ENTRY_C_OUTER = 0x51;
int ENTRY_C_OUTER_PROD = 0x41;
int ENTRY_C_OUTER_PROD_TEST = 0x33;
int ENTRY_C_OUTER_PROD_TOR_TEST = 0x57;
int ENTRY_A_OUTER_PROD_TOR_TEST = 0xc9;
int ENTRY_B_OUTER_PROD_EUC_TEST = 0xaf;
int ENTRY_C_OUTER_PROD_EUC_TEST = 0xa1;
int ENTRY_C_INNER_PROD_EUC_TEST = 0xc5;
int ENTRY_C_INNER_PROD_ELIP_TEST = 0xa2;
int ENTRY_C_INNER_PROD_RELAY_TEST = 0xf5;
int ENTRY_C_BLOCK_REL_FLAG_TEST = 0x0fffffff;
int ENTRY_C_BLOCK_REL_FLAG_VECTOR = 0x0effffff;
unsigned reflect(unsigned center, unsigned (*r)(unsigned))
{
return (*r)(center)^center;
}
unsigned char base(unsigned char a, unsigned char (*s)(unsigned char), int pos)
{
return (*s)(pos)^a;
}
void transHomExt(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))
{
for(unsigned i = 0; i<data.size(); i++)
{
unsigned char d = data[i];
for(unsigned j=0; j<CYCLE; j++)
{
d = (*f)(d)^base(d, g, d);
}
data[i] = d;
}
}
void transHom(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))
{
for(unsigned i = 0; i<data.size(); i++)
{
unsigned char d = data[i];
for(unsigned j=0; j<CYCLE; j++)
{
d = (*f)(d)^(*g)(d);
}
data[i] = d;
}
}
void trans(vector<unsigned char>& data, unsigned char (*f)(unsigned char))
{
for(unsigned i = 0; i<data.size(); i++)
{
unsigned char d = data[i];
for(unsigned j=0; j<CYCLE; j++)
{
d = (*f)(d);
}
data[i] = d;
}
}
vector<double> f_dist(vector<unsigned char>& in)
{
vector<double> fdist;
fdist.resize(256);
for(unsigned i = 0; i<in.size(); i++)
{
fdist[in[i]]++;
}
for(unsigned i=0; i<fdist.size(); i++)
{
fdist[i] = (fdist[i] / in.size()) * 100;
}
return fdist;
}
double s_entropy(vector<double>& v)
{
double entropy = 0;
double p;
for(unsigned i = 0; i < v.size(); i++)
{
p = v[i] / 100;
if (p == 0) continue;
entropy += p * std::log(p) / std::log(2);
}
return -entropy;
}
void rms(const string& s, string& r)
{
for(unsigned int i=0; i<s.size(); i++)
{
if(::isspace(s[i])) continue;
r+= s[i];
}
}
//add extended euc
double sw(double weight, int i, int j, int (*inv)(int, int))
{
return weight*(*inv)(i, j);
}
//Suggest we wrap these routines in a base class in particular for testing
//and expose test api
void hPerm(int s, int n, void (*p)(int), void (*inv)(int, int), void (*center)(int))
{
if(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST ] == s)
{
(*center)(s);
return;
}
if(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST ] == s)
{
(*p)(s);
return;
}
if(s == 1)
{
(*p)(n);
return;
}
for(int i=0; i< s; i++)
{
hPerm(s-1, n, p, inv, p);
if(s%2 == 1)
(*inv)(0, s-1);
else
(*inv)(i, s-1);
}
}
double ic(const string& t)
{
string text; rms(t, text);
vector<double> freq(256,0);
for(unsigned int i=0; i<text.size(); i++)
{
if(text[i] == ' ') continue;
freq[text[i]] ++;
}
double sum=0;
for(unsigned int i=0; i<freq.size(); i++)
{
if(freq[i] != 0)
{
double c = freq[i];
if(c != 0)
sum += c * (c - 1);
}
}
double ic = 26 * sum / (text.size() * (text.size() - 1));
return ic;
}
int outer_sect(int (*s)(int), int (*t)(int), int r, int q)
{
return (*s)(r) * (*t)(q);
}
void switchIO(unsigned char (*p)(unsigned char, unsigned char), unsigned char m)
{
//test seq
(*p)(transition_seq[ENTRY_LINK__], m);
(*p)(transition_seq[ENTRY_LINK__TEST], m);
(*p)(transition_seq[ENTRY_C_REF_ECM], m);
(*p)(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST ], m);
(*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_LINK__TEST]);
(*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_C_REF_ECM]);
}
//Suggest we wrap these in util base class, abstract col cont
std::tuple<int, int, int> extended_gcd(int __alpha, int __beta, int (*col)(int x, int y))
{
if(__alpha == 0) return make_tuple(__beta,0,1);
int __com=0;
int x=0;
int y=0;
tie(__com, x, y) = extended_gcd(__beta%__alpha, __alpha, col);
return make_tuple(__com, y-(__beta/__alpha)*x, x);
}
std::tuple<int, int, int> extended_gcd(int __alpha, int __beta)
{
if(__alpha == 0) return make_tuple(__beta,0,1);
int __com=0;
int x=0;
int y=0;
tie(__com, x, y) = extended_gcd(__beta%__alpha, __alpha);
return make_tuple(__com, y-(__beta/__alpha)*x, x);
}
<commit_msg>block rel, flag test, ext<commit_after>#include "twister.h"
const unsigned CYCLE = 0x100;
//Suggest we wrap these arrays inside an fsm or test base class
const unsigned C_TRANS_ = 0xff;
int block_units[][0x10] = {
0x74, 0x63, 0x69, 0x67, 0x72, 0x68, 0x6e, 0x6c, 0x61, 0x67, 0x74, 0x6c, 0x69, 0x73, 0x61, 0x61, 0x6f, 0x6d, 0x6f, 0x72, 0x6e, 0x72, 0x69, 0x6d, 0x6e, 0x6e, 0x65, 0x74, 0x72, 0x6e, 0x6b, 0x73, 0x61, 0x6f, 0x65, 0x69, 0x73, 0x64, 0x6c, 0x65, 0x69, 0x6b, 0x68, 0x68, 0x68, 0x65, 0x72, 0x64, 0x66, 0x74, 0x61, 0x73, 0x6f, 0x69, 0x65, 0x74, 0x69, 0x68, 0x6e, 0x65, 0x62, 0x74, 0x6b, 0x65
};
int triad_units[][0x03] = {
0x31, 0xfe, 0x45, 0x74, 0x68, 0x65, 0x74, 0x68, 0x61, 0x65, 0x74, 0x68, 0x66, 0x6f, 0x72, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x65, 0x68, 0x61, 0x74, 0x68, 0x69, 0x73, 0x1a, 0x36, 0x49, 0x91, 0x43, 0x53
};
const int transition_seq[] = { 0xce, 0xab, 0xdf, 0xcf, 0xee,
0xcf, 0xad, 0xdf, 0xff, 0xce,
0x32, 0x40, 0xd3, 0x27, 0x82,
0xda, 0xee, 0xff, 0xfc, 0xbf,
0x1c, 0x90, 0x13, 0x4a, 0xa5,
0xe0, 0x21, 0x9f, 0xe1, 0xc6,
0xaf, 0x05, 0x81, 0xf0, 0xee,
0xe4, 0x38, 0x1f, 0x60, 0x24,
0x0c, 0x35, 0x51, 0x32, 0xcf,
0x12, 0x9a, 0x30, 0x44, 0x72,
0x51, 0x3c, 0x61, 0x2d, 0x5f,
0x04, 0x1c, 0x52, 0xca, 0xdf,
0x12, 0x0b, 0x30, 0xa0, 0x1e,
0x03, 0x14, 0x09, 0x73, 0x23,
0xf2, 0xca, 0xa2, 0x51, 0xc6,
0x01, 0xdf, 0x41, 0x96, 0xa0,
0x51, 0x19, 0x71, 0x23, 0x47,
0xcb, 0xbd, 0xba, 0xac, 0xdf,
0xdf, 0xde, 0xcd, 0xfd, 0xca };
int ENTRY_LINK__ = 0x05;
int ENTRY_LINK__TEST = 0x09;
int ENTRY_C_REF_ECM = 0x10;
int ENTRY_C_REF_ECM_TEST = 0x03;
int ENTRY_C_OUTER = 0x51;
int ENTRY_C_OUTER_PROD = 0x41;
int ENTRY_C_OUTER_PROD_TEST = 0x33;
int ENTRY_C_OUTER_PROD_TOR_TEST = 0x57;
int ENTRY_A_OUTER_PROD_TOR_TEST = 0xc9;
int ENTRY_B_OUTER_PROD_EUC_TEST = 0xaf;
int ENTRY_C_OUTER_PROD_EUC_TEST = 0xa1;
int ENTRY_C_INNER_PROD_EUC_TEST = 0xc5;
int ENTRY_C_INNER_PROD_ELIP_TEST = 0xa2;
int ENTRY_C_INNER_PROD_RELAY_TEST = 0xf5;
int ENTRY_C_BLOCK_REL_FLAG_TEST = 0x0fffffff;
int ENTRY_C_BLOCK_REL_FLAG_VECTOR = 0x0effffff;
unsigned reflect(unsigned center, unsigned (*r)(unsigned))
{
return (*r)(center)^center;
}
unsigned char base(unsigned char a, unsigned char (*s)(unsigned char), int pos)
{
return (*s)(pos)^a;
}
void transHomExt(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))
{
for(unsigned i = 0; i<data.size(); i++)
{
unsigned char d = data[i];
for(unsigned j=0; j<CYCLE; j++)
{
d = (*f)(d)^base(d, g, d);
}
data[i] = d;
}
}
void transHom(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))
{
for(unsigned i = 0; i<data.size(); i++)
{
unsigned char d = data[i];
for(unsigned j=0; j<CYCLE; j++)
{
d = (*f)(d)^(*g)(d);
}
data[i] = d;
}
}
void trans(vector<unsigned char>& data, unsigned char (*f)(unsigned char))
{
for(unsigned i = 0; i<data.size(); i++)
{
unsigned char d = data[i];
for(unsigned j=0; j<CYCLE; j++)
{
d = (*f)(d);
}
data[i] = d;
}
}
vector<double> f_dist(vector<unsigned char>& in)
{
vector<double> fdist;
fdist.resize(256);
for(unsigned i = 0; i<in.size(); i++)
{
fdist[in[i]]++;
}
for(unsigned i=0; i<fdist.size(); i++)
{
fdist[i] = (fdist[i] / in.size()) * 100;
}
return fdist;
}
double s_entropy(vector<double>& v)
{
double entropy = 0;
double p;
for(unsigned i = 0; i < v.size(); i++)
{
p = v[i] / 100;
if (p == 0) continue;
entropy += p * std::log(p) / std::log(2);
}
return -entropy;
}
void rms(const string& s, string& r)
{
for(unsigned int i=0; i<s.size(); i++)
{
if(::isspace(s[i])) continue;
r+= s[i];
}
}
//add extended euc
double sw(double weight, int i, int j, int (*inv)(int, int))
{
return weight*(*inv)(i, j);
}
//Suggest we wrap these routines in a base class in particular for testing
//and expose test api
void hPerm(int s, int n, void (*p)(int), void (*inv)(int, int), void (*center)(int))
{
if(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST] == s)
{
(*center)(s);
return;
}
if(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST ] == s)
{
(*p)(s);
return;
}
if(s == 1)
{
(*p)(n);
return;
}
for(int i=0; i< s; i++)
{
hPerm(s-1, n, p, inv, p);
if(s%2 == 1)
(*inv)(0, s-1);
else
(*inv)(i, s-1);
}
}
double ic(const string& t)
{
string text; rms(t, text);
vector<double> freq(256,0);
for(unsigned int i=0; i<text.size(); i++)
{
if(text[i] == ' ') continue;
freq[text[i]] ++;
}
double sum=0;
for(unsigned int i=0; i<freq.size(); i++)
{
if(freq[i] != 0)
{
double c = freq[i];
if(c != 0)
sum += c * (c - 1);
}
}
double ic = 26 * sum / (text.size() * (text.size() - 1));
return ic;
}
int outer_sect(int (*s)(int), int (*t)(int), int r, int q)
{
return (*s)(r) * (*t)(q);
}
void switchIO(unsigned char (*p)(unsigned char, unsigned char), unsigned char m)
{
//test seq
(*p)(transition_seq[ENTRY_LINK__], m);
(*p)(transition_seq[ENTRY_LINK__TEST], m);
(*p)(transition_seq[ENTRY_C_REF_ECM], m);
(*p)(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST ], m);
(*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_LINK__TEST]);
(*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_C_REF_ECM]);
}
//Suggest we wrap these in util base class, abstract col cont
std::tuple<int, int, int> extended_gcd(int __alpha, int __beta, int (*col)(int x, int y))
{
if(__alpha == 0) return make_tuple(__beta,0,1);
int __com=0;
int x=0;
int y=0;
tie(__com, x, y) = extended_gcd(__beta%__alpha, __alpha, col);
return make_tuple(__com, y-(__beta/__alpha)*x, x);
}
std::tuple<int, int, int> extended_gcd(int __alpha, int __beta)
{
if(__alpha == 0) return make_tuple(__beta,0,1);
int __com=0;
int x=0;
int y=0;
tie(__com, x, y) = extended_gcd(__beta%__alpha, __alpha);
return make_tuple(__com, y-(__beta/__alpha)*x, x);
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <queue>
#include <vector>
#include <utility>
#include <iostream>
#include <string>
#include <stack>
#include <queue>
using namespace std;
queue<string> lv1;
queue<string> lv2;
queue<string> lv3;
string temp;
int templv;
int temptime=0;
int usernum;
int users=0;
int read(int now){
if(now < temptime || users>usernum) return 0;
do{
if(temp.empty()){
}else{
switch(templv){
case 1:
lv1.push(temp);break;
case 2:
lv2.push(temp);break;
case 3:
lv3.push(temp);break;
}
}
users++;
if(users<=usernum){
cin >>temptime>>templv>>temp;
}
else
return 0;
}while(temptime<=now);
}
int pop(){
if(lv3.size()>0){
cout<<lv3.front()<<endl;
lv3.pop();
return 3;
}
if(lv2.size()>0){
cout<<lv2.front()<<endl;
lv2.pop();
return 2;
}
if(lv1.size()>0){
cout<<lv1.front()<<endl;
lv1.pop();
return 1;
}
return 0;
}
int main(int argc, char const *argv[])
{
int time;
scanf("%d%d",&usernum,&time);
for (int i = 0; i < time; ++i)
{
read(i);
//cout<<i<<"\n"<<lv1.size()<<lv2.size()<<lv3.size()<<endl;
if(i%5==0)
pop();
}
//while(pop()){}
return 0;
}<commit_msg>update uoj2254<commit_after>#include <stdio.h>
#include <queue>
#include <vector>
#include <utility>
#include <iostream>
#include <string>
#include <stack>
#include <queue>
using namespace std;
queue<string> lv1;
queue<string> lv2;
queue<string> lv3;
queue<string> lv4;
string temp;
int templv;
int temptime=0;
int usernum;
int users=0;
int read(int now){
if(now < temptime || users>usernum) return 0;
do{
if(temp.empty()){
}else{
switch(templv){
case 1:
lv1.push(temp);break;
case 2:
lv2.push(temp);break;
case 3:
lv3.push(temp);break;
case 4:
lv4.push(temp);break;
}
}
users++;
if(users<=usernum){
cin >>temptime>>templv>>temp;
}
else
return 0;
}while(temptime<=now);
}
int pop(){
if(lv4.size()>0){
cout<<lv4.front()<<endl;
lv4.pop();
return 4;
}
if(lv3.size()>0){
cout<<lv3.front()<<endl;
lv3.pop();
return 3;
}
if(lv2.size()>0){
cout<<lv2.front()<<endl;
lv2.pop();
return 2;
}
if(lv1.size()>0){
cout<<lv1.front()<<endl;
lv1.pop();
return 1;
}
return 0;
}
int main(int argc, char const *argv[])
{
int time;
scanf("%d%d",&usernum,&time);
for (int i = 0; i < time; ++i)
{
read(i);
//cout<<i<<"\n"<<lv1.size()<<lv2.size()<<lv3.size()<<endl;
if(i%5==0)
pop();
}
//while(pop()){}
return 0;
}<|endoftext|>
|
<commit_before>#include "tictactoe.h"
#include <iostream>
#include <utility>
using namespace std;
const string TicTacToe::SPACE = " ";
const int TicTacToe::X = 1;
const int TicTacToe::O = 2;
const string TicTacToe::LINE = "-----------";
TicTacToe::TicTacToe() {
for(int row = 0; row < 3; row++) {
for(int col = 0; col < 3; col++) {
board[row][col] = 0;
}
}
}
void TicTacToe::draw_board() {
cout << LINE << endl;
for(int row = 0; row < 3; row++) {
cout << "|";
for(int col = 0; col < 3; col++) {
cout << char_map[board[row][col]] << (col == 2 ? "|" : SPACE);
}
cout << endl;
}
cout << LINE << endl;
}
bool TicTacToe::game_over() {
return check_rows() || check_cols() || check_diagonals();
}
bool TicTacToe::check_rows() {
for(int row = 0; row < 3; row++) {
if( ((board[row][0] == board[row][1]) && (board[row][0] == board[row][2])) && board[row][0]) {
return true;
}
}
return false;
}
bool TicTacToe::check_cols() {
for(int col = 0; col < 3; col++) {
if( ((board[0][col] == board[1][col]) && (board[0][col] == board[2][col])) && board[0][col]) {
return true;
}
}
return false;
}
bool TicTacToe::check_diagonals() {
if( (board[1][1] > 0) && (
(board[0][0] == board[1][1] && board[0][0] == board[2][2]) || (board[0][2] == board[1][1] && board[0][2] == board[2][0])
)
) {
return true;
}
return false;
}
bool TicTacToe::check_move(int row, int col) {
if (row > 2 || col > 2) {
return false;
}
return board[row][col] == 0;
}
bool TicTacToe::player_move(int row, int col, int player) {
if(check_move(row, col)) {
board[row][col] = player;
return true;
}
return false;
}
void TicTacToe::start() {
draw_board();
pair<int, int> Players(X, O);
pair<int, int> Swapped(O, X);
int row, column;
while(!game_over()) {
cout << "Player " << char_map[Players.first] << ", make your move, row and column on separate lines" << endl;
cin >> row >> column;
if (cin.fail()) {
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
if(player_move(row, column, Players.first)) {
draw_board();
swap(Players, Swapped);
} else {
draw_board();
}
}
draw_board();
cout << "Game Over" << endl;
return;
}
<commit_msg>Unsigned short int for rows, columns<commit_after>#include "tictactoe.h"
#include <iostream>
#include <utility>
using namespace std;
const string TicTacToe::SPACE = " ";
const int TicTacToe::X = 1;
const int TicTacToe::O = 2;
const string TicTacToe::LINE = "-----------";
TicTacToe::TicTacToe() {
for(int row = 0; row < 3; row++) {
for(int col = 0; col < 3; col++) {
board[row][col] = 0;
}
}
}
void TicTacToe::draw_board() {
cout << LINE << endl;
for(int row = 0; row < 3; row++) {
cout << "|";
for(int col = 0; col < 3; col++) {
cout << char_map[board[row][col]] << (col == 2 ? "|" : SPACE);
}
cout << endl;
}
cout << LINE << endl;
}
bool TicTacToe::game_over() {
return check_rows() || check_cols() || check_diagonals();
}
bool TicTacToe::check_rows() {
for(int row = 0; row < 3; row++) {
if( ((board[row][0] == board[row][1]) && (board[row][0] == board[row][2])) && board[row][0]) {
return true;
}
}
return false;
}
bool TicTacToe::check_cols() {
for(int col = 0; col < 3; col++) {
if( ((board[0][col] == board[1][col]) && (board[0][col] == board[2][col])) && board[0][col]) {
return true;
}
}
return false;
}
bool TicTacToe::check_diagonals() {
if( (board[1][1] > 0) && (
(board[0][0] == board[1][1] && board[0][0] == board[2][2]) || (board[0][2] == board[1][1] && board[0][2] == board[2][0])
)
) {
return true;
}
return false;
}
bool TicTacToe::check_move(int row, int col) {
if (row > 2 || col > 2) {
return false;
}
return board[row][col] == 0;
}
bool TicTacToe::player_move(int row, int col, int player) {
if(check_move(row, col)) {
board[row][col] = player;
return true;
}
return false;
}
void TicTacToe::start() {
draw_board();
pair<int, int> Players(X, O);
pair<int, int> Swapped(O, X);
short unsigned int row, column;
while(!game_over()) {
cout << "Player " << char_map[Players.first] << ", make your move, row and column on separate lines" << endl;
cin >> row >> column;
if (cin.fail()) {
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
if(player_move(row, column, Players.first)) {
draw_board();
swap(Players, Swapped);
} else {
draw_board();
}
}
draw_board();
cout << "Game Over" << endl;
return;
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <vector>
#define OK 1
#define ERROR 0
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define ElemType int
using namespace std;
int main()
{
std::vector<ElemType> v;
int a, i;
ElemType e, x;
if(v.empty()) // 判断顺序表是否创建成功
{
printf("A Sequence List Has Created.\n");
}
while(1)
{
printf("1:Insert element\n2:Delete element\n3:Load all elements\n0:Exit\nPlease choose:\n");
scanf("%d",&a);
switch(a)
{
case 1: scanf("%d%d",&i,&x);
vector<ElemType>::iterator I;
I = v.begin()+i;
if(v.insert(I,x)) printf("Insert Error!\n"); // 判断i值是否合法,请填空
else printf("The Element %d is Successfully Inserted!\n", x);
break;
case 2: scanf("%d",&i);
vector<ElemType>::iterator I = v.begin();
I=I+i;
if(v.erase(I)) printf("Delete Error!\n"); // 判断i值是否合法,请填空
else printf("The Element %d is Successfully Deleted!\n", e);
break;
case 3:
vector<ElemType>::iterator tempIterator;
for( tempIterator = v.begin(); tempIterator != v.end(); tempIterator++ )
cout << *tempIterator;
cout << endl;
break;
case 0: return 1;
}
}
}<commit_msg>update uoj8576<commit_after>#include <stdio.h>
#include <vector>
#define OK 1
#define ERROR 0
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define ElemType int
using namespace std;
int main()
{
std::vector<ElemType> v;
int a, i;
ElemType e, x;
if(v.empty()) // 判断顺序表是否创建成功
{
printf("A Sequence List Has Created.\n");
}
while(1)
{
printf("1:Insert element\n2:Delete element\n3:Load all elements\n0:Exit\nPlease choose:\n");
scanf("%d",&a);
switch(a)
{
case 1: scanf("%d%d",&i,&x);
if(v.insert(v.begin()+i,x)) printf("Insert Error!\n"); // 判断i值是否合法,请填空
else printf("The Element %d is Successfully Inserted!\n", x);
break;
case 2: scanf("%d",&i);
vector<ElemType>::iterator I = v.begin();
I=I+i;
if(v.erase(I)) printf("Delete Error!\n"); // 判断i值是否合法,请填空
else printf("The Element %d is Successfully Deleted!\n", e);
break;
case 3:
vector<ElemType>::iterator tempIterator;
for( tempIterator = v.begin(); tempIterator != v.end(); tempIterator++ )
cout << *tempIterator;
cout << endl;
break;
case 0: return 1;
}
}
}<|endoftext|>
|
<commit_before>// Copyright (c) 2014-2018 The Crown developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "updater.h"
#include "clientversion.h"
#include "util.h"
#include "chainparams.h"
#include "rpcprotocol.h"
#include <stdio.h>
#include <curl/curl.h>
#include <boost/thread.hpp>
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
struct DownloadProgress {
double lastruntime;
CURL *curl;
void(*progressFunction)(curl_off_t, curl_off_t);
};
// Global updater instance
Updater updater;
Updater::Updater() :
os(DetectOS()),
status(false),
version(-1),
stopDownload(false),
url("https://raw.githubusercontent.com/Crowndev/crowncoin/master/update.json")
{
}
Updater::OS Updater::DetectOS()
{
OS os = Updater::LINUX_32;
#ifdef _WIN32
os = Updater::WINDOWS_32;
#ifdef _WIN64
os = Updater::WINDOWS_64;
#endif
#elif __APPLE__
os = Updater::MAC_OS;
#elif __linux__
os = Updater::LINUX_32;
#if defined(__i386__) || defined(__i686__) || defined(__i486__) || defined(__i586__)
os = Updater::LINUX_32;
#elif defined(__x86_64__) || defined(__amd64__)
os = Updater::LINUX_64;
#endif
#endif
return os;
}
size_t GetUpdateData(const char *data, size_t size, size_t nmemb, std::string *updateData) {
size_t len = size * nmemb;
if (updateData != NULL)
{
// Append the data to the buffer
updateData->append(data, len);
}
return len;
}
Value Updater::ParseJson(std::string info)
{
Value value;
json_spirit::read_string(info, value);
return value;
}
bool Updater::NeedToBeUpdated()
{
if (jsonData.type() == obj_type)
{
Value version = find_value(jsonData.get_obj(), "NeedToBeUpdated");
if (version.type() == bool_type)
{
return version.get_bool();
}
}
return false;
}
void Updater::SetJsonPath()
{
updaterInfoUrl = url;
if (mapArgs.count("-updateurl"))
{
updaterInfoUrl = mapArgs["-updateurl"];
}
}
void Updater::LoadUpdateInfo()
{
CURL *curl;
std::string updateData;
SetJsonPath();
CURLcode res = CURLE_FAILED_INIT;
curl = curl_easy_init();
if (curl)
{
curl_easy_setopt(curl, CURLOPT_URL, updaterInfoUrl.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, GetUpdateData);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &updateData);
res = curl_easy_perform(curl);
if (res == CURLE_OK)
{
long response_code;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
if (response_code == HTTP_OK)
{
CheckAndUpdateStatus(updateData);
}
else
{
LogPrintf("Updater::GetUpdateInfo() - Error! Server response code - %d\n", response_code);
throw std::runtime_error(strprintf("Error! Failed to get update information. \nServer response code - %d\n", response_code));
}
}
else
{
LogPrintf("Updater::GetUpdateInfo() - Error! Couldn't get data json. Error code - %d\n", res);
throw std::runtime_error(strprintf("Error! Couldn't get data json. Error code - %d\n", res));
}
curl_easy_cleanup(curl);
}
}
std::string Updater::GetOsString(boost::optional<OS> os)
{
if (!os) {
return GetOsString(GetOS());
}
switch(os.get()) {
case Updater::LINUX_32:
return "Linux32";
case Updater::LINUX_64:
return "Linux64";
case Updater::WINDOWS_32:
return "Win32";
case Updater::WINDOWS_64:
return "Win64";
case Updater::MAC_OS:
return "Osx";
default:
assert(false);
}
return "";
}
std::string Updater::GetUrl(const Value& value)
{
if (value.type() == obj_type)
{
Value urlValue = find_value(value.get_obj(), "Url");
if (urlValue.type() == str_type)
{
return urlValue.get_str();
}
}
return "";
}
std::string Updater::GetSha256sum(Value value)
{
if (value.type() == obj_type)
{
Value sha256sumValue = find_value(value.get_obj(), "sha256sum");
if (sha256sumValue.type() == str_type)
{
return sha256sumValue.get_str();
}
}
return "";
}
int Updater::GetVersionFromJson()
{
if (jsonData.type() == obj_type)
{
Value version = find_value(jsonData.get_obj(), "Version");
if (version.type() == int_type)
{
return version.get_int();
}
}
return -1;
}
std::string Updater::GetDownloadUrl(boost::optional<OS> version)
{
Value json = find_value(jsonData.get_obj(), GetOsString(version));
return GetUrl(json);
}
std::string Updater::GetDownloadSha256Sum(boost::optional<OS> version)
{
Value json = find_value(jsonData.get_obj(), GetOsString(version));
return GetSha256sum(json);
}
static size_t write_data(void *ptr, size_t size, size_t nmemb, const void *stream)
{
size_t written = fwrite(ptr, size, nmemb, (FILE *)stream);
return written;
}
static int xferinfo(void *p,
curl_off_t dltotal, curl_off_t dlnow,
curl_off_t ultotal, curl_off_t ulnow)
{
struct DownloadProgress *myp = (struct DownloadProgress*)p;
myp->progressFunction(dlnow, dltotal);
return updater.GetStopDownload();
}
void Updater::DownloadFileAsync(std::string url, std::string fileName, void(progressFunction)(curl_off_t, curl_off_t))
{
boost::thread t(boost::bind(&Updater::DownloadFile, this, url, fileName, progressFunction));
}
CURLcode Updater::DownloadFile(std::string url, std::string fileName, void(progressFunction)(curl_off_t, curl_off_t))
{
stopDownload = false;
CURL *curl_handle;
struct DownloadProgress prog;
prog.progressFunction = progressFunction;
FILE *pagefile;
CURLcode res = CURLE_FAILED_INIT;
curl_global_init(CURL_GLOBAL_ALL);
curl_handle = curl_easy_init();
curl_easy_setopt(curl_handle, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 0L);
curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl_handle, CURLOPT_XFERINFOFUNCTION, xferinfo);
curl_easy_setopt(curl_handle, CURLOPT_XFERINFODATA, &prog);
pagefile = fopen(fileName.c_str(), "wb");
if(pagefile) {
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, pagefile);
res = curl_easy_perform(curl_handle);
fclose(pagefile);
}
curl_easy_cleanup(curl_handle);
if (res != CURLE_OK)
{
LogPrintf("Updater::DownloadFile() - Error! Failed to download file - %s. Error code - %d\n", url, res);
}
return res;
}
void Updater::StopDownload()
{
stopDownload = true;
}
void Updater::CheckAndUpdateStatus(const std::string& updateData)
{
jsonData = ParseJson(updateData);
version = GetVersionFromJson();
LogPrintf("Updater::GetUpdateInfo() - Got version from json: %d\n", version);
if (version > CLIENT_VERSION && NeedToBeUpdated())
{
LogPrintf("Updater::GetUpdateInfo() - Version is old\n");
// There is an update
status = true;
}
}
bool Updater::GetStatus()
{
LoadUpdateInfo();
return status;
}
<commit_msg>Fixed certificate issue<commit_after>// Copyright (c) 2014-2018 The Crown developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "updater.h"
#include "clientversion.h"
#include "util.h"
#include "chainparams.h"
#include "rpcprotocol.h"
#include <stdio.h>
#include <curl/curl.h>
#include <boost/thread.hpp>
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
struct DownloadProgress {
double lastruntime;
CURL *curl;
void(*progressFunction)(curl_off_t, curl_off_t);
};
// Global updater instance
Updater updater;
Updater::Updater() :
os(DetectOS()),
status(false),
version(-1),
stopDownload(false),
url("https://raw.githubusercontent.com/Crowndev/crowncoin/master/update.json")
{
}
Updater::OS Updater::DetectOS()
{
OS os = Updater::LINUX_32;
#ifdef _WIN32
os = Updater::WINDOWS_32;
#ifdef _WIN64
os = Updater::WINDOWS_64;
#endif
#elif __APPLE__
os = Updater::MAC_OS;
#elif __linux__
os = Updater::LINUX_32;
#if defined(__i386__) || defined(__i686__) || defined(__i486__) || defined(__i586__)
os = Updater::LINUX_32;
#elif defined(__x86_64__) || defined(__amd64__)
os = Updater::LINUX_64;
#endif
#endif
return os;
}
size_t GetUpdateData(const char *data, size_t size, size_t nmemb, std::string *updateData) {
size_t len = size * nmemb;
if (updateData != NULL)
{
// Append the data to the buffer
updateData->append(data, len);
}
return len;
}
Value Updater::ParseJson(std::string info)
{
Value value;
json_spirit::read_string(info, value);
return value;
}
bool Updater::NeedToBeUpdated()
{
if (jsonData.type() == obj_type)
{
Value version = find_value(jsonData.get_obj(), "NeedToBeUpdated");
if (version.type() == bool_type)
{
return version.get_bool();
}
}
return false;
}
void Updater::SetJsonPath()
{
updaterInfoUrl = url;
if (mapArgs.count("-updateurl"))
{
updaterInfoUrl = mapArgs["-updateurl"];
}
}
void Updater::LoadUpdateInfo()
{
CURL *curl;
std::string updateData;
SetJsonPath();
CURLcode res = CURLE_FAILED_INIT;
curl = curl_easy_init();
if (curl)
{
curl_easy_setopt(curl, CURLOPT_URL, updaterInfoUrl.c_str());
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, GetUpdateData);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &updateData);
res = curl_easy_perform(curl);
if (res == CURLE_OK)
{
long response_code;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
if (response_code == HTTP_OK)
{
CheckAndUpdateStatus(updateData);
}
else
{
LogPrintf("Updater::GetUpdateInfo() - Error! Server response code - %d\n", response_code);
throw std::runtime_error(strprintf("Error! Failed to get update information. \nServer response code - %d\n", response_code));
}
}
else
{
LogPrintf("Updater::GetUpdateInfo() - Error! Couldn't get data json. Error code - %d\n", res);
throw std::runtime_error(strprintf("Error! Couldn't get data json. Error code - %d\n", res));
}
curl_easy_cleanup(curl);
}
}
std::string Updater::GetOsString(boost::optional<OS> os)
{
if (!os) {
return GetOsString(GetOS());
}
switch(os.get()) {
case Updater::LINUX_32:
return "Linux32";
case Updater::LINUX_64:
return "Linux64";
case Updater::WINDOWS_32:
return "Win32";
case Updater::WINDOWS_64:
return "Win64";
case Updater::MAC_OS:
return "Osx";
default:
assert(false);
}
return "";
}
std::string Updater::GetUrl(const Value& value)
{
if (value.type() == obj_type)
{
Value urlValue = find_value(value.get_obj(), "Url");
if (urlValue.type() == str_type)
{
return urlValue.get_str();
}
}
return "";
}
std::string Updater::GetSha256sum(Value value)
{
if (value.type() == obj_type)
{
Value sha256sumValue = find_value(value.get_obj(), "sha256sum");
if (sha256sumValue.type() == str_type)
{
return sha256sumValue.get_str();
}
}
return "";
}
int Updater::GetVersionFromJson()
{
if (jsonData.type() == obj_type)
{
Value version = find_value(jsonData.get_obj(), "Version");
if (version.type() == int_type)
{
return version.get_int();
}
}
return -1;
}
std::string Updater::GetDownloadUrl(boost::optional<OS> version)
{
Value json = find_value(jsonData.get_obj(), GetOsString(version));
return GetUrl(json);
}
std::string Updater::GetDownloadSha256Sum(boost::optional<OS> version)
{
Value json = find_value(jsonData.get_obj(), GetOsString(version));
return GetSha256sum(json);
}
static size_t write_data(void *ptr, size_t size, size_t nmemb, const void *stream)
{
size_t written = fwrite(ptr, size, nmemb, (FILE *)stream);
return written;
}
static int xferinfo(void *p,
curl_off_t dltotal, curl_off_t dlnow,
curl_off_t ultotal, curl_off_t ulnow)
{
struct DownloadProgress *myp = (struct DownloadProgress*)p;
myp->progressFunction(dlnow, dltotal);
return updater.GetStopDownload();
}
void Updater::DownloadFileAsync(std::string url, std::string fileName, void(progressFunction)(curl_off_t, curl_off_t))
{
boost::thread t(boost::bind(&Updater::DownloadFile, this, url, fileName, progressFunction));
}
CURLcode Updater::DownloadFile(std::string url, std::string fileName, void(progressFunction)(curl_off_t, curl_off_t))
{
stopDownload = false;
CURL *curl_handle;
struct DownloadProgress prog;
prog.progressFunction = progressFunction;
FILE *pagefile;
CURLcode res = CURLE_FAILED_INIT;
curl_global_init(CURL_GLOBAL_ALL);
curl_handle = curl_easy_init();
curl_easy_setopt(curl_handle, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, false);
curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 0L);
curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl_handle, CURLOPT_XFERINFOFUNCTION, xferinfo);
curl_easy_setopt(curl_handle, CURLOPT_XFERINFODATA, &prog);
pagefile = fopen(fileName.c_str(), "wb");
if(pagefile) {
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, pagefile);
res = curl_easy_perform(curl_handle);
fclose(pagefile);
}
curl_easy_cleanup(curl_handle);
if (res != CURLE_OK)
{
LogPrintf("Updater::DownloadFile() - Error! Failed to download file - %s. Error code - %d\n", url, res);
}
return res;
}
void Updater::StopDownload()
{
stopDownload = true;
}
void Updater::CheckAndUpdateStatus(const std::string& updateData)
{
jsonData = ParseJson(updateData);
version = GetVersionFromJson();
LogPrintf("Updater::GetUpdateInfo() - Got version from json: %d\n", version);
if (version > CLIENT_VERSION && NeedToBeUpdated())
{
LogPrintf("Updater::GetUpdateInfo() - Version is old\n");
// There is an update
status = true;
}
}
bool Updater::GetStatus()
{
LoadUpdateInfo();
return status;
}
<|endoftext|>
|
<commit_before>#include <HsFFI.h>
#include <QtCore/QString>
#include <QtCore/QMutexLocker>
#include <QtQml/QQmlEngine>
#include "Object.h"
#include "Class.h"
#include "Manager.h"
static const char* cRefSrcNames[] = {"Hndl", "Weak", "Obj", "Event", "Var"};
HsQMLObjectFinaliser::HsQMLObjectFinaliser(HsQMLObjFinaliserCb cb)
: mFinaliseCb(cb)
{}
HsQMLObjectFinaliser::~HsQMLObjectFinaliser()
{
gManager->freeFun(reinterpret_cast<HsFunPtr>(mFinaliseCb));
}
void HsQMLObjectFinaliser::finalise(HsQMLObjectProxy* proxy) const
{
mFinaliseCb(reinterpret_cast<HsQMLObjectHandle*>(proxy));
}
HsQMLObjectProxy::HsQMLObjectProxy(HsStablePtr haskell, HsQMLClass* klass)
: mHaskell(haskell)
, mKlass(klass)
, mSerial(gManager->updateCounter(HsQMLManager::ObjectSerial, 1))
, mObject(NULL)
, mRefCount(0)
{
ref(Handle);
mKlass->ref(HsQMLClass::ObjProxy);
gManager->updateCounter(HsQMLManager::ObjectCount, 1);
}
HsQMLObjectProxy::~HsQMLObjectProxy()
{
mKlass->deref(HsQMLClass::ObjProxy);
gManager->updateCounter(HsQMLManager::ObjectCount, -1);
}
HsStablePtr HsQMLObjectProxy::haskell() const
{
return mHaskell;
}
HsQMLClass* HsQMLObjectProxy::klass() const
{
return mKlass;
}
HsQMLObject* HsQMLObjectProxy::object(HsQMLEngine* engine)
{
Q_ASSERT(gManager->isEventThread());
Q_ASSERT(engine);
if (!mObject) {
mObject = new HsQMLObject(this, engine);
HSQML_LOG(5,
QString().sprintf("New QObject, class=%s, id=%d, qptr=%p.",
mKlass->name(), mSerial, mObject));
}
// Old objects may have lost their lock via weak references in addition
// to new objects needing it.
tryGCLock();
return mObject;
}
void HsQMLObjectProxy::clearObject()
{
Q_ASSERT(gManager->isEventThread());
HSQML_LOG(5,
QString().sprintf("Release QObject, class=%s, id=%d, qptr=%p.",
mKlass->name(), mSerial, mObject));
mObject = NULL;
runFinalisers();
}
void HsQMLObjectProxy::tryGCLock()
{
Q_ASSERT(gManager->isEventThread());
if (mObject && mHndlCount.loadAcquire() > 0 && !mObject->isGCLocked()) {
mObject->setGCLock();
HSQML_LOG(5,
QString().sprintf("Lock QObject, class=%s, id=%d, qptr=%p.",
mKlass->name(), mSerial, mObject));
}
}
void HsQMLObjectProxy::removeGCLock()
{
Q_ASSERT(gManager->isEventThread());
if (mObject && mHndlCount.loadAcquire() == 0) {
if (mObject->isGCLocked()) {
mObject->clearGCLock();
HSQML_LOG(5,
QString().sprintf("Unlock QObject, class=%s, id=%d, qptr=%p.",
mKlass->name(), mSerial, mObject));
}
else {
// If there had been a QML object then this would have happened
// when the QML GC collected it.
runFinalisers();
}
}
}
void HsQMLObjectProxy::addFinaliser(const HsQMLObjectFinaliser::Ref& f)
{
QMutexLocker locker(&mFinaliseMutex);
mFinalisers.append(f);
}
void HsQMLObjectProxy::runFinalisers()
{
// Copy and clear finalisers under lock
mFinaliseMutex.lock();
const Finalisers fs = mFinalisers;
mFinalisers.clear();
mFinaliseMutex.unlock();
// Call finalisers outside lock so they can re-addFinaliser()
Q_FOREACH(const HsQMLObjectFinaliser::Ref& f, fs) {
ref(Handle);
f->finalise(this);
}
}
HsQMLEngine* HsQMLObjectProxy::engine() const
{
if (mObject != NULL) {
return mObject->engine();
}
return NULL;
}
void HsQMLObjectProxy::ref(RefSrc src)
{
int count = mRefCount.fetchAndAddOrdered(1);
HSQML_LOG(count == 0 ? 3 : 4,
QString().sprintf("%s ObjProxy, class=%s, id=%d, src=%s, count=%d.",
count ? "Ref" : "New", mKlass->name(),
mSerial, cRefSrcNames[src], count+1));
if (src == Handle || src == Variant) {
mHndlCount.fetchAndAddOrdered(1);
}
}
void HsQMLObjectProxy::deref(RefSrc src)
{
// Remove JavaScript GC lock when there are no strong handles
if (src == Handle || src == Variant) {
int hndlCount = mHndlCount.fetchAndAddOrdered(-1);
if (hndlCount == 1 && mObject) {
if (src == Handle) {
// Handles can be dereferenced from any thread. The event will
// remove the lock if there are still no handles by the time
// it reaches the event loop.
gManager->postObjectEvent(new HsQMLObjectEvent(this));
}
else {
removeGCLock();
}
}
}
int count = mRefCount.fetchAndAddOrdered(-1);
HSQML_LOG(count == 1 ? 3 : 4,
QString().sprintf("%s ObjProxy, class=%s, id=%d, src=%s, count=%d.",
count > 1 ? "Deref" : "Delete", mKlass->name(),
mSerial, cRefSrcNames[src], count));
if (count == 1) {
delete this;
}
}
HsQMLObjectEvent::HsQMLObjectEvent(HsQMLObjectProxy* proxy)
: QEvent(HsQMLManagerApp::RemoveGCLockEvent)
, mProxy(proxy)
{
mProxy->ref(HsQMLObjectProxy::Event);
}
HsQMLObjectEvent::~HsQMLObjectEvent()
{
mProxy->deref(HsQMLObjectProxy::Event);
}
void HsQMLObjectEvent::process()
{
Q_ASSERT(type() == HsQMLManagerApp::RemoveGCLockEvent);
mProxy->removeGCLock();
}
HsQMLObject::HsQMLObject(HsQMLObjectProxy* proxy, HsQMLEngine* engine)
: mProxy(proxy)
, mHaskell(proxy->haskell())
, mKlass(proxy->klass())
, mEngine(engine)
{
QQmlEngine::setObjectOwnership(
this, QQmlEngine::JavaScriptOwnership);
mProxy->ref(HsQMLObjectProxy::Object);
gManager->registerObject(this);
gManager->updateCounter(HsQMLManager::QObjectCount, 1);
}
HsQMLObject::~HsQMLObject()
{
mProxy->clearObject();
mProxy->deref(HsQMLObjectProxy::Object);
gManager->unregisterObject(this);
gManager->updateCounter(HsQMLManager::QObjectCount, -1);
}
const QMetaObject* HsQMLObject::metaObject() const
{
return QObject::d_ptr->metaObject ?
QObject::d_ptr->dynamicMetaObject() : mKlass->metaObj();
}
void* HsQMLObject::qt_metacast(const char* clname)
{
if (!clname) {
return 0;
}
if (!strcmp(clname, mKlass->metaObj()->className())) {
return static_cast<void*>(const_cast<HsQMLObject*>(this));
}
return QObject::qt_metacast(clname);
}
int HsQMLObject::qt_metacall(QMetaObject::Call c, int id, void** a)
{
id = QObject::qt_metacall(c, id, a);
if (id < 0) {
return id;
}
gManager->setActiveEngine(mEngine);
if (QMetaObject::InvokeMetaMethod == c) {
mKlass->methods()[id](this, a);
id -= mKlass->methodCount();
}
else if (QMetaObject::ReadProperty == c) {
mKlass->properties()[2*id](this, a);
id -= mKlass->propertyCount();
}
else if (QMetaObject::WriteProperty == c) {
HsQMLUniformFunc uf = mKlass->properties()[2*id+1];
if (uf) {
uf(this, a);
}
id -= mKlass->propertyCount();
}
else if (QMetaObject::QueryPropertyDesignable == c ||
QMetaObject::QueryPropertyScriptable == c ||
QMetaObject::QueryPropertyStored == c ||
QMetaObject::QueryPropertyEditable == c ||
QMetaObject::QueryPropertyUser == c) {
id -= mKlass->propertyCount();
}
gManager->setActiveEngine(NULL);
return id;
}
void HsQMLObject::setGCLock()
{
mGCLock = mEngine->declEngine()->newQObject(this);
}
void HsQMLObject::clearGCLock()
{
mGCLock = QJSValue(QJSValue::NullValue);
}
bool HsQMLObject::isGCLocked() const
{
return mGCLock.isQObject();
}
QJSValue* HsQMLObject::gcLockVar()
{
return &mGCLock;
}
HsQMLObjectProxy* HsQMLObject::proxy() const
{
return mProxy;
}
HsQMLEngine* HsQMLObject::engine() const
{
return mEngine;
}
extern "C" HsQMLObjectHandle* hsqml_create_object(
HsStablePtr haskell, HsQMLClassHandle* kHndl)
{
HsQMLObjectProxy* proxy = new HsQMLObjectProxy(haskell, (HsQMLClass*)kHndl);
return (HsQMLObjectHandle*)proxy;
}
extern "C" int hsqml_object_set_active(
HsQMLObjectHandle* hndl)
{
HsQMLObjectProxy* proxy = (HsQMLObjectProxy*)hndl;
if (proxy) {
HsQMLEngine* engine = proxy->engine();
if (engine) {
gManager->setActiveEngine(engine);
}
else {
// Nothing can be done if the object hasn't been marshalled before
// because otherwise the relevant engine is unknown.
return false;
}
}
else {
gManager->setActiveEngine(NULL);
}
return true;
}
extern "C" HsStablePtr hsqml_object_get_hs_typerep(
HsQMLObjectHandle* hndl)
{
HsQMLObjectProxy* proxy = (HsQMLObjectProxy*)hndl;
return proxy->klass()->hsTypeRep();
}
extern HsStablePtr hsqml_object_get_hs_value(
HsQMLObjectHandle* hndl)
{
HsQMLObjectProxy* proxy = (HsQMLObjectProxy*)hndl;
return proxy->haskell();
}
extern void* hsqml_object_get_pointer(
HsQMLObjectHandle* hndl)
{
HsQMLObjectProxy* proxy = reinterpret_cast<HsQMLObjectProxy*>(hndl);
return (void*)proxy->object(gManager->activeEngine());
}
extern HsQMLJValHandle* hsqml_object_get_jval(
HsQMLObjectHandle* hndl)
{
HsQMLObjectProxy* proxy = reinterpret_cast<HsQMLObjectProxy*>(hndl);
HsQMLObject* obj = proxy->object(gManager->activeEngine());
return reinterpret_cast<HsQMLJValHandle*>(obj->gcLockVar());
}
extern HsQMLObjectHandle* hsqml_get_object_from_pointer(
void* ptr)
{
// Return NULL if the input pointer is NULL
if (!ptr) {
return NULL;
}
// Get object proxy
HsQMLObject* object = (HsQMLObject*)ptr;
HsQMLObjectProxy* proxy = object->proxy();
proxy->ref(HsQMLObjectProxy::Handle);
proxy->tryGCLock();
return (HsQMLObjectHandle*)proxy;
}
extern HsQMLObjectHandle* hsqml_get_object_from_jval(
HsQMLJValHandle* jvalHndl)
{
QJSValue* jval = reinterpret_cast<QJSValue*>(jvalHndl);
return hsqml_get_object_from_pointer(jval->toQObject());
}
extern void hsqml_object_reference_handle(
HsQMLObjectHandle* hndl,
int weak)
{
HsQMLObjectProxy* proxy = (HsQMLObjectProxy*)hndl;
proxy->ref(weak ? HsQMLObjectProxy::WeakHandle : HsQMLObjectProxy::Handle);
}
extern void hsqml_finalise_object_handle(
HsQMLObjectHandle* hndl)
{
if (hndl) {
HsQMLObjectProxy* proxy = (HsQMLObjectProxy*)hndl;
proxy->deref(HsQMLObjectProxy::Handle);
}
}
extern void hsqml_finalise_object_weak_handle(
HsQMLObjectHandle* hndl)
{
if (hndl) {
HsQMLObjectProxy* proxy = (HsQMLObjectProxy*)hndl;
proxy->deref(HsQMLObjectProxy::WeakHandle);
}
}
extern void hsqml_fire_signal(
HsQMLObjectHandle* hndl, int idx, void** args)
{
HsQMLObjectProxy* proxy = (HsQMLObjectProxy*)hndl;
HsQMLEngine* engine = proxy->engine();
// Ignore objects which haven't been marshalled as they are not connected.
if (engine) {
// Clear active engine in case the slot code calls back into Haskell.
Q_ASSERT(gManager->activeEngine() == engine);
gManager->setActiveEngine(NULL);
HsQMLObject* obj = proxy->object(engine);
QMetaObject::activate(obj, proxy->klass()->metaObj(), idx, args);
}
}
extern HsQMLObjFinaliserHandle* hsqml_create_obj_finaliser(
HsQMLObjFinaliserCb cb)
{
return reinterpret_cast<HsQMLObjFinaliserHandle*>(
new HsQMLObjectFinaliser::Ref(new HsQMLObjectFinaliser(cb)));
}
extern void hsqml_finalise_obj_finaliser(
HsQMLObjFinaliserHandle* hndl)
{
HsQMLObjectFinaliser::Ref* fp =
reinterpret_cast<HsQMLObjectFinaliser::Ref*>(hndl);
delete fp;
}
extern void hsqml_object_add_finaliser(
HsQMLObjectHandle* hndl, HsQMLObjFinaliserHandle* fhndl)
{
HsQMLObjectProxy* proxy = reinterpret_cast<HsQMLObjectProxy*>(hndl);
proxy->addFinaliser(*reinterpret_cast<HsQMLObjectFinaliser::Ref*>(fhndl));
}
<commit_msg>Fix leaking stable pointers when objects are collected.<commit_after>#include <HsFFI.h>
#include <QtCore/QString>
#include <QtCore/QMutexLocker>
#include <QtQml/QQmlEngine>
#include "Object.h"
#include "Class.h"
#include "Manager.h"
static const char* cRefSrcNames[] = {"Hndl", "Weak", "Obj", "Event", "Var"};
HsQMLObjectFinaliser::HsQMLObjectFinaliser(HsQMLObjFinaliserCb cb)
: mFinaliseCb(cb)
{}
HsQMLObjectFinaliser::~HsQMLObjectFinaliser()
{
gManager->freeFun(reinterpret_cast<HsFunPtr>(mFinaliseCb));
}
void HsQMLObjectFinaliser::finalise(HsQMLObjectProxy* proxy) const
{
mFinaliseCb(reinterpret_cast<HsQMLObjectHandle*>(proxy));
}
HsQMLObjectProxy::HsQMLObjectProxy(HsStablePtr haskell, HsQMLClass* klass)
: mHaskell(haskell)
, mKlass(klass)
, mSerial(gManager->updateCounter(HsQMLManager::ObjectSerial, 1))
, mObject(NULL)
, mRefCount(0)
{
ref(Handle);
mKlass->ref(HsQMLClass::ObjProxy);
gManager->updateCounter(HsQMLManager::ObjectCount, 1);
}
HsQMLObjectProxy::~HsQMLObjectProxy()
{
mKlass->deref(HsQMLClass::ObjProxy);
gManager->updateCounter(HsQMLManager::ObjectCount, -1);
gManager->freeStable(mHaskell);
}
HsStablePtr HsQMLObjectProxy::haskell() const
{
return mHaskell;
}
HsQMLClass* HsQMLObjectProxy::klass() const
{
return mKlass;
}
HsQMLObject* HsQMLObjectProxy::object(HsQMLEngine* engine)
{
Q_ASSERT(gManager->isEventThread());
Q_ASSERT(engine);
if (!mObject) {
mObject = new HsQMLObject(this, engine);
HSQML_LOG(5,
QString().sprintf("New QObject, class=%s, id=%d, qptr=%p.",
mKlass->name(), mSerial, mObject));
}
// Old objects may have lost their lock via weak references in addition
// to new objects needing it.
tryGCLock();
return mObject;
}
void HsQMLObjectProxy::clearObject()
{
Q_ASSERT(gManager->isEventThread());
HSQML_LOG(5,
QString().sprintf("Release QObject, class=%s, id=%d, qptr=%p.",
mKlass->name(), mSerial, mObject));
mObject = NULL;
runFinalisers();
}
void HsQMLObjectProxy::tryGCLock()
{
Q_ASSERT(gManager->isEventThread());
if (mObject && mHndlCount.loadAcquire() > 0 && !mObject->isGCLocked()) {
mObject->setGCLock();
HSQML_LOG(5,
QString().sprintf("Lock QObject, class=%s, id=%d, qptr=%p.",
mKlass->name(), mSerial, mObject));
}
}
void HsQMLObjectProxy::removeGCLock()
{
Q_ASSERT(gManager->isEventThread());
if (mObject && mHndlCount.loadAcquire() == 0) {
if (mObject->isGCLocked()) {
mObject->clearGCLock();
HSQML_LOG(5,
QString().sprintf("Unlock QObject, class=%s, id=%d, qptr=%p.",
mKlass->name(), mSerial, mObject));
}
else {
// If there had been a QML object then this would have happened
// when the QML GC collected it.
runFinalisers();
}
}
}
void HsQMLObjectProxy::addFinaliser(const HsQMLObjectFinaliser::Ref& f)
{
QMutexLocker locker(&mFinaliseMutex);
mFinalisers.append(f);
}
void HsQMLObjectProxy::runFinalisers()
{
// Copy and clear finalisers under lock
mFinaliseMutex.lock();
const Finalisers fs = mFinalisers;
mFinalisers.clear();
mFinaliseMutex.unlock();
// Call finalisers outside lock so they can re-addFinaliser()
Q_FOREACH(const HsQMLObjectFinaliser::Ref& f, fs) {
ref(Handle);
f->finalise(this);
}
}
HsQMLEngine* HsQMLObjectProxy::engine() const
{
if (mObject != NULL) {
return mObject->engine();
}
return NULL;
}
void HsQMLObjectProxy::ref(RefSrc src)
{
int count = mRefCount.fetchAndAddOrdered(1);
HSQML_LOG(count == 0 ? 3 : 4,
QString().sprintf("%s ObjProxy, class=%s, id=%d, src=%s, count=%d.",
count ? "Ref" : "New", mKlass->name(),
mSerial, cRefSrcNames[src], count+1));
if (src == Handle || src == Variant) {
mHndlCount.fetchAndAddOrdered(1);
}
}
void HsQMLObjectProxy::deref(RefSrc src)
{
// Remove JavaScript GC lock when there are no strong handles
if (src == Handle || src == Variant) {
int hndlCount = mHndlCount.fetchAndAddOrdered(-1);
if (hndlCount == 1 && mObject) {
if (src == Handle) {
// Handles can be dereferenced from any thread. The event will
// remove the lock if there are still no handles by the time
// it reaches the event loop.
gManager->postObjectEvent(new HsQMLObjectEvent(this));
}
else {
removeGCLock();
}
}
}
int count = mRefCount.fetchAndAddOrdered(-1);
HSQML_LOG(count == 1 ? 3 : 4,
QString().sprintf("%s ObjProxy, class=%s, id=%d, src=%s, count=%d.",
count > 1 ? "Deref" : "Delete", mKlass->name(),
mSerial, cRefSrcNames[src], count));
if (count == 1) {
delete this;
}
}
HsQMLObjectEvent::HsQMLObjectEvent(HsQMLObjectProxy* proxy)
: QEvent(HsQMLManagerApp::RemoveGCLockEvent)
, mProxy(proxy)
{
mProxy->ref(HsQMLObjectProxy::Event);
}
HsQMLObjectEvent::~HsQMLObjectEvent()
{
mProxy->deref(HsQMLObjectProxy::Event);
}
void HsQMLObjectEvent::process()
{
Q_ASSERT(type() == HsQMLManagerApp::RemoveGCLockEvent);
mProxy->removeGCLock();
}
HsQMLObject::HsQMLObject(HsQMLObjectProxy* proxy, HsQMLEngine* engine)
: mProxy(proxy)
, mHaskell(proxy->haskell())
, mKlass(proxy->klass())
, mEngine(engine)
{
QQmlEngine::setObjectOwnership(
this, QQmlEngine::JavaScriptOwnership);
mProxy->ref(HsQMLObjectProxy::Object);
gManager->registerObject(this);
gManager->updateCounter(HsQMLManager::QObjectCount, 1);
}
HsQMLObject::~HsQMLObject()
{
mProxy->clearObject();
mProxy->deref(HsQMLObjectProxy::Object);
gManager->unregisterObject(this);
gManager->updateCounter(HsQMLManager::QObjectCount, -1);
}
const QMetaObject* HsQMLObject::metaObject() const
{
return QObject::d_ptr->metaObject ?
QObject::d_ptr->dynamicMetaObject() : mKlass->metaObj();
}
void* HsQMLObject::qt_metacast(const char* clname)
{
if (!clname) {
return 0;
}
if (!strcmp(clname, mKlass->metaObj()->className())) {
return static_cast<void*>(const_cast<HsQMLObject*>(this));
}
return QObject::qt_metacast(clname);
}
int HsQMLObject::qt_metacall(QMetaObject::Call c, int id, void** a)
{
id = QObject::qt_metacall(c, id, a);
if (id < 0) {
return id;
}
gManager->setActiveEngine(mEngine);
if (QMetaObject::InvokeMetaMethod == c) {
mKlass->methods()[id](this, a);
id -= mKlass->methodCount();
}
else if (QMetaObject::ReadProperty == c) {
mKlass->properties()[2*id](this, a);
id -= mKlass->propertyCount();
}
else if (QMetaObject::WriteProperty == c) {
HsQMLUniformFunc uf = mKlass->properties()[2*id+1];
if (uf) {
uf(this, a);
}
id -= mKlass->propertyCount();
}
else if (QMetaObject::QueryPropertyDesignable == c ||
QMetaObject::QueryPropertyScriptable == c ||
QMetaObject::QueryPropertyStored == c ||
QMetaObject::QueryPropertyEditable == c ||
QMetaObject::QueryPropertyUser == c) {
id -= mKlass->propertyCount();
}
gManager->setActiveEngine(NULL);
return id;
}
void HsQMLObject::setGCLock()
{
mGCLock = mEngine->declEngine()->newQObject(this);
}
void HsQMLObject::clearGCLock()
{
mGCLock = QJSValue(QJSValue::NullValue);
}
bool HsQMLObject::isGCLocked() const
{
return mGCLock.isQObject();
}
QJSValue* HsQMLObject::gcLockVar()
{
return &mGCLock;
}
HsQMLObjectProxy* HsQMLObject::proxy() const
{
return mProxy;
}
HsQMLEngine* HsQMLObject::engine() const
{
return mEngine;
}
extern "C" HsQMLObjectHandle* hsqml_create_object(
HsStablePtr haskell, HsQMLClassHandle* kHndl)
{
HsQMLObjectProxy* proxy = new HsQMLObjectProxy(haskell, (HsQMLClass*)kHndl);
return (HsQMLObjectHandle*)proxy;
}
extern "C" int hsqml_object_set_active(
HsQMLObjectHandle* hndl)
{
HsQMLObjectProxy* proxy = (HsQMLObjectProxy*)hndl;
if (proxy) {
HsQMLEngine* engine = proxy->engine();
if (engine) {
gManager->setActiveEngine(engine);
}
else {
// Nothing can be done if the object hasn't been marshalled before
// because otherwise the relevant engine is unknown.
return false;
}
}
else {
gManager->setActiveEngine(NULL);
}
return true;
}
extern "C" HsStablePtr hsqml_object_get_hs_typerep(
HsQMLObjectHandle* hndl)
{
HsQMLObjectProxy* proxy = (HsQMLObjectProxy*)hndl;
return proxy->klass()->hsTypeRep();
}
extern HsStablePtr hsqml_object_get_hs_value(
HsQMLObjectHandle* hndl)
{
HsQMLObjectProxy* proxy = (HsQMLObjectProxy*)hndl;
return proxy->haskell();
}
extern void* hsqml_object_get_pointer(
HsQMLObjectHandle* hndl)
{
HsQMLObjectProxy* proxy = reinterpret_cast<HsQMLObjectProxy*>(hndl);
return (void*)proxy->object(gManager->activeEngine());
}
extern HsQMLJValHandle* hsqml_object_get_jval(
HsQMLObjectHandle* hndl)
{
HsQMLObjectProxy* proxy = reinterpret_cast<HsQMLObjectProxy*>(hndl);
HsQMLObject* obj = proxy->object(gManager->activeEngine());
return reinterpret_cast<HsQMLJValHandle*>(obj->gcLockVar());
}
extern HsQMLObjectHandle* hsqml_get_object_from_pointer(
void* ptr)
{
// Return NULL if the input pointer is NULL
if (!ptr) {
return NULL;
}
// Get object proxy
HsQMLObject* object = (HsQMLObject*)ptr;
HsQMLObjectProxy* proxy = object->proxy();
proxy->ref(HsQMLObjectProxy::Handle);
proxy->tryGCLock();
return (HsQMLObjectHandle*)proxy;
}
extern HsQMLObjectHandle* hsqml_get_object_from_jval(
HsQMLJValHandle* jvalHndl)
{
QJSValue* jval = reinterpret_cast<QJSValue*>(jvalHndl);
return hsqml_get_object_from_pointer(jval->toQObject());
}
extern void hsqml_object_reference_handle(
HsQMLObjectHandle* hndl,
int weak)
{
HsQMLObjectProxy* proxy = (HsQMLObjectProxy*)hndl;
proxy->ref(weak ? HsQMLObjectProxy::WeakHandle : HsQMLObjectProxy::Handle);
}
extern void hsqml_finalise_object_handle(
HsQMLObjectHandle* hndl)
{
if (hndl) {
HsQMLObjectProxy* proxy = (HsQMLObjectProxy*)hndl;
proxy->deref(HsQMLObjectProxy::Handle);
}
}
extern void hsqml_finalise_object_weak_handle(
HsQMLObjectHandle* hndl)
{
if (hndl) {
HsQMLObjectProxy* proxy = (HsQMLObjectProxy*)hndl;
proxy->deref(HsQMLObjectProxy::WeakHandle);
}
}
extern void hsqml_fire_signal(
HsQMLObjectHandle* hndl, int idx, void** args)
{
HsQMLObjectProxy* proxy = (HsQMLObjectProxy*)hndl;
HsQMLEngine* engine = proxy->engine();
// Ignore objects which haven't been marshalled as they are not connected.
if (engine) {
// Clear active engine in case the slot code calls back into Haskell.
Q_ASSERT(gManager->activeEngine() == engine);
gManager->setActiveEngine(NULL);
HsQMLObject* obj = proxy->object(engine);
QMetaObject::activate(obj, proxy->klass()->metaObj(), idx, args);
}
}
extern HsQMLObjFinaliserHandle* hsqml_create_obj_finaliser(
HsQMLObjFinaliserCb cb)
{
return reinterpret_cast<HsQMLObjFinaliserHandle*>(
new HsQMLObjectFinaliser::Ref(new HsQMLObjectFinaliser(cb)));
}
extern void hsqml_finalise_obj_finaliser(
HsQMLObjFinaliserHandle* hndl)
{
HsQMLObjectFinaliser::Ref* fp =
reinterpret_cast<HsQMLObjectFinaliser::Ref*>(hndl);
delete fp;
}
extern void hsqml_object_add_finaliser(
HsQMLObjectHandle* hndl, HsQMLObjFinaliserHandle* fhndl)
{
HsQMLObjectProxy* proxy = reinterpret_cast<HsQMLObjectProxy*>(hndl);
proxy->addFinaliser(*reinterpret_cast<HsQMLObjectFinaliser::Ref*>(fhndl));
}
<|endoftext|>
|
<commit_before>/*
* UsbDk filter/redirector driver
*
* Copyright (c) 2013 Red Hat, Inc.
*
* Authors:
* Dmitry Fleytman <dfleytma@redhat.com>
*
*/
#include "driver.h"
#include "Filter.h"
#include "device.tmh"
// {C0F2DADE-8235-4065-89A8-58DB74DDC9AC}
DEFINE_GUID(GUID_USBDK_CLONE_PDO,
0xc0f2dade, 0x8235, 0x4065, 0x89, 0xa8, 0x58, 0xdb, 0x74, 0xdd, 0xc9, 0xac);
typedef struct _CONTROL_DEVICE_EXTENSION {
} PDO_CLONE_EXTENSION, *PPDO_CLONE_EXTENSION;
WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(PDO_CLONE_EXTENSION, PdoCloneGetData)
static WDFDEVICE
UsbDkClonePdo(WDFDEVICE ParentDevice)
{
WDFDEVICE ClonePdo;
NTSTATUS status;
PWDFDEVICE_INIT DevInit;
WDF_OBJECT_ATTRIBUTES DevAttr;
PAGED_CODE();
DevInit = WdfPdoInitAllocate(ParentDevice);
if (DevInit == NULL) {
TraceEvents(TRACE_LEVEL_ERROR, TRACE_DEVICE, "%!FUNC! WdfPdoInitAllocate returned NULL");
return WDF_NO_HANDLE;
}
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&DevAttr, PDO_CLONE_EXTENSION);
#define CLONE_HARDWARE_IDS L"USB\\Vid_FEED&Pid_CAFE&Rev_0001\0USB\\Vid_FEED&Pid_CAFE\0"
#define CLONE_COMPATIBLE_IDS L"USB\\Class_FF&SubClass_FF&Prot_FF\0USB\\Class_FF&SubClass_FF\0USB\\Class_FF\0"
#define CLONE_INSTANCE_ID L"111222333"
DECLARE_CONST_UNICODE_STRING(CloneHwId, CLONE_HARDWARE_IDS);
DECLARE_CONST_UNICODE_STRING(CloneCompatId, CLONE_COMPATIBLE_IDS);
DECLARE_CONST_UNICODE_STRING(CloneInstanceId, CLONE_INSTANCE_ID);
//TODO: Check error codes
WdfPdoInitAssignDeviceID(DevInit, &CloneHwId);
WdfPdoInitAddCompatibleID(DevInit, &CloneCompatId);
WdfPdoInitAddHardwareID(DevInit, &CloneCompatId);
WdfPdoInitAssignInstanceID(DevInit, &CloneInstanceId);
status = WdfDeviceCreate(&DevInit, &DevAttr, &ClonePdo);
if (!NT_SUCCESS(status))
{
TraceEvents(TRACE_LEVEL_ERROR, TRACE_DEVICE, "%!FUNC! WdfDeviceCreate returned %!STATUS!", status);
WdfDeviceInitFree(DevInit);
return WDF_NO_HANDLE;
}
return ClonePdo;
}
VOID UsbDkQDRPostProcessWi(_In_ PVOID WdfDevice)
{
WDFDEVICE Device = (WDFDEVICE) WdfDevice;
PDEVICE_CONTEXT Ctx = DeviceGetContext(WdfDevice);
ASSERT(Ctx->QDRIrp != NULL);
TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "%!FUNC! Entry");
PDEVICE_RELATIONS Relations = (PDEVICE_RELATIONS) Ctx->QDRIrp->IoStatus.Information;
if (Relations)
{
if (Relations->Count > 0)
{
Ctx->ClonedPdo = Relations->Objects[0];
WDFDEVICE PdoClone = UsbDkClonePdo(Device);
if (PdoClone != WDF_NO_HANDLE)
{
Relations->Objects[0] = WdfDeviceWdmGetDeviceObject(PdoClone);
ObReferenceObject(Relations->Objects[0]);
TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "%!FUNC! Replaced PDO 0x%p with 0x%p",
Ctx->ClonedPdo, Relations->Objects[0]);
//TODO: Temporary to allow normal USB hub driver unload
ObDereferenceObject(Ctx->ClonedPdo);
}
else
{
TraceEvents(TRACE_LEVEL_ERROR, TRACE_DEVICE, "%!FUNC! Failed to create clone PDO");
}
}
}
PIRP QDRIrp = Ctx->QDRIrp;
Ctx->QDRIrp = NULL;
IoCompleteRequest(QDRIrp, IO_NO_INCREMENT);
}
NTSTATUS UsbDkQDRPostProcess(_In_ PDEVICE_OBJECT DeviceObject, _In_ PIRP Irp, _In_ PVOID WdfDevice)
{
PDEVICE_CONTEXT Ctx = DeviceGetContext(WdfDevice);
UNREFERENCED_PARAMETER(DeviceObject);
if (Irp->PendingReturned)
{
IoMarkIrpPending(Irp);
}
ASSERT(Ctx->QDRIrp == NULL);
TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "%!FUNC! Queuing work item");
Ctx->QDRIrp = Irp;
Ctx->QDRCompletionWorkItem.Enqueue();
return STATUS_MORE_PROCESSING_REQUIRED;
}
static NTSTATUS UsbDkQDRPreProcess(_In_ WDFDEVICE Device, _Inout_ PIRP Irp)
{
PDEVICE_OBJECT wdmDevice = WdfDeviceWdmGetDeviceObject(Device);
PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
if (BusRelations != irpStack->Parameters.QueryDeviceRelations.Type)
{
IoSkipCurrentIrpStackLocation(Irp);
}
else
{
IoCopyCurrentIrpStackLocationToNext(Irp);
IoSetCompletionRoutineEx(wdmDevice, Irp, UsbDkQDRPostProcess, Device, TRUE, FALSE, FALSE);
}
return WdfDeviceWdmDispatchPreprocessedIrp(Device, Irp);
}
static NTSTATUS
UsbDkSetupFiltering(_In_ PWDFDEVICE_INIT DeviceInit)
{
UCHAR minorCode = IRP_MN_QUERY_DEVICE_RELATIONS;
PAGED_CODE();
WdfFdoInitSetFilter(DeviceInit);
NTSTATUS status = WdfDeviceInitAssignWdmIrpPreprocessCallback(DeviceInit,
UsbDkQDRPreProcess,
IRP_MJ_PNP, &minorCode, 1);
if (!NT_SUCCESS(status))
{
TraceEvents(TRACE_LEVEL_ERROR, TRACE_DEVICE, "%!FUNC! status: %!STATUS!", status);
}
return status;
}
VOID
UsbDkEvtDeviceContextCleanup(_In_ WDFOBJECT DeviceObject)
{
PAGED_CODE();
TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "%!FUNC! Entry");
auto deviceContext = DeviceGetContext(DeviceObject);
if (deviceContext->Initialized)
{
deviceContext->QDRCompletionWorkItem.~CWdfWorkitem();
}
}
NTSTATUS
UsbDkCreateDevice(_Inout_ PWDFDEVICE_INIT DeviceInit)
{
WDF_OBJECT_ATTRIBUTES deviceAttributes;
WDFDEVICE device;
PAGED_CODE();
TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "%!FUNC! Entry");
auto status = UsbDkSetupFiltering(DeviceInit);
if (!NT_SUCCESS(status))
{
return status;
}
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&deviceAttributes, DEVICE_CONTEXT);
deviceAttributes.EvtCleanupCallback = UsbDkEvtDeviceContextCleanup;
status = WdfDeviceCreate(&DeviceInit, &deviceAttributes, &device);
if (!NT_SUCCESS(status))
{
TraceEvents(TRACE_LEVEL_ERROR, TRACE_DEVICE, "%!FUNC! WdfDeviceCreate status: %!STATUS!", status);
return status;
}
if (UsbDkShouldAttach(device))
{
auto deviceContext = DeviceGetContext(device);
deviceContext->IOTarget = WdfDeviceGetIoTarget(device);
deviceContext->QDRIrp = NULL;
deviceContext->ClonedPdo = NULL;
new (&deviceContext->QDRCompletionWorkItem) CWdfWorkitem(device, UsbDkQDRPostProcessWi, device);
status = deviceContext->QDRCompletionWorkItem.Create();
deviceContext->Initialized = TRUE;
ULONG traceLevel = NT_SUCCESS(status) ? TRACE_LEVEL_INFORMATION : TRACE_LEVEL_ERROR;
TraceEvents(traceLevel, TRACE_DEVICE, "%!FUNC! Attachment status: %!STATUS!", status);
}
else
{
status = STATUS_NOT_SUPPORTED;
TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "%!FUNC! Not attached");
}
return status;
}
<commit_msg>UsbDk: Introduce redirected device IDs dumps<commit_after>/*
* UsbDk filter/redirector driver
*
* Copyright (c) 2013 Red Hat, Inc.
*
* Authors:
* Dmitry Fleytman <dfleytma@redhat.com>
*
*/
#include "driver.h"
#include "Filter.h"
#include "DeviceAccess.h"
#include "device.tmh"
extern "C"
{
#include <ntstrsafe.h>
}
// {C0F2DADE-8235-4065-89A8-58DB74DDC9AC}
DEFINE_GUID(GUID_USBDK_CLONE_PDO,
0xc0f2dade, 0x8235, 0x4065, 0x89, 0xa8, 0x58, 0xdb, 0x74, 0xdd, 0xc9, 0xac);
typedef struct _CONTROL_DEVICE_EXTENSION {
} PDO_CLONE_EXTENSION, *PPDO_CLONE_EXTENSION;
WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(PDO_CLONE_EXTENSION, PdoCloneGetData)
static WDFDEVICE
UsbDkClonePdo(WDFDEVICE ParentDevice)
{
WDFDEVICE ClonePdo;
NTSTATUS status;
PWDFDEVICE_INIT DevInit;
WDF_OBJECT_ATTRIBUTES DevAttr;
PAGED_CODE();
DevInit = WdfPdoInitAllocate(ParentDevice);
if (DevInit == NULL) {
TraceEvents(TRACE_LEVEL_ERROR, TRACE_DEVICE, "%!FUNC! WdfPdoInitAllocate returned NULL");
return WDF_NO_HANDLE;
}
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&DevAttr, PDO_CLONE_EXTENSION);
#define CLONE_HARDWARE_IDS L"USB\\Vid_FEED&Pid_CAFE&Rev_0001\0USB\\Vid_FEED&Pid_CAFE\0"
#define CLONE_COMPATIBLE_IDS L"USB\\Class_FF&SubClass_FF&Prot_FF\0USB\\Class_FF&SubClass_FF\0USB\\Class_FF\0"
#define CLONE_INSTANCE_ID L"111222333"
DECLARE_CONST_UNICODE_STRING(CloneHwId, CLONE_HARDWARE_IDS);
DECLARE_CONST_UNICODE_STRING(CloneCompatId, CLONE_COMPATIBLE_IDS);
DECLARE_CONST_UNICODE_STRING(CloneInstanceId, CLONE_INSTANCE_ID);
//TODO: Check error codes
WdfPdoInitAssignDeviceID(DevInit, &CloneHwId);
WdfPdoInitAddCompatibleID(DevInit, &CloneCompatId);
WdfPdoInitAddHardwareID(DevInit, &CloneCompatId);
WdfPdoInitAssignInstanceID(DevInit, &CloneInstanceId);
status = WdfDeviceCreate(&DevInit, &DevAttr, &ClonePdo);
if (!NT_SUCCESS(status))
{
TraceEvents(TRACE_LEVEL_ERROR, TRACE_DEVICE, "%!FUNC! WdfDeviceCreate returned %!STATUS!", status);
WdfDeviceInitFree(DevInit);
return WDF_NO_HANDLE;
}
return ClonePdo;
}
//TODO: Temporary function, printouts only
VOID UsbDkDumpHWIds(CDeviceAccess* devAcc)
{
CObjHolder<CRegText> IDs(devAcc->GetHardwareIDs());
if (!IDs || IDs->empty())
{
TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "%!FUNC! No HW IDs read");
}
else
{
TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "%!FUNC! HW IDs read");
IDs->Dump();
}
CObjHolder<CRegText> DevIDs(devAcc->GetDeviceID());
if (!DevIDs || DevIDs->empty())
{
TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "%!FUNC! No Device IDs read");
}
else
{
TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "%!FUNC! Device IDs read");
DevIDs->Dump();
}
}
VOID UsbDkQDRPostProcessWi(_In_ PVOID WdfDevice)
{
WDFDEVICE Device = (WDFDEVICE) WdfDevice;
PDEVICE_CONTEXT Ctx = DeviceGetContext(WdfDevice);
ASSERT(Ctx->QDRIrp != NULL);
TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "%!FUNC! Entry");
PDEVICE_RELATIONS Relations = (PDEVICE_RELATIONS) Ctx->QDRIrp->IoStatus.Information;
if (Relations)
{
if (Relations->Count > 0)
{
Ctx->ClonedPdo = Relations->Objects[0];
{
//TEMPORARY: To verify we see HW ids of PDO to be cloned
CObjHolder<CDeviceAccess> pdoAccess(CDeviceAccess::GetDeviceAccess(Ctx->ClonedPdo));
if (pdoAccess)
{
UsbDkDumpHWIds(pdoAccess);
}
}
WDFDEVICE PdoClone = UsbDkClonePdo(Device);
if (PdoClone != WDF_NO_HANDLE)
{
Relations->Objects[0] = WdfDeviceWdmGetDeviceObject(PdoClone);
ObReferenceObject(Relations->Objects[0]);
TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "%!FUNC! Replaced PDO 0x%p with 0x%p",
Ctx->ClonedPdo, Relations->Objects[0]);
//TODO: Temporary to allow normal USB hub driver unload
ObDereferenceObject(Ctx->ClonedPdo);
}
else
{
TraceEvents(TRACE_LEVEL_ERROR, TRACE_DEVICE, "%!FUNC! Failed to create clone PDO");
}
}
}
PIRP QDRIrp = Ctx->QDRIrp;
Ctx->QDRIrp = NULL;
IoCompleteRequest(QDRIrp, IO_NO_INCREMENT);
}
NTSTATUS UsbDkQDRPostProcess(_In_ PDEVICE_OBJECT DeviceObject, _In_ PIRP Irp, _In_ PVOID WdfDevice)
{
PDEVICE_CONTEXT Ctx = DeviceGetContext(WdfDevice);
UNREFERENCED_PARAMETER(DeviceObject);
if (Irp->PendingReturned)
{
IoMarkIrpPending(Irp);
}
ASSERT(Ctx->QDRIrp == NULL);
TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "%!FUNC! Queuing work item");
Ctx->QDRIrp = Irp;
Ctx->QDRCompletionWorkItem.Enqueue();
return STATUS_MORE_PROCESSING_REQUIRED;
}
static NTSTATUS UsbDkQDRPreProcess(_In_ WDFDEVICE Device, _Inout_ PIRP Irp)
{
PDEVICE_OBJECT wdmDevice = WdfDeviceWdmGetDeviceObject(Device);
PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
if (BusRelations != irpStack->Parameters.QueryDeviceRelations.Type)
{
IoSkipCurrentIrpStackLocation(Irp);
}
else
{
IoCopyCurrentIrpStackLocationToNext(Irp);
IoSetCompletionRoutineEx(wdmDevice, Irp, UsbDkQDRPostProcess, Device, TRUE, FALSE, FALSE);
}
return WdfDeviceWdmDispatchPreprocessedIrp(Device, Irp);
}
static NTSTATUS
UsbDkSetupFiltering(_In_ PWDFDEVICE_INIT DeviceInit)
{
UCHAR minorCode = IRP_MN_QUERY_DEVICE_RELATIONS;
PAGED_CODE();
WdfFdoInitSetFilter(DeviceInit);
NTSTATUS status = WdfDeviceInitAssignWdmIrpPreprocessCallback(DeviceInit,
UsbDkQDRPreProcess,
IRP_MJ_PNP, &minorCode, 1);
if (!NT_SUCCESS(status))
{
TraceEvents(TRACE_LEVEL_ERROR, TRACE_DEVICE, "%!FUNC! status: %!STATUS!", status);
}
return status;
}
VOID
UsbDkEvtDeviceContextCleanup(_In_ WDFOBJECT DeviceObject)
{
PAGED_CODE();
TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "%!FUNC! Entry");
auto deviceContext = DeviceGetContext(DeviceObject);
if (deviceContext->Initialized)
{
deviceContext->QDRCompletionWorkItem.~CWdfWorkitem();
}
}
NTSTATUS
UsbDkCreateDevice(_Inout_ PWDFDEVICE_INIT DeviceInit)
{
WDF_OBJECT_ATTRIBUTES deviceAttributes;
WDFDEVICE device;
PAGED_CODE();
TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "%!FUNC! Entry");
auto status = UsbDkSetupFiltering(DeviceInit);
if (!NT_SUCCESS(status))
{
return status;
}
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&deviceAttributes, DEVICE_CONTEXT);
deviceAttributes.EvtCleanupCallback = UsbDkEvtDeviceContextCleanup;
status = WdfDeviceCreate(&DeviceInit, &deviceAttributes, &device);
if (!NT_SUCCESS(status))
{
TraceEvents(TRACE_LEVEL_ERROR, TRACE_DEVICE, "%!FUNC! WdfDeviceCreate status: %!STATUS!", status);
return status;
}
if (UsbDkShouldAttach(device))
{
auto deviceContext = DeviceGetContext(device);
deviceContext->IOTarget = WdfDeviceGetIoTarget(device);
deviceContext->QDRIrp = NULL;
deviceContext->ClonedPdo = NULL;
new (&deviceContext->QDRCompletionWorkItem) CWdfWorkitem(device, UsbDkQDRPostProcessWi, device);
status = deviceContext->QDRCompletionWorkItem.Create();
deviceContext->Initialized = TRUE;
ULONG traceLevel = NT_SUCCESS(status) ? TRACE_LEVEL_INFORMATION : TRACE_LEVEL_ERROR;
TraceEvents(traceLevel, TRACE_DEVICE, "%!FUNC! Attachment status: %!STATUS!", status);
}
else
{
status = STATUS_NOT_SUPPORTED;
TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "%!FUNC! Not attached");
}
return status;
}
<|endoftext|>
|
<commit_before>/***************************************************************************
* @file The code is for the exercises in C++ Primmer 5th Edition
* @author Yue Wang
* @date 22 DEC 2013
* Jun 2015
* @remark
***************************************************************************/
//
// Exercise 12.6:
// Write a function that returns a dynamically allocated vector of ints.
// Pass that vector to another function that reads the standard input to
// give values to the elements. Pass the vector to another function to print
// the values that were read.
// Remember to delete the vector at the appropriate time.
//
#include <iostream>
#include <vector>
using Ptr = std::vector<int>*;
auto make_dynamically() -> Ptr
{
return new std::vector < int > { };
}
auto populate(Ptr vec) -> Ptr
{
for (int i; std::cout << "Pls Enter:\n", std::cin >> i; vec->push_back(i));
return vec;
}
auto print(Ptr vec) -> std::ostream&
{
for (auto i : *vec) std::cout << i << " ";
return std::cout;
}
int main()
{
auto vec = populate(make_dynamically());
print(vec) << std::endl;
delete vec;
return 0;
}
<commit_msg>Update ex12_06.cpp<commit_after>/***************************************************************************
* @file The code is for the exercises in C++ Primmer 5th Edition
* @author Yue Wang
* @date 22 DEC 2013
* Jun 2015
* Oct 2015
* @remark
***************************************************************************/
//
// Exercise 12.6:
// Write a function that returns a dynamically allocated vector of ints.
// Pass that vector to another function that reads the standard input to
// give values to the elements. Pass the vector to another function to print
// the values that were read.
// Remember to delete the vector at the appropriate time.
//
#include <iostream>
#include <vector>
using Ptr = std::vector<int>*;
auto make_dynamically()
{
return new std::vector < int > { };
}
auto populate(Ptr vec)
{
for (int i; std::cout << "Pls Enter:\n", std::cin >> i; vec->push_back(i));
return vec;
}
auto print(Ptr vec) -> std::ostream&
{
for (auto i : *vec) std::cout << i << " ";
return std::cout;
}
int main()
{
auto vec = populate(make_dynamically());
print(vec) << std::endl;
delete vec;
return 0;
}
<|endoftext|>
|
<commit_before>#include "LedStripController.h"
#include "Layer.h"
#include <cstdio>
#include <QTimer>
#include <QString>
#include <ws2811.h>
#include <wiringPi.h>
Q_LOGGING_CATEGORY(CONTROLLER, "ledify.controller", QtWarningMsg)
#define NUM_LEDS 300
#define GPIO_PIN 18
#define DMA 10
#define TARGET_FREQ WS2811_TARGET_FREQ
#define STRIP_TYPE SK6812_STRIP_GRBW
#define FPS 40
ws2811_t ledStrip {
.render_wait_time = 0,
.device = nullptr,
.rpi_hw = nullptr,
.freq = TARGET_FREQ,
.dmanum = DMA,
.channel =
{
{
.gpionum = GPIO_PIN,
.invert = 0,
.count = NUM_LEDS,
.strip_type = STRIP_TYPE,
.leds = nullptr,
.brightness = 255,
.wshift = 0,
.rshift = 0,
.gshift = 0,
.bshift = 0,
.gamma = 0
}
},
};
LedStripController::LedStripController() {
connect(this, &LedStripController::terminated, this, &LedStripController::deinitialize);
m_layerController.addColorLayer(0, 0, 0, 0, 0);
m_layerController.setAsRootLayer(0);
m_executor.reset(new CommandExecutor(&m_layerController, &m_fpsCalculator));
m_loopTimer = new QTimer(this);
m_loopTimer->setSingleShot(true);
m_loopTimer->setInterval(5000);
connect(m_loopTimer, &QTimer::timeout, this, &LedStripController::drawLoop);
}
void LedStripController::initialize() {
initializeWiringPi();
initializeLedStrip();
restServer.registerCallback([this] (QString &command) -> QString {
auto result = parseReceivedString(command);
if (!m_relayController.isOn()) {
m_relayController.turnOn();
m_loopTimer->start(2000);
} else {
m_loopTimer->start(0);
}
return result;
});
}
bool LedStripController::writeChar(char c) {
if (m_commandReader.receivedChar(c)) {
return parseReceivedString(m_commandReader.command()).isEmpty();
}
return false;
}
bool LedStripController::animationFinished() {
return m_layerController.rootLayer()->animationFinished();
}
void LedStripController::draw(uint32_t *ledsRgbw, int numLeds) {
m_fpsCalculator.tick();
auto *rootLayer = m_layerController.rootLayer();
rootLayer->startDraw();
auto child = rootLayer->child();
if (child.isNull()) {
return;
}
for (uint16_t i = 0; i < numLeds; i++) {
ledsRgbw[i] = child->pixel(i);
}
rootLayer->endDraw();
}
bool LedStripController::isAnyLedOn() {
for (int i = 0; i < NUM_LEDS; i++) {
if (ledStrip.channel[0].leds[i] != 0) {
return true;
}
}
return false;
}
QString LedStripController::parseReceivedString(const QString &string) {
qCDebug(CONTROLLER) << "Recv:" << string;
auto commandAndArgs = string.split("=");
if (commandAndArgs.empty()) {
qCDebug(CONTROLLER) << "Empty command";
return "Empty command";
}
auto command = commandAndArgs.first();
QStringList args;
if (commandAndArgs.count() >= 2) {
args = commandAndArgs[1].split(",");
}
QString response;
m_executor->parseCommand(command, args, response);
return response;
}
void LedStripController::commandOff() {
QString str;
m_executor->cOff(QStringList(), str);
}
void LedStripController::commandOnIfNight() {
QString str;
m_executor->cOnIfNight(QStringList(), str);
}
void LedStripController::startDrawLoop() {
m_loopTimer->start(0);
}
void LedStripController::terminate() {
qCDebug(CONTROLLER) << "Terminating...";
connect(&m_relayController, &RelayController::relayStateChanged,
this, [this] (int, bool state) {
if (!state) {
emit terminated();
}
});
commandOff();
QTimer::singleShot(3000, this, [this] { //force
m_relayController.turnOff(0);
emit terminated();
});
// m_terminating = true;
}
void LedStripController::initializeWiringPi() {
if (wiringPiSetup() == -1) {
qCritical(CONTROLLER) << "Unable to start wiringPi:"
<< strerror (errno);
emit terminated();
}
}
void LedStripController::initializeLedStrip() {
ws2811_return_t errCode;
if ((errCode = ws2811_init(&ledStrip)) != WS2811_SUCCESS) {
fprintf(stderr, "ws2811_init failed: %s\n", ws2811_get_return_t_str(errCode));
emit terminated();
}
}
void LedStripController::deinitialize() {
deinitializeLedStrip();
}
void LedStripController::deinitializeLedStrip() {
ws2811_fini(&ledStrip);
}
void LedStripController::drawLoop() {
auto startMs = millis();
if (!m_relayController.isOn()) {
return;
}
draw(static_cast<uint32_t *>(ledStrip.channel[0].leds), NUM_LEDS);
ws2811_return_t errCode;
if ((errCode = ws2811_render(&ledStrip)) != WS2811_SUCCESS) {
fprintf(stderr, "ws2811_render failed: %s\n", ws2811_get_return_t_str(errCode));
terminate();
}
if (animationFinished()) {
if (isAnyLedOn()) {
m_loopTimer->start(5000);
} else {
m_relayController.turnOff();
}
} else {
const auto sleepMs = 1000 / FPS;
auto diffProcessingMs = static_cast<int>(millis() - startMs);
m_loopTimer->start(qMax(sleepMs - diffProcessingMs, 1));
}
}
LayerController &LedStripController::layerController() {
return m_layerController;
}
<commit_msg>Refactor and turn off/on leds depending on if any LED is on<commit_after>#include "LedStripController.h"
#include "Layer.h"
#include <cstdio>
#include <QTimer>
#include <QString>
#include <ws2811.h>
#include <wiringPi.h>
Q_LOGGING_CATEGORY(CONTROLLER, "ledify.controller", QtWarningMsg)
#define NUM_LEDS 300
#define GPIO_PIN 18
#define DMA 10
#define TARGET_FREQ WS2811_TARGET_FREQ
#define STRIP_TYPE SK6812_STRIP_GRBW
#define FPS 40
ws2811_t ledStrip {
.render_wait_time = 0,
.device = nullptr,
.rpi_hw = nullptr,
.freq = TARGET_FREQ,
.dmanum = DMA,
.channel =
{
{
.gpionum = GPIO_PIN,
.invert = 0,
.count = NUM_LEDS,
.strip_type = STRIP_TYPE,
.leds = nullptr,
.brightness = 255,
.wshift = 0,
.rshift = 0,
.gshift = 0,
.bshift = 0,
.gamma = 0
}
},
};
LedStripController::LedStripController() {
connect(this, &LedStripController::terminated, this, &LedStripController::deinitialize);
m_layerController.addColorLayer(0, 0, 0, 0, 0);
m_layerController.setAsRootLayer(0);
m_executor.reset(new CommandExecutor(&m_layerController, &m_fpsCalculator));
m_loopTimer = new QTimer(this);
m_loopTimer->setSingleShot(true);
m_loopTimer->setInterval(5000);
connect(m_loopTimer, &QTimer::timeout, this, &LedStripController::drawLoop);
}
void LedStripController::initialize() {
initializeWiringPi();
initializeLedStrip();
restServer.registerCallback([this] (QString &command) -> QString {
auto result = parseReceivedString(command);
m_relayController.turnOn();
if (!m_relayController.isOn()) {
m_loopTimer->start(2000);
} else {
m_loopTimer->start(0);
}
return result;
});
}
bool LedStripController::writeChar(char c) {
if (m_commandReader.receivedChar(c)) {
return parseReceivedString(m_commandReader.command()).isEmpty();
}
return false;
}
bool LedStripController::animationFinished() {
return m_layerController.rootLayer()->animationFinished();
}
void LedStripController::draw(uint32_t *ledsRgbw, int numLeds) {
m_fpsCalculator.tick();
auto *rootLayer = m_layerController.rootLayer();
rootLayer->startDraw();
auto child = rootLayer->child();
if (child.isNull()) {
return;
}
for (uint16_t i = 0; i < numLeds; i++) {
ledsRgbw[i] = child->pixel(i);
}
rootLayer->endDraw();
}
bool LedStripController::isAnyLedOn() {
for (int i = 0; i < NUM_LEDS; i++) {
if (ledStrip.channel[0].leds[i] != 0) {
return true;
}
}
return false;
}
QString LedStripController::parseReceivedString(const QString &string) {
qCDebug(CONTROLLER) << "Recv:" << string;
auto commandAndArgs = string.split("=");
if (commandAndArgs.empty()) {
qCDebug(CONTROLLER) << "Empty command";
return "Empty command";
}
auto command = commandAndArgs.first();
QStringList args;
if (commandAndArgs.count() >= 2) {
args = commandAndArgs[1].split(",");
}
QString response;
m_executor->parseCommand(command, args, response);
return response;
}
void LedStripController::commandOff() {
QString str;
m_executor->cOff(QStringList(), str);
}
void LedStripController::commandOnIfNight() {
QString str;
m_executor->cOnIfNight(QStringList(), str);
}
void LedStripController::startDrawLoop() {
m_loopTimer->start(0);
}
void LedStripController::terminate() {
qCDebug(CONTROLLER) << "Terminating...";
connect(&m_relayController, &RelayController::relayStateChanged,
this, [this] (int, bool state) {
if (!state) {
emit terminated();
}
});
commandOff();
QTimer::singleShot(3000, this, [this] { //force
m_relayController.turnOff(0);
emit terminated();
});
// m_terminating = true;
}
void LedStripController::initializeWiringPi() {
if (wiringPiSetup() == -1) {
qCritical(CONTROLLER) << "Unable to start wiringPi:"
<< strerror (errno);
emit terminated();
}
}
void LedStripController::initializeLedStrip() {
ws2811_return_t errCode;
if ((errCode = ws2811_init(&ledStrip)) != WS2811_SUCCESS) {
fprintf(stderr, "ws2811_init failed: %s\n", ws2811_get_return_t_str(errCode));
emit terminated();
}
}
void LedStripController::deinitialize() {
deinitializeLedStrip();
}
void LedStripController::deinitializeLedStrip() {
ws2811_fini(&ledStrip);
}
void LedStripController::drawLoop() {
auto startMs = millis();
if (!m_relayController.isOn()) {
return;
}
draw(static_cast<uint32_t *>(ledStrip.channel[0].leds), NUM_LEDS);
ws2811_return_t errCode;
if ((errCode = ws2811_render(&ledStrip)) != WS2811_SUCCESS) {
fprintf(stderr, "ws2811_render failed: %s\n", ws2811_get_return_t_str(errCode));
terminate();
}
if (animationFinished()) {
if (isAnyLedOn()) {
m_loopTimer->start(5000);
} else {
m_relayController.turnOff();
}
} else {
const auto sleepMs = 1000 / FPS;
auto diffProcessingMs = static_cast<int>(millis() - startMs);
m_loopTimer->start(qMax(sleepMs - diffProcessingMs, 1));
}
}
LayerController &LedStripController::layerController() {
return m_layerController;
}
<|endoftext|>
|
<commit_before>#include "get-drvs.hh"
#include "util.hh"
#include "eval-inline.hh"
#include <cstring>
namespace nix {
string DrvInfo::queryDrvPath()
{
if (drvPath == "" && attrs) {
Bindings::iterator i = attrs->find(state->sDrvPath);
PathSet context;
drvPath = i != attrs->end() ? state->coerceToPath(*i->pos, *i->value, context) : "";
}
return drvPath;
}
string DrvInfo::queryOutPath()
{
if (outPath == "" && attrs) {
Bindings::iterator i = attrs->find(state->sOutPath);
PathSet context;
outPath = i != attrs->end() ? state->coerceToPath(*i->pos, *i->value, context) : "";
}
return outPath;
}
DrvInfo::Outputs DrvInfo::queryOutputs(bool onlyOutputsToInstall)
{
if (outputs.empty()) {
/* Get the ‘outputs’ list. */
Bindings::iterator i;
if (attrs && (i = attrs->find(state->sOutputs)) != attrs->end()) {
state->forceList(*i->value, *i->pos);
/* For each output... */
for (unsigned int j = 0; j < i->value->listSize(); ++j) {
/* Evaluate the corresponding set. */
string name = state->forceStringNoCtx(*i->value->listElems()[j], *i->pos);
Bindings::iterator out = attrs->find(state->symbols.create(name));
if (out == attrs->end()) continue; // FIXME: throw error?
state->forceAttrs(*out->value);
/* And evaluate its ‘outPath’ attribute. */
Bindings::iterator outPath = out->value->attrs->find(state->sOutPath);
if (outPath == out->value->attrs->end()) continue; // FIXME: throw error?
PathSet context;
outputs[name] = state->coerceToPath(*outPath->pos, *outPath->value, context);
}
} else
outputs["out"] = queryOutPath();
}
if (!onlyOutputsToInstall || !attrs)
return outputs;
/* Check for `meta.outputsToInstall` and return `outputs` reduced to that. */
const Value * outTI = queryMeta("outputsToInstall");
if (!outTI) return outputs;
const auto errMsg = Error("this derivation has bad ‘meta.outputsToInstall’");
/* ^ this shows during `nix-env -i` right under the bad derivation */
if (!outTI->isList()) throw errMsg;
Outputs result;
for (auto i = outTI->listElems(); i != outTI->listElems() + outTI->listSize(); ++i) {
if ((*i)->type != tString) throw errMsg;
auto out = outputs.find((*i)->string.s);
if (out == outputs.end()) throw errMsg;
result.insert(*out);
}
return result;
}
string DrvInfo::queryOutputName()
{
if (outputName == "" && attrs) {
Bindings::iterator i = attrs->find(state->sOutputName);
outputName = i != attrs->end() ? state->forceStringNoCtx(*i->value) : "";
}
return outputName;
}
Bindings * DrvInfo::getMeta()
{
if (meta) return meta;
if (!attrs) return 0;
Bindings::iterator a = attrs->find(state->sMeta);
if (a == attrs->end()) return 0;
state->forceAttrs(*a->value, *a->pos);
meta = a->value->attrs;
return meta;
}
StringSet DrvInfo::queryMetaNames()
{
StringSet res;
if (!getMeta()) return res;
for (auto & i : *meta)
res.insert(i.name);
return res;
}
bool DrvInfo::checkMeta(Value & v)
{
state->forceValue(v);
if (v.isList()) {
for (unsigned int n = 0; n < v.listSize(); ++n)
if (!checkMeta(*v.listElems()[n])) return false;
return true;
}
else if (v.type == tAttrs) {
Bindings::iterator i = v.attrs->find(state->sOutPath);
if (i != v.attrs->end()) return false;
for (auto & i : *v.attrs)
if (!checkMeta(*i.value)) return false;
return true;
}
else return v.type == tInt || v.type == tBool || v.type == tString ||
v.type == tFloat;
}
Value * DrvInfo::queryMeta(const string & name)
{
if (!getMeta()) return 0;
Bindings::iterator a = meta->find(state->symbols.create(name));
if (a == meta->end() || !checkMeta(*a->value)) return 0;
return a->value;
}
string DrvInfo::queryMetaString(const string & name)
{
Value * v = queryMeta(name);
if (!v || v->type != tString) return "";
return v->string.s;
}
NixInt DrvInfo::queryMetaInt(const string & name, NixInt def)
{
Value * v = queryMeta(name);
if (!v) return def;
if (v->type == tInt) return v->integer;
if (v->type == tString) {
/* Backwards compatibility with before we had support for
integer meta fields. */
NixInt n;
if (string2Int(v->string.s, n)) return n;
}
return def;
}
NixFloat DrvInfo::queryMetaFloat(const string & name, NixFloat def)
{
Value * v = queryMeta(name);
if (!v) return def;
if (v->type == tFloat) return v->fpoint;
if (v->type == tString) {
/* Backwards compatibility with before we had support for
float meta fields. */
NixFloat n;
if (string2Float(v->string.s, n)) return n;
}
return def;
}
bool DrvInfo::queryMetaBool(const string & name, bool def)
{
Value * v = queryMeta(name);
if (!v) return def;
if (v->type == tBool) return v->boolean;
if (v->type == tString) {
/* Backwards compatibility with before we had support for
Boolean meta fields. */
if (strcmp(v->string.s, "true") == 0) return true;
if (strcmp(v->string.s, "false") == 0) return false;
}
return def;
}
void DrvInfo::setMeta(const string & name, Value * v)
{
getMeta();
Bindings * old = meta;
meta = state->allocBindings(1 + (old ? old->size() : 0));
Symbol sym = state->symbols.create(name);
if (old)
for (auto i : *old)
if (i.name != sym)
meta->push_back(i);
if (v) meta->push_back(Attr(sym, v));
meta->sort();
}
/* Cache for already considered attrsets. */
typedef set<Bindings *> Done;
/* Evaluate value `v'. If it evaluates to a set of type `derivation',
then put information about it in `drvs' (unless it's already in `done').
The result boolean indicates whether it makes sense
for the caller to recursively search for derivations in `v'. */
static bool getDerivation(EvalState & state, Value & v,
const string & attrPath, DrvInfos & drvs, Done & done,
bool ignoreAssertionFailures)
{
try {
state.forceValue(v);
if (!state.isDerivation(v)) return true;
/* Remove spurious duplicates (e.g., a set like `rec { x =
derivation {...}; y = x;}'. */
if (done.find(v.attrs) != done.end()) return false;
done.insert(v.attrs);
Bindings::iterator i = v.attrs->find(state.sName);
/* !!! We really would like to have a decent back trace here. */
if (i == v.attrs->end()) throw TypeError("derivation name missing");
Bindings::iterator i2 = v.attrs->find(state.sSystem);
DrvInfo drv(state, state.forceStringNoCtx(*i->value), attrPath,
i2 == v.attrs->end() ? "unknown" : state.forceStringNoCtx(*i2->value, *i2->pos),
v.attrs);
drvs.push_back(drv);
return false;
} catch (AssertionError & e) {
if (ignoreAssertionFailures) return false;
throw;
}
}
bool getDerivation(EvalState & state, Value & v, DrvInfo & drv,
bool ignoreAssertionFailures)
{
Done done;
DrvInfos drvs;
getDerivation(state, v, "", drvs, done, ignoreAssertionFailures);
if (drvs.size() != 1) return false;
drv = drvs.front();
return true;
}
static string addToPath(const string & s1, const string & s2)
{
return s1.empty() ? s2 : s1 + "." + s2;
}
static void getDerivations(EvalState & state, Value & vIn,
const string & pathPrefix, Bindings & autoArgs,
DrvInfos & drvs, Done & done,
bool ignoreAssertionFailures)
{
Value v;
state.autoCallFunction(autoArgs, vIn, v);
/* Process the expression. */
if (!getDerivation(state, v, pathPrefix, drvs, done, ignoreAssertionFailures)) ;
else if (v.type == tAttrs) {
/* !!! undocumented hackery to support combining channels in
nix-env.cc. */
bool combineChannels = v.attrs->find(state.symbols.create("_combineChannels")) != v.attrs->end();
/* Consider the attributes in sorted order to get more
deterministic behaviour in nix-env operations (e.g. when
there are names clashes between derivations, the derivation
bound to the attribute with the "lower" name should take
precedence). */
for (auto & i : v.attrs->lexicographicOrder()) {
Activity act(*logger, lvlDebug, format("evaluating attribute ‘%1%’") % i->name);
string pathPrefix2 = addToPath(pathPrefix, i->name);
if (combineChannels)
getDerivations(state, *i->value, pathPrefix2, autoArgs, drvs, done, ignoreAssertionFailures);
else if (getDerivation(state, *i->value, pathPrefix2, drvs, done, ignoreAssertionFailures)) {
/* If the value of this attribute is itself a set,
should we recurse into it? => Only if it has a
`recurseForDerivations = true' attribute. */
if (i->value->type == tAttrs) {
Bindings::iterator j = i->value->attrs->find(state.symbols.create("recurseForDerivations"));
if (j != i->value->attrs->end() && state.forceBool(*j->value, *j->pos))
getDerivations(state, *i->value, pathPrefix2, autoArgs, drvs, done, ignoreAssertionFailures);
}
}
}
}
else if (v.isList()) {
for (unsigned int n = 0; n < v.listSize(); ++n) {
Activity act(*logger, lvlDebug, "evaluating list element");
string pathPrefix2 = addToPath(pathPrefix, (format("%1%") % n).str());
if (getDerivation(state, *v.listElems()[n], pathPrefix2, drvs, done, ignoreAssertionFailures))
getDerivations(state, *v.listElems()[n], pathPrefix2, autoArgs, drvs, done, ignoreAssertionFailures);
}
}
else throw TypeError("expression does not evaluate to a derivation (or a set or list of those)");
}
void getDerivations(EvalState & state, Value & v, const string & pathPrefix,
Bindings & autoArgs, DrvInfos & drvs, bool ignoreAssertionFailures)
{
Done done;
getDerivations(state, v, pathPrefix, autoArgs, drvs, done, ignoreAssertionFailures);
}
}
<commit_msg>getDerivations(): Filter out packages with bad derivation names<commit_after>#include "get-drvs.hh"
#include "util.hh"
#include "eval-inline.hh"
#include <cstring>
#include <regex>
namespace nix {
string DrvInfo::queryDrvPath()
{
if (drvPath == "" && attrs) {
Bindings::iterator i = attrs->find(state->sDrvPath);
PathSet context;
drvPath = i != attrs->end() ? state->coerceToPath(*i->pos, *i->value, context) : "";
}
return drvPath;
}
string DrvInfo::queryOutPath()
{
if (outPath == "" && attrs) {
Bindings::iterator i = attrs->find(state->sOutPath);
PathSet context;
outPath = i != attrs->end() ? state->coerceToPath(*i->pos, *i->value, context) : "";
}
return outPath;
}
DrvInfo::Outputs DrvInfo::queryOutputs(bool onlyOutputsToInstall)
{
if (outputs.empty()) {
/* Get the ‘outputs’ list. */
Bindings::iterator i;
if (attrs && (i = attrs->find(state->sOutputs)) != attrs->end()) {
state->forceList(*i->value, *i->pos);
/* For each output... */
for (unsigned int j = 0; j < i->value->listSize(); ++j) {
/* Evaluate the corresponding set. */
string name = state->forceStringNoCtx(*i->value->listElems()[j], *i->pos);
Bindings::iterator out = attrs->find(state->symbols.create(name));
if (out == attrs->end()) continue; // FIXME: throw error?
state->forceAttrs(*out->value);
/* And evaluate its ‘outPath’ attribute. */
Bindings::iterator outPath = out->value->attrs->find(state->sOutPath);
if (outPath == out->value->attrs->end()) continue; // FIXME: throw error?
PathSet context;
outputs[name] = state->coerceToPath(*outPath->pos, *outPath->value, context);
}
} else
outputs["out"] = queryOutPath();
}
if (!onlyOutputsToInstall || !attrs)
return outputs;
/* Check for `meta.outputsToInstall` and return `outputs` reduced to that. */
const Value * outTI = queryMeta("outputsToInstall");
if (!outTI) return outputs;
const auto errMsg = Error("this derivation has bad ‘meta.outputsToInstall’");
/* ^ this shows during `nix-env -i` right under the bad derivation */
if (!outTI->isList()) throw errMsg;
Outputs result;
for (auto i = outTI->listElems(); i != outTI->listElems() + outTI->listSize(); ++i) {
if ((*i)->type != tString) throw errMsg;
auto out = outputs.find((*i)->string.s);
if (out == outputs.end()) throw errMsg;
result.insert(*out);
}
return result;
}
string DrvInfo::queryOutputName()
{
if (outputName == "" && attrs) {
Bindings::iterator i = attrs->find(state->sOutputName);
outputName = i != attrs->end() ? state->forceStringNoCtx(*i->value) : "";
}
return outputName;
}
Bindings * DrvInfo::getMeta()
{
if (meta) return meta;
if (!attrs) return 0;
Bindings::iterator a = attrs->find(state->sMeta);
if (a == attrs->end()) return 0;
state->forceAttrs(*a->value, *a->pos);
meta = a->value->attrs;
return meta;
}
StringSet DrvInfo::queryMetaNames()
{
StringSet res;
if (!getMeta()) return res;
for (auto & i : *meta)
res.insert(i.name);
return res;
}
bool DrvInfo::checkMeta(Value & v)
{
state->forceValue(v);
if (v.isList()) {
for (unsigned int n = 0; n < v.listSize(); ++n)
if (!checkMeta(*v.listElems()[n])) return false;
return true;
}
else if (v.type == tAttrs) {
Bindings::iterator i = v.attrs->find(state->sOutPath);
if (i != v.attrs->end()) return false;
for (auto & i : *v.attrs)
if (!checkMeta(*i.value)) return false;
return true;
}
else return v.type == tInt || v.type == tBool || v.type == tString ||
v.type == tFloat;
}
Value * DrvInfo::queryMeta(const string & name)
{
if (!getMeta()) return 0;
Bindings::iterator a = meta->find(state->symbols.create(name));
if (a == meta->end() || !checkMeta(*a->value)) return 0;
return a->value;
}
string DrvInfo::queryMetaString(const string & name)
{
Value * v = queryMeta(name);
if (!v || v->type != tString) return "";
return v->string.s;
}
NixInt DrvInfo::queryMetaInt(const string & name, NixInt def)
{
Value * v = queryMeta(name);
if (!v) return def;
if (v->type == tInt) return v->integer;
if (v->type == tString) {
/* Backwards compatibility with before we had support for
integer meta fields. */
NixInt n;
if (string2Int(v->string.s, n)) return n;
}
return def;
}
NixFloat DrvInfo::queryMetaFloat(const string & name, NixFloat def)
{
Value * v = queryMeta(name);
if (!v) return def;
if (v->type == tFloat) return v->fpoint;
if (v->type == tString) {
/* Backwards compatibility with before we had support for
float meta fields. */
NixFloat n;
if (string2Float(v->string.s, n)) return n;
}
return def;
}
bool DrvInfo::queryMetaBool(const string & name, bool def)
{
Value * v = queryMeta(name);
if (!v) return def;
if (v->type == tBool) return v->boolean;
if (v->type == tString) {
/* Backwards compatibility with before we had support for
Boolean meta fields. */
if (strcmp(v->string.s, "true") == 0) return true;
if (strcmp(v->string.s, "false") == 0) return false;
}
return def;
}
void DrvInfo::setMeta(const string & name, Value * v)
{
getMeta();
Bindings * old = meta;
meta = state->allocBindings(1 + (old ? old->size() : 0));
Symbol sym = state->symbols.create(name);
if (old)
for (auto i : *old)
if (i.name != sym)
meta->push_back(i);
if (v) meta->push_back(Attr(sym, v));
meta->sort();
}
/* Cache for already considered attrsets. */
typedef set<Bindings *> Done;
/* Evaluate value `v'. If it evaluates to a set of type `derivation',
then put information about it in `drvs' (unless it's already in `done').
The result boolean indicates whether it makes sense
for the caller to recursively search for derivations in `v'. */
static bool getDerivation(EvalState & state, Value & v,
const string & attrPath, DrvInfos & drvs, Done & done,
bool ignoreAssertionFailures)
{
try {
state.forceValue(v);
if (!state.isDerivation(v)) return true;
/* Remove spurious duplicates (e.g., a set like `rec { x =
derivation {...}; y = x;}'. */
if (done.find(v.attrs) != done.end()) return false;
done.insert(v.attrs);
Bindings::iterator i = v.attrs->find(state.sName);
/* !!! We really would like to have a decent back trace here. */
if (i == v.attrs->end()) throw TypeError("derivation name missing");
Bindings::iterator i2 = v.attrs->find(state.sSystem);
DrvInfo drv(state, state.forceStringNoCtx(*i->value), attrPath,
i2 == v.attrs->end() ? "unknown" : state.forceStringNoCtx(*i2->value, *i2->pos),
v.attrs);
drvs.push_back(drv);
return false;
} catch (AssertionError & e) {
if (ignoreAssertionFailures) return false;
throw;
}
}
bool getDerivation(EvalState & state, Value & v, DrvInfo & drv,
bool ignoreAssertionFailures)
{
Done done;
DrvInfos drvs;
getDerivation(state, v, "", drvs, done, ignoreAssertionFailures);
if (drvs.size() != 1) return false;
drv = drvs.front();
return true;
}
static string addToPath(const string & s1, const string & s2)
{
return s1.empty() ? s2 : s1 + "." + s2;
}
static std::regex attrRegex("[A-Za-z_][A-Za-z0-9-_+]*");
static void getDerivations(EvalState & state, Value & vIn,
const string & pathPrefix, Bindings & autoArgs,
DrvInfos & drvs, Done & done,
bool ignoreAssertionFailures)
{
Value v;
state.autoCallFunction(autoArgs, vIn, v);
/* Process the expression. */
if (!getDerivation(state, v, pathPrefix, drvs, done, ignoreAssertionFailures)) ;
else if (v.type == tAttrs) {
/* !!! undocumented hackery to support combining channels in
nix-env.cc. */
bool combineChannels = v.attrs->find(state.symbols.create("_combineChannels")) != v.attrs->end();
/* Consider the attributes in sorted order to get more
deterministic behaviour in nix-env operations (e.g. when
there are names clashes between derivations, the derivation
bound to the attribute with the "lower" name should take
precedence). */
for (auto & i : v.attrs->lexicographicOrder()) {
Activity act(*logger, lvlDebug, format("evaluating attribute ‘%1%’") % i->name);
if (!std::regex_match(std::string(i->name), attrRegex))
continue;
string pathPrefix2 = addToPath(pathPrefix, i->name);
if (combineChannels)
getDerivations(state, *i->value, pathPrefix2, autoArgs, drvs, done, ignoreAssertionFailures);
else if (getDerivation(state, *i->value, pathPrefix2, drvs, done, ignoreAssertionFailures)) {
/* If the value of this attribute is itself a set,
should we recurse into it? => Only if it has a
`recurseForDerivations = true' attribute. */
if (i->value->type == tAttrs) {
Bindings::iterator j = i->value->attrs->find(state.symbols.create("recurseForDerivations"));
if (j != i->value->attrs->end() && state.forceBool(*j->value, *j->pos))
getDerivations(state, *i->value, pathPrefix2, autoArgs, drvs, done, ignoreAssertionFailures);
}
}
}
}
else if (v.isList()) {
for (unsigned int n = 0; n < v.listSize(); ++n) {
Activity act(*logger, lvlDebug, "evaluating list element");
string pathPrefix2 = addToPath(pathPrefix, (format("%1%") % n).str());
if (getDerivation(state, *v.listElems()[n], pathPrefix2, drvs, done, ignoreAssertionFailures))
getDerivations(state, *v.listElems()[n], pathPrefix2, autoArgs, drvs, done, ignoreAssertionFailures);
}
}
else throw TypeError("expression does not evaluate to a derivation (or a set or list of those)");
}
void getDerivations(EvalState & state, Value & v, const string & pathPrefix,
Bindings & autoArgs, DrvInfos & drvs, bool ignoreAssertionFailures)
{
Done done;
getDerivations(state, v, pathPrefix, autoArgs, drvs, done, ignoreAssertionFailures);
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("GraniteCoin");
// Client version number
#define CLIENT_VERSION_SUFFIX "-final"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID " Release"
# define GIT_COMMIT_DATE "Wed, 21 May 2014"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build)
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Update version.cpp<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("granite");
// Client version number
#define CLIENT_VERSION_SUFFIX "-final"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID " Release"
# define GIT_COMMIT_DATE "Wed, 21 May 2014"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build)
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>
|
<commit_before>/*
* ThreadSafeStackTrace.cpp
*
* Copyright (C) 2006 - 2008 by Universitaet Stuttgart (VIS).
* Alle Rechte vorbehalten.
*/
#include "vislib/ThreadSafeStackTrace.h"
#include "vislib/assert.h"
/*
* vislib::sys::ThreadSafeStackTrace::GetStackString
*/
void vislib::sys::ThreadSafeStackTrace::GetStackString(char *outStr,
unsigned int &strSize) {
vislib::StackTrace::GetStackString(outStr, strSize);
}
/*
* vislib::sys::ThreadSafeStackTrace::GetStackString
*/
void vislib::sys::ThreadSafeStackTrace::GetStackString(wchar_t *outStr,
unsigned int &strSize) {
vislib::StackTrace::GetStackString(outStr, strSize);
}
/*
* vislib::sys::ThreadSafeStackTrace::Initialise
*/
bool vislib::sys::ThreadSafeStackTrace::Initialise(
vislib::SmartPtr<vislib::StackTrace> manager, bool force) {
if (manager.IsNull()) {
return vislib::StackTrace::Initialise(new ThreadSafeStackTrace(),
force);
}
return vislib::StackTrace::Initialise(manager, force);
}
/*
* vislib::sys::ThreadSafeStackTrace::Manager
*/
vislib::SmartPtr<vislib::StackTrace>
vislib::sys::ThreadSafeStackTrace::Manager(void) {
return vislib::StackTrace::Manager();
}
/*
* vislib::sys::ThreadSafeStackTrace::~ThreadSafeStackTrace
*/
vislib::sys::ThreadSafeStackTrace::~ThreadSafeStackTrace(void) {
this->critSect.Lock();
this->valid = false;
ThreadStackRoot *r;
StackElement *e;
while (this->stacks) {
r = this->stacks;
this->stacks = r->next;
while (r->stack) {
e = r->stack;
r->stack = e->next;
e->func = NULL; // DO NOT DELETE
e->file = NULL; // DO NOT DELETE
e->next = NULL;
delete e;
}
delete r;
}
this->critSect.Unlock();
}
/*
* vislib::sys::ThreadSafeStackTrace::ThreadSafeStackTrace
*/
vislib::sys::ThreadSafeStackTrace::ThreadSafeStackTrace(void) : StackTrace(),
critSect(), stacks(NULL), valid(true) {
// Intentionally empty
}
/*
* vislib::sys::ThreadSafeStackTrace::pop
*/
void vislib::sys::ThreadSafeStackTrace::pop(int id) {
this->critSect.Lock();
if (!this->valid) return;
DWORD ctid = vislib::sys::Thread::CurrentID();
ThreadStackRoot *r = this->stacks;
while (r != NULL) {
if (r->id == ctid) {
this->stack = r->stack;
StackTrace::pop(id);
r->stack = this->stack;
if (r->stack == NULL) {
if (this->stacks == r) {
this->stacks = r->next;
} else {
ThreadStackRoot *p = this->stacks;
while ((p->next != NULL) && (p->next != r)) {
p = p->next;
}
ASSERT(p->next == r);
p->next = r->next;
}
delete r;
}
break;
}
r = r->next;
}
this->critSect.Unlock();
}
/*
* vislib::sys::ThreadSafeStackTrace::push
*/
int vislib::sys::ThreadSafeStackTrace::push(const char* func, const char* file, const int line) {
int retval = 0;
this->critSect.Lock();
if (!this->valid) return 0;
DWORD ctid = vislib::sys::Thread::CurrentID();
ThreadStackRoot *root = NULL;
ThreadStackRoot *r = this->stacks;
while (r != NULL) {
if (r->id == ctid) {
root = r;
break;
}
r = r->next;
}
if (root == NULL) {
root = new ThreadStackRoot;
root->id = ctid;
root->stack = NULL;
root->next = this->stacks;
this->stacks = root;
}
this->stack = root->stack;
retval = StackTrace::push(func, file, line);
root->stack = this->stack;
this->critSect.Unlock();
return retval;
}
/*
* vislib::sys::ThreadSafeStackTrace::startUseStack
*/
vislib::StackTrace::StackElement*
vislib::sys::ThreadSafeStackTrace::startUseStack(void) {
this->critSect.Lock();
if (!this->valid) return NULL;
DWORD ctid = vislib::sys::Thread::CurrentID();
ThreadStackRoot *r = this->stacks;
while (r != NULL) {
if (r->id == ctid) {
return r->stack;
}
r = r->next;
}
return NULL;
}
/*
* vislib::sys::ThreadSafeStackTrace::stopUseStack
*/
void vislib::sys::ThreadSafeStackTrace::stopUseStack(
vislib::StackTrace::StackElement* stack) {
// stack could be used for sanity check here
this->critSect.Unlock();
}
<commit_msg>bigfix: ThreadSafeStackTrace no longer corrupts simple base class member<commit_after>/*
* ThreadSafeStackTrace.cpp
*
* Copyright (C) 2006 - 2008 by Universitaet Stuttgart (VIS).
* Alle Rechte vorbehalten.
*/
#include "vislib/ThreadSafeStackTrace.h"
#include "vislib/assert.h"
/*
* vislib::sys::ThreadSafeStackTrace::GetStackString
*/
void vislib::sys::ThreadSafeStackTrace::GetStackString(char *outStr,
unsigned int &strSize) {
vislib::StackTrace::GetStackString(outStr, strSize);
}
/*
* vislib::sys::ThreadSafeStackTrace::GetStackString
*/
void vislib::sys::ThreadSafeStackTrace::GetStackString(wchar_t *outStr,
unsigned int &strSize) {
vislib::StackTrace::GetStackString(outStr, strSize);
}
/*
* vislib::sys::ThreadSafeStackTrace::Initialise
*/
bool vislib::sys::ThreadSafeStackTrace::Initialise(
vislib::SmartPtr<vislib::StackTrace> manager, bool force) {
if (manager.IsNull()) {
return vislib::StackTrace::Initialise(new ThreadSafeStackTrace(),
force);
}
return vislib::StackTrace::Initialise(manager, force);
}
/*
* vislib::sys::ThreadSafeStackTrace::Manager
*/
vislib::SmartPtr<vislib::StackTrace>
vislib::sys::ThreadSafeStackTrace::Manager(void) {
return vislib::StackTrace::Manager();
}
/*
* vislib::sys::ThreadSafeStackTrace::~ThreadSafeStackTrace
*/
vislib::sys::ThreadSafeStackTrace::~ThreadSafeStackTrace(void) {
this->critSect.Lock();
this->valid = false;
ThreadStackRoot *r;
StackElement *e;
while (this->stacks) {
r = this->stacks;
this->stacks = r->next;
while (r->stack) {
e = r->stack;
r->stack = e->next;
e->func = NULL; // DO NOT DELETE
e->file = NULL; // DO NOT DELETE
e->next = NULL;
delete e;
}
delete r;
}
this->critSect.Unlock();
}
/*
* vislib::sys::ThreadSafeStackTrace::ThreadSafeStackTrace
*/
vislib::sys::ThreadSafeStackTrace::ThreadSafeStackTrace(void) : StackTrace(),
critSect(), stacks(NULL), valid(true) {
// Intentionally empty
}
/*
* vislib::sys::ThreadSafeStackTrace::pop
*/
void vislib::sys::ThreadSafeStackTrace::pop(int id) {
this->critSect.Lock();
if (!this->valid) return;
DWORD ctid = vislib::sys::Thread::CurrentID();
ThreadStackRoot *r = this->stacks;
while (r != NULL) {
if (r->id == ctid) {
this->stack = r->stack;
StackTrace::pop(id);
r->stack = this->stack;
this->stack = NULL;
if (r->stack == NULL) {
if (this->stacks == r) {
this->stacks = r->next;
} else {
ThreadStackRoot *p = this->stacks;
while ((p->next != NULL) && (p->next != r)) {
p = p->next;
}
ASSERT(p->next == r);
p->next = r->next;
}
delete r;
}
break;
}
r = r->next;
}
this->critSect.Unlock();
}
/*
* vislib::sys::ThreadSafeStackTrace::push
*/
int vislib::sys::ThreadSafeStackTrace::push(const char* func, const char* file, const int line) {
int retval = 0;
this->critSect.Lock();
if (!this->valid) return 0;
DWORD ctid = vislib::sys::Thread::CurrentID();
ThreadStackRoot *root = NULL;
ThreadStackRoot *r = this->stacks;
while (r != NULL) {
if (r->id == ctid) {
root = r;
break;
}
r = r->next;
}
if (root == NULL) {
root = new ThreadStackRoot;
root->id = ctid;
root->stack = NULL;
root->next = this->stacks;
this->stacks = root;
}
this->stack = root->stack;
retval = StackTrace::push(func, file, line);
root->stack = this->stack;
this->stack = NULL;
this->critSect.Unlock();
return retval;
}
/*
* vislib::sys::ThreadSafeStackTrace::startUseStack
*/
vislib::StackTrace::StackElement*
vislib::sys::ThreadSafeStackTrace::startUseStack(void) {
this->critSect.Lock();
if (!this->valid) return NULL;
DWORD ctid = vislib::sys::Thread::CurrentID();
ThreadStackRoot *r = this->stacks;
while (r != NULL) {
if (r->id == ctid) {
return r->stack;
}
r = r->next;
}
return NULL;
}
/*
* vislib::sys::ThreadSafeStackTrace::stopUseStack
*/
void vislib::sys::ThreadSafeStackTrace::stopUseStack(
vislib::StackTrace::StackElement* stack) {
// stack could be used for sanity check here
this->critSect.Unlock();
}
<|endoftext|>
|
<commit_before>#include "globals.hh"
#include "util.hh"
#include "archive.hh"
#include "args.hh"
#include "abstract-setting-to-json.hh"
#include "compute-levels.hh"
#include <algorithm>
#include <map>
#include <thread>
#include <dlfcn.h>
#include <sys/utsname.h>
#include <nlohmann/json.hpp>
namespace nix {
/* The default location of the daemon socket, relative to nixStateDir.
The socket is in a directory to allow you to control access to the
Nix daemon by setting the mode/ownership of the directory
appropriately. (This wouldn't work on the socket itself since it
must be deleted and recreated on startup.) */
#define DEFAULT_SOCKET_PATH "/daemon-socket/socket"
Settings settings;
static GlobalConfig::Register rSettings(&settings);
Settings::Settings()
: nixPrefix(NIX_PREFIX)
, nixStore(canonPath(getEnv("NIX_STORE_DIR").value_or(getEnv("NIX_STORE").value_or(NIX_STORE_DIR))))
, nixDataDir(canonPath(getEnv("NIX_DATA_DIR").value_or(NIX_DATA_DIR)))
, nixLogDir(canonPath(getEnv("NIX_LOG_DIR").value_or(NIX_LOG_DIR)))
, nixStateDir(canonPath(getEnv("NIX_STATE_DIR").value_or(NIX_STATE_DIR)))
, nixConfDir(canonPath(getEnv("NIX_CONF_DIR").value_or(NIX_CONF_DIR)))
, nixUserConfFiles(getUserConfigFiles())
, nixBinDir(canonPath(getEnv("NIX_BIN_DIR").value_or(NIX_BIN_DIR)))
, nixManDir(canonPath(NIX_MAN_DIR))
, nixDaemonSocketFile(canonPath(getEnv("NIX_DAEMON_SOCKET_PATH").value_or(nixStateDir + DEFAULT_SOCKET_PATH)))
{
buildUsersGroup = getuid() == 0 ? "nixbld" : "";
lockCPU = getEnv("NIX_AFFINITY_HACK") == "1";
allowSymlinkedStore = getEnv("NIX_IGNORE_SYMLINK_STORE") == "1";
caFile = getEnv("NIX_SSL_CERT_FILE").value_or(getEnv("SSL_CERT_FILE").value_or(""));
if (caFile == "") {
for (auto & fn : {"/etc/ssl/certs/ca-certificates.crt", "/nix/var/nix/profiles/default/etc/ssl/certs/ca-bundle.crt"})
if (pathExists(fn)) {
caFile = fn;
break;
}
}
/* Backwards compatibility. */
auto s = getEnv("NIX_REMOTE_SYSTEMS");
if (s) {
Strings ss;
for (auto & p : tokenizeString<Strings>(*s, ":"))
ss.push_back("@" + p);
builders = concatStringsSep(" ", ss);
}
#if defined(__linux__) && defined(SANDBOX_SHELL)
sandboxPaths = tokenizeString<StringSet>("/bin/sh=" SANDBOX_SHELL);
#endif
/* chroot-like behavior from Apple's sandbox */
#if __APPLE__
sandboxPaths = tokenizeString<StringSet>("/System/Library/Frameworks /System/Library/PrivateFrameworks /bin/sh /bin/bash /private/tmp /private/var/tmp /usr/lib");
allowedImpureHostPrefixes = tokenizeString<StringSet>("/System/Library /usr/lib /dev /bin/sh");
#endif
buildHook = getSelfExe().value_or("nix") + " __build-remote";
}
void loadConfFile()
{
globalConfig.applyConfigFile(settings.nixConfDir + "/nix.conf");
/* We only want to send overrides to the daemon, i.e. stuff from
~/.nix/nix.conf or the command line. */
globalConfig.resetOverridden();
auto files = settings.nixUserConfFiles;
for (auto file = files.rbegin(); file != files.rend(); file++) {
globalConfig.applyConfigFile(*file);
}
auto nixConfEnv = getEnv("NIX_CONFIG");
if (nixConfEnv.has_value()) {
globalConfig.applyConfig(nixConfEnv.value(), "NIX_CONFIG");
}
}
std::vector<Path> getUserConfigFiles()
{
// Use the paths specified in NIX_USER_CONF_FILES if it has been defined
auto nixConfFiles = getEnv("NIX_USER_CONF_FILES");
if (nixConfFiles.has_value()) {
return tokenizeString<std::vector<std::string>>(nixConfFiles.value(), ":");
}
// Use the paths specified by the XDG spec
std::vector<Path> files;
auto dirs = getConfigDirs();
for (auto & dir : dirs) {
files.insert(files.end(), dir + "/nix/nix.conf");
}
return files;
}
unsigned int Settings::getDefaultCores()
{
const unsigned int concurrency = std::max(1U, std::thread::hardware_concurrency());
const unsigned int maxCPU = getMaxCPU();
if (maxCPU > 0)
return maxCPU;
else
return concurrency;
}
StringSet Settings::getDefaultSystemFeatures()
{
/* For backwards compatibility, accept some "features" that are
used in Nixpkgs to route builds to certain machines but don't
actually require anything special on the machines. */
StringSet features{"nixos-test", "benchmark", "big-parallel"};
#if __linux__
if (access("/dev/kvm", R_OK | W_OK) == 0)
features.insert("kvm");
#endif
return features;
}
StringSet Settings::getDefaultExtraPlatforms()
{
StringSet extraPlatforms;
if (std::string{SYSTEM} == "x86_64-linux" && !isWSL1())
extraPlatforms.insert("i686-linux");
#if __linux__
StringSet levels = computeLevels();
for (auto iter = levels.begin(); iter != levels.end(); ++iter)
extraPlatforms.insert(*iter + "-linux");
#elif __APPLE__
// Rosetta 2 emulation layer can run x86_64 binaries on aarch64
// machines. Note that we can’t force processes from executing
// x86_64 in aarch64 environments or vice versa since they can
// always exec with their own binary preferences.
if (std::string{SYSTEM} == "aarch64-darwin") {
if (runProgram(RunOptions {.program = "arch", .args = {"-arch", "x86_64", "/bin/pwd"}, .mergeStderrToStdout = true}).first == 0) {
debug("Rosetta detected");
extraPlatforms.insert("x86_64-darwin");
} else
debug("Rosetta not detected");
}
#endif
return extraPlatforms;
}
bool Settings::isExperimentalFeatureEnabled(const ExperimentalFeature & feature)
{
auto & f = experimentalFeatures.get();
return std::find(f.begin(), f.end(), feature) != f.end();
}
void Settings::requireExperimentalFeature(const ExperimentalFeature & feature)
{
if (!isExperimentalFeatureEnabled(feature))
throw MissingExperimentalFeature(feature);
}
bool Settings::isWSL1()
{
struct utsname utsbuf;
uname(&utsbuf);
// WSL1 uses -Microsoft suffix
// WSL2 uses -microsoft-standard suffix
return hasSuffix(utsbuf.release, "-Microsoft");
}
const std::string nixVersion = PACKAGE_VERSION;
NLOHMANN_JSON_SERIALIZE_ENUM(SandboxMode, {
{SandboxMode::smEnabled, true},
{SandboxMode::smRelaxed, "relaxed"},
{SandboxMode::smDisabled, false},
});
template<> void BaseSetting<SandboxMode>::set(const std::string & str, bool append)
{
if (str == "true") value = smEnabled;
else if (str == "relaxed") value = smRelaxed;
else if (str == "false") value = smDisabled;
else throw UsageError("option '%s' has invalid value '%s'", name, str);
}
template<> bool BaseSetting<SandboxMode>::isAppendable()
{
return false;
}
template<> std::string BaseSetting<SandboxMode>::to_string() const
{
if (value == smEnabled) return "true";
else if (value == smRelaxed) return "relaxed";
else if (value == smDisabled) return "false";
else abort();
}
template<> void BaseSetting<SandboxMode>::convertToArg(Args & args, const std::string & category)
{
args.addFlag({
.longName = name,
.description = "Enable sandboxing.",
.category = category,
.handler = {[=]() { override(smEnabled); }}
});
args.addFlag({
.longName = "no-" + name,
.description = "Disable sandboxing.",
.category = category,
.handler = {[=]() { override(smDisabled); }}
});
args.addFlag({
.longName = "relaxed-" + name,
.description = "Enable sandboxing, but allow builds to disable it.",
.category = category,
.handler = {[=]() { override(smRelaxed); }}
});
}
void MaxBuildJobsSetting::set(const std::string & str, bool append)
{
if (str == "auto") value = std::max(1U, std::thread::hardware_concurrency());
else {
if (auto n = string2Int<decltype(value)>(str))
value = *n;
else
throw UsageError("configuration setting '%s' should be 'auto' or an integer", name);
}
}
void PluginFilesSetting::set(const std::string & str, bool append)
{
if (pluginsLoaded)
throw UsageError("plugin-files set after plugins were loaded, you may need to move the flag before the subcommand");
BaseSetting<Paths>::set(str, append);
}
void initPlugins()
{
assert(!settings.pluginFiles.pluginsLoaded);
for (const auto & pluginFile : settings.pluginFiles.get()) {
Paths pluginFiles;
try {
auto ents = readDirectory(pluginFile);
for (const auto & ent : ents)
pluginFiles.emplace_back(pluginFile + "/" + ent.name);
} catch (SysError & e) {
if (e.errNo != ENOTDIR)
throw;
pluginFiles.emplace_back(pluginFile);
}
for (const auto & file : pluginFiles) {
/* handle is purposefully leaked as there may be state in the
DSO needed by the action of the plugin. */
void *handle =
dlopen(file.c_str(), RTLD_LAZY | RTLD_LOCAL);
if (!handle)
throw Error("could not dynamically open plugin file '%s': %s", file, dlerror());
}
}
/* Since plugins can add settings, try to re-apply previously
unknown settings. */
globalConfig.reapplyUnknownSettings();
globalConfig.warnUnknownSettings();
/* Tell the user if they try to set plugin-files after we've already loaded */
settings.pluginFiles.pluginsLoaded = true;
}
}
<commit_msg>Use /usr/bin/true<commit_after>#include "globals.hh"
#include "util.hh"
#include "archive.hh"
#include "args.hh"
#include "abstract-setting-to-json.hh"
#include "compute-levels.hh"
#include <algorithm>
#include <map>
#include <thread>
#include <dlfcn.h>
#include <sys/utsname.h>
#include <nlohmann/json.hpp>
namespace nix {
/* The default location of the daemon socket, relative to nixStateDir.
The socket is in a directory to allow you to control access to the
Nix daemon by setting the mode/ownership of the directory
appropriately. (This wouldn't work on the socket itself since it
must be deleted and recreated on startup.) */
#define DEFAULT_SOCKET_PATH "/daemon-socket/socket"
Settings settings;
static GlobalConfig::Register rSettings(&settings);
Settings::Settings()
: nixPrefix(NIX_PREFIX)
, nixStore(canonPath(getEnv("NIX_STORE_DIR").value_or(getEnv("NIX_STORE").value_or(NIX_STORE_DIR))))
, nixDataDir(canonPath(getEnv("NIX_DATA_DIR").value_or(NIX_DATA_DIR)))
, nixLogDir(canonPath(getEnv("NIX_LOG_DIR").value_or(NIX_LOG_DIR)))
, nixStateDir(canonPath(getEnv("NIX_STATE_DIR").value_or(NIX_STATE_DIR)))
, nixConfDir(canonPath(getEnv("NIX_CONF_DIR").value_or(NIX_CONF_DIR)))
, nixUserConfFiles(getUserConfigFiles())
, nixBinDir(canonPath(getEnv("NIX_BIN_DIR").value_or(NIX_BIN_DIR)))
, nixManDir(canonPath(NIX_MAN_DIR))
, nixDaemonSocketFile(canonPath(getEnv("NIX_DAEMON_SOCKET_PATH").value_or(nixStateDir + DEFAULT_SOCKET_PATH)))
{
buildUsersGroup = getuid() == 0 ? "nixbld" : "";
lockCPU = getEnv("NIX_AFFINITY_HACK") == "1";
allowSymlinkedStore = getEnv("NIX_IGNORE_SYMLINK_STORE") == "1";
caFile = getEnv("NIX_SSL_CERT_FILE").value_or(getEnv("SSL_CERT_FILE").value_or(""));
if (caFile == "") {
for (auto & fn : {"/etc/ssl/certs/ca-certificates.crt", "/nix/var/nix/profiles/default/etc/ssl/certs/ca-bundle.crt"})
if (pathExists(fn)) {
caFile = fn;
break;
}
}
/* Backwards compatibility. */
auto s = getEnv("NIX_REMOTE_SYSTEMS");
if (s) {
Strings ss;
for (auto & p : tokenizeString<Strings>(*s, ":"))
ss.push_back("@" + p);
builders = concatStringsSep(" ", ss);
}
#if defined(__linux__) && defined(SANDBOX_SHELL)
sandboxPaths = tokenizeString<StringSet>("/bin/sh=" SANDBOX_SHELL);
#endif
/* chroot-like behavior from Apple's sandbox */
#if __APPLE__
sandboxPaths = tokenizeString<StringSet>("/System/Library/Frameworks /System/Library/PrivateFrameworks /bin/sh /bin/bash /private/tmp /private/var/tmp /usr/lib");
allowedImpureHostPrefixes = tokenizeString<StringSet>("/System/Library /usr/lib /dev /bin/sh");
#endif
buildHook = getSelfExe().value_or("nix") + " __build-remote";
}
void loadConfFile()
{
globalConfig.applyConfigFile(settings.nixConfDir + "/nix.conf");
/* We only want to send overrides to the daemon, i.e. stuff from
~/.nix/nix.conf or the command line. */
globalConfig.resetOverridden();
auto files = settings.nixUserConfFiles;
for (auto file = files.rbegin(); file != files.rend(); file++) {
globalConfig.applyConfigFile(*file);
}
auto nixConfEnv = getEnv("NIX_CONFIG");
if (nixConfEnv.has_value()) {
globalConfig.applyConfig(nixConfEnv.value(), "NIX_CONFIG");
}
}
std::vector<Path> getUserConfigFiles()
{
// Use the paths specified in NIX_USER_CONF_FILES if it has been defined
auto nixConfFiles = getEnv("NIX_USER_CONF_FILES");
if (nixConfFiles.has_value()) {
return tokenizeString<std::vector<std::string>>(nixConfFiles.value(), ":");
}
// Use the paths specified by the XDG spec
std::vector<Path> files;
auto dirs = getConfigDirs();
for (auto & dir : dirs) {
files.insert(files.end(), dir + "/nix/nix.conf");
}
return files;
}
unsigned int Settings::getDefaultCores()
{
const unsigned int concurrency = std::max(1U, std::thread::hardware_concurrency());
const unsigned int maxCPU = getMaxCPU();
if (maxCPU > 0)
return maxCPU;
else
return concurrency;
}
StringSet Settings::getDefaultSystemFeatures()
{
/* For backwards compatibility, accept some "features" that are
used in Nixpkgs to route builds to certain machines but don't
actually require anything special on the machines. */
StringSet features{"nixos-test", "benchmark", "big-parallel"};
#if __linux__
if (access("/dev/kvm", R_OK | W_OK) == 0)
features.insert("kvm");
#endif
return features;
}
StringSet Settings::getDefaultExtraPlatforms()
{
StringSet extraPlatforms;
if (std::string{SYSTEM} == "x86_64-linux" && !isWSL1())
extraPlatforms.insert("i686-linux");
#if __linux__
StringSet levels = computeLevels();
for (auto iter = levels.begin(); iter != levels.end(); ++iter)
extraPlatforms.insert(*iter + "-linux");
#elif __APPLE__
// Rosetta 2 emulation layer can run x86_64 binaries on aarch64
// machines. Note that we can’t force processes from executing
// x86_64 in aarch64 environments or vice versa since they can
// always exec with their own binary preferences.
if (std::string{SYSTEM} == "aarch64-darwin") {
if (runProgram(RunOptions {.program = "arch", .args = {"-arch", "x86_64", "/usr/bin/true"}, .mergeStderrToStdout = true}).first == 0) {
debug("Rosetta detected");
extraPlatforms.insert("x86_64-darwin");
} else
debug("Rosetta not detected");
}
#endif
return extraPlatforms;
}
bool Settings::isExperimentalFeatureEnabled(const ExperimentalFeature & feature)
{
auto & f = experimentalFeatures.get();
return std::find(f.begin(), f.end(), feature) != f.end();
}
void Settings::requireExperimentalFeature(const ExperimentalFeature & feature)
{
if (!isExperimentalFeatureEnabled(feature))
throw MissingExperimentalFeature(feature);
}
bool Settings::isWSL1()
{
struct utsname utsbuf;
uname(&utsbuf);
// WSL1 uses -Microsoft suffix
// WSL2 uses -microsoft-standard suffix
return hasSuffix(utsbuf.release, "-Microsoft");
}
const std::string nixVersion = PACKAGE_VERSION;
NLOHMANN_JSON_SERIALIZE_ENUM(SandboxMode, {
{SandboxMode::smEnabled, true},
{SandboxMode::smRelaxed, "relaxed"},
{SandboxMode::smDisabled, false},
});
template<> void BaseSetting<SandboxMode>::set(const std::string & str, bool append)
{
if (str == "true") value = smEnabled;
else if (str == "relaxed") value = smRelaxed;
else if (str == "false") value = smDisabled;
else throw UsageError("option '%s' has invalid value '%s'", name, str);
}
template<> bool BaseSetting<SandboxMode>::isAppendable()
{
return false;
}
template<> std::string BaseSetting<SandboxMode>::to_string() const
{
if (value == smEnabled) return "true";
else if (value == smRelaxed) return "relaxed";
else if (value == smDisabled) return "false";
else abort();
}
template<> void BaseSetting<SandboxMode>::convertToArg(Args & args, const std::string & category)
{
args.addFlag({
.longName = name,
.description = "Enable sandboxing.",
.category = category,
.handler = {[=]() { override(smEnabled); }}
});
args.addFlag({
.longName = "no-" + name,
.description = "Disable sandboxing.",
.category = category,
.handler = {[=]() { override(smDisabled); }}
});
args.addFlag({
.longName = "relaxed-" + name,
.description = "Enable sandboxing, but allow builds to disable it.",
.category = category,
.handler = {[=]() { override(smRelaxed); }}
});
}
void MaxBuildJobsSetting::set(const std::string & str, bool append)
{
if (str == "auto") value = std::max(1U, std::thread::hardware_concurrency());
else {
if (auto n = string2Int<decltype(value)>(str))
value = *n;
else
throw UsageError("configuration setting '%s' should be 'auto' or an integer", name);
}
}
void PluginFilesSetting::set(const std::string & str, bool append)
{
if (pluginsLoaded)
throw UsageError("plugin-files set after plugins were loaded, you may need to move the flag before the subcommand");
BaseSetting<Paths>::set(str, append);
}
void initPlugins()
{
assert(!settings.pluginFiles.pluginsLoaded);
for (const auto & pluginFile : settings.pluginFiles.get()) {
Paths pluginFiles;
try {
auto ents = readDirectory(pluginFile);
for (const auto & ent : ents)
pluginFiles.emplace_back(pluginFile + "/" + ent.name);
} catch (SysError & e) {
if (e.errNo != ENOTDIR)
throw;
pluginFiles.emplace_back(pluginFile);
}
for (const auto & file : pluginFiles) {
/* handle is purposefully leaked as there may be state in the
DSO needed by the action of the plugin. */
void *handle =
dlopen(file.c_str(), RTLD_LAZY | RTLD_LOCAL);
if (!handle)
throw Error("could not dynamically open plugin file '%s': %s", file, dlerror());
}
}
/* Since plugins can add settings, try to re-apply previously
unknown settings. */
globalConfig.reapplyUnknownSettings();
globalConfig.warnUnknownSettings();
/* Tell the user if they try to set plugin-files after we've already loaded */
settings.pluginFiles.pluginsLoaded = true;
}
}
<|endoftext|>
|
<commit_before>#include <cctype>
#include <fstream>
#include <stdio.h>
#include <sstream> // ostringstream
#include "utils/logoutput.h"
#include "settings.h"
#include "settingRegistry.h"
namespace cura
{
//c++11 no longer defines M_PI, so add our own constant.
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
std::string toString(EGCodeFlavor flavor)
{
switch (flavor)
{
case EGCodeFlavor::BFB:
return "BFB";
case EGCodeFlavor::MACH3:
return "Mach3";
case EGCodeFlavor::MAKERBOT:
return "Makerbot";
case EGCodeFlavor::ULTIGCODE:
return "UltiGcode";
case EGCodeFlavor::REPRAP_VOLUMATRIC:
return "RepRap(Volumentric)";
case EGCodeFlavor::REPRAP:
default:
return "RepRap";
}
}
SettingsBaseVirtual::SettingsBaseVirtual()
: parent(NULL)
{
}
SettingsBaseVirtual::SettingsBaseVirtual(SettingsBaseVirtual* parent)
: parent(parent)
{
}
SettingsBase::SettingsBase()
: SettingsBaseVirtual(NULL)
{
}
SettingsBase::SettingsBase(SettingsBaseVirtual* parent)
: SettingsBaseVirtual(parent)
{
}
SettingsMessenger::SettingsMessenger(SettingsBaseVirtual* parent)
: SettingsBaseVirtual(parent)
{
}
void SettingsBase::setSetting(std::string key, std::string value)
{
if (SettingRegistry::getInstance()->settingExists(key))
{
setting_values[key] = value;
}
else
{
cura::logError("Warning: setting an unregistered setting %s\n", key.c_str() );
setting_values[key] = value; // Handy when programmers are in the process of introducing a new setting
}
}
std::string SettingsBase::getSettingString(std::string key)
{
if (setting_values.find(key) != setting_values.end())
{
return setting_values[key];
}
if (parent)
{
return parent->getSettingString(key);
}
if (SettingRegistry::getInstance()->settingExists(key))
{
setting_values[key] = SettingRegistry::getInstance()->getSettingConfig(key)->getDefaultValue();
}
else
{
setting_values[key] = "";
cura::logError("Unregistered setting %s\n", key.c_str());
}
return setting_values[key];
}
void SettingsMessenger::setSetting(std::string key, std::string value)
{
parent->setSetting(key, value);
}
std::string SettingsMessenger::getSettingString(std::string key)
{
return parent->getSettingString(key);
}
void SettingsBase::setExtruderTrainDefaults(unsigned int extruder_nr)
{
const SettingContainer* machine_extruder_trains = SettingRegistry::getInstance()->getCategory(std::string("machine_extruder_trains"));
if (!machine_extruder_trains)
{
// no machine_extruder_trains setting present; just use defaults for each train..
return;
}
const SettingConfig* train = machine_extruder_trains->getChild(extruder_nr);
if (!train)
{
logError("Not enough extruder trains specified in JSON: %i\n", extruder_nr);
return;
}
for (const SettingConfig& setting : train->getChildren())
{
if (setting_values.find(setting.getKey()) == setting_values.end())
{
setSetting(setting.getKey(), setting.getDefaultValue());
}
}
}
int SettingsBaseVirtual::getSettingAsIndex(std::string key)
{
std::string value = getSettingString(key);
return atoi(value.c_str());
}
int SettingsBaseVirtual::getSettingAsCount(std::string key)
{
std::string value = getSettingString(key);
return atoi(value.c_str());
}
int SettingsBaseVirtual::getSettingInMicrons(std::string key)
{
std::string value = getSettingString(key);
return atof(value.c_str()) * 1000.0;
}
double SettingsBaseVirtual::getSettingInAngleRadians(std::string key)
{
std::string value = getSettingString(key);
return atof(value.c_str()) / 180.0 * M_PI;
}
bool SettingsBaseVirtual::getSettingBoolean(std::string key)
{
std::string value = getSettingString(key);
if (value == "on")
return true;
if (value == "yes")
return true;
if (value == "true" or value == "True") //Python uses "True"
return true;
int num = atoi(value.c_str());
return num != 0;
}
double SettingsBaseVirtual::getSettingInDegreeCelsius(std::string key)
{
std::string value = getSettingString(key);
return atof(value.c_str());
}
double SettingsBaseVirtual::getSettingInMillimetersPerSecond(std::string key)
{
std::string value = getSettingString(key);
return std::max(1.0, atof(value.c_str()));
}
double SettingsBaseVirtual::getSettingInCubicMillimeters(std::string key)
{
std::string value = getSettingString(key);
return std::max(0.0, atof(value.c_str()));
}
double SettingsBaseVirtual::getSettingInPercentage(std::string key)
{
std::string value = getSettingString(key);
return std::max(0.0, atof(value.c_str()));
}
double SettingsBaseVirtual::getSettingInSeconds(std::string key)
{
std::string value = getSettingString(key);
return std::max(0.0, atof(value.c_str()));
}
EGCodeFlavor SettingsBaseVirtual::getSettingAsGCodeFlavor(std::string key)
{
std::string value = getSettingString(key);
if (value == "RepRap")
return EGCodeFlavor::REPRAP;
else if (value == "UltiGCode")
return EGCodeFlavor::ULTIGCODE;
else if (value == "Makerbot")
return EGCodeFlavor::MAKERBOT;
else if (value == "BFB")
return EGCodeFlavor::BFB;
else if (value == "MACH3")
return EGCodeFlavor::MACH3;
else if (value == "RepRap (Volumatric)")
return EGCodeFlavor::REPRAP_VOLUMATRIC;
return EGCodeFlavor::REPRAP;
}
EFillMethod SettingsBaseVirtual::getSettingAsFillMethod(std::string key)
{
std::string value = getSettingString(key);
if (value == "lines")
return EFillMethod::LINES;
if (value == "grid")
return EFillMethod::GRID;
if (value == "triangles")
return EFillMethod::TRIANGLES;
if (value == "concentric")
return EFillMethod::CONCENTRIC;
if (value == "zigzag")
return EFillMethod::ZIG_ZAG;
return EFillMethod::NONE;
}
EPlatformAdhesion SettingsBaseVirtual::getSettingAsPlatformAdhesion(std::string key)
{
std::string value = getSettingString(key);
if (value == "brim")
return EPlatformAdhesion::BRIM;
if (value == "raft")
return EPlatformAdhesion::RAFT;
return EPlatformAdhesion::SKIRT;
}
ESupportType SettingsBaseVirtual::getSettingAsSupportType(std::string key)
{
std::string value = getSettingString(key);
if (value == "everywhere")
return ESupportType::EVERYWHERE;
if (value == "buildplate")
return ESupportType::PLATFORM_ONLY;
return ESupportType::NONE;
}
EZSeamType SettingsBaseVirtual::getSettingAsZSeamType(std::string key)
{
std::string value = getSettingString(key);
if (value == "random")
return EZSeamType::RANDOM;
if (value == "shortest")
return EZSeamType::SHORTEST;
if (value == "back")
return EZSeamType::BACK;
return EZSeamType::SHORTEST;
}
ESurfaceMode SettingsBaseVirtual::getSettingAsSurfaceMode(std::string key)
{
std::string value = getSettingString(key);
if (value == "normal")
return ESurfaceMode::NORMAL;
if (value == "surface")
return ESurfaceMode::SURFACE;
if (value == "both")
return ESurfaceMode::BOTH;
return ESurfaceMode::NORMAL;
}
FillPerimeterGapMode SettingsBaseVirtual::getSettingAsFillPerimeterGapMode(std::string key)
{
std::string value = getSettingString(key);
if (value == "nowhere")
{
return FillPerimeterGapMode::NOWHERE;
}
if (value == "everywhere")
{
return FillPerimeterGapMode::EVERYWHERE;
}
if (value == "skin")
{
return FillPerimeterGapMode::SKIN;
}
return FillPerimeterGapMode::NOWHERE;
}
}//namespace cura
<commit_msg>bugfix: gcode flavor prepended for UM2 was incorrect<commit_after>#include <cctype>
#include <fstream>
#include <stdio.h>
#include <sstream> // ostringstream
#include "utils/logoutput.h"
#include "settings.h"
#include "settingRegistry.h"
namespace cura
{
//c++11 no longer defines M_PI, so add our own constant.
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
std::string toString(EGCodeFlavor flavor)
{
switch (flavor)
{
case EGCodeFlavor::BFB:
return "BFB";
case EGCodeFlavor::MACH3:
return "Mach3";
case EGCodeFlavor::MAKERBOT:
return "Makerbot";
case EGCodeFlavor::ULTIGCODE:
return "UltiGCode";
case EGCodeFlavor::REPRAP_VOLUMATRIC:
return "RepRap(Volumentric)";
case EGCodeFlavor::REPRAP:
default:
return "RepRap";
}
}
SettingsBaseVirtual::SettingsBaseVirtual()
: parent(NULL)
{
}
SettingsBaseVirtual::SettingsBaseVirtual(SettingsBaseVirtual* parent)
: parent(parent)
{
}
SettingsBase::SettingsBase()
: SettingsBaseVirtual(NULL)
{
}
SettingsBase::SettingsBase(SettingsBaseVirtual* parent)
: SettingsBaseVirtual(parent)
{
}
SettingsMessenger::SettingsMessenger(SettingsBaseVirtual* parent)
: SettingsBaseVirtual(parent)
{
}
void SettingsBase::setSetting(std::string key, std::string value)
{
if (SettingRegistry::getInstance()->settingExists(key))
{
setting_values[key] = value;
}
else
{
cura::logError("Warning: setting an unregistered setting %s\n", key.c_str() );
setting_values[key] = value; // Handy when programmers are in the process of introducing a new setting
}
}
std::string SettingsBase::getSettingString(std::string key)
{
if (setting_values.find(key) != setting_values.end())
{
return setting_values[key];
}
if (parent)
{
return parent->getSettingString(key);
}
if (SettingRegistry::getInstance()->settingExists(key))
{
setting_values[key] = SettingRegistry::getInstance()->getSettingConfig(key)->getDefaultValue();
}
else
{
setting_values[key] = "";
cura::logError("Unregistered setting %s\n", key.c_str());
}
return setting_values[key];
}
void SettingsMessenger::setSetting(std::string key, std::string value)
{
parent->setSetting(key, value);
}
std::string SettingsMessenger::getSettingString(std::string key)
{
return parent->getSettingString(key);
}
void SettingsBase::setExtruderTrainDefaults(unsigned int extruder_nr)
{
const SettingContainer* machine_extruder_trains = SettingRegistry::getInstance()->getCategory(std::string("machine_extruder_trains"));
if (!machine_extruder_trains)
{
// no machine_extruder_trains setting present; just use defaults for each train..
return;
}
const SettingConfig* train = machine_extruder_trains->getChild(extruder_nr);
if (!train)
{
logError("Not enough extruder trains specified in JSON: %i\n", extruder_nr);
return;
}
for (const SettingConfig& setting : train->getChildren())
{
if (setting_values.find(setting.getKey()) == setting_values.end())
{
setSetting(setting.getKey(), setting.getDefaultValue());
}
}
}
int SettingsBaseVirtual::getSettingAsIndex(std::string key)
{
std::string value = getSettingString(key);
return atoi(value.c_str());
}
int SettingsBaseVirtual::getSettingAsCount(std::string key)
{
std::string value = getSettingString(key);
return atoi(value.c_str());
}
int SettingsBaseVirtual::getSettingInMicrons(std::string key)
{
std::string value = getSettingString(key);
return atof(value.c_str()) * 1000.0;
}
double SettingsBaseVirtual::getSettingInAngleRadians(std::string key)
{
std::string value = getSettingString(key);
return atof(value.c_str()) / 180.0 * M_PI;
}
bool SettingsBaseVirtual::getSettingBoolean(std::string key)
{
std::string value = getSettingString(key);
if (value == "on")
return true;
if (value == "yes")
return true;
if (value == "true" or value == "True") //Python uses "True"
return true;
int num = atoi(value.c_str());
return num != 0;
}
double SettingsBaseVirtual::getSettingInDegreeCelsius(std::string key)
{
std::string value = getSettingString(key);
return atof(value.c_str());
}
double SettingsBaseVirtual::getSettingInMillimetersPerSecond(std::string key)
{
std::string value = getSettingString(key);
return std::max(1.0, atof(value.c_str()));
}
double SettingsBaseVirtual::getSettingInCubicMillimeters(std::string key)
{
std::string value = getSettingString(key);
return std::max(0.0, atof(value.c_str()));
}
double SettingsBaseVirtual::getSettingInPercentage(std::string key)
{
std::string value = getSettingString(key);
return std::max(0.0, atof(value.c_str()));
}
double SettingsBaseVirtual::getSettingInSeconds(std::string key)
{
std::string value = getSettingString(key);
return std::max(0.0, atof(value.c_str()));
}
EGCodeFlavor SettingsBaseVirtual::getSettingAsGCodeFlavor(std::string key)
{
std::string value = getSettingString(key);
if (value == "RepRap")
return EGCodeFlavor::REPRAP;
else if (value == "UltiGCode")
return EGCodeFlavor::ULTIGCODE;
else if (value == "Makerbot")
return EGCodeFlavor::MAKERBOT;
else if (value == "BFB")
return EGCodeFlavor::BFB;
else if (value == "MACH3")
return EGCodeFlavor::MACH3;
else if (value == "RepRap (Volumatric)")
return EGCodeFlavor::REPRAP_VOLUMATRIC;
return EGCodeFlavor::REPRAP;
}
EFillMethod SettingsBaseVirtual::getSettingAsFillMethod(std::string key)
{
std::string value = getSettingString(key);
if (value == "lines")
return EFillMethod::LINES;
if (value == "grid")
return EFillMethod::GRID;
if (value == "triangles")
return EFillMethod::TRIANGLES;
if (value == "concentric")
return EFillMethod::CONCENTRIC;
if (value == "zigzag")
return EFillMethod::ZIG_ZAG;
return EFillMethod::NONE;
}
EPlatformAdhesion SettingsBaseVirtual::getSettingAsPlatformAdhesion(std::string key)
{
std::string value = getSettingString(key);
if (value == "brim")
return EPlatformAdhesion::BRIM;
if (value == "raft")
return EPlatformAdhesion::RAFT;
return EPlatformAdhesion::SKIRT;
}
ESupportType SettingsBaseVirtual::getSettingAsSupportType(std::string key)
{
std::string value = getSettingString(key);
if (value == "everywhere")
return ESupportType::EVERYWHERE;
if (value == "buildplate")
return ESupportType::PLATFORM_ONLY;
return ESupportType::NONE;
}
EZSeamType SettingsBaseVirtual::getSettingAsZSeamType(std::string key)
{
std::string value = getSettingString(key);
if (value == "random")
return EZSeamType::RANDOM;
if (value == "shortest")
return EZSeamType::SHORTEST;
if (value == "back")
return EZSeamType::BACK;
return EZSeamType::SHORTEST;
}
ESurfaceMode SettingsBaseVirtual::getSettingAsSurfaceMode(std::string key)
{
std::string value = getSettingString(key);
if (value == "normal")
return ESurfaceMode::NORMAL;
if (value == "surface")
return ESurfaceMode::SURFACE;
if (value == "both")
return ESurfaceMode::BOTH;
return ESurfaceMode::NORMAL;
}
FillPerimeterGapMode SettingsBaseVirtual::getSettingAsFillPerimeterGapMode(std::string key)
{
std::string value = getSettingString(key);
if (value == "nowhere")
{
return FillPerimeterGapMode::NOWHERE;
}
if (value == "everywhere")
{
return FillPerimeterGapMode::EVERYWHERE;
}
if (value == "skin")
{
return FillPerimeterGapMode::SKIN;
}
return FillPerimeterGapMode::NOWHERE;
}
}//namespace cura
<|endoftext|>
|
<commit_before>/*
* Copyright 2009-2017 The VOTCA Development Team
* (http://www.votca.org)
*
* 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 <votca/xtp/gwbse.h>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include <boost/numeric/ublas/operation.hpp>
#include <votca/xtp/aomatrix.h>
#include <votca/xtp/threecenters.h>
// #include <votca/xtp/logger.h>
#include <votca/xtp/qmpackagefactory.h>
#include <boost/math/constants/constants.hpp>
#include <boost/numeric/ublas/symmetric.hpp>
#include <votca/xtp/aoshell.h>
using boost::format;
using namespace boost::filesystem;
namespace votca {
namespace xtp {
namespace ub = boost::numeric::ublas;
void GWBSE::PPM_construct_parameters(const ub::matrix<double>& _overlap_cholesky_inverse) {
// multiply with L-1^t from the right
ub::matrix<double> _temp = ub::prod(_epsilon[0], ub::trans(_overlap_cholesky_inverse));
// multiply with L-1 from the left
_temp = ub::prod(_overlap_cholesky_inverse, _temp);
// get eigenvalues and eigenvectors of this matrix
ub::vector<double> _eigenvalues;
ub::matrix<double> _eigenvectors;
linalg_eigenvalues(_temp, _eigenvalues, _eigenvectors);
_eigenvectors=ub::trans(_eigenvectors);
// multiply eigenvectors with overlap_cholesky_inverse and store as eigenvalues of epsilon
_ppm_phi = ub::prod(_eigenvectors, _overlap_cholesky_inverse);
// store PPM weights from eigenvalues
_ppm_weight.resize(_eigenvalues.size());
for (unsigned _i = 0; _i < _eigenvalues.size(); _i++) {
_ppm_weight(_i) = 1.0 - 1.0 / _eigenvalues(_i);
}
// determine PPM frequencies
_ppm_freq.resize(_eigenvalues.size());
// a) phi^t * epsilon(1) * phi
_temp = ub::prod(_ppm_phi, _epsilon[1]);
_eigenvectors = ub::prod(_temp, ub::trans(_ppm_phi));
// b) invert
linalg_invert(_eigenvectors, _temp);
// c) PPM parameters -> diagonal elements
#pragma omp parallel for
for (unsigned _i = 0; _i < _eigenvalues.size(); _i++) {
if (_screening_freq(1, 0) == 0.0) {
if (_ppm_weight(_i) < 1.e-5) {
_ppm_weight(_i) = 0.0;
_ppm_freq(_i) = 0.5;//Hartree
continue;
} else {
double _nom = _temp(_i, _i) - 1.0;
double _frac = -1.0 * _nom / (_nom + _ppm_weight(_i)) * _screening_freq(1, 1) * _screening_freq(1, 1);
_ppm_freq(_i) = sqrt(std::abs(_frac));
}
} else {
// only purely imaginary frequency assumed
cerr << " mixed frequency! real part: " << _screening_freq(1, 0) << " imaginary part: " << _screening_freq(1, 1) << flush;
exit(1);
}
}
// epsilon can be deleted
_epsilon[0].resize(0, 0);
_epsilon[1].resize(0, 0);
return;
}
//imaginary
ub::matrix<double> GWBSE::RPA_imaginary(const TCMatrix& _Mmn_RPA,const double screening_freq) {
const int _size = _Mmn_RPA.get_beta(); // size of gwbasis
const int index_n = _Mmn_RPA.get_nmin();
const int index_m = _Mmn_RPA.get_mmin();
const double screenf2=screening_freq * screening_freq;
std::vector<ub::matrix<double> > result_thread;
unsigned nthreads = 1;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#endif
const ub::vector<double>& qp_energies= _qp_energies;
for(unsigned i=0;i<nthreads;++i){
result_thread.push_back(ub::zero_matrix<double>(_size));
}
#pragma omp parallel for
for(unsigned thread=0;thread<nthreads;++thread){
for (int _m_level = thread; _m_level < _Mmn_RPA.get_mtot(); _m_level+=nthreads) {
const double _qp_energy_m=qp_energies(_m_level + index_m);
#if (GWBSE_DOUBLE)
const ub::matrix<double>& Mmn_RPA = _Mmn_RPA[ _m_level ];
#else
const ub::matrix<double> Mmn_RPA = _Mmn_RPA[ _m_level ];
#endif
// a temporary matrix, that will get filled in empty levels loop
ub::matrix<double> _temp = ub::matrix<double>(_Mmn_RPA.get_ntot(), _size);
// loop over empty levels
for (int _n_level = 0; _n_level < _Mmn_RPA.get_ntot(); _n_level++) {
const double _deltaE = qp_energies(_n_level + index_n) -_qp_energy_m ; // get indices and units right!!!
// this only works, if we have either purely real or purely imaginary frequencies
// purely imaginary
const double _energy_factor = 4.0 * _deltaE / (_deltaE * _deltaE + screenf2);//hartree
for (int _i_gw = 0; _i_gw < _size; _i_gw++) {
_temp(_n_level, _i_gw) = _energy_factor * Mmn_RPA(_i_gw, _n_level);
} // matrix size
} // empty levels
// now multiply and add to epsilon
result_thread[thread] += ub::prod(Mmn_RPA, _temp);
} // occupied levels
}
ub::matrix<double> result=ub::zero_matrix<double>(_size);
for(unsigned thread=0;thread<nthreads;++thread){
result+=result_thread[thread];
}
return result;
}
//real
ub::matrix<double> GWBSE::RPA_real(const TCMatrix& _Mmn_RPA, const double screening_freq) {
const int _size = _Mmn_RPA.get_beta(); // size of gwbasis
const int index_n = _Mmn_RPA.get_nmin();
const int index_m = _Mmn_RPA.get_mmin();
const ub::vector<double>& qp_energies= _qp_energies;
std::vector<ub::matrix<double> > result_thread;
unsigned nthreads = 1;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#endif
for(unsigned i=0;i<nthreads;++i){
result_thread.push_back(ub::zero_matrix<double>(_size));
}
#pragma omp parallel for
for(unsigned thread=0;thread<nthreads;++thread){
for (int _m_level = thread; _m_level < _Mmn_RPA.get_mtot(); _m_level+=nthreads) {
const double _qp_energy_m=qp_energies(_m_level + index_m);
#if (GWBSE_DOUBLE)
const ub::matrix<double>& Mmn_RPA = _Mmn_RPA[ _m_level ];
#else
const ub::matrix<double> Mmn_RPA = _Mmn_RPA[ _m_level ];
#endif
// a temporary matrix, that will get filled in empty levels loop
ub::matrix<double> _temp = ub::matrix<double>(_Mmn_RPA.get_ntot(), _size);
// loop over empty levels
for (int _n_level = 0; _n_level < _Mmn_RPA.get_ntot(); _n_level++) {
const double _deltaE = qp_energies(_n_level + index_n) - _qp_energy_m; // get indices and units right!!!
// this only works, if we have either purely real or purely imaginary frequencies
// purely real
const double _energy_factor =2.0* (1.0 / (_deltaE - screening_freq) + 1.0 / (_deltaE + screening_freq));//hartree
for (int _i_gw = 0; _i_gw < _size; _i_gw++) {
_temp(_n_level, _i_gw) = _energy_factor * Mmn_RPA(_i_gw, _n_level);
} // matrix size
} // empty levels
// now multiply and add to epsilon
result_thread[thread] += ub::prod(Mmn_RPA, _temp);
} // occupied levels
}
ub::matrix<double> result=ub::zero_matrix<double>(_size);
for(unsigned thread=0;thread<nthreads;++thread){
result+=result_thread[thread];
}
return result;
}
void GWBSE::RPA_calculate_epsilon(const TCMatrix& _Mmn_RPA){
// loop over frequencies
for ( unsigned _i_freq = 0 ; _i_freq < _screening_freq.size1() ; _i_freq++ ){
if ( _screening_freq( _i_freq, 0) == 0.0 ) {
_epsilon[ _i_freq ]+=RPA_imaginary(_Mmn_RPA, _screening_freq( _i_freq, 1));
}
else if ( _screening_freq( _i_freq, 1) == 0.0 ) {
// purely real
_epsilon[ _i_freq ]+= RPA_real(_Mmn_RPA, _screening_freq( _i_freq, 0));
}
else {
// mixed -> FAIL
cerr << " mixed frequency! real part: " << _screening_freq( _i_freq, 0 ) << " imaginary part: " << _screening_freq( _i_freq, 1 ) << flush;
exit(1);
}
} // loop over frequencies
return;
}
void GWBSE::RPA_prepare_threecenters(TCMatrix& _Mmn_RPA,const TCMatrix& _Mmn_full){
ub::range full=ub::range(0, _Mmn_full.get_beta());
ub::range RPA_cut=ub::range(_Mmn_RPA.get_nmin() - _Mmn_full.get_nmin(), _Mmn_RPA.get_nmax() - _Mmn_full.get_nmin() + 1);
// loop over m-levels in _Mmn_RPA
#pragma omp parallel for
for (int _m_level = 0; _m_level < _Mmn_RPA.size(); _m_level++) {
// copy to _Mmn_RPA
_Mmn_RPA[ _m_level ] = ub::project(_Mmn_full[ _m_level ], full, RPA_cut);
}// loop m-levels
return;
}
}};
<commit_msg>rewrote RPA to old stuff again<commit_after>/*
* Copyright 2009-2017 The VOTCA Development Team
* (http://www.votca.org)
*
* 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 <votca/xtp/gwbse.h>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include <boost/numeric/ublas/operation.hpp>
#include <votca/xtp/aomatrix.h>
#include <votca/xtp/threecenters.h>
// #include <votca/xtp/logger.h>
#include <votca/xtp/qmpackagefactory.h>
#include <boost/math/constants/constants.hpp>
#include <boost/numeric/ublas/symmetric.hpp>
#include <votca/xtp/aoshell.h>
using boost::format;
using namespace boost::filesystem;
namespace votca {
namespace xtp {
namespace ub = boost::numeric::ublas;
void GWBSE::PPM_construct_parameters(const ub::matrix<double>& _overlap_cholesky_inverse) {
// multiply with L-1^t from the right
ub::matrix<double> _temp = ub::prod(_epsilon[0], ub::trans(_overlap_cholesky_inverse));
// multiply with L-1 from the left
_temp = ub::prod(_overlap_cholesky_inverse, _temp);
// get eigenvalues and eigenvectors of this matrix
ub::vector<double> _eigenvalues;
ub::matrix<double> _eigenvectors;
linalg_eigenvalues(_temp, _eigenvalues, _eigenvectors);
_eigenvectors=ub::trans(_eigenvectors);
// multiply eigenvectors with overlap_cholesky_inverse and store as eigenvalues of epsilon
_ppm_phi = ub::prod(_eigenvectors, _overlap_cholesky_inverse);
// store PPM weights from eigenvalues
_ppm_weight.resize(_eigenvalues.size());
for (unsigned _i = 0; _i < _eigenvalues.size(); _i++) {
_ppm_weight(_i) = 1.0 - 1.0 / _eigenvalues(_i);
}
// determine PPM frequencies
_ppm_freq.resize(_eigenvalues.size());
// a) phi^t * epsilon(1) * phi
_temp = ub::prod(_ppm_phi, _epsilon[1]);
_eigenvectors = ub::prod(_temp, ub::trans(_ppm_phi));
// b) invert
linalg_invert(_eigenvectors, _temp);
// c) PPM parameters -> diagonal elements
#pragma omp parallel for
for (unsigned _i = 0; _i < _eigenvalues.size(); _i++) {
if (_screening_freq(1, 0) == 0.0) {
if (_ppm_weight(_i) < 1.e-5) {
_ppm_weight(_i) = 0.0;
_ppm_freq(_i) = 0.5;//Hartree
continue;
} else {
double _nom = _temp(_i, _i) - 1.0;
double _frac = -1.0 * _nom / (_nom + _ppm_weight(_i)) * _screening_freq(1, 1) * _screening_freq(1, 1);
_ppm_freq(_i) = sqrt(std::abs(_frac));
}
} else {
// only purely imaginary frequency assumed
cerr << " mixed frequency! real part: " << _screening_freq(1, 0) << " imaginary part: " << _screening_freq(1, 1) << flush;
exit(1);
}
}
// epsilon can be deleted
_epsilon[0].resize(0, 0);
_epsilon[1].resize(0, 0);
return;
}
//imaginary
ub::matrix<double> GWBSE::RPA_imaginary(const TCMatrix& _Mmn_RPA,const double screening_freq) {
const int _size = _Mmn_RPA.get_beta(); // size of gwbasis
const int index_n = _Mmn_RPA.get_nmin();
const int index_m = _Mmn_RPA.get_mmin();
const double screenf2=screening_freq * screening_freq;
ub::matrix<double> result=ub::zero_matrix<double>(_size);
const ub::vector<double>& qp_energies= _qp_energies;
#pragma omp parallel for
for (int _m_level = 0; _m_level < _Mmn_RPA.get_mtot(); _m_level++) {
const double _qp_energy_m=qp_energies(_m_level + index_m);
#if (GWBSE_DOUBLE)
const ub::matrix<double>& Mmn_RPA = _Mmn_RPA[ _m_level ];
#else
const ub::matrix<double> Mmn_RPA = _Mmn_RPA[ _m_level ];
#endif
// a temporary matrix, that will get filled in empty levels loop
ub::matrix<double> _temp = ub::matrix<double>(_Mmn_RPA.get_ntot(), _size);
// loop over empty levels
for (int _n_level = 0; _n_level < _Mmn_RPA.get_ntot(); _n_level++) {
const double _deltaE = qp_energies(_n_level + index_n) -_qp_energy_m ; // get indices and units right!!!
// this only works, if we have either purely real or purely imaginary frequencies
// purely imaginary
const double _energy_factor = 4.0 * _deltaE / (_deltaE * _deltaE + screenf2);//hartree
for (int _i_gw = 0; _i_gw < _size; _i_gw++) {
_temp(_n_level, _i_gw) = _energy_factor * Mmn_RPA(_i_gw, _n_level);
} // matrix size
} // empty levels
_temp=ub::prod(Mmn_RPA, _temp);
// now multiply and add to epsilon
#pragma omp critical
{
result+=_temp;
}
} // occupied levels
return result;
}
//real
ub::matrix<double> GWBSE::RPA_real(const TCMatrix& _Mmn_RPA, const double screening_freq) {
const int _size = _Mmn_RPA.get_beta(); // size of gwbasis
const int index_n = _Mmn_RPA.get_nmin();
const int index_m = _Mmn_RPA.get_mmin();
const ub::vector<double>& qp_energies= _qp_energies;
ub::matrix<double> result=ub::zero_matrix<double>(_size);
#pragma omp parallel for
for (int _m_level = 0; _m_level < _Mmn_RPA.get_mtot(); _m_level++) {
const double _qp_energy_m=qp_energies(_m_level + index_m);
#if (GWBSE_DOUBLE)
const ub::matrix<double>& Mmn_RPA = _Mmn_RPA[ _m_level ];
#else
const ub::matrix<double> Mmn_RPA = _Mmn_RPA[ _m_level ];
#endif
// a temporary matrix, that will get filled in empty levels loop
ub::matrix<double> _temp = ub::matrix<double>(_Mmn_RPA.get_ntot(), _size);
// loop over empty levels
for (int _n_level = 0; _n_level < _Mmn_RPA.get_ntot(); _n_level++) {
const double _deltaE = qp_energies(_n_level + index_n) - _qp_energy_m; // get indices and units right!!!
// this only works, if we have either purely real or purely imaginary frequencies
// purely real
const double _energy_factor =2.0* (1.0 / (_deltaE - screening_freq) + 1.0 / (_deltaE + screening_freq));//hartree
for (int _i_gw = 0; _i_gw < _size; _i_gw++) {
_temp(_n_level, _i_gw) = _energy_factor * Mmn_RPA(_i_gw, _n_level);
} // matrix size
} // empty levels
// now multiply and add to epsilon
_temp=ub::prod(Mmn_RPA, _temp);
#pragma omp critical
{
result+=_temp;
}
} // occupied levels
return result;
}
void GWBSE::RPA_calculate_epsilon(const TCMatrix& _Mmn_RPA){
// loop over frequencies
for ( unsigned _i_freq = 0 ; _i_freq < _screening_freq.size1() ; _i_freq++ ){
if ( _screening_freq( _i_freq, 0) == 0.0 ) {
_epsilon[ _i_freq ]+=RPA_imaginary(_Mmn_RPA, _screening_freq( _i_freq, 1));
}
else if ( _screening_freq( _i_freq, 1) == 0.0 ) {
// purely real
_epsilon[ _i_freq ]+= RPA_real(_Mmn_RPA, _screening_freq( _i_freq, 0));
}
else {
// mixed -> FAIL
cerr << " mixed frequency! real part: " << _screening_freq( _i_freq, 0 ) << " imaginary part: " << _screening_freq( _i_freq, 1 ) << flush;
exit(1);
}
} // loop over frequencies
return;
}
void GWBSE::RPA_prepare_threecenters(TCMatrix& _Mmn_RPA,const TCMatrix& _Mmn_full){
ub::range full=ub::range(0, _Mmn_full.get_beta());
ub::range RPA_cut=ub::range(_Mmn_RPA.get_nmin() - _Mmn_full.get_nmin(), _Mmn_RPA.get_nmax() - _Mmn_full.get_nmin() + 1);
// loop over m-levels in _Mmn_RPA
#pragma omp parallel for
for (int _m_level = 0; _m_level < _Mmn_RPA.size(); _m_level++) {
// copy to _Mmn_RPA
_Mmn_RPA[ _m_level ] = ub::project(_Mmn_full[ _m_level ], full, RPA_cut);
}// loop m-levels
return;
}
}};
<|endoftext|>
|
<commit_before>#include <map>
#include <cmath>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <ctime>
#include <memory>
#include "ChatBot.h"
struct userinfo
{
unsigned smiles;
int lastReply;
long long context;
userinfo(): smiles(0), lastReply(0), context(0) {}
explicit userinfo(const wstring &s): userinfo()
{
wstring t;
unsigned i = 0;
for(;s[i]!=L';'&&i<s.length();i++)
t.push_back(s[i]);
if(i == s.length())
return;
smiles = stoi(t);
t.clear();
i++;
for(;s[i]!=L';'&&i<s.length();i++)
t.push_back(s[i]);
if(i == s.length())
return;
lastReply = stoi(t);
t.clear();
i++;
for(;i<s.length();i++)
t.push_back(s[i]);
context = stoll(t);
}
wstring dump() const
{
return to_wstring(smiles) + L';' + to_wstring(lastReply) + L';' + to_wstring(context);
}
};
struct replyinfo
{
vector<wstring> replies;
wstring limiter;
long long context;
replyinfo(): replies(), limiter(), context(0) {}
replyinfo(vector<wstring> &r, wstring &l, long long c): replies(r), limiter(l), context(c) {}
};
unsigned MAX_SMILES;
int myName;
vector<wstring> request;
vector<shared_ptr<replyinfo> > reply;
vector<pair<vector<long long>, long long> > tf;
vector<pair<long long, long long> > fixedstem;
vector<pair<long long, long long> > replaced;
vector<pair<long long, bool> > blacklist;
vector<long long> plain_blacklist;
vector<double> tfnorm;
map<long long, int> df;
map<int, userinfo> users;
set<long long> names;
map<long long, wstring> context_map;
inline double tfidf(long long &word)
{
return df.count(word) ? log((double)tf.size() / df[word]) : 0.;
}
inline double sqr(double x)
{
return x * x;
}
double norm(vector<long long> &arr)
{
double ans = 0;
for(auto&& i: arr)
{
ans += sqr(tfidf(i));
}
return sqrt(ans);
}
wstring RandReply(vector<wstring> &v)
{
return v.size() == 1 ? v[0] : v[rand() % v.size()];
}
int randint(int a, int b)
{
return rand() % (b - a + 1) + a;
}
void SwapFirst(vector<wstring> &v, bool canStay)
{
if(v.size() > 1)
{
swap(v[0], v[randint(1 - canStay, v.size()-1)]);
}
}
template<class T>
vector<long long> PlainWords(const vector<pair<long long, T> > &words_pos)
{
vector<long long> words;
for(auto &i : words_pos)
words.push_back(i.first);
return words;
}
void Highlight(wstring &line, const vector<pair<long long, pair<int, int> > > &words_pos, const vector<long long> &common)
{
set<int> bpos;
for(auto i : common)
{
for(auto& j : words_pos)
{
if(i == j.first)
{
bpos.insert(j.second.first);
bpos.insert(-(j.second.first + j.second.second)-1);
}
}
}
int tadd = 0;
for(int i=0;i<(int)line.size();i++)
{
if(bpos.count(-i-1))
{
line.insert(i+tadd, L"}`");
tadd += 2;
}
if(bpos.count(i))
{
line.insert(i+tadd, L"`{");
tadd += 2;
}
}
}
long long phnamec = phash(L"firstnamec");
bool HasLetters(const wstring &line)
{
for(auto i : line)
{
if(towupper(i) != towlower(i) || i == '?')
return true;
}
return false;
}
//-1: comment
//-2: flat
wstring Say(wstring &line, int id, bool conf)
{
vector<wstring> limiters;
line += L' ';
if(id > 0)
{
wistringstream is;
is.str(line);
wstring t;
is >> t;
while(t.length() && t[0] != L'|')
{
if(t[0] == L'@')
{
limiters.push_back(t.substr(1));
}
is >> t;
}
getline(is, line);
}
long long context = users[id].context;
if(line[1] == L'$' && id == -2)
{
wstring ctx;
int i;
for(i=2;line[i]!=L' ';i++)
{
ctx += line[i];
}
line = line.substr(i);
context = phash(ctx);
}
auto words_pos = splitWords(line, fixedstem, replaced, names);
vector<long long> words = PlainWords(words_pos);
if(conf)
{
replace(words.begin(), words.end(), phname, phnamec);
}
sort(words.begin(), words.end());
words.resize(unique(words.begin(), words.end()) - words.begin());
for(auto &i : blacklist)
{
if(i.second && id != -1)
continue;
if(find(words.begin(), words.end(), i.first) != words.end())
{
Highlight(line, words_pos, (id==-1) ? PlainWords(blacklist) : plain_blacklist);
wcerr << "red|" << line << L"- blacklisted\n";
return L"$blacklisted";
}
}
double mx = 0;
int imx = 0;
vector<long long> common;
for(int i=0;i<(int)tf.size();i++)
{
if(tf[i].second != 0 && context != tf[i].second)
{
continue;
}
common.clear();
set_intersection(words.begin(), words.end(), tf[i].first.begin(), tf[i].first.end(), back_inserter(common));
double ans = 0;
for(auto&& word: common)
{
ans += sqr(tfidf(word));
}
ans /= tfnorm[i];
if(ans > mx + 0.00000001 || (tf[i].second && ans > mx - 0.00000001))
{
mx = ans;
imx = i;
}
}
if(mx == 0)
{
if(conf && !HasLetters(line))
{
wcerr << "red|" << line << "- no match\n";
users[id].smiles++;
return L"";
}
if(id >= 0 && users[id].smiles >= MAX_SMILES)
{
wcerr << "red|" << line << "- too many smiles\n";
return L"";
}
if(id >= 0)
{
wcerr << "yellow|" << line << L"- no match\n";
users[id].smiles++;
}
return L"$noans";
}
common.clear();
set_intersection(words.begin(), words.end(), tf[imx].first.begin(), tf[imx].first.end(), back_inserter(common));
Highlight(line, words_pos, common);
wstring req = request[imx];
Highlight(req, splitWords(req, fixedstem, replaced, names), common);
if(id >= 0)
{
users[id].context = reply[imx]->context;
if(users[id].lastReply == imx + 1)
{
users[id].lastReply = -(imx + 1);
}
else if(users[id].lastReply == -(imx + 1))
{
wcerr << "red|" << line << L"== " << req << (tf[imx].second ? L" (context, " : L" (") << mx / norm(words) << L")" << " - repeated\n";
return L"";
}
else
{
users[id].lastReply = imx + 1;
}
users[id].smiles = 0;
}
if(id >= 0)
{
for(auto &limiter : limiters)
{
if(limiter == reply[imx]->limiter)
{
wcerr << "red|" << line << L"== " << req << (tf[imx].second ? L" (context, " : L" (") << mx / norm(words) << L")" << " - limited\n";
return L"";
}
}
wcerr << "green|" << line << L"== " << req << (tf[imx].second ? L" (context, " : L" (") << mx / norm(words) << L")";
if(reply[imx]->replies.size() > 1)
{
wcerr << L", " << reply[imx]->replies.size() << L" replies";
}
wcerr << L"\n";
}
if(id == -2)
{
for(int i=0;i<(int)reply[imx]->replies.size();i++)
{
req += '|';
req += reply[imx]->replies[i];
}
req += '|';
req += to_wstring(mx / norm(words));
req += '|';
req += context_map[reply[imx]->context];
req += '|';
req += reply[imx]->limiter;
return req;
}
wstring ans = (reply[imx]->limiter.length() ? L"@" + reply[imx]->limiter : L"") + L"|" + reply[imx]->replies[0];
SwapFirst(reply[imx]->replies, 0);
return ans;
}
shared_ptr<replyinfo> splitReply(const wstring &t)
{
vector<wstring> ans;
wstring s;
wstring ctx;
wstring lim;
int i = 0;
if(t[0] == L'@')
{
for(i=1;i<(int)t.size();i++)
{
if(t[i] == L' ')
{
i++;
break;
}
lim += t[i];
}
}
if(t[i] == L'$')
{
i++;
for(;i<(int)t.size();i++)
{
if(t[i] == L' ')
{
i++;
break;
}
ctx += t[i];
}
}
for(;i<(int)t.size();i++)
{
if(t[i] == L'|')
{
if(s.length())
ans.push_back(s);
s.clear();
}
else
{
s.push_back(t[i]);
}
}
if(s.length())
ans.push_back(s);
context_map[phash(ctx)] = ctx;
return make_shared<replyinfo>(ans, lim, phash(ctx));
}
void AddReply(const wstring &req, const wstring &rep)
{
auto v = splitReply(rep);
auto u = *splitReply(req);
SwapFirst(v->replies, 1);
for(wstring& i : u.replies)
{
reply.push_back(v);
request.push_back(i);
auto words_pos = splitWords(i, fixedstem, replaced, names);
vector<long long> words = PlainWords(words_pos);
sort(words.begin(), words.end());
words.resize(unique(words.begin(), words.end()) - words.begin());
for(auto& j: words)
{
df[j]++;
}
tf.push_back({words, u.context});
}
}
wchar_t buf1[12000], buf2[12000];
const string file = "data/bot.txt";
const string filebl = "data/blacklist.txt";
const string filestem = "data/fixedstem.txt";
const string filenames = "data/names.txt";
void Load()
{
locale loc("");
reply.clear();
request.clear();
tf.clear();
tfnorm.clear();
df.clear();
blacklist.clear();
plain_blacklist.clear();
fixedstem.clear();
names.clear();
context_map.clear();
context_map[0] = L"";
srand(time(0));
wifstream fin(file);
wifstream fstem(filestem);
fstem.imbue(loc);
while(fstem >> buf1)
{
fstem >> buf2;
if(buf1[0] == '$')
{
replaced.push_back(make_pair(stem(buf1 + 1), stem(buf2)));
}
else
{
wstring s = buf1;
for(auto &i : s)
i = towupper(i);
fixedstem.push_back(make_pair(phash(s), phash(buf2)));
}
}
fstem.close();
fin.imbue(loc);
while(fin.getline(buf1, 10000))
{
fin.getline(buf2, 10000);
AddReply(buf1, buf2); //this should be done BEFORE filling names
}
df[phnamec] = 10000;
for(auto&& i : tf)
{
tfnorm.push_back(norm(i.first));
}
fin.close();
wifstream fbl(filebl);
fbl.imbue(loc);
while(fbl.getline(buf1, 10000))
{
if(buf1[0] == '$')
blacklist.push_back({stem(buf1 + 1), 1});
else
{
blacklist.push_back({stem(buf1), 0});
plain_blacklist.push_back(stem(buf1));
}
}
fbl.close();
wifstream fnm(filenames);
fnm.imbue(loc);
long long phmyname = phash(L"а");
for(int l=0;fnm.getline(buf1, 10000);l++)
{
int j = 0;
for(int i=0;buf1[i];i++)
{
if(buf1[i] <= L' ')
{
buf2[j] = 0;
if(l == myName)
replaced.push_back(make_pair(stem(buf2), phmyname));
else
names.insert(phash(buf2));
j = 0;
}
else
{
buf2[j++] = towupper(buf1[i]);
}
}
buf2[j] = 0;
if(l == myName)
fixedstem.push_back(make_pair(phash(buf2), phmyname));
else
names.insert(phash(buf2));
}
fnm.close();
for(auto &i : users)
{
i.second.lastReply = 0;
}
}
void LoadData(const wstring &data)
{
users.clear();
wistringstream is;
is.str(data);
int id;
wstring s;
while(is >> id)
{
is >> s;
users[id] = userinfo(s);
}
}
wstring Dump()
{
wstring res;
for(auto &i : users)
{
res += to_wstring(i.first) + L' ' + i.second.dump() + L' ';
}
return res;
}
<commit_msg>Highlight blacklisted names correctly<commit_after>#include <map>
#include <cmath>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <ctime>
#include <memory>
#include "ChatBot.h"
struct userinfo
{
unsigned smiles;
int lastReply;
long long context;
userinfo(): smiles(0), lastReply(0), context(0) {}
explicit userinfo(const wstring &s): userinfo()
{
wstring t;
unsigned i = 0;
for(;s[i]!=L';'&&i<s.length();i++)
t.push_back(s[i]);
if(i == s.length())
return;
smiles = stoi(t);
t.clear();
i++;
for(;s[i]!=L';'&&i<s.length();i++)
t.push_back(s[i]);
if(i == s.length())
return;
lastReply = stoi(t);
t.clear();
i++;
for(;i<s.length();i++)
t.push_back(s[i]);
context = stoll(t);
}
wstring dump() const
{
return to_wstring(smiles) + L';' + to_wstring(lastReply) + L';' + to_wstring(context);
}
};
struct replyinfo
{
vector<wstring> replies;
wstring limiter;
long long context;
replyinfo(): replies(), limiter(), context(0) {}
replyinfo(vector<wstring> &r, wstring &l, long long c): replies(r), limiter(l), context(c) {}
};
unsigned MAX_SMILES;
int myName;
vector<wstring> request;
vector<shared_ptr<replyinfo> > reply;
vector<pair<vector<long long>, long long> > tf;
vector<pair<long long, long long> > fixedstem;
vector<pair<long long, long long> > replaced;
vector<pair<long long, bool> > blacklist;
vector<long long> plain_blacklist;
vector<double> tfnorm;
map<long long, int> df;
map<int, userinfo> users;
set<long long> names;
map<long long, wstring> context_map;
inline double tfidf(long long &word)
{
return df.count(word) ? log((double)tf.size() / df[word]) : 0.;
}
inline double sqr(double x)
{
return x * x;
}
double norm(vector<long long> &arr)
{
double ans = 0;
for(auto&& i: arr)
{
ans += sqr(tfidf(i));
}
return sqrt(ans);
}
wstring RandReply(vector<wstring> &v)
{
return v.size() == 1 ? v[0] : v[rand() % v.size()];
}
int randint(int a, int b)
{
return rand() % (b - a + 1) + a;
}
void SwapFirst(vector<wstring> &v, bool canStay)
{
if(v.size() > 1)
{
swap(v[0], v[randint(1 - canStay, v.size()-1)]);
}
}
template<class T>
vector<long long> PlainWords(const vector<pair<long long, T> > &words_pos)
{
vector<long long> words;
for(auto &i : words_pos)
words.push_back(i.first);
return words;
}
void Highlight(wstring &line, const vector<pair<long long, pair<int, int> > > &words_pos, const vector<long long> &common)
{
set<int> bpos;
for(auto i : common)
{
for(auto& j : words_pos)
{
if(i == j.first)
{
bpos.insert(j.second.first);
bpos.insert(-(j.second.first + j.second.second)-1);
}
}
}
int tadd = 0;
for(int i=0;i<(int)line.size();i++)
{
if(bpos.count(-i-1))
{
line.insert(i+tadd, L"}`");
tadd += 2;
}
if(bpos.count(i))
{
line.insert(i+tadd, L"`{");
tadd += 2;
}
}
}
long long phnamec = phash(L"firstnamec");
bool HasLetters(const wstring &line)
{
for(auto i : line)
{
if(towupper(i) != towlower(i) || i == '?')
return true;
}
return false;
}
//-1: comment
//-2: flat
wstring Say(wstring &line, int id, bool conf)
{
vector<wstring> limiters;
line += L' ';
if(id > 0)
{
wistringstream is;
is.str(line);
wstring t;
is >> t;
while(t.length() && t[0] != L'|')
{
if(t[0] == L'@')
{
limiters.push_back(t.substr(1));
}
is >> t;
}
getline(is, line);
}
long long context = users[id].context;
if(line[1] == L'$' && id == -2)
{
wstring ctx;
int i;
for(i=2;line[i]!=L' ';i++)
{
ctx += line[i];
}
line = line.substr(i);
context = phash(ctx);
}
auto words_pos = splitWords(line, fixedstem, replaced, names);
if(conf)
{
for(auto &i : words_pos)
{
if(i.first == phname)
i.first = phnamec;
}
}
vector<long long> words = PlainWords(words_pos);
sort(words.begin(), words.end());
words.resize(unique(words.begin(), words.end()) - words.begin());
for(auto &i : blacklist)
{
if(i.second && id != -1)
continue;
if(find(words.begin(), words.end(), i.first) != words.end())
{
Highlight(line, words_pos, (id==-1) ? PlainWords(blacklist) : plain_blacklist);
wcerr << "red|" << line << L"- blacklisted\n";
return L"$blacklisted";
}
}
double mx = 0;
int imx = 0;
vector<long long> common;
for(int i=0;i<(int)tf.size();i++)
{
if(tf[i].second != 0 && context != tf[i].second)
{
continue;
}
common.clear();
set_intersection(words.begin(), words.end(), tf[i].first.begin(), tf[i].first.end(), back_inserter(common));
double ans = 0;
for(auto&& word: common)
{
ans += sqr(tfidf(word));
}
ans /= tfnorm[i];
if(ans > mx + 0.00000001 || (tf[i].second && ans > mx - 0.00000001))
{
mx = ans;
imx = i;
}
}
if(mx == 0)
{
if(conf && !HasLetters(line))
{
wcerr << "red|" << line << "- no match\n";
users[id].smiles++;
return L"";
}
if(id >= 0 && users[id].smiles >= MAX_SMILES)
{
wcerr << "red|" << line << "- too many smiles\n";
return L"";
}
if(id >= 0)
{
wcerr << "yellow|" << line << L"- no match\n";
users[id].smiles++;
}
return L"$noans";
}
common.clear();
set_intersection(words.begin(), words.end(), tf[imx].first.begin(), tf[imx].first.end(), back_inserter(common));
Highlight(line, words_pos, common);
wstring req = request[imx];
Highlight(req, splitWords(req, fixedstem, replaced, names), common);
if(id >= 0)
{
users[id].context = reply[imx]->context;
if(users[id].lastReply == imx + 1)
{
users[id].lastReply = -(imx + 1);
}
else if(users[id].lastReply == -(imx + 1))
{
wcerr << "red|" << line << L"== " << req << (tf[imx].second ? L" (context, " : L" (") << mx / norm(words) << L")" << " - repeated\n";
return L"";
}
else
{
users[id].lastReply = imx + 1;
}
users[id].smiles = 0;
}
if(id >= 0)
{
for(auto &limiter : limiters)
{
if(limiter == reply[imx]->limiter)
{
wcerr << "red|" << line << L"== " << req << (tf[imx].second ? L" (context, " : L" (") << mx / norm(words) << L")" << " - limited\n";
return L"";
}
}
wcerr << "green|" << line << L"== " << req << (tf[imx].second ? L" (context, " : L" (") << mx / norm(words) << L")";
if(reply[imx]->replies.size() > 1)
{
wcerr << L", " << reply[imx]->replies.size() << L" replies";
}
wcerr << L"\n";
}
if(id == -2)
{
for(int i=0;i<(int)reply[imx]->replies.size();i++)
{
req += '|';
req += reply[imx]->replies[i];
}
req += '|';
req += to_wstring(mx / norm(words));
req += '|';
req += context_map[reply[imx]->context];
req += '|';
req += reply[imx]->limiter;
return req;
}
wstring ans = (reply[imx]->limiter.length() ? L"@" + reply[imx]->limiter : L"") + L"|" + reply[imx]->replies[0];
SwapFirst(reply[imx]->replies, 0);
return ans;
}
shared_ptr<replyinfo> splitReply(const wstring &t)
{
vector<wstring> ans;
wstring s;
wstring ctx;
wstring lim;
int i = 0;
if(t[0] == L'@')
{
for(i=1;i<(int)t.size();i++)
{
if(t[i] == L' ')
{
i++;
break;
}
lim += t[i];
}
}
if(t[i] == L'$')
{
i++;
for(;i<(int)t.size();i++)
{
if(t[i] == L' ')
{
i++;
break;
}
ctx += t[i];
}
}
for(;i<(int)t.size();i++)
{
if(t[i] == L'|')
{
if(s.length())
ans.push_back(s);
s.clear();
}
else
{
s.push_back(t[i]);
}
}
if(s.length())
ans.push_back(s);
context_map[phash(ctx)] = ctx;
return make_shared<replyinfo>(ans, lim, phash(ctx));
}
void AddReply(const wstring &req, const wstring &rep)
{
auto v = splitReply(rep);
auto u = *splitReply(req);
SwapFirst(v->replies, 1);
for(wstring& i : u.replies)
{
reply.push_back(v);
request.push_back(i);
auto words_pos = splitWords(i, fixedstem, replaced, names);
vector<long long> words = PlainWords(words_pos);
sort(words.begin(), words.end());
words.resize(unique(words.begin(), words.end()) - words.begin());
for(auto& j: words)
{
df[j]++;
}
tf.push_back({words, u.context});
}
}
wchar_t buf1[12000], buf2[12000];
const string file = "data/bot.txt";
const string filebl = "data/blacklist.txt";
const string filestem = "data/fixedstem.txt";
const string filenames = "data/names.txt";
void Load()
{
locale loc("");
reply.clear();
request.clear();
tf.clear();
tfnorm.clear();
df.clear();
blacklist.clear();
plain_blacklist.clear();
fixedstem.clear();
names.clear();
context_map.clear();
context_map[0] = L"";
srand(time(0));
wifstream fin(file);
wifstream fstem(filestem);
fstem.imbue(loc);
while(fstem >> buf1)
{
fstem >> buf2;
if(buf1[0] == '$')
{
replaced.push_back(make_pair(stem(buf1 + 1), stem(buf2)));
}
else
{
wstring s = buf1;
for(auto &i : s)
i = towupper(i);
fixedstem.push_back(make_pair(phash(s), phash(buf2)));
}
}
fstem.close();
fin.imbue(loc);
while(fin.getline(buf1, 10000))
{
fin.getline(buf2, 10000);
AddReply(buf1, buf2); //this should be done BEFORE filling names
}
df[phnamec] = 10000;
for(auto&& i : tf)
{
tfnorm.push_back(norm(i.first));
}
fin.close();
wifstream fbl(filebl);
fbl.imbue(loc);
while(fbl.getline(buf1, 10000))
{
if(buf1[0] == '$')
blacklist.push_back({stem(buf1 + 1), 1});
else
{
blacklist.push_back({stem(buf1), 0});
plain_blacklist.push_back(stem(buf1));
}
}
fbl.close();
wifstream fnm(filenames);
fnm.imbue(loc);
long long phmyname = phash(L"а");
for(int l=0;fnm.getline(buf1, 10000);l++)
{
int j = 0;
for(int i=0;buf1[i];i++)
{
if(buf1[i] <= L' ')
{
buf2[j] = 0;
if(l == myName)
replaced.push_back(make_pair(stem(buf2), phmyname));
else
names.insert(phash(buf2));
j = 0;
}
else
{
buf2[j++] = towupper(buf1[i]);
}
}
buf2[j] = 0;
if(l == myName)
fixedstem.push_back(make_pair(phash(buf2), phmyname));
else
names.insert(phash(buf2));
}
fnm.close();
for(auto &i : users)
{
i.second.lastReply = 0;
}
}
void LoadData(const wstring &data)
{
users.clear();
wistringstream is;
is.str(data);
int id;
wstring s;
while(is >> id)
{
is >> s;
users[id] = userinfo(s);
}
}
wstring Dump()
{
wstring res;
for(auto &i : users)
{
res += to_wstring(i.first) + L' ' + i.second.dump() + L' ';
}
return res;
}
<|endoftext|>
|
<commit_before>//===- NameMap.cpp - PDB Name Map -------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/Raw/NameMap.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/DebugInfo/CodeView/StreamReader.h"
#include "llvm/DebugInfo/PDB/Raw/RawError.h"
using namespace llvm;
using namespace llvm::pdb;
NameMap::NameMap() {}
Error NameMap::load(codeview::StreamReader &Stream) {
// This is some sort of weird string-set/hash table encoded in the stream.
// It starts with the number of bytes in the table.
uint32_t NumberOfBytes;
if (auto EC = Stream.readInteger(NumberOfBytes))
return joinErrors(std::move(EC),
make_error<RawError>(raw_error_code::corrupt_file,
"Expected name map length"));
if (Stream.bytesRemaining() < NumberOfBytes)
return make_error<RawError>(raw_error_code::corrupt_file,
"Invalid name map length");
// Following that field is the starting offset of strings in the name table.
uint32_t StringsOffset = Stream.getOffset();
Stream.setOffset(StringsOffset + NumberOfBytes);
// This appears to be equivalent to the total number of strings *actually*
// in the name table.
uint32_t HashSize;
if (auto EC = Stream.readInteger(HashSize))
return joinErrors(std::move(EC),
make_error<RawError>(raw_error_code::corrupt_file,
"Expected name map hash size"));
// This appears to be an upper bound on the number of strings in the name
// table.
uint32_t MaxNumberOfStrings;
if (auto EC = Stream.readInteger(MaxNumberOfStrings))
return joinErrors(std::move(EC),
make_error<RawError>(raw_error_code::corrupt_file,
"Expected name map max strings"));
const uint32_t MaxNumberOfWords = UINT32_MAX / sizeof(uint32_t);
// This appears to be a hash table which uses bitfields to determine whether
// or not a bucket is 'present'.
uint32_t NumPresentWords;
if (auto EC = Stream.readInteger(NumPresentWords))
return joinErrors(std::move(EC),
make_error<RawError>(raw_error_code::corrupt_file,
"Expected name map num words"));
if (NumPresentWords > MaxNumberOfWords)
return make_error<RawError>(raw_error_code::corrupt_file,
"Number of present words is too large");
// Store all the 'present' bits in a vector for later processing.
SmallVector<uint32_t, 1> PresentWords;
for (uint32_t I = 0; I != NumPresentWords; ++I) {
uint32_t Word;
if (auto EC = Stream.readInteger(Word))
return joinErrors(std::move(EC),
make_error<RawError>(raw_error_code::corrupt_file,
"Expected name map word"));
PresentWords.push_back(Word);
}
// This appears to be a hash table which uses bitfields to determine whether
// or not a bucket is 'deleted'.
uint32_t NumDeletedWords;
if (auto EC = Stream.readInteger(NumDeletedWords))
return joinErrors(
std::move(EC),
make_error<RawError>(raw_error_code::corrupt_file,
"Expected name map num deleted words"));
if (NumDeletedWords > MaxNumberOfWords)
return make_error<RawError>(raw_error_code::corrupt_file,
"Number of deleted words is too large");
// Store all the 'deleted' bits in a vector for later processing.
SmallVector<uint32_t, 1> DeletedWords;
for (uint32_t I = 0; I != NumDeletedWords; ++I) {
uint32_t Word;
if (auto EC = Stream.readInteger(Word))
return joinErrors(std::move(EC),
make_error<RawError>(raw_error_code::corrupt_file,
"Expected name map deleted word"));
DeletedWords.push_back(Word);
}
BitVector Present(MaxNumberOfStrings, false);
if (!PresentWords.empty())
Present.setBitsInMask(PresentWords.data(), PresentWords.size());
BitVector Deleted(MaxNumberOfStrings, false);
if (!DeletedWords.empty())
Deleted.setBitsInMask(DeletedWords.data(), DeletedWords.size());
for (uint32_t I = 0; I < MaxNumberOfStrings; ++I) {
if (!Present.test(I))
continue;
// For all present entries, dump out their mapping.
// This appears to be an offset relative to the start of the strings.
// It tells us where the null-terminated string begins.
uint32_t NameOffset;
if (auto EC = Stream.readInteger(NameOffset))
return joinErrors(std::move(EC),
make_error<RawError>(raw_error_code::corrupt_file,
"Expected name map name offset"));
// This appears to be a stream number into the stream directory.
uint32_t NameIndex;
if (auto EC = Stream.readInteger(NameIndex))
return joinErrors(std::move(EC),
make_error<RawError>(raw_error_code::corrupt_file,
"Expected name map name index"));
// Compute the offset of the start of the string relative to the stream.
uint32_t StringOffset = StringsOffset + NameOffset;
uint32_t OldOffset = Stream.getOffset();
// Pump out our c-string from the stream.
StringRef Str;
Stream.setOffset(StringOffset);
if (auto EC = Stream.readZeroString(Str))
return joinErrors(std::move(EC),
make_error<RawError>(raw_error_code::corrupt_file,
"Expected name map name"));
Stream.setOffset(OldOffset);
// Add this to a string-map from name to stream number.
Mapping.insert({Str, NameIndex});
}
return Error::success();
}
iterator_range<StringMapConstIterator<uint32_t>> NameMap::entries() const {
return llvm::make_range<StringMapConstIterator<uint32_t>>(Mapping.begin(),
Mapping.end());
}
bool NameMap::tryGetValue(StringRef Name, uint32_t &Value) const {
auto Iter = Mapping.find(Name);
if (Iter == Mapping.end())
return false;
Value = Iter->second;
return true;
}
<commit_msg>Tighten some of the name map checks further<commit_after>//===- NameMap.cpp - PDB Name Map -------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/Raw/NameMap.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/DebugInfo/CodeView/StreamReader.h"
#include "llvm/DebugInfo/PDB/Raw/RawError.h"
using namespace llvm;
using namespace llvm::pdb;
NameMap::NameMap() {}
Error NameMap::load(codeview::StreamReader &Stream) {
// This is some sort of weird string-set/hash table encoded in the stream.
// It starts with the number of bytes in the table.
uint32_t NumberOfBytes;
if (auto EC = Stream.readInteger(NumberOfBytes))
return joinErrors(std::move(EC),
make_error<RawError>(raw_error_code::corrupt_file,
"Expected name map length"));
if (Stream.bytesRemaining() < NumberOfBytes)
return make_error<RawError>(raw_error_code::corrupt_file,
"Invalid name map length");
// Following that field is the starting offset of strings in the name table.
uint32_t StringsOffset = Stream.getOffset();
Stream.setOffset(StringsOffset + NumberOfBytes);
// This appears to be equivalent to the total number of strings *actually*
// in the name table.
uint32_t HashSize;
if (auto EC = Stream.readInteger(HashSize))
return joinErrors(std::move(EC),
make_error<RawError>(raw_error_code::corrupt_file,
"Expected name map hash size"));
// This appears to be an upper bound on the number of strings in the name
// table.
uint32_t MaxNumberOfStrings;
if (auto EC = Stream.readInteger(MaxNumberOfStrings))
return joinErrors(std::move(EC),
make_error<RawError>(raw_error_code::corrupt_file,
"Expected name map max strings"));
if (MaxNumberOfStrings > (UINT32_MAX / sizeof(uint32_t)))
return make_error<RawError>(raw_error_code::corrupt_file,
"Implausible number of strings");
const uint32_t MaxNumberOfWords = UINT32_MAX / (sizeof(uint32_t) * 8);
// This appears to be a hash table which uses bitfields to determine whether
// or not a bucket is 'present'.
uint32_t NumPresentWords;
if (auto EC = Stream.readInteger(NumPresentWords))
return joinErrors(std::move(EC),
make_error<RawError>(raw_error_code::corrupt_file,
"Expected name map num words"));
if (NumPresentWords > MaxNumberOfWords)
return make_error<RawError>(raw_error_code::corrupt_file,
"Number of present words is too large");
// Store all the 'present' bits in a vector for later processing.
SmallVector<uint32_t, 1> PresentWords;
for (uint32_t I = 0; I != NumPresentWords; ++I) {
uint32_t Word;
if (auto EC = Stream.readInteger(Word))
return joinErrors(std::move(EC),
make_error<RawError>(raw_error_code::corrupt_file,
"Expected name map word"));
PresentWords.push_back(Word);
}
// This appears to be a hash table which uses bitfields to determine whether
// or not a bucket is 'deleted'.
uint32_t NumDeletedWords;
if (auto EC = Stream.readInteger(NumDeletedWords))
return joinErrors(
std::move(EC),
make_error<RawError>(raw_error_code::corrupt_file,
"Expected name map num deleted words"));
if (NumDeletedWords > MaxNumberOfWords)
return make_error<RawError>(raw_error_code::corrupt_file,
"Number of deleted words is too large");
// Store all the 'deleted' bits in a vector for later processing.
SmallVector<uint32_t, 1> DeletedWords;
for (uint32_t I = 0; I != NumDeletedWords; ++I) {
uint32_t Word;
if (auto EC = Stream.readInteger(Word))
return joinErrors(std::move(EC),
make_error<RawError>(raw_error_code::corrupt_file,
"Expected name map deleted word"));
DeletedWords.push_back(Word);
}
BitVector Present(MaxNumberOfStrings, false);
if (!PresentWords.empty())
Present.setBitsInMask(PresentWords.data(), PresentWords.size());
BitVector Deleted(MaxNumberOfStrings, false);
if (!DeletedWords.empty())
Deleted.setBitsInMask(DeletedWords.data(), DeletedWords.size());
for (uint32_t I = 0; I < MaxNumberOfStrings; ++I) {
if (!Present.test(I))
continue;
// For all present entries, dump out their mapping.
// This appears to be an offset relative to the start of the strings.
// It tells us where the null-terminated string begins.
uint32_t NameOffset;
if (auto EC = Stream.readInteger(NameOffset))
return joinErrors(std::move(EC),
make_error<RawError>(raw_error_code::corrupt_file,
"Expected name map name offset"));
// This appears to be a stream number into the stream directory.
uint32_t NameIndex;
if (auto EC = Stream.readInteger(NameIndex))
return joinErrors(std::move(EC),
make_error<RawError>(raw_error_code::corrupt_file,
"Expected name map name index"));
// Compute the offset of the start of the string relative to the stream.
uint32_t StringOffset = StringsOffset + NameOffset;
uint32_t OldOffset = Stream.getOffset();
// Pump out our c-string from the stream.
StringRef Str;
Stream.setOffset(StringOffset);
if (auto EC = Stream.readZeroString(Str))
return joinErrors(std::move(EC),
make_error<RawError>(raw_error_code::corrupt_file,
"Expected name map name"));
Stream.setOffset(OldOffset);
// Add this to a string-map from name to stream number.
Mapping.insert({Str, NameIndex});
}
return Error::success();
}
iterator_range<StringMapConstIterator<uint32_t>> NameMap::entries() const {
return llvm::make_range<StringMapConstIterator<uint32_t>>(Mapping.begin(),
Mapping.end());
}
bool NameMap::tryGetValue(StringRef Name, uint32_t &Value) const {
auto Iter = Mapping.find(Name);
if (Iter == Mapping.end())
return false;
Value = Iter->second;
return true;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012, 2015, 2017 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.
*
* 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.
*/
#include "sim/drain.hh"
#include <algorithm>
#include "base/logging.hh"
#include "base/trace.hh"
#include "debug/Drain.hh"
#include "sim/sim_exit.hh"
#include "sim/sim_object.hh"
DrainManager DrainManager::_instance;
DrainManager::DrainManager()
: _count(0),
_state(DrainState::Running)
{
}
DrainManager::~DrainManager()
{
}
bool
DrainManager::tryDrain()
{
panic_if(_state == DrainState::Drained,
"Trying to drain a drained system\n");
panic_if(_count != 0,
"Drain counter must be zero at the start of a drain cycle\n");
DPRINTF(Drain, "Trying to drain %u objects.\n", drainableCount());
_state = DrainState::Draining;
for (auto *obj : _allDrainable) {
DrainState status = obj->dmDrain();
if (Debug::Drain && status != DrainState::Drained) {
SimObject *temp = dynamic_cast<SimObject*>(obj);
if (temp)
DPRINTF(Drain, "Failed to drain %s\n", temp->name());
}
_count += status == DrainState::Drained ? 0 : 1;
}
if (_count == 0) {
DPRINTF(Drain, "Drain done.\n");
_state = DrainState::Drained;
return true;
} else {
DPRINTF(Drain, "Need another drain cycle. %u/%u objects not ready.\n",
_count, drainableCount());
return false;
}
}
void
DrainManager::resume()
{
panic_if(_state == DrainState::Running,
"Trying to resume a system that is already running\n");
warn_if(_state == DrainState::Draining,
"Resuming a system that isn't fully drained, this is untested and "
"likely to break\n");
panic_if(_state == DrainState::Resuming,
"Resuming a system that is already trying to resume. This should "
"never happen.\n");
panic_if(_count != 0,
"Resume called in the middle of a drain cycle. %u objects "
"left to drain.\n", _count);
// At this point in time the DrainManager and all objects will be
// in the the Drained state. New objects (i.e., objects created
// while resuming) will inherit the Resuming state from the
// DrainManager, which means we have to resume objects until all
// objects are in the Running state.
_state = DrainState::Resuming;
do {
DPRINTF(Drain, "Resuming %u objects.\n", drainableCount());
for (auto *obj : _allDrainable) {
if (obj->drainState() != DrainState::Running) {
assert(obj->drainState() == DrainState::Drained ||
obj->drainState() == DrainState::Resuming);
obj->dmDrainResume();
}
}
} while (!allInState(DrainState::Running));
_state = DrainState::Running;
}
void
DrainManager::preCheckpointRestore()
{
panic_if(_state != DrainState::Running,
"preCheckpointRestore() called on a system that isn't in the "
"Running state.\n");
DPRINTF(Drain, "Applying pre-restore fixes to %u objects.\n",
drainableCount());
_state = DrainState::Drained;
for (auto *obj : _allDrainable)
obj->_drainState = DrainState::Drained;
}
void
DrainManager::signalDrainDone()
{
assert(_count > 0);
if (--_count == 0) {
DPRINTF(Drain, "All %u objects drained..\n", drainableCount());
exitSimLoop("Finished drain", 0);
}
}
void
DrainManager::registerDrainable(Drainable *obj)
{
std::lock_guard<std::mutex> lock(globalLock);
assert(std::find(_allDrainable.begin(), _allDrainable.end(), obj) ==
_allDrainable.end());
_allDrainable.push_back(obj);
}
void
DrainManager::unregisterDrainable(Drainable *obj)
{
std::lock_guard<std::mutex> lock(globalLock);
auto o = std::find(_allDrainable.begin(), _allDrainable.end(), obj);
assert(o != _allDrainable.end());
_allDrainable.erase(o);
}
bool
DrainManager::allInState(DrainState state) const
{
for (const auto *obj : _allDrainable) {
if (obj->drainState() != state)
return false;
}
return true;
}
size_t
DrainManager::drainableCount() const
{
std::lock_guard<std::mutex> lock(globalLock);
return _allDrainable.size();
}
Drainable::Drainable()
: _drainManager(DrainManager::instance()),
_drainState(_drainManager.state())
{
_drainManager.registerDrainable(this);
}
Drainable::~Drainable()
{
_drainManager.unregisterDrainable(this);
}
DrainState
Drainable::dmDrain()
{
_drainState = DrainState::Draining;
_drainState = drain();
assert(_drainState == DrainState::Draining ||
_drainState == DrainState::Drained);
return _drainState;
}
void
Drainable::dmDrainResume()
{
panic_if(_drainState != DrainState::Drained &&
_drainState != DrainState::Resuming,
"Trying to resume an object that hasn't been drained\n");
_drainState = DrainState::Running;
drainResume();
}
<commit_msg>sim: Remove SimObject dependency from Drainable<commit_after>/*
* Copyright (c) 2012, 2015, 2017 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.
*
* 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.
*/
#include "sim/drain.hh"
#include <algorithm>
#include "base/logging.hh"
#include "base/named.hh"
#include "base/trace.hh"
#include "debug/Drain.hh"
#include "sim/sim_exit.hh"
DrainManager DrainManager::_instance;
DrainManager::DrainManager()
: _count(0),
_state(DrainState::Running)
{
}
DrainManager::~DrainManager()
{
}
bool
DrainManager::tryDrain()
{
panic_if(_state == DrainState::Drained,
"Trying to drain a drained system\n");
panic_if(_count != 0,
"Drain counter must be zero at the start of a drain cycle\n");
DPRINTF(Drain, "Trying to drain %u objects.\n", drainableCount());
_state = DrainState::Draining;
for (auto *obj : _allDrainable) {
DrainState status = obj->dmDrain();
if (Debug::Drain && status != DrainState::Drained) {
Named *temp = dynamic_cast<Named*>(obj);
if (temp)
DPRINTF(Drain, "Failed to drain %s\n", temp->name());
}
_count += status == DrainState::Drained ? 0 : 1;
}
if (_count == 0) {
DPRINTF(Drain, "Drain done.\n");
_state = DrainState::Drained;
return true;
} else {
DPRINTF(Drain, "Need another drain cycle. %u/%u objects not ready.\n",
_count, drainableCount());
return false;
}
}
void
DrainManager::resume()
{
panic_if(_state == DrainState::Running,
"Trying to resume a system that is already running\n");
warn_if(_state == DrainState::Draining,
"Resuming a system that isn't fully drained, this is untested and "
"likely to break\n");
panic_if(_state == DrainState::Resuming,
"Resuming a system that is already trying to resume. This should "
"never happen.\n");
panic_if(_count != 0,
"Resume called in the middle of a drain cycle. %u objects "
"left to drain.\n", _count);
// At this point in time the DrainManager and all objects will be
// in the the Drained state. New objects (i.e., objects created
// while resuming) will inherit the Resuming state from the
// DrainManager, which means we have to resume objects until all
// objects are in the Running state.
_state = DrainState::Resuming;
do {
DPRINTF(Drain, "Resuming %u objects.\n", drainableCount());
for (auto *obj : _allDrainable) {
if (obj->drainState() != DrainState::Running) {
assert(obj->drainState() == DrainState::Drained ||
obj->drainState() == DrainState::Resuming);
obj->dmDrainResume();
}
}
} while (!allInState(DrainState::Running));
_state = DrainState::Running;
}
void
DrainManager::preCheckpointRestore()
{
panic_if(_state != DrainState::Running,
"preCheckpointRestore() called on a system that isn't in the "
"Running state.\n");
DPRINTF(Drain, "Applying pre-restore fixes to %u objects.\n",
drainableCount());
_state = DrainState::Drained;
for (auto *obj : _allDrainable)
obj->_drainState = DrainState::Drained;
}
void
DrainManager::signalDrainDone()
{
assert(_count > 0);
if (--_count == 0) {
DPRINTF(Drain, "All %u objects drained..\n", drainableCount());
exitSimLoop("Finished drain", 0);
}
}
void
DrainManager::registerDrainable(Drainable *obj)
{
std::lock_guard<std::mutex> lock(globalLock);
assert(std::find(_allDrainable.begin(), _allDrainable.end(), obj) ==
_allDrainable.end());
_allDrainable.push_back(obj);
}
void
DrainManager::unregisterDrainable(Drainable *obj)
{
std::lock_guard<std::mutex> lock(globalLock);
auto o = std::find(_allDrainable.begin(), _allDrainable.end(), obj);
assert(o != _allDrainable.end());
_allDrainable.erase(o);
}
bool
DrainManager::allInState(DrainState state) const
{
for (const auto *obj : _allDrainable) {
if (obj->drainState() != state)
return false;
}
return true;
}
size_t
DrainManager::drainableCount() const
{
std::lock_guard<std::mutex> lock(globalLock);
return _allDrainable.size();
}
Drainable::Drainable()
: _drainManager(DrainManager::instance()),
_drainState(_drainManager.state())
{
_drainManager.registerDrainable(this);
}
Drainable::~Drainable()
{
_drainManager.unregisterDrainable(this);
}
DrainState
Drainable::dmDrain()
{
_drainState = DrainState::Draining;
_drainState = drain();
assert(_drainState == DrainState::Draining ||
_drainState == DrainState::Drained);
return _drainState;
}
void
Drainable::dmDrainResume()
{
panic_if(_drainState != DrainState::Drained &&
_drainState != DrainState::Resuming,
"Trying to resume an object that hasn't been drained\n");
_drainState = DrainState::Running;
drainResume();
}
<|endoftext|>
|
<commit_before>// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %S/swift-functions-errors.swift -typecheck -module-name Functions -clang-header-expose-decls=has-expose-attr -emit-clang-header-path %t/functions.h
// RUN: %target-interop-build-clangxx -std=c++17 -x objective-c++ -c %s -I %t -o %t/swift-functions-errors-execution.o
// RUN: %target-interop-build-swift %S/swift-functions-errors.swift -o %t/swift-functions-errors-execution -Xlinker %t/swift-functions-errors-execution.o -module-name Functions -Xfrontend -entry-point-function-name -Xfrontend swiftMain
// RUN: %target-codesign %t/swift-functions-errors-execution
// RUN: %target-run %t/swift-functions-errors-execution | %FileCheck %s
// REQUIRES: executable_test
#include <cassert>
#include <cstdio>
#include "functions.h"
int main() {
static_assert(!noexcept(Functions::emptyThrowFunction()), "noexcept function");
static_assert(!noexcept(Functions::throwFunction()), "noexcept function");
static_assert(!noexcept(Functions::throwFunctionWithReturn()), "noexcept function");
try {
Functions::emptyThrowFunction();
} catch (swift::Error& e) {
printf("Exception\n");
}
try {
Functions::throwFunction();
} catch (swift::Error& e) {
auto errorVal = e.as<Functions::NaiveErrors>();
if (errorVal) {
assert(errorVal == Functions::NaiveErrors::throwError);
errorVal->getMessage();
}
}
try {
Functions::throwFunctionWithReturn();
} catch (swift::Error& e) {
printf("Exception\n");
}
try {
Functions::testDestroyedError();
} catch(const swift::Error &e) { }
return 0;
}
// CHECK: passEmptyThrowFunction
// CHECK-NEXT: passThrowFunction
// CHECK-NEXT: throwError
// CHECK-NEXT: passThrowFunctionWithReturn
// CHECK-NEXT: Exception
// CHECK-NEXT: Test destroyed<commit_msg>Fixing test to check the new realist implementation of dynamic cast<commit_after>// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %S/swift-functions-errors.swift -typecheck -module-name Functions -clang-header-expose-decls=has-expose-attr -emit-clang-header-path %t/functions.h
// RUN: %target-interop-build-clangxx -std=c++17 -x objective-c++ -c %s -I %t -o %t/swift-functions-errors-execution.o
// RUN: %target-interop-build-swift %S/swift-functions-errors.swift -o %t/swift-functions-errors-execution -Xlinker %t/swift-functions-errors-execution.o -module-name Functions -Xfrontend -entry-point-function-name -Xfrontend swiftMain
// RUN: %target-codesign %t/swift-functions-errors-execution
// RUN: %target-run %t/swift-functions-errors-execution | %FileCheck %s
// REQUIRES: executable_test
#include <cassert>
#include <cstdio>
#include "functions.h"
int main() {
static_assert(!noexcept(Functions::emptyThrowFunction()), "noexcept function");
static_assert(!noexcept(Functions::throwFunction()), "noexcept function");
static_assert(!noexcept(Functions::throwFunctionWithReturn()), "noexcept function");
try {
Functions::emptyThrowFunction();
} catch (swift::Error& e) {
printf("Exception\n");
}
try {
Functions::throwFunction();
} catch (swift::Error& e) {
auto errorVal = e.as<Functions::NaiveErrors>();
assert(errorVal == Functions::NaiveErrors::throwError);
errorVal.getMessage();
}
try {
Functions::throwFunctionWithReturn();
} catch (swift::Error& e) {
printf("Exception\n");
}
try {
Functions::testDestroyedError();
} catch(const swift::Error &e) { }
return 0;
}
// CHECK: passEmptyThrowFunction
// CHECK-NEXT: passThrowFunction
// CHECK-NEXT: throwError
// CHECK-NEXT: passThrowFunctionWithReturn
// CHECK-NEXT: Exception
// CHECK-NEXT: Test destroyed
<|endoftext|>
|
<commit_before><commit_msg>Add the initial template of the solution to question 3.8<commit_after><|endoftext|>
|
<commit_before>/*!
* @file libpsalm.cpp
* @brief Exports a function for filling holes in meshes. Used by GigaMesh.
* @author Bastian Rieck <bastian.rieck@iwr.uni-heidelberg.de>
*/
#include <sstream>
#include <string>
#include <vector>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include "libpsalm.h"
#include "mesh.h"
#include "SubdivisionAlgorithms/Liepa.h"
#include "TriangulationAlgorithms/MinimumWeightTriangulation.h"
/*!
* Generates a filename by creating a UUID and attaching the extension
* onto it. This function is used for debugging purposes in order to save
* auxiliary results of the triangulation.
*
* @param extension File extension
* @return UUID.extension as a filename
*/
std::string generate_filename(std::string extension = "ply")
{
boost::uuids::uuid uuid = boost::uuids::random_generator()();
std::stringstream converter;
converter << uuid << "." << extension;
return(converter.str());
}
/*!
* Given a polygonal line described as a list of vertices, this function
* triangulates the hole and subdivides it. Afterwards, the new data is
* stored in some arrays given as parameters of the caller.
*
* @param num_vertices Number of vertices in polygonal line
* @param vertex_IDs List of vertex IDs, used to identify them. If
* this parameter is NULL, the mesh class will
* assign sequential vertex IDs, starting with 0.
* @param coordinates Array of vertex coordinates (size: 3*num_vertices)
* @param normals Array of vertex normals (size: 3*num_vertices)
* @param desired_density Desired density value (approximate) for the
* filled hole
*
* @param num_new_vertices Number of new vertices created by the algorithm
* @param new_coordinates Array of vertex coordinates created by the
* algorithm (size: 3*num_new_vertices)
* @param num_new_faces Number of new faces created by the algorithm
* @param new_vertex_IDs List of vertex IDs for the new faces (size:
* 3*num_new_faces). Negative IDs signify that the
* vertex is _not_ new.
*
* The nomenclature here might be confusing: new_vertex_IDs contains 3
* vertex IDs that describe a new face created by the algorithm.
*
* @returns true if the hole could be filled, otherwise false
*/
bool fill_hole( int num_vertices, long* vertex_IDs, double* coordinates, double* normals, double desired_density,
int* num_new_vertices, double** new_coordinates, int* num_new_faces, long** new_vertex_IDs)
{
bool result = true;
if( num_vertices == 0 ||
coordinates == NULL ||
num_new_vertices == NULL ||
new_coordinates == NULL ||
num_new_faces == NULL ||
new_vertex_IDs == NULL)
return(false);
psalm::mesh M;
psalm::Liepa liepa_algorithm;
psalm::MinimumWeightTriangulation triangulation_algorithm;
M.load_raw_data(num_vertices, vertex_IDs, coordinates, normals);
result = triangulation_algorithm.apply_to(M); // step 1: triangulate the hole
double density = M.get_density();
if(density <= desired_density)
liepa_algorithm.set_alpha(libpsalm::estimate_density( density, // step 2: estimate density based on input parameters
// and the triangulation from step 1
desired_density));
else
liepa_algorithm.set_alpha(1.0);
result = (result && liepa_algorithm.apply_to(M)); // step 3: apply Liepa's subdivision scheme; density
// parameter has been set in step 2
if(result)
{
M.save_raw_data(num_new_vertices,
new_coordinates,
num_new_faces,
new_vertex_IDs);
/*
XXX
system("touch cat.ply");
M.save("test.ply");
M.save(generate_filename());
system("../catply.pl test.ply cat.ply > cat_.ply");
system("mv cat_.ply cat.ply");
*/
}
// signal an error for the calling function
else
{
*num_new_vertices = 0;
*num_new_faces = 0;
}
return(result);
}
/*!
* Given a mesh input density and the desired density of the triangulated
* hole, calculates an estimate for the density parameter of Liepa's
* subdivision scheme.
*
* @param input_density Average density of the input data
* @param desired_density Desired density of triangulated hole
*
* @returns Estimated value for the alpha parameter of Liepa's subdivision
* scheme.
*
* @warning The estimation is only useful for density values < 2000. A
* density much larger than this would require separate treatment.
*/
namespace libpsalm
{
double estimate_density(double input_density, double desired_density)
{
// Fitted parameter values with asymptotic standard error of < 3%,
// which is sufficient for most mesh data.
double a0 = 7.63324e-07;
double a1 = -0.00710062;
double b0 = -4.70052e-07;
double b1 = 0.00573126 ;
double c0 = 2.29083;
/*
double a0 = 6.08864e-07;
double a1 = -0.00167679;
double b0 = -1.61397e-06;
double b1 = 0.00500891;
double c0 = 1.77846;
*/
double x = input_density; // abbreviations so that the function is written more easily
double y = desired_density;
return(a0*x*x+a1*x+b0*y*y+b1*y+c0);
}
} // end of namespace "libpsalm"
<commit_msg>libpsalm: Removed old density parameter values<commit_after>/*!
* @file libpsalm.cpp
* @brief Exports a function for filling holes in meshes. Used by GigaMesh.
* @author Bastian Rieck <bastian.rieck@iwr.uni-heidelberg.de>
*/
#include <sstream>
#include <string>
#include <vector>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include "libpsalm.h"
#include "mesh.h"
#include "SubdivisionAlgorithms/Liepa.h"
#include "TriangulationAlgorithms/MinimumWeightTriangulation.h"
/*!
* Generates a filename by creating a UUID and attaching the extension
* onto it. This function is used for debugging purposes in order to save
* auxiliary results of the triangulation.
*
* @param extension File extension
* @return UUID.extension as a filename
*/
std::string generate_filename(std::string extension = "ply")
{
boost::uuids::uuid uuid = boost::uuids::random_generator()();
std::stringstream converter;
converter << uuid << "." << extension;
return(converter.str());
}
/*!
* Given a polygonal line described as a list of vertices, this function
* triangulates the hole and subdivides it. Afterwards, the new data is
* stored in some arrays given as parameters of the caller.
*
* @param num_vertices Number of vertices in polygonal line
* @param vertex_IDs List of vertex IDs, used to identify them. If
* this parameter is NULL, the mesh class will
* assign sequential vertex IDs, starting with 0.
* @param coordinates Array of vertex coordinates (size: 3*num_vertices)
* @param normals Array of vertex normals (size: 3*num_vertices)
* @param desired_density Desired density value (approximate) for the
* filled hole
*
* @param num_new_vertices Number of new vertices created by the algorithm
* @param new_coordinates Array of vertex coordinates created by the
* algorithm (size: 3*num_new_vertices)
* @param num_new_faces Number of new faces created by the algorithm
* @param new_vertex_IDs List of vertex IDs for the new faces (size:
* 3*num_new_faces). Negative IDs signify that the
* vertex is _not_ new.
*
* The nomenclature here might be confusing: new_vertex_IDs contains 3
* vertex IDs that describe a new face created by the algorithm.
*
* @returns true if the hole could be filled, otherwise false
*/
bool fill_hole( int num_vertices, long* vertex_IDs, double* coordinates, double* normals, double desired_density,
int* num_new_vertices, double** new_coordinates, int* num_new_faces, long** new_vertex_IDs)
{
bool result = true;
if( num_vertices == 0 ||
coordinates == NULL ||
num_new_vertices == NULL ||
new_coordinates == NULL ||
num_new_faces == NULL ||
new_vertex_IDs == NULL)
return(false);
psalm::mesh M;
psalm::Liepa liepa_algorithm;
psalm::MinimumWeightTriangulation triangulation_algorithm;
M.load_raw_data(num_vertices, vertex_IDs, coordinates, normals);
result = triangulation_algorithm.apply_to(M); // step 1: triangulate the hole
double density = M.get_density();
if(density <= desired_density)
liepa_algorithm.set_alpha(libpsalm::estimate_density( density, // step 2: estimate density based on input parameters
// and the triangulation from step 1
desired_density));
else
liepa_algorithm.set_alpha(1.0);
result = (result && liepa_algorithm.apply_to(M)); // step 3: apply Liepa's subdivision scheme; density
// parameter has been set in step 2
if(result)
{
M.save_raw_data(num_new_vertices,
new_coordinates,
num_new_faces,
new_vertex_IDs);
/*
XXX
system("touch cat.ply");
M.save("test.ply");
M.save(generate_filename());
system("../catply.pl test.ply cat.ply > cat_.ply");
system("mv cat_.ply cat.ply");
*/
}
// signal an error for the calling function
else
{
*num_new_vertices = 0;
*num_new_faces = 0;
}
return(result);
}
/*!
* Given a mesh input density and the desired density of the triangulated
* hole, calculates an estimate for the density parameter of Liepa's
* subdivision scheme.
*
* @param input_density Average density of the input data
* @param desired_density Desired density of triangulated hole
*
* @returns Estimated value for the alpha parameter of Liepa's subdivision
* scheme.
*
* @warning The estimation is only useful for density values < 2000. A
* density much larger than this would require separate treatment.
*/
namespace libpsalm
{
double estimate_density(double input_density, double desired_density)
{
// Fitted parameter values with asymptotic standard error of < 3%,
// which is sufficient for most mesh data.
double a0 = 7.63324e-07;
double a1 = -0.00710062;
double b0 = -4.70052e-07;
double b1 = 0.00573126 ;
double c0 = 2.29083;
double x = input_density; // abbreviations so that the function is written more easily
double y = desired_density;
return(a0*x*x+a1*x+b0*y*y+b1*y+c0);
}
} // end of namespace "libpsalm"
<|endoftext|>
|
<commit_before>//
// src/macho/container.cc
// tbd
//
// Created by inoahdev on 4/24/17.
// Copyright © 2017 inoahdev. All rights reserved.
//
#include <mach-o/swap.h>
#include <cstdlib>
#include "container.h"
namespace macho {
container::container(FILE *file, const long &macho_base)
: file_(file), macho_base_(macho_base), is_architecture_(false) {
const auto position = ftell(file);
fseek(file, 0, SEEK_END);
this->size_ = ftell(file);
fseek(file, position, SEEK_SET);
this->validate();
}
container::container(FILE *file, const long &macho_base, const struct fat_arch &architecture)
: file_(file), macho_base_(macho_base), base_(architecture.offset), size_(architecture.size), is_architecture_(true) {
this->validate();
}
container::container(FILE *file, const long &macho_base, const struct fat_arch_64 &architecture)
: file_(file), macho_base_(macho_base), base_(architecture.offset), size_(architecture.size), is_architecture_(true) {
this->validate();
}
container::~container() {
auto &cached = cached_;
if (cached) {
delete cached;
}
auto &string_table = string_table_;
if (string_table) {
delete[] string_table;
}
}
void container::validate() {
auto base = this->base();
auto &file = file_;
auto &header = header_;
auto &magic = header.magic;
auto &should_swap = should_swap_;
auto position = ftell(file);
fseek(file, base, SEEK_SET);
fread(&magic, sizeof(uint32_t), 1, file);
const auto is_regular_macho_file = magic == MH_MAGIC || magic == MH_CIGAM || magic == MH_MAGIC_64 || magic == MH_CIGAM_64;
if (is_regular_macho_file) {
fread(&header.cputype, sizeof(struct mach_header) - sizeof(uint32_t), 1, file);
if (magic == MH_CIGAM || magic == MH_CIGAM_64) {
should_swap = true;
swap_mach_header(&header, NX_LittleEndian);
}
} else {
const auto is_fat_macho_file = magic == MH_MAGIC || magic == MH_CIGAM || magic == MH_MAGIC_64 || magic == MH_CIGAM_64;
if (is_fat_macho_file) {
fprintf(stderr, "Architecture at offset (%ld) cannot be a fat mach-o file itself\n", base);
exit(1);
} else {
fprintf(stderr, "Architecture at offset (%ld) is not a valid mach-o base\n", base);
exit(1);
}
}
fseek(file, position, SEEK_SET);
}
void container::iterate_load_commands(const std::function<bool (const struct load_command *)> &callback) {
const auto &header = header_;
const auto &file = file_;
const auto &is_architecture = is_architecture_;
const auto &should_swap = should_swap_;
const auto &ncmds = header.ncmds;
const auto &sizeofcmds = header.sizeofcmds;
auto &cached = cached_;
if (!cached) {
cached = new char[sizeofcmds];
auto base = this->base() + sizeof(struct mach_header);
if (this->is_64_bit()) {
base += sizeof(uint32_t);
}
const auto position = ftell(file);
fseek(file, base, SEEK_SET);
fread(cached, sizeofcmds, 1, file);
fseek(file, position, SEEK_SET);
}
auto size_used = 0;
auto cached_index = 0;
auto should_callback = true;
for (auto i = 0; i < ncmds; i++) {
auto load_cmd = (struct load_command *)&cached[cached_index];
if (should_swap && !swapped_cache) {
swap_load_command(load_cmd, NX_LittleEndian);
}
const auto &cmdsize = load_cmd->cmdsize;
if (cmdsize < sizeof(struct load_command)) {
if (is_architecture) {
fprintf(stderr, "Load-command (at index %d) of architecture is too small to be valid\n", i);
} else {
fprintf(stderr, "Load-command (at index %d) of mach-o file is too small to be valid\n", i);
}
exit(1);
}
if (cmdsize >= sizeofcmds) {
if (is_architecture) {
fprintf(stderr, "Load-command (at index %d) of architecture is larger than/or equal to entire area allocated for load-commands\n", i);
} else {
fprintf(stderr, "Load-command (at index %d) of mach-o file is larger than/or equal to entire area allocated for load-commands\n", i);
}
exit(1);
}
size_used += cmdsize;
if (size_used > sizeofcmds) {
if (is_architecture) {
fprintf(stderr, "Load-command (at index %d) of architecture goes past end of area allocated for load-commands\n", i);
} else {
fprintf(stderr, "Load-command (at index %d) of mach-o file goes past end of area allocated for load-commands\n", i);
}
exit(1);
} else if (size_used == sizeofcmds && i != ncmds - 1) {
if (is_architecture) {
fprintf(stderr, "Load-command (at index %d) of architecture takes up all of the remaining space allocated for load-commands\n", i);
} else {
fprintf(stderr, "Load-command (at index %d) of mach-o file takes up all of the remaining space allocated for load-commands\n", i);
}
exit(1);
}
if (should_callback) {
auto result = callback(load_cmd);
if (!result) {
should_callback = false;
}
} else if (swapped_cache) {
break;
}
cached_index += cmdsize;
}
swapped_cache = true;
}
void container::iterate_symbols(const std::function<bool (const struct nlist_64 &, const char *)> &callback) {
auto &file = file_;
auto &is_architecture = is_architecture_;
auto &should_swap = should_swap_;
auto base = this->base();
auto position = ftell(file);
struct symtab_command *symtab_command = nullptr;
iterate_load_commands([&](const struct load_command *load_cmd) {
if (load_cmd->cmd != LC_SYMTAB) {
return true;
}
symtab_command = (struct symtab_command *)load_cmd;
if (should_swap) {
swap_symtab_command(symtab_command, NX_LittleEndian);
}
return false;
});
if (!symtab_command) {
if (is_architecture) {
fputs("Architecture does not have a symbol-table\n", stderr);
} else {
fputs("Mach-o file does not have a symbol-table\n", stderr);
}
exit(1);
}
const auto &string_table_offset = symtab_command->stroff;
if (string_table_offset > size_) {
if (is_architecture) {
fputs("Architecture has a string-table outside of its container\n", stderr);
} else {
fputs("Mach-o file has a string-table outside of its container\n", stderr);
}
exit(1);
}
const auto &string_table_size = symtab_command->strsize;
if (string_table_offset + string_table_size > size_) {
if (is_architecture) {
fputs("Architecture has a string-table that goes outside of its container\n", stderr);
} else {
fputs("Mach-o file has a string-table that goes outside of its container\n", stderr);
}
exit(1);
}
const auto &symbol_table_offset = symtab_command->symoff;
if (symbol_table_offset > size_) {
if (is_architecture) {
fputs("Architecture has a symbol-table that is outside of its container\n", stderr);
} else {
fputs("Mach-o file has a symbol-table that is outside of its container\n", stderr);
}
exit(1);
}
auto &string_table = string_table_;
if (!string_table) {
string_table = new char[string_table_size];
fseek(file, base + string_table_offset, SEEK_SET);
fread(string_table, string_table_size, 1, file);
}
const auto &symbol_table_count = symtab_command->nsyms;
fseek(file, base + symbol_table_offset, SEEK_SET);
if (this->is_64_bit()) {
const auto symbol_table_size = sizeof(struct nlist_64) * symbol_table_count;
if (symbol_table_offset + symbol_table_size > size_) {
if (is_architecture) {
fputs("Architecture has a symbol-table that goes outside of its container\n", stderr);
} else {
fputs("Mach-o file has a symbol-table that goes outside of its container\n", stderr);
}
exit(1);
}
const auto symbol_table = new struct nlist_64[symbol_table_count];
fread(symbol_table, symbol_table_size, 1, file);
if (should_swap) {
swap_nlist_64(symbol_table, symbol_table_count, NX_LittleEndian);
}
for (auto i = 0; i < symbol_table_count; i++) {
const auto &symbol_table_entry = symbol_table[i];
const auto &symbol_table_entry_string_table_index = symbol_table_entry.n_un.n_strx;
if (symbol_table_entry_string_table_index > (string_table_size - 1)) {
fprintf(stderr, "Symbol-table entry (at index %d) has symbol-string past end of string-table\n", i);
exit(1);
}
const auto symbol_table_string_table_string = &string_table[symbol_table_entry_string_table_index];
const auto result = callback(symbol_table_entry, symbol_table_string_table_string);
if (!result) {
break;
}
}
delete[] symbol_table;
} else {
const auto symbol_table_size = sizeof(struct nlist) * symbol_table_count;
if (symbol_table_offset + symbol_table_size > size_) {
if (is_architecture) {
fputs("Architecture has a symbol-table that goes outside of its container\n", stderr);
} else {
fputs("Mach-o file has a symbol-table that goes outside of its container\n", stderr);
}
exit(1);
}
const auto symbol_table = new struct nlist[symbol_table_count];
fread(symbol_table, symbol_table_size, 1, file);
if (should_swap) {
swap_nlist(symbol_table, symbol_table_count, NX_LittleEndian);
}
for (auto i = 0; i < symbol_table_count; i++) {
const auto &symbol_table_entry = symbol_table[i];
const auto &symbol_table_entry_string_table_index = symbol_table_entry.n_un.n_strx;
if (symbol_table_entry_string_table_index > (string_table_size - 1)) {
fprintf(stderr, "Symbol-table entry (at index %d) has symbol-string past end of string-table\n", i);
exit(1);
}
const struct nlist_64 symbol_table_entry_64 = { { symbol_table_entry.n_un.n_strx }, symbol_table_entry.n_type, symbol_table_entry.n_sect, (uint16_t)symbol_table_entry.n_desc, symbol_table_entry.n_value };
const auto symbol_table_string_table_string = &string_table[symbol_table_entry_string_table_index];
const auto result = callback(symbol_table_entry_64, symbol_table_string_table_string);
if (!result) {
break;
}
}
delete[] symbol_table;
}
fseek(file, position, SEEK_SET);
}
}
<commit_msg>cached load-commands should be deleted with `delete[]`<commit_after>//
// src/macho/container.cc
// tbd
//
// Created by inoahdev on 4/24/17.
// Copyright © 2017 inoahdev. All rights reserved.
//
#include <mach-o/swap.h>
#include <cstdlib>
#include "container.h"
namespace macho {
container::container(FILE *file, const long &macho_base)
: file_(file), macho_base_(macho_base), is_architecture_(false) {
const auto position = ftell(file);
fseek(file, 0, SEEK_END);
this->size_ = ftell(file);
fseek(file, position, SEEK_SET);
this->validate();
}
container::container(FILE *file, const long &macho_base, const struct fat_arch &architecture)
: file_(file), macho_base_(macho_base), base_(architecture.offset), size_(architecture.size), is_architecture_(true) {
this->validate();
}
container::container(FILE *file, const long &macho_base, const struct fat_arch_64 &architecture)
: file_(file), macho_base_(macho_base), base_(architecture.offset), size_(architecture.size), is_architecture_(true) {
this->validate();
}
container::~container() {
auto &cached = cached_;
if (cached) {
delete[] cached;
}
auto &string_table = string_table_;
if (string_table) {
delete[] string_table;
}
}
void container::validate() {
auto base = this->base();
auto &file = file_;
auto &header = header_;
auto &magic = header.magic;
auto &should_swap = should_swap_;
auto position = ftell(file);
fseek(file, base, SEEK_SET);
fread(&magic, sizeof(uint32_t), 1, file);
const auto is_regular_macho_file = magic == MH_MAGIC || magic == MH_CIGAM || magic == MH_MAGIC_64 || magic == MH_CIGAM_64;
if (is_regular_macho_file) {
fread(&header.cputype, sizeof(struct mach_header) - sizeof(uint32_t), 1, file);
if (magic == MH_CIGAM || magic == MH_CIGAM_64) {
should_swap = true;
swap_mach_header(&header, NX_LittleEndian);
}
} else {
const auto is_fat_macho_file = magic == MH_MAGIC || magic == MH_CIGAM || magic == MH_MAGIC_64 || magic == MH_CIGAM_64;
if (is_fat_macho_file) {
fprintf(stderr, "Architecture at offset (%ld) cannot be a fat mach-o file itself\n", base);
exit(1);
} else {
fprintf(stderr, "Architecture at offset (%ld) is not a valid mach-o base\n", base);
exit(1);
}
}
fseek(file, position, SEEK_SET);
}
void container::iterate_load_commands(const std::function<bool (const struct load_command *)> &callback) {
const auto &header = header_;
const auto &file = file_;
const auto &is_architecture = is_architecture_;
const auto &should_swap = should_swap_;
const auto &ncmds = header.ncmds;
const auto &sizeofcmds = header.sizeofcmds;
auto &cached = cached_;
if (!cached) {
cached = new char[sizeofcmds];
auto base = this->base() + sizeof(struct mach_header);
if (this->is_64_bit()) {
base += sizeof(uint32_t);
}
const auto position = ftell(file);
fseek(file, base, SEEK_SET);
fread(cached, sizeofcmds, 1, file);
fseek(file, position, SEEK_SET);
}
auto size_used = 0;
auto cached_index = 0;
auto should_callback = true;
for (auto i = 0; i < ncmds; i++) {
auto load_cmd = (struct load_command *)&cached[cached_index];
if (should_swap && !swapped_cache) {
swap_load_command(load_cmd, NX_LittleEndian);
}
const auto &cmdsize = load_cmd->cmdsize;
if (cmdsize < sizeof(struct load_command)) {
if (is_architecture) {
fprintf(stderr, "Load-command (at index %d) of architecture is too small to be valid\n", i);
} else {
fprintf(stderr, "Load-command (at index %d) of mach-o file is too small to be valid\n", i);
}
exit(1);
}
if (cmdsize >= sizeofcmds) {
if (is_architecture) {
fprintf(stderr, "Load-command (at index %d) of architecture is larger than/or equal to entire area allocated for load-commands\n", i);
} else {
fprintf(stderr, "Load-command (at index %d) of mach-o file is larger than/or equal to entire area allocated for load-commands\n", i);
}
exit(1);
}
size_used += cmdsize;
if (size_used > sizeofcmds) {
if (is_architecture) {
fprintf(stderr, "Load-command (at index %d) of architecture goes past end of area allocated for load-commands\n", i);
} else {
fprintf(stderr, "Load-command (at index %d) of mach-o file goes past end of area allocated for load-commands\n", i);
}
exit(1);
} else if (size_used == sizeofcmds && i != ncmds - 1) {
if (is_architecture) {
fprintf(stderr, "Load-command (at index %d) of architecture takes up all of the remaining space allocated for load-commands\n", i);
} else {
fprintf(stderr, "Load-command (at index %d) of mach-o file takes up all of the remaining space allocated for load-commands\n", i);
}
exit(1);
}
if (should_callback) {
auto result = callback(load_cmd);
if (!result) {
should_callback = false;
}
} else if (swapped_cache) {
break;
}
cached_index += cmdsize;
}
swapped_cache = true;
}
void container::iterate_symbols(const std::function<bool (const struct nlist_64 &, const char *)> &callback) {
auto &file = file_;
auto &is_architecture = is_architecture_;
auto &should_swap = should_swap_;
auto base = this->base();
auto position = ftell(file);
struct symtab_command *symtab_command = nullptr;
iterate_load_commands([&](const struct load_command *load_cmd) {
if (load_cmd->cmd != LC_SYMTAB) {
return true;
}
symtab_command = (struct symtab_command *)load_cmd;
if (should_swap) {
swap_symtab_command(symtab_command, NX_LittleEndian);
}
return false;
});
if (!symtab_command) {
if (is_architecture) {
fputs("Architecture does not have a symbol-table\n", stderr);
} else {
fputs("Mach-o file does not have a symbol-table\n", stderr);
}
exit(1);
}
const auto &string_table_offset = symtab_command->stroff;
if (string_table_offset > size_) {
if (is_architecture) {
fputs("Architecture has a string-table outside of its container\n", stderr);
} else {
fputs("Mach-o file has a string-table outside of its container\n", stderr);
}
exit(1);
}
const auto &string_table_size = symtab_command->strsize;
if (string_table_offset + string_table_size > size_) {
if (is_architecture) {
fputs("Architecture has a string-table that goes outside of its container\n", stderr);
} else {
fputs("Mach-o file has a string-table that goes outside of its container\n", stderr);
}
exit(1);
}
const auto &symbol_table_offset = symtab_command->symoff;
if (symbol_table_offset > size_) {
if (is_architecture) {
fputs("Architecture has a symbol-table that is outside of its container\n", stderr);
} else {
fputs("Mach-o file has a symbol-table that is outside of its container\n", stderr);
}
exit(1);
}
auto &string_table = string_table_;
if (!string_table) {
string_table = new char[string_table_size];
fseek(file, base + string_table_offset, SEEK_SET);
fread(string_table, string_table_size, 1, file);
}
const auto &symbol_table_count = symtab_command->nsyms;
fseek(file, base + symbol_table_offset, SEEK_SET);
if (this->is_64_bit()) {
const auto symbol_table_size = sizeof(struct nlist_64) * symbol_table_count;
if (symbol_table_offset + symbol_table_size > size_) {
if (is_architecture) {
fputs("Architecture has a symbol-table that goes outside of its container\n", stderr);
} else {
fputs("Mach-o file has a symbol-table that goes outside of its container\n", stderr);
}
exit(1);
}
const auto symbol_table = new struct nlist_64[symbol_table_count];
fread(symbol_table, symbol_table_size, 1, file);
if (should_swap) {
swap_nlist_64(symbol_table, symbol_table_count, NX_LittleEndian);
}
for (auto i = 0; i < symbol_table_count; i++) {
const auto &symbol_table_entry = symbol_table[i];
const auto &symbol_table_entry_string_table_index = symbol_table_entry.n_un.n_strx;
if (symbol_table_entry_string_table_index > (string_table_size - 1)) {
fprintf(stderr, "Symbol-table entry (at index %d) has symbol-string past end of string-table\n", i);
exit(1);
}
const auto symbol_table_string_table_string = &string_table[symbol_table_entry_string_table_index];
const auto result = callback(symbol_table_entry, symbol_table_string_table_string);
if (!result) {
break;
}
}
delete[] symbol_table;
} else {
const auto symbol_table_size = sizeof(struct nlist) * symbol_table_count;
if (symbol_table_offset + symbol_table_size > size_) {
if (is_architecture) {
fputs("Architecture has a symbol-table that goes outside of its container\n", stderr);
} else {
fputs("Mach-o file has a symbol-table that goes outside of its container\n", stderr);
}
exit(1);
}
const auto symbol_table = new struct nlist[symbol_table_count];
fread(symbol_table, symbol_table_size, 1, file);
if (should_swap) {
swap_nlist(symbol_table, symbol_table_count, NX_LittleEndian);
}
for (auto i = 0; i < symbol_table_count; i++) {
const auto &symbol_table_entry = symbol_table[i];
const auto &symbol_table_entry_string_table_index = symbol_table_entry.n_un.n_strx;
if (symbol_table_entry_string_table_index > (string_table_size - 1)) {
fprintf(stderr, "Symbol-table entry (at index %d) has symbol-string past end of string-table\n", i);
exit(1);
}
const struct nlist_64 symbol_table_entry_64 = { { symbol_table_entry.n_un.n_strx }, symbol_table_entry.n_type, symbol_table_entry.n_sect, (uint16_t)symbol_table_entry.n_desc, symbol_table_entry.n_value };
const auto symbol_table_string_table_string = &string_table[symbol_table_entry_string_table_index];
const auto result = callback(symbol_table_entry_64, symbol_table_string_table_string);
if (!result) {
break;
}
}
delete[] symbol_table;
}
fseek(file, position, SEEK_SET);
}
}
<|endoftext|>
|
<commit_before>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2011, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "dparse.h"
#include "helper.hh"
#include <getopt.h>
#include <glib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
extern "C" {
extern D_ParserTables parser_tables_lang;
};
void block(int fd)
{
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags & (~O_NONBLOCK));
}
void nonblock(int fd)
{
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
void print_usage()
{
std::printf(
"Usage: lang [options] inputfile\n"
"Options:\n"
" -h print usage\n"
" -o output to a file (defaults to stdout)\n"
" -c compile (needs to have output file)\n"
);
}
extern std::string result;
std::string compile_command("g++ -fPIC -shared -x c++ - -I /usr/include/fmbt -o ");
int main(int argc,char** argv) {
int c;
bool lib=false;
FILE* outputfile=stdout;
static struct option long_opts[] = {
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
while ((c = getopt_long (argc, argv, "b:hco:", long_opts, NULL)) != -1) {
switch (c)
{
case 'b':
compile_command=optarg;
compile_command+=" ";
break;
case 'c':
lib=true;
break;
case 'o':
outputfile=fopen(optarg,"w");
compile_command=compile_command+optarg;
if (!outputfile) {
std::printf("Can't open output file \"%s\"\n",optarg);
return 1;
}
break;
case 'h':
print_usage();
return 0;
default:
return 2;
}
}
if (optind == argc || (lib && outputfile==stdout)) {
print_usage();
return -1;
}
char *s;
D_Parser *p = new_D_Parser(&parser_tables_lang, 512);
s=readfile(argv[optind],false);
if (!s) {
std::printf("Can't read input file \"%s\"\n",argv[optind]);
return 3;
}
dparse(p,s,std::strlen(s));
if (lib) {
int _stdin,_stdout;//,_stder;
GPid pid;
int argc;
char b[512];
gchar **argv=(gchar**)malloc(42*sizeof(gchar*));
GError *gerr=NULL;
g_shell_parse_argv(compile_command.c_str(),
&argc,&argv,&gerr);
g_spawn_async_with_pipes(NULL,argv,NULL,G_SPAWN_SEARCH_PATH,NULL,&pid,NULL,&_stdin,&_stdout,NULL,&gerr);
nonblock(_stdout);
unsigned int pos=0;
unsigned int wrote=0;
do {
wrote=TEMP_FAILURE_RETRY(write(_stdin,result.c_str()+pos,result.length()-pos));
pos+=wrote;
read(_stdout,b,512);
} while (wrote>0 && pos<result.length());
close(_stdin);
block(_stdout);
while(read(_stdout,b,512)) {}
} else {
fprintf(outputfile,"%s",result.c_str());
}
free_D_Parser(p);
free(s);
return 0;
}
<commit_msg>fmbt-aalc usage string fixed<commit_after>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2011, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "dparse.h"
#include "helper.hh"
#include <getopt.h>
#include <glib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
extern "C" {
extern D_ParserTables parser_tables_lang;
};
void block(int fd)
{
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags & (~O_NONBLOCK));
}
void nonblock(int fd)
{
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
void print_usage()
{
std::printf(
"Usage: fmbt-aalc [options] inputfile\n"
"Options:\n"
" -h print usage\n"
" -o output to a file (defaults to stdout)\n"
" -c compile (needs to have output file)\n"
);
}
extern std::string result;
std::string compile_command("g++ -fPIC -shared -x c++ - -I /usr/include/fmbt -o ");
int main(int argc,char** argv) {
int c;
bool lib=false;
FILE* outputfile=stdout;
static struct option long_opts[] = {
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
while ((c = getopt_long (argc, argv, "b:hco:", long_opts, NULL)) != -1) {
switch (c)
{
case 'b':
compile_command=optarg;
compile_command+=" ";
break;
case 'c':
lib=true;
break;
case 'o':
outputfile=fopen(optarg,"w");
compile_command=compile_command+optarg;
if (!outputfile) {
std::printf("Can't open output file \"%s\"\n",optarg);
return 1;
}
break;
case 'h':
print_usage();
return 0;
default:
return 2;
}
}
if (optind == argc || (lib && outputfile==stdout)) {
print_usage();
return -1;
}
char *s;
D_Parser *p = new_D_Parser(&parser_tables_lang, 512);
s=readfile(argv[optind],false);
if (!s) {
std::printf("Can't read input file \"%s\"\n",argv[optind]);
return 3;
}
dparse(p,s,std::strlen(s));
if (lib) {
int _stdin,_stdout;//,_stder;
GPid pid;
int argc;
char b[512];
gchar **argv=(gchar**)malloc(42*sizeof(gchar*));
GError *gerr=NULL;
g_shell_parse_argv(compile_command.c_str(),
&argc,&argv,&gerr);
g_spawn_async_with_pipes(NULL,argv,NULL,G_SPAWN_SEARCH_PATH,NULL,&pid,NULL,&_stdin,&_stdout,NULL,&gerr);
nonblock(_stdout);
unsigned int pos=0;
unsigned int wrote=0;
do {
wrote=TEMP_FAILURE_RETRY(write(_stdin,result.c_str()+pos,result.length()-pos));
pos+=wrote;
read(_stdout,b,512);
} while (wrote>0 && pos<result.length());
close(_stdin);
block(_stdout);
while(read(_stdout,b,512)) {}
} else {
fprintf(outputfile,"%s",result.c_str());
}
free_D_Parser(p);
free(s);
return 0;
}
<|endoftext|>
|
<commit_before>/**
* @author: Jeff Thompson
* See COPYING for copyright and distribution information.
*/
#include <stdexcept>
#include "../NDN.hpp"
#include "../c/encoding/BinaryXMLElementReader.h"
#include "TcpTransport.hpp"
using namespace std;
namespace ndn {
void TcpTransport::connect(NDN &ndn)
{
ndn_Error error;
if (error = ndn_TcpTransport_connect(&transport_, (char *)ndn.getHost(), ndn.getPort()))
throw std::runtime_error(ndn_getErrorString(error));
// TODO: Properly indicate connected status.
ndn_ = &ndn;
}
void TcpTransport::send(unsigned char *data, unsigned int dataLength)
{
ndn_Error error;
if (error = ndn_TcpTransport_send(&transport_, data, dataLength))
throw std::runtime_error(ndn_getErrorString(error));
}
void TcpTransport::tempReceive()
{
if (!ndn_)
// TODO: Properly check if connected.
return;
ndn_BinaryXMLElementReader elementReader;
// Automaticall cast ndn_ to (struct ndn_ElementListener *)
ndn_BinaryXMLElementReader_init(&elementReader, ndn_);
unsigned char buffer[8000];
ndn_Error error;
unsigned int nBytes;
if (error = ndn_TcpTransport_receive(&transport_, buffer, sizeof(buffer), &nBytes))
throw std::runtime_error(ndn_getErrorString(error));
ndn_BinaryXMLElementReader_onReceivedData(&elementReader, buffer, nBytes);
}
}
<commit_msg>Fix comment typo<commit_after>/**
* @author: Jeff Thompson
* See COPYING for copyright and distribution information.
*/
#include <stdexcept>
#include "../NDN.hpp"
#include "../c/encoding/BinaryXMLElementReader.h"
#include "TcpTransport.hpp"
using namespace std;
namespace ndn {
void TcpTransport::connect(NDN &ndn)
{
ndn_Error error;
if (error = ndn_TcpTransport_connect(&transport_, (char *)ndn.getHost(), ndn.getPort()))
throw std::runtime_error(ndn_getErrorString(error));
// TODO: Properly indicate connected status.
ndn_ = &ndn;
}
void TcpTransport::send(unsigned char *data, unsigned int dataLength)
{
ndn_Error error;
if (error = ndn_TcpTransport_send(&transport_, data, dataLength))
throw std::runtime_error(ndn_getErrorString(error));
}
void TcpTransport::tempReceive()
{
if (!ndn_)
// TODO: Properly check if connected.
return;
ndn_BinaryXMLElementReader elementReader;
// Automatically cast ndn_ to (struct ndn_ElementListener *)
ndn_BinaryXMLElementReader_init(&elementReader, ndn_);
unsigned char buffer[8000];
ndn_Error error;
unsigned int nBytes;
if (error = ndn_TcpTransport_receive(&transport_, buffer, sizeof(buffer), &nBytes))
throw std::runtime_error(ndn_getErrorString(error));
ndn_BinaryXMLElementReader_onReceivedData(&elementReader, buffer, nBytes);
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 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 "net/base/listen_socket_unittest.h"
#include <fcntl.h>
#include "base/eintr_wrapper.h"
#include "net/base/net_util.h"
#include "testing/platform_test.h"
const int ListenSocketTester::kTestPort = 9999;
static const int kReadBufSize = 1024;
static const char* kHelloWorld = "HELLO, WORLD";
static const int kMaxQueueSize = 20;
static const char* kLoopback = "127.0.0.1";
static const int kDefaultTimeoutMs = 5000;
#if defined(OS_POSIX)
static const char* kSemaphoreName = "chromium.listen_socket";
#endif
ListenSocket* ListenSocketTester::DoListen() {
return ListenSocket::Listen(kLoopback, kTestPort, this);
}
void ListenSocketTester::SetUp() {
#if defined(OS_WIN)
InitializeCriticalSection(&lock_);
semaphore_ = CreateSemaphore(NULL, 0, kMaxQueueSize, NULL);
server_ = NULL;
net::EnsureWinsockInit();
#elif defined(OS_POSIX)
ASSERT_EQ(0, pthread_mutex_init(&lock_, NULL ));
sem_unlink(kSemaphoreName);
semaphore_ = sem_open(kSemaphoreName, O_CREAT, 0, 0);
ASSERT_NE(SEM_FAILED, semaphore_);
#endif
base::Thread::Options options;
options.message_loop_type = MessageLoop::TYPE_IO;
thread_.reset(new base::Thread("socketio_test"));
thread_->StartWithOptions(options);
loop_ = (MessageLoopForIO*)thread_->message_loop();
loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &ListenSocketTester::Listen));
// verify Listen succeeded
ASSERT_TRUE(NextAction(kDefaultTimeoutMs));
ASSERT_FALSE(server_ == NULL);
ASSERT_EQ(ACTION_LISTEN, last_action_.type());
// verify the connect/accept and setup test_socket_
test_socket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct sockaddr_in client;
client.sin_family = AF_INET;
client.sin_addr.s_addr = inet_addr(kLoopback);
client.sin_port = htons(kTestPort);
int ret =
HANDLE_EINTR(connect(test_socket_, reinterpret_cast<sockaddr*>(&client),
sizeof(client)));
ASSERT_NE(ret, SOCKET_ERROR);
net::SetNonBlocking(test_socket_);
ASSERT_TRUE(NextAction(kDefaultTimeoutMs));
ASSERT_EQ(ACTION_ACCEPT, last_action_.type());
}
void ListenSocketTester::TearDown() {
// verify close
#if defined(OS_WIN)
closesocket(test_socket_);
#elif defined(OS_POSIX)
close(test_socket_);
#endif
ASSERT_TRUE(NextAction(kDefaultTimeoutMs));
ASSERT_EQ(ACTION_CLOSE, last_action_.type());
loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &ListenSocketTester::Shutdown));
ASSERT_TRUE(NextAction(kDefaultTimeoutMs));
ASSERT_EQ(ACTION_SHUTDOWN, last_action_.type());
#if defined(OS_WIN)
CloseHandle(semaphore_);
semaphore_ = 0;
DeleteCriticalSection(&lock_);
#elif defined(OS_POSIX)
ASSERT_EQ(0, pthread_mutex_lock(&lock_));
semaphore_ = NULL;
ASSERT_EQ(0, pthread_mutex_unlock(&lock_));
ASSERT_EQ(0, sem_unlink(kSemaphoreName));
ASSERT_EQ(0, pthread_mutex_destroy(&lock_));
#endif
thread_.reset();
loop_ = NULL;
}
void ListenSocketTester::ReportAction(const ListenSocketTestAction& action) {
#if defined(OS_WIN)
EnterCriticalSection(&lock_);
queue_.push_back(action);
LeaveCriticalSection(&lock_);
ReleaseSemaphore(semaphore_, 1, NULL);
#elif defined(OS_POSIX)
ASSERT_EQ(0, pthread_mutex_lock(&lock_));
queue_.push_back(action);
ASSERT_EQ(0, pthread_mutex_unlock(&lock_));
ASSERT_EQ(0, sem_post(semaphore_));
#endif
}
bool ListenSocketTester::NextAction(int timeout) {
#if defined(OS_WIN)
DWORD ret = ::WaitForSingleObject(semaphore_, timeout);
if (ret != WAIT_OBJECT_0)
return false;
EnterCriticalSection(&lock_);
if (queue_.size() == 0) {
LeaveCriticalSection(&lock_);
return false;
}
last_action_ = queue_.front();
queue_.pop_front();
LeaveCriticalSection(&lock_);
return true;
#elif defined(OS_POSIX)
if (semaphore_ == SEM_FAILED)
return false;
while (true) {
int result = sem_trywait(semaphore_);
PlatformThread::Sleep(1); // 1MS sleep
timeout--;
if (timeout <= 0)
return false;
if (result == 0)
break;
}
pthread_mutex_lock(&lock_);
if (queue_.size() == 0) {
pthread_mutex_unlock(&lock_);
return false;
}
last_action_ = queue_.front();
queue_.pop_front();
pthread_mutex_unlock(&lock_);
return true;
#endif
}
int ListenSocketTester::ClearTestSocket() {
char buf[kReadBufSize];
int len_ret = 0;
int time_out = 0;
do {
int len = HANDLE_EINTR(recv(test_socket_, buf, kReadBufSize, 0));
#if defined(OS_WIN)
if (len == SOCKET_ERROR) {
int err = WSAGetLastError();
if (err == WSAEWOULDBLOCK) {
#elif defined(OS_POSIX)
if (len == SOCKET_ERROR) {
if (errno == EWOULDBLOCK || errno == EAGAIN) {
#endif
PlatformThread::Sleep(1);
time_out++;
if (time_out > 10)
break;
continue; // still trying
}
} else if (len == 0) {
// socket closed
break;
} else {
time_out = 0;
len_ret += len;
}
} while (true);
return len_ret;
}
void ListenSocketTester::Shutdown() {
connection_->Release();
connection_ = NULL;
server_->Release();
server_ = NULL;
ReportAction(ListenSocketTestAction(ACTION_SHUTDOWN));
}
void ListenSocketTester::Listen() {
server_ = DoListen();
if (server_) {
server_->AddRef();
ReportAction(ListenSocketTestAction(ACTION_LISTEN));
}
}
void ListenSocketTester::SendFromTester() {
connection_->Send(kHelloWorld);
ReportAction(ListenSocketTestAction(ACTION_SEND));
}
void ListenSocketTester::DidAccept(ListenSocket *server,
ListenSocket *connection) {
connection_ = connection;
connection_->AddRef();
ReportAction(ListenSocketTestAction(ACTION_ACCEPT));
}
void ListenSocketTester::DidRead(ListenSocket *connection,
const std::string& data) {
ReportAction(ListenSocketTestAction(ACTION_READ, data));
}
void ListenSocketTester::DidClose(ListenSocket *sock) {
ReportAction(ListenSocketTestAction(ACTION_CLOSE));
}
bool ListenSocketTester::Send(SOCKET sock, const std::string& str) {
int len = static_cast<int>(str.length());
int send_len = HANDLE_EINTR(send(sock, str.data(), len, 0));
if (send_len == SOCKET_ERROR) {
LOG(ERROR) << "send failed: " << errno;
return false;
} else if (send_len != len) {
return false;
}
return true;
}
void ListenSocketTester::TestClientSend() {
ASSERT_TRUE(Send(test_socket_, kHelloWorld));
ASSERT_TRUE(NextAction(kDefaultTimeoutMs));
ASSERT_EQ(ACTION_READ, last_action_.type());
ASSERT_EQ(last_action_.data(), kHelloWorld);
}
void ListenSocketTester::TestClientSendLong() {
int hello_len = strlen(kHelloWorld);
std::string long_string;
int long_len = 0;
for (int i = 0; i < 200; i++) {
long_string += kHelloWorld;
long_len += hello_len;
}
ASSERT_TRUE(Send(test_socket_, long_string));
int read_len = 0;
while (read_len < long_len) {
ASSERT_TRUE(NextAction(kDefaultTimeoutMs));
ASSERT_EQ(ACTION_READ, last_action_.type());
std::string last_data = last_action_.data();
size_t len = last_data.length();
if (long_string.compare(read_len, len, last_data)) {
ASSERT_EQ(long_string.compare(read_len, len, last_data), 0);
}
read_len += static_cast<int>(last_data.length());
}
ASSERT_EQ(read_len, long_len);
}
void ListenSocketTester::TestServerSend() {
loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &ListenSocketTester::SendFromTester));
ASSERT_TRUE(NextAction(kDefaultTimeoutMs));
ASSERT_EQ(ACTION_SEND, last_action_.type());
// TODO(erikkay): Without this sleep, the recv seems to fail a small amount
// of the time. I could fix this by making the socket blocking, but then
// this test might hang in the case of errors. It would be nice to do
// something that felt more reliable here.
PlatformThread::Sleep(10); // sleep for 10ms
const int buf_len = 200;
char buf[buf_len+1];
int recv_len;
do {
recv_len = HANDLE_EINTR(recv(test_socket_, buf, buf_len, 0));
#if defined(OS_POSIX)
} while (recv_len == SOCKET_ERROR && errno == EINTR);
#else
} while (false);
#endif
ASSERT_NE(recv_len, SOCKET_ERROR);
buf[recv_len] = 0;
ASSERT_STREQ(buf, kHelloWorld);
}
class ListenSocketTest: public PlatformTest {
public:
ListenSocketTest() {
tester_ = NULL;
}
virtual void SetUp() {
PlatformTest::SetUp();
tester_ = new ListenSocketTester();
tester_->SetUp();
}
virtual void TearDown() {
PlatformTest::TearDown();
tester_->TearDown();
tester_ = NULL;
}
scoped_refptr<ListenSocketTester> tester_;
};
TEST_F(ListenSocketTest, ClientSend) {
tester_->TestClientSend();
}
TEST_F(ListenSocketTest, ClientSendLong) {
tester_->TestClientSendLong();
}
TEST_F(ListenSocketTest, ServerSend) {
tester_->TestServerSend();
}
<commit_msg>Coverity: Assert that socket() returns a successful value.<commit_after>// Copyright (c) 2006-2008 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 "net/base/listen_socket_unittest.h"
#include <fcntl.h>
#include "base/eintr_wrapper.h"
#include "net/base/net_util.h"
#include "testing/platform_test.h"
const int ListenSocketTester::kTestPort = 9999;
static const int kReadBufSize = 1024;
static const char* kHelloWorld = "HELLO, WORLD";
static const int kMaxQueueSize = 20;
static const char* kLoopback = "127.0.0.1";
static const int kDefaultTimeoutMs = 5000;
#if defined(OS_POSIX)
static const char* kSemaphoreName = "chromium.listen_socket";
#endif
ListenSocket* ListenSocketTester::DoListen() {
return ListenSocket::Listen(kLoopback, kTestPort, this);
}
void ListenSocketTester::SetUp() {
#if defined(OS_WIN)
InitializeCriticalSection(&lock_);
semaphore_ = CreateSemaphore(NULL, 0, kMaxQueueSize, NULL);
server_ = NULL;
net::EnsureWinsockInit();
#elif defined(OS_POSIX)
ASSERT_EQ(0, pthread_mutex_init(&lock_, NULL));
sem_unlink(kSemaphoreName);
semaphore_ = sem_open(kSemaphoreName, O_CREAT, 0, 0);
ASSERT_NE(SEM_FAILED, semaphore_);
#endif
base::Thread::Options options;
options.message_loop_type = MessageLoop::TYPE_IO;
thread_.reset(new base::Thread("socketio_test"));
thread_->StartWithOptions(options);
loop_ = reinterpret_cast<MessageLoopForIO*>(thread_->message_loop());
loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &ListenSocketTester::Listen));
// verify Listen succeeded
ASSERT_TRUE(NextAction(kDefaultTimeoutMs));
ASSERT_FALSE(server_ == NULL);
ASSERT_EQ(ACTION_LISTEN, last_action_.type());
// verify the connect/accept and setup test_socket_
test_socket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
ASSERT_NE(-1, test_socket_);
struct sockaddr_in client;
client.sin_family = AF_INET;
client.sin_addr.s_addr = inet_addr(kLoopback);
client.sin_port = htons(kTestPort);
int ret =
HANDLE_EINTR(connect(test_socket_, reinterpret_cast<sockaddr*>(&client),
sizeof(client)));
ASSERT_NE(ret, SOCKET_ERROR);
net::SetNonBlocking(test_socket_);
ASSERT_TRUE(NextAction(kDefaultTimeoutMs));
ASSERT_EQ(ACTION_ACCEPT, last_action_.type());
}
void ListenSocketTester::TearDown() {
// verify close
#if defined(OS_WIN)
closesocket(test_socket_);
#elif defined(OS_POSIX)
close(test_socket_);
#endif
ASSERT_TRUE(NextAction(kDefaultTimeoutMs));
ASSERT_EQ(ACTION_CLOSE, last_action_.type());
loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &ListenSocketTester::Shutdown));
ASSERT_TRUE(NextAction(kDefaultTimeoutMs));
ASSERT_EQ(ACTION_SHUTDOWN, last_action_.type());
#if defined(OS_WIN)
CloseHandle(semaphore_);
semaphore_ = 0;
DeleteCriticalSection(&lock_);
#elif defined(OS_POSIX)
ASSERT_EQ(0, pthread_mutex_lock(&lock_));
semaphore_ = NULL;
ASSERT_EQ(0, pthread_mutex_unlock(&lock_));
ASSERT_EQ(0, sem_unlink(kSemaphoreName));
ASSERT_EQ(0, pthread_mutex_destroy(&lock_));
#endif
thread_.reset();
loop_ = NULL;
}
void ListenSocketTester::ReportAction(const ListenSocketTestAction& action) {
#if defined(OS_WIN)
EnterCriticalSection(&lock_);
queue_.push_back(action);
LeaveCriticalSection(&lock_);
ReleaseSemaphore(semaphore_, 1, NULL);
#elif defined(OS_POSIX)
ASSERT_EQ(0, pthread_mutex_lock(&lock_));
queue_.push_back(action);
ASSERT_EQ(0, pthread_mutex_unlock(&lock_));
ASSERT_EQ(0, sem_post(semaphore_));
#endif
}
bool ListenSocketTester::NextAction(int timeout) {
#if defined(OS_WIN)
DWORD ret = ::WaitForSingleObject(semaphore_, timeout);
if (ret != WAIT_OBJECT_0)
return false;
EnterCriticalSection(&lock_);
if (queue_.size() == 0) {
LeaveCriticalSection(&lock_);
return false;
}
last_action_ = queue_.front();
queue_.pop_front();
LeaveCriticalSection(&lock_);
return true;
#elif defined(OS_POSIX)
if (semaphore_ == SEM_FAILED)
return false;
while (true) {
int result = sem_trywait(semaphore_);
PlatformThread::Sleep(1); // 1MS sleep
timeout--;
if (timeout <= 0)
return false;
if (result == 0)
break;
}
pthread_mutex_lock(&lock_);
if (queue_.size() == 0) {
pthread_mutex_unlock(&lock_);
return false;
}
last_action_ = queue_.front();
queue_.pop_front();
pthread_mutex_unlock(&lock_);
return true;
#endif
}
int ListenSocketTester::ClearTestSocket() {
char buf[kReadBufSize];
int len_ret = 0;
int time_out = 0;
do {
int len = HANDLE_EINTR(recv(test_socket_, buf, kReadBufSize, 0));
#if defined(OS_WIN)
if (len == SOCKET_ERROR) {
int err = WSAGetLastError();
if (err == WSAEWOULDBLOCK) {
#elif defined(OS_POSIX)
if (len == SOCKET_ERROR) {
if (errno == EWOULDBLOCK || errno == EAGAIN) {
#endif
PlatformThread::Sleep(1);
time_out++;
if (time_out > 10)
break;
continue; // still trying
}
} else if (len == 0) {
// socket closed
break;
} else {
time_out = 0;
len_ret += len;
}
} while (true);
return len_ret;
}
void ListenSocketTester::Shutdown() {
connection_->Release();
connection_ = NULL;
server_->Release();
server_ = NULL;
ReportAction(ListenSocketTestAction(ACTION_SHUTDOWN));
}
void ListenSocketTester::Listen() {
server_ = DoListen();
if (server_) {
server_->AddRef();
ReportAction(ListenSocketTestAction(ACTION_LISTEN));
}
}
void ListenSocketTester::SendFromTester() {
connection_->Send(kHelloWorld);
ReportAction(ListenSocketTestAction(ACTION_SEND));
}
void ListenSocketTester::DidAccept(ListenSocket *server,
ListenSocket *connection) {
connection_ = connection;
connection_->AddRef();
ReportAction(ListenSocketTestAction(ACTION_ACCEPT));
}
void ListenSocketTester::DidRead(ListenSocket *connection,
const std::string& data) {
ReportAction(ListenSocketTestAction(ACTION_READ, data));
}
void ListenSocketTester::DidClose(ListenSocket *sock) {
ReportAction(ListenSocketTestAction(ACTION_CLOSE));
}
bool ListenSocketTester::Send(SOCKET sock, const std::string& str) {
int len = static_cast<int>(str.length());
int send_len = HANDLE_EINTR(send(sock, str.data(), len, 0));
if (send_len == SOCKET_ERROR) {
LOG(ERROR) << "send failed: " << errno;
return false;
} else if (send_len != len) {
return false;
}
return true;
}
void ListenSocketTester::TestClientSend() {
ASSERT_TRUE(Send(test_socket_, kHelloWorld));
ASSERT_TRUE(NextAction(kDefaultTimeoutMs));
ASSERT_EQ(ACTION_READ, last_action_.type());
ASSERT_EQ(last_action_.data(), kHelloWorld);
}
void ListenSocketTester::TestClientSendLong() {
int hello_len = strlen(kHelloWorld);
std::string long_string;
int long_len = 0;
for (int i = 0; i < 200; i++) {
long_string += kHelloWorld;
long_len += hello_len;
}
ASSERT_TRUE(Send(test_socket_, long_string));
int read_len = 0;
while (read_len < long_len) {
ASSERT_TRUE(NextAction(kDefaultTimeoutMs));
ASSERT_EQ(ACTION_READ, last_action_.type());
std::string last_data = last_action_.data();
size_t len = last_data.length();
if (long_string.compare(read_len, len, last_data)) {
ASSERT_EQ(long_string.compare(read_len, len, last_data), 0);
}
read_len += static_cast<int>(last_data.length());
}
ASSERT_EQ(read_len, long_len);
}
void ListenSocketTester::TestServerSend() {
loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &ListenSocketTester::SendFromTester));
ASSERT_TRUE(NextAction(kDefaultTimeoutMs));
ASSERT_EQ(ACTION_SEND, last_action_.type());
// TODO(erikkay): Without this sleep, the recv seems to fail a small amount
// of the time. I could fix this by making the socket blocking, but then
// this test might hang in the case of errors. It would be nice to do
// something that felt more reliable here.
PlatformThread::Sleep(10); // sleep for 10ms
const int buf_len = 200;
char buf[buf_len+1];
int recv_len;
do {
recv_len = HANDLE_EINTR(recv(test_socket_, buf, buf_len, 0));
#if defined(OS_POSIX)
} while (recv_len == SOCKET_ERROR && errno == EINTR);
#else
} while (false);
#endif
ASSERT_NE(recv_len, SOCKET_ERROR);
buf[recv_len] = 0;
ASSERT_STREQ(buf, kHelloWorld);
}
class ListenSocketTest: public PlatformTest {
public:
ListenSocketTest() {
tester_ = NULL;
}
virtual void SetUp() {
PlatformTest::SetUp();
tester_ = new ListenSocketTester();
tester_->SetUp();
}
virtual void TearDown() {
PlatformTest::TearDown();
tester_->TearDown();
tester_ = NULL;
}
scoped_refptr<ListenSocketTester> tester_;
};
TEST_F(ListenSocketTest, ClientSend) {
tester_->TestClientSend();
}
TEST_F(ListenSocketTest, ClientSendLong) {
tester_->TestClientSendLong();
}
TEST_F(ListenSocketTest, ServerSend) {
tester_->TestServerSend();
}
<|endoftext|>
|
<commit_before>// ------------------------------------------------------------------
// pion-net: a C++ framework for building lightweight HTTP interfaces
// ------------------------------------------------------------------
// Copyright (C) 2007-2008 Atomic Labs, Inc. (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
//
#ifndef __PION_HTTPTYPES_HEADER__
#define __PION_HTTPTYPES_HEADER__
#include <string>
#include <cctype>
#include <pion/PionConfig.hpp>
#include <pion/PionHashMap.hpp>
namespace pion { // begin namespace pion
namespace net { // begin namespace net (Pion Network Library)
///
/// HTTPTypes: common data types used by HTTP
///
struct PION_NET_API HTTPTypes
{
/// virtual destructor
virtual ~HTTPTypes() {}
// generic strings used by HTTP
static const std::string STRING_EMPTY;
static const std::string STRING_CRLF;
static const std::string STRING_HTTP_VERSION;
static const std::string HEADER_NAME_VALUE_DELIMITER;
// common HTTP header names
static const std::string HEADER_HOST;
static const std::string HEADER_COOKIE;
static const std::string HEADER_SET_COOKIE;
static const std::string HEADER_CONNECTION;
static const std::string HEADER_CONTENT_TYPE;
static const std::string HEADER_CONTENT_LENGTH;
static const std::string HEADER_CONTENT_LOCATION;
static const std::string HEADER_LAST_MODIFIED;
static const std::string HEADER_IF_MODIFIED_SINCE;
static const std::string HEADER_TRANSFER_ENCODING;
static const std::string HEADER_LOCATION;
// common HTTP content types
static const std::string CONTENT_TYPE_HTML;
static const std::string CONTENT_TYPE_TEXT;
static const std::string CONTENT_TYPE_XML;
static const std::string CONTENT_TYPE_URLENCODED;
// common HTTP request methods
static const std::string REQUEST_METHOD_HEAD;
static const std::string REQUEST_METHOD_GET;
static const std::string REQUEST_METHOD_PUT;
static const std::string REQUEST_METHOD_POST;
static const std::string REQUEST_METHOD_DELETE;
// common HTTP response messages
static const std::string RESPONSE_MESSAGE_OK;
static const std::string RESPONSE_MESSAGE_CREATED;
static const std::string RESPONSE_MESSAGE_NO_CONTENT;
static const std::string RESPONSE_MESSAGE_FORBIDDEN;
static const std::string RESPONSE_MESSAGE_NOT_FOUND;
static const std::string RESPONSE_MESSAGE_METHOD_NOT_ALLOWED;
static const std::string RESPONSE_MESSAGE_NOT_MODIFIED;
static const std::string RESPONSE_MESSAGE_BAD_REQUEST;
static const std::string RESPONSE_MESSAGE_SERVER_ERROR;
static const std::string RESPONSE_MESSAGE_NOT_IMPLEMENTED;
// common HTTP response codes
static const unsigned int RESPONSE_CODE_OK;
static const unsigned int RESPONSE_CODE_CREATED;
static const unsigned int RESPONSE_CODE_NO_CONTENT;
static const unsigned int RESPONSE_CODE_FORBIDDEN;
static const unsigned int RESPONSE_CODE_NOT_FOUND;
static const unsigned int RESPONSE_CODE_METHOD_NOT_ALLOWED;
static const unsigned int RESPONSE_CODE_NOT_MODIFIED;
static const unsigned int RESPONSE_CODE_BAD_REQUEST;
static const unsigned int RESPONSE_CODE_SERVER_ERROR;
static const unsigned int RESPONSE_CODE_NOT_IMPLEMENTED;
/// used for case-insensitive comparisons of HTTP header names
struct HeadersAreEqual {
inline bool operator()(const std::string& str1, const std::string& str2) const {
if (str1.size() != str2.size())
return false;
std::string::const_iterator it1 = str1.begin();
std::string::const_iterator it2 = str2.begin();
while ( (it1!=str1.end()) && (it2!=str2.end()) ) {
if (tolower(*it1) != tolower(*it2))
return false;
++it1;
++it2;
}
return true;
}
};
/// your plain old string hash algorithm, except case insensitive
struct HashHeader {
inline unsigned long operator()(const std::string& str) const {
unsigned long value = 0;
for (std::string::const_iterator i = str.begin(); i!= str.end(); ++i)
value = static_cast<unsigned char>(tolower(*i)) + (value << 6) + (value << 16) - value;
return value;
}
};
/// use case-insensitive comparisons for HTTP header names
typedef PION_HASH_MULTIMAP<std::string, std::string, HashHeader, HeadersAreEqual > Headers;
/// data type for a dictionary of strings (used for HTTP headers)
typedef PION_HASH_MULTIMAP<std::string, std::string, PION_HASH_STRING > StringDictionary;
/// data type for HTTP query parameters
typedef StringDictionary QueryParams;
/// data type for HTTP cookie parameters
typedef StringDictionary CookieParams;
/// escapes URL-encoded strings (a%20value+with%20spaces)
static std::string url_decode(const std::string& str);
/// encodes strings so that they are safe for URLs (with%20spaces)
static std::string url_encode(const std::string& str);
/// converts time_t format into an HTTP-date string
static std::string get_date_string(const time_t t);
/// builds an HTTP query string from a collection of query parameters
static std::string make_query_string(const QueryParams& query_params);
/**
* creates a "Set-Cookie" header
*
* @param name the name of the cookie
* @param value the value of the cookie
* @param path the path of the cookie
* @param has_max_age true if the max_age value should be set
* @param max_age the life of the cookie, in seconds (0 = discard)
*
* @return the new "Set-Cookie" header
*/
static std::string make_set_cookie_header(const std::string& name,
const std::string& value,
const std::string& path,
const bool has_max_age = false,
const unsigned long max_age = 0);
};
} // end namespace net
} // end namespace pion
#endif
<commit_msg>Added MSVC specific code for the new case insensitive header map.<commit_after>// ------------------------------------------------------------------
// pion-net: a C++ framework for building lightweight HTTP interfaces
// ------------------------------------------------------------------
// Copyright (C) 2007-2008 Atomic Labs, Inc. (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
//
#ifndef __PION_HTTPTYPES_HEADER__
#define __PION_HTTPTYPES_HEADER__
#include <string>
#include <cctype>
#include <pion/PionConfig.hpp>
#include <pion/PionHashMap.hpp>
namespace pion { // begin namespace pion
namespace net { // begin namespace net (Pion Network Library)
///
/// HTTPTypes: common data types used by HTTP
///
struct PION_NET_API HTTPTypes
{
/// virtual destructor
virtual ~HTTPTypes() {}
// generic strings used by HTTP
static const std::string STRING_EMPTY;
static const std::string STRING_CRLF;
static const std::string STRING_HTTP_VERSION;
static const std::string HEADER_NAME_VALUE_DELIMITER;
// common HTTP header names
static const std::string HEADER_HOST;
static const std::string HEADER_COOKIE;
static const std::string HEADER_SET_COOKIE;
static const std::string HEADER_CONNECTION;
static const std::string HEADER_CONTENT_TYPE;
static const std::string HEADER_CONTENT_LENGTH;
static const std::string HEADER_CONTENT_LOCATION;
static const std::string HEADER_LAST_MODIFIED;
static const std::string HEADER_IF_MODIFIED_SINCE;
static const std::string HEADER_TRANSFER_ENCODING;
static const std::string HEADER_LOCATION;
// common HTTP content types
static const std::string CONTENT_TYPE_HTML;
static const std::string CONTENT_TYPE_TEXT;
static const std::string CONTENT_TYPE_XML;
static const std::string CONTENT_TYPE_URLENCODED;
// common HTTP request methods
static const std::string REQUEST_METHOD_HEAD;
static const std::string REQUEST_METHOD_GET;
static const std::string REQUEST_METHOD_PUT;
static const std::string REQUEST_METHOD_POST;
static const std::string REQUEST_METHOD_DELETE;
// common HTTP response messages
static const std::string RESPONSE_MESSAGE_OK;
static const std::string RESPONSE_MESSAGE_CREATED;
static const std::string RESPONSE_MESSAGE_NO_CONTENT;
static const std::string RESPONSE_MESSAGE_FORBIDDEN;
static const std::string RESPONSE_MESSAGE_NOT_FOUND;
static const std::string RESPONSE_MESSAGE_METHOD_NOT_ALLOWED;
static const std::string RESPONSE_MESSAGE_NOT_MODIFIED;
static const std::string RESPONSE_MESSAGE_BAD_REQUEST;
static const std::string RESPONSE_MESSAGE_SERVER_ERROR;
static const std::string RESPONSE_MESSAGE_NOT_IMPLEMENTED;
// common HTTP response codes
static const unsigned int RESPONSE_CODE_OK;
static const unsigned int RESPONSE_CODE_CREATED;
static const unsigned int RESPONSE_CODE_NO_CONTENT;
static const unsigned int RESPONSE_CODE_FORBIDDEN;
static const unsigned int RESPONSE_CODE_NOT_FOUND;
static const unsigned int RESPONSE_CODE_METHOD_NOT_ALLOWED;
static const unsigned int RESPONSE_CODE_NOT_MODIFIED;
static const unsigned int RESPONSE_CODE_BAD_REQUEST;
static const unsigned int RESPONSE_CODE_SERVER_ERROR;
static const unsigned int RESPONSE_CODE_NOT_IMPLEMENTED;
/// used for case-insensitive comparisons of HTTP header names
struct HeadersAreEqual {
inline bool operator()(const std::string& str1, const std::string& str2) const {
if (str1.size() != str2.size())
return false;
std::string::const_iterator it1 = str1.begin();
std::string::const_iterator it2 = str2.begin();
while ( (it1!=str1.end()) && (it2!=str2.end()) ) {
if (tolower(*it1) != tolower(*it2))
return false;
++it1;
++it2;
}
return true;
}
};
/// your plain old string hash algorithm, except case insensitive
struct HashHeader {
inline unsigned long operator()(const std::string& str) const {
unsigned long value = 0;
for (std::string::const_iterator i = str.begin(); i!= str.end(); ++i)
value = static_cast<unsigned char>(tolower(*i)) + (value << 6) + (value << 16) - value;
return value;
}
};
struct CaseInsensitiveLess {
bool operator()(const std::string& str1, const std::string& str2) const {
if (str1.size() < str2.size())
return true;
std::string::const_iterator it1 = str1.begin();
std::string::const_iterator it2 = str2.begin();
while ( (it1 != str1.end()) && (it2 != str2.end()) ) {
if (tolower(*it1) < tolower(*it2))
return true;
++it1;
++it2;
}
return false;
}
};
/// use case-insensitive comparisons for HTTP header names
#ifdef _MSC_VER
typedef PION_HASH_MULTIMAP<std::string, std::string, stdext::hash_compare<std::string, CaseInsensitiveLess> > Headers;
#else
typedef PION_HASH_MULTIMAP<std::string, std::string, HashHeader, HeadersAreEqual > Headers;
#endif
/// data type for a dictionary of strings (used for HTTP headers)
typedef PION_HASH_MULTIMAP<std::string, std::string, PION_HASH_STRING > StringDictionary;
/// data type for HTTP query parameters
typedef StringDictionary QueryParams;
/// data type for HTTP cookie parameters
typedef StringDictionary CookieParams;
/// escapes URL-encoded strings (a%20value+with%20spaces)
static std::string url_decode(const std::string& str);
/// encodes strings so that they are safe for URLs (with%20spaces)
static std::string url_encode(const std::string& str);
/// converts time_t format into an HTTP-date string
static std::string get_date_string(const time_t t);
/// builds an HTTP query string from a collection of query parameters
static std::string make_query_string(const QueryParams& query_params);
/**
* creates a "Set-Cookie" header
*
* @param name the name of the cookie
* @param value the value of the cookie
* @param path the path of the cookie
* @param has_max_age true if the max_age value should be set
* @param max_age the life of the cookie, in seconds (0 = discard)
*
* @return the new "Set-Cookie" header
*/
static std::string make_set_cookie_header(const std::string& name,
const std::string& value,
const std::string& path,
const bool has_max_age = false,
const unsigned long max_age = 0);
};
} // end namespace net
} // end namespace pion
#endif
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <vvasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "BackendPasses.h"
#include "llvm/Analysis/InlineCost.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/AlwaysInliner.h"
#include "llvm/Transforms/IPO/Inliner.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Transforms/Scalar.h"
//#include "clang/Basic/LangOptions.h"
//#include "clang/Basic/TargetOptions.h"
#include "clang/Frontend/CodeGenOptions.h"
using namespace cling;
using namespace clang;
using namespace llvm;
using namespace llvm::legacy;
namespace {
class KeepLocalGVPass: public ModulePass {
static char ID;
bool runOnGlobal(GlobalValue& GV) {
if (GV.isDeclaration())
return false; // no change.
// GV is a definition.
llvm::GlobalValue::LinkageTypes LT = GV.getLinkage();
if (!GV.isDiscardableIfUnused(LT))
return false;
if (LT == llvm::GlobalValue::InternalLinkage
|| LT == llvm::GlobalValue::PrivateLinkage) {
GV.setLinkage(llvm::GlobalValue::ExternalLinkage);
return true; // a change!
}
return false;
}
public:
KeepLocalGVPass() : ModulePass(ID) {}
bool runOnModule(Module &M) override {
bool ret = false;
for (auto &&F: M)
ret |= runOnGlobal(F);
for (auto &&G: M.globals())
ret |= runOnGlobal(G);
return ret;
}
};
}
char KeepLocalGVPass::ID = 0;
BackendPasses::~BackendPasses() {
//delete m_PMBuilder->Inliner;
}
void BackendPasses::CreatePasses(llvm::Module& M, int OptLevel)
{
// From BackEndUtil's clang::EmitAssemblyHelper::CreatePasses().
#if 0
CodeGenOptions::InliningMethod Inlining = m_CGOpts.getInlining();
CodeGenOptions& CGOpts_ = const_cast<CodeGenOptions&>(m_CGOpts);
// DON'T: we will not find our symbols...
//CGOpts_.CXXCtorDtorAliases = 1;
// Default clang -O2 on Linux 64bit also has the following, but see
// CIFactory.cpp.
CGOpts_.DisableFPElim = 0;
CGOpts_.DiscardValueNames = 1;
CGOpts_.OmitLeafFramePointer = 1;
CGOpts_.OptimizationLevel = 2;
CGOpts_.RelaxAll = 0;
CGOpts_.UnrollLoops = 1;
CGOpts_.VectorizeLoop = 1;
CGOpts_.VectorizeSLP = 1;
#endif
#if 0 // def __GNUC__
// Better inlining is pending https://bugs.llvm.org//show_bug.cgi?id=19668
// and its consequence https://sft.its.cern.ch/jira/browse/ROOT-7111
// shown e.g. by roottest/cling/stl/map/badstringMap
if (Inlining > CodeGenOptions::NormalInlining)
Inlining = CodeGenOptions::NormalInlining;
#endif
// Handle disabling of LLVM optimization, where we want to preserve the
// internal module before any optimization.
if (m_CGOpts.DisableLLVMPasses) {
OptLevel = 0;
// Always keep at least ForceInline - NoInlining is deadly for libc++.
// Inlining = CGOpts.NoInlining;
}
llvm::PassManagerBuilder PMBuilder;
PMBuilder.OptLevel = OptLevel;
PMBuilder.SizeLevel = m_CGOpts.OptimizeSize;
PMBuilder.BBVectorize = 0; // m_CGOpts.VectorizeBB;
PMBuilder.SLPVectorize = OptLevel > 1 ? 1 : 0; // m_CGOpts.VectorizeSLP
PMBuilder.LoopVectorize = OptLevel > 1 ? 1 : 0; // m_CGOpts.VectorizeLoop
PMBuilder.DisableTailCalls = m_CGOpts.DisableTailCalls;
PMBuilder.DisableUnrollLoops = !m_CGOpts.UnrollLoops;
PMBuilder.MergeFunctions = m_CGOpts.MergeFunctions;
PMBuilder.RerollLoops = m_CGOpts.RerollLoops;
PMBuilder.LibraryInfo = new TargetLibraryInfoImpl(m_TM.getTargetTriple());
// At O0 and O1 we only run the always inliner which is more efficient. At
// higher optimization levels we run the normal inliner.
if (m_CGOpts.OptimizationLevel <= 1) {
bool InsertLifetimeIntrinsics = m_CGOpts.OptimizationLevel != 0;
PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
} else {
PMBuilder.Inliner = createFunctionInliningPass(m_CGOpts.OptimizationLevel,
m_CGOpts.OptimizeSize,
(!m_CGOpts.SampleProfileFile.empty() && m_CGOpts.EmitSummaryIndex));
}
// Set up the per-module pass manager.
m_MPM[OptLevel].reset(new legacy::PassManager());
m_MPM[OptLevel]->add(new KeepLocalGVPass());
m_MPM[OptLevel]->add(createTargetTransformInfoWrapperPass(
m_TM.getTargetIRAnalysis()));
m_TM.adjustPassManager(PMBuilder);
PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
[&](const PassManagerBuilder &,
legacy::PassManagerBase &PM) {
PM.add(createAddDiscriminatorsPass());
});
//if (!CGOpts.RewriteMapFiles.empty())
// addSymbolRewriterPass(CGOpts, m_MPM);
PMBuilder.populateModulePassManager(*m_MPM[OptLevel]);
m_FPM[OptLevel].reset(new legacy::FunctionPassManager(&M));
m_FPM[OptLevel]->add(createTargetTransformInfoWrapperPass(
m_TM.getTargetIRAnalysis()));
if (m_CGOpts.VerifyModule)
m_FPM[OptLevel]->add(createVerifierPass());
PMBuilder.populateFunctionPassManager(*m_FPM[OptLevel]);
}
void BackendPasses::runOnModule(Module& M, int OptLevel) {
if (OptLevel < 0)
OptLevel = 0;
if (OptLevel > 3)
OptLevel = 3;
if (!m_MPM[OptLevel])
CreatePasses(M, OptLevel);
static constexpr std::array<llvm::CodeGenOpt::Level, 4> CGOptLevel {{
llvm::CodeGenOpt::None,
llvm::CodeGenOpt::Less,
llvm::CodeGenOpt::Default,
llvm::CodeGenOpt::Aggressive
}};
// TM's OptLevel is used to build orc::SimpleCompiler passes for every Module.
m_TM.setOptLevel(CGOptLevel[OptLevel]);
// Run the per-function passes on the module.
m_FPM[OptLevel]->doInitialization();
for (auto&& I: M.functions())
if (!I.isDeclaration())
m_FPM[OptLevel]->run(I);
m_FPM[OptLevel]->doFinalization();
m_MPM[OptLevel]->run(M);
}
<commit_msg>BBVectorize flag was unused and went away in LLVM 5.0<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <vvasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "BackendPasses.h"
#include "llvm/Analysis/InlineCost.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/AlwaysInliner.h"
#include "llvm/Transforms/IPO/Inliner.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Transforms/Scalar.h"
//#include "clang/Basic/LangOptions.h"
//#include "clang/Basic/TargetOptions.h"
#include "clang/Frontend/CodeGenOptions.h"
using namespace cling;
using namespace clang;
using namespace llvm;
using namespace llvm::legacy;
namespace {
class KeepLocalGVPass: public ModulePass {
static char ID;
bool runOnGlobal(GlobalValue& GV) {
if (GV.isDeclaration())
return false; // no change.
// GV is a definition.
llvm::GlobalValue::LinkageTypes LT = GV.getLinkage();
if (!GV.isDiscardableIfUnused(LT))
return false;
if (LT == llvm::GlobalValue::InternalLinkage
|| LT == llvm::GlobalValue::PrivateLinkage) {
GV.setLinkage(llvm::GlobalValue::ExternalLinkage);
return true; // a change!
}
return false;
}
public:
KeepLocalGVPass() : ModulePass(ID) {}
bool runOnModule(Module &M) override {
bool ret = false;
for (auto &&F: M)
ret |= runOnGlobal(F);
for (auto &&G: M.globals())
ret |= runOnGlobal(G);
return ret;
}
};
}
char KeepLocalGVPass::ID = 0;
BackendPasses::~BackendPasses() {
//delete m_PMBuilder->Inliner;
}
void BackendPasses::CreatePasses(llvm::Module& M, int OptLevel)
{
// From BackEndUtil's clang::EmitAssemblyHelper::CreatePasses().
#if 0
CodeGenOptions::InliningMethod Inlining = m_CGOpts.getInlining();
CodeGenOptions& CGOpts_ = const_cast<CodeGenOptions&>(m_CGOpts);
// DON'T: we will not find our symbols...
//CGOpts_.CXXCtorDtorAliases = 1;
// Default clang -O2 on Linux 64bit also has the following, but see
// CIFactory.cpp.
CGOpts_.DisableFPElim = 0;
CGOpts_.DiscardValueNames = 1;
CGOpts_.OmitLeafFramePointer = 1;
CGOpts_.OptimizationLevel = 2;
CGOpts_.RelaxAll = 0;
CGOpts_.UnrollLoops = 1;
CGOpts_.VectorizeLoop = 1;
CGOpts_.VectorizeSLP = 1;
#endif
#if 0 // def __GNUC__
// Better inlining is pending https://bugs.llvm.org//show_bug.cgi?id=19668
// and its consequence https://sft.its.cern.ch/jira/browse/ROOT-7111
// shown e.g. by roottest/cling/stl/map/badstringMap
if (Inlining > CodeGenOptions::NormalInlining)
Inlining = CodeGenOptions::NormalInlining;
#endif
// Handle disabling of LLVM optimization, where we want to preserve the
// internal module before any optimization.
if (m_CGOpts.DisableLLVMPasses) {
OptLevel = 0;
// Always keep at least ForceInline - NoInlining is deadly for libc++.
// Inlining = CGOpts.NoInlining;
}
llvm::PassManagerBuilder PMBuilder;
PMBuilder.OptLevel = OptLevel;
PMBuilder.SizeLevel = m_CGOpts.OptimizeSize;
PMBuilder.SLPVectorize = OptLevel > 1 ? 1 : 0; // m_CGOpts.VectorizeSLP
PMBuilder.LoopVectorize = OptLevel > 1 ? 1 : 0; // m_CGOpts.VectorizeLoop
PMBuilder.DisableTailCalls = m_CGOpts.DisableTailCalls;
PMBuilder.DisableUnrollLoops = !m_CGOpts.UnrollLoops;
PMBuilder.MergeFunctions = m_CGOpts.MergeFunctions;
PMBuilder.RerollLoops = m_CGOpts.RerollLoops;
PMBuilder.LibraryInfo = new TargetLibraryInfoImpl(m_TM.getTargetTriple());
// At O0 and O1 we only run the always inliner which is more efficient. At
// higher optimization levels we run the normal inliner.
if (m_CGOpts.OptimizationLevel <= 1) {
bool InsertLifetimeIntrinsics = m_CGOpts.OptimizationLevel != 0;
PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
} else {
PMBuilder.Inliner = createFunctionInliningPass(m_CGOpts.OptimizationLevel,
m_CGOpts.OptimizeSize,
(!m_CGOpts.SampleProfileFile.empty() && m_CGOpts.EmitSummaryIndex));
}
// Set up the per-module pass manager.
m_MPM[OptLevel].reset(new legacy::PassManager());
m_MPM[OptLevel]->add(new KeepLocalGVPass());
m_MPM[OptLevel]->add(createTargetTransformInfoWrapperPass(
m_TM.getTargetIRAnalysis()));
m_TM.adjustPassManager(PMBuilder);
PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
[&](const PassManagerBuilder &,
legacy::PassManagerBase &PM) {
PM.add(createAddDiscriminatorsPass());
});
//if (!CGOpts.RewriteMapFiles.empty())
// addSymbolRewriterPass(CGOpts, m_MPM);
PMBuilder.populateModulePassManager(*m_MPM[OptLevel]);
m_FPM[OptLevel].reset(new legacy::FunctionPassManager(&M));
m_FPM[OptLevel]->add(createTargetTransformInfoWrapperPass(
m_TM.getTargetIRAnalysis()));
if (m_CGOpts.VerifyModule)
m_FPM[OptLevel]->add(createVerifierPass());
PMBuilder.populateFunctionPassManager(*m_FPM[OptLevel]);
}
void BackendPasses::runOnModule(Module& M, int OptLevel) {
if (OptLevel < 0)
OptLevel = 0;
if (OptLevel > 3)
OptLevel = 3;
if (!m_MPM[OptLevel])
CreatePasses(M, OptLevel);
static constexpr std::array<llvm::CodeGenOpt::Level, 4> CGOptLevel {{
llvm::CodeGenOpt::None,
llvm::CodeGenOpt::Less,
llvm::CodeGenOpt::Default,
llvm::CodeGenOpt::Aggressive
}};
// TM's OptLevel is used to build orc::SimpleCompiler passes for every Module.
m_TM.setOptLevel(CGOptLevel[OptLevel]);
// Run the per-function passes on the module.
m_FPM[OptLevel]->doInitialization();
for (auto&& I: M.functions())
if (!I.isDeclaration())
m_FPM[OptLevel]->run(I);
m_FPM[OptLevel]->doFinalization();
m_MPM[OptLevel]->run(M);
}
<|endoftext|>
|
<commit_before>/*
* Author(s):
* - Chris Kilner <ckilner@aldebaran-robotics.com>
* - Cedric Gestes <gestes@aldebaran-robotics.com>
*
* Copyright (C) 2010 Aldebaran Robotics
*/
#include "src/messaging/server_impl.hpp"
#include <string>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <qimessaging/serialization.hpp>
#include <qimessaging/transport/buffer.hpp>
#include "src/messaging/network/endpoints.hpp"
#include "src/messaging/network/master_endpoint.hpp"
#include <qi/log.hpp>
#include <qimessaging/exceptions.hpp>
namespace qi {
using qi::Message;
namespace detail {
ServerImpl::~ServerImpl() {
if (!_isMasterServer) {
_masterClient.unregisterEndpoint(_endpointContext);
}
}
ServerImpl::ServerImpl(const std::string& name, Context *ctx)
: ImplBase(ctx),
_isMasterServer(false),
_transportServer(_masterClient.getQiContextPtr()->getTransportContext())
{
_endpointContext.type = SERVER_ENDPOINT;
_endpointContext.name = name;
_endpointContext.contextID = _masterClient.getQiContextPtr()->getID();
}
void ServerImpl::connect(const std::string &masterAddress)
{
//TODO
std::pair<std::string, int> masterEndpointAndPort;
if (!qi::detail::validateMasterEndpoint(masterAddress, masterEndpointAndPort)) {
_isInitialized = false;
qiLogError("qimessaging") << "\"" << _endpointContext.name << "\" initialized with invalid master "
"address: \"" << masterAddress << "\" All calls will fail."
<< std::endl;
return;
}
// TODO cleanup... the above work could be done in master client
// all we need below is the port. Indeed, if coming from the master,
// all we want is a port.
if (_endpointContext.name == "master") {
// we are the master's server, so we don't need a client to ourselves
_isMasterServer = true;
_isInitialized = true;
_endpointContext.port = masterEndpointAndPort.second;
} else {
_masterClient.connect(masterAddress);
_endpointContext.port = _masterClient.getNewPort(_endpointContext.machineID);
_masterClient.registerMachine(_machineContext);
_masterClient.registerEndpoint(_endpointContext);
_isInitialized = _masterClient.isInitialized();
}
_transportServer.serve(qi::detail::getEndpoints(_endpointContext, _machineContext));
_transportServer.setMessageHandler(this);
boost::thread serverThread(
::boost::bind(&qi::transport::TransportServer::run, &_transportServer));
}
void ServerImpl::messageHandler(std::string& defData, std::string& resultData) {
// handle message
Message def(defData);
Message result(resultData);
std::string methodSignature;
def.readString(methodSignature);
const ServiceInfo& si = xGetService(methodSignature);
if (si.methodName.empty() || !si.functor) {
qiLogError("qimessaging") << "Server Error: Method not found: " << qi::signatureToString(methodSignature) << std::endl;
return;
}
si.functor->call(def, result);
resultData = result.str();
}
void ServerImpl::advertiseService(
const std::string& methodSignature,
qi::Functor* functor)
{
if (! _isInitialized ) {
qiLogError("qimessaging") << "Attempt to use uninitialized server: \"" << _endpointContext.name <<
"\". Service \"" << qi::signatureToString(methodSignature) << "\" not added."
<< std::endl;
throw qi::transport::ServerException(
std::string("Attempt to use uninitialized server: \"") +
_endpointContext.name + "\". Service not added.");
return;
}
ServiceInfo service(methodSignature, functor);
//std::cout << "Added Service" << hash << std::endl;
_localServices.insert(methodSignature, service);
if (!_isMasterServer) {
_masterClient.registerService(methodSignature, _endpointContext);
}
}
void ServerImpl::unadvertiseService(const std::string& methodSignature) {
_masterClient.unregisterService(methodSignature);
_localServices.remove(methodSignature);
}
const ServiceInfo& ServerImpl::xGetService(
const std::string& methodSignature)
{
// functors ... should be found here
return _localServices.get(methodSignature);
}
}
}
<commit_msg>server: change log msg<commit_after>/*
* Author(s):
* - Chris Kilner <ckilner@aldebaran-robotics.com>
* - Cedric Gestes <gestes@aldebaran-robotics.com>
*
* Copyright (C) 2010 Aldebaran Robotics
*/
#include "src/messaging/server_impl.hpp"
#include <string>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <qimessaging/serialization.hpp>
#include <qimessaging/transport/buffer.hpp>
#include "src/messaging/network/endpoints.hpp"
#include "src/messaging/network/master_endpoint.hpp"
#include <qi/log.hpp>
#include <qimessaging/exceptions.hpp>
namespace qi {
using qi::Message;
namespace detail {
ServerImpl::~ServerImpl() {
if (!_isMasterServer) {
_masterClient.unregisterEndpoint(_endpointContext);
}
}
ServerImpl::ServerImpl(const std::string& name, Context *ctx)
: ImplBase(ctx),
_isMasterServer(false),
_transportServer(_masterClient.getQiContextPtr()->getTransportContext())
{
_endpointContext.type = SERVER_ENDPOINT;
_endpointContext.name = name;
_endpointContext.contextID = _masterClient.getQiContextPtr()->getID();
}
void ServerImpl::connect(const std::string &masterAddress)
{
//TODO
std::pair<std::string, int> masterEndpointAndPort;
if (!qi::detail::validateMasterEndpoint(masterAddress, masterEndpointAndPort)) {
_isInitialized = false;
qiLogError("qimessaging") << "\"" << _endpointContext.name << "\" initialized with invalid master "
"address: \"" << masterAddress << "\" All calls will fail."
<< std::endl;
return;
}
// TODO cleanup... the above work could be done in master client
// all we need below is the port. Indeed, if coming from the master,
// all we want is a port.
if (_endpointContext.name == "master") {
// we are the master's server, so we don't need a client to ourselves
_isMasterServer = true;
_isInitialized = true;
_endpointContext.port = masterEndpointAndPort.second;
} else {
_masterClient.connect(masterAddress);
_endpointContext.port = _masterClient.getNewPort(_endpointContext.machineID);
_masterClient.registerMachine(_machineContext);
_masterClient.registerEndpoint(_endpointContext);
_isInitialized = _masterClient.isInitialized();
}
_transportServer.serve(qi::detail::getEndpoints(_endpointContext, _machineContext));
_transportServer.setMessageHandler(this);
boost::thread serverThread(
::boost::bind(&qi::transport::TransportServer::run, &_transportServer));
}
void ServerImpl::messageHandler(std::string& defData, std::string& resultData) {
// handle message
Message def(defData);
Message result(resultData);
std::string methodSignature;
def.readString(methodSignature);
const ServiceInfo& si = xGetService(methodSignature);
if (si.methodName.empty() || !si.functor) {
qiLogError("qimessaging") << "Server Error: Method not found(" << methodSignature << "): " << qi::signatureToString(methodSignature) << std::endl;
return;
}
si.functor->call(def, result);
resultData = result.str();
}
void ServerImpl::advertiseService(
const std::string& methodSignature,
qi::Functor* functor)
{
if (! _isInitialized ) {
qiLogError("qimessaging") << "Attempt to use uninitialized server: \"" << _endpointContext.name <<
"\". Service \"" << qi::signatureToString(methodSignature) << "\" not added."
<< std::endl;
throw qi::transport::ServerException(
std::string("Attempt to use uninitialized server: \"") +
_endpointContext.name + "\". Service not added.");
return;
}
ServiceInfo service(methodSignature, functor);
//std::cout << "Added Service" << hash << std::endl;
_localServices.insert(methodSignature, service);
if (!_isMasterServer) {
_masterClient.registerService(methodSignature, _endpointContext);
}
}
void ServerImpl::unadvertiseService(const std::string& methodSignature) {
_masterClient.unregisterService(methodSignature);
_localServices.remove(methodSignature);
}
const ServiceInfo& ServerImpl::xGetService(
const std::string& methodSignature)
{
// functors ... should be found here
return _localServices.get(methodSignature);
}
}
}
<|endoftext|>
|
<commit_before>/*
**
** Author(s):
** - Herve Cuche <hcuche@aldebaran-robotics.com>
**
** Copyright (C) 2011 Aldebaran Robotics
*/
#include <string>
#include <sstream>
#include <iostream>
#include <map>
#include <vector>
#include <fstream>
#include <tinyxml/tinyxml.h>
#include <qimessaging/value.hpp>
#include <qimessaging/signature.hpp>
#include <qipreference/preference.hpp>
namespace qi {
namespace pref {
class PreferenceMapPrivate
{
public:
PreferenceMapPrivate();
~PreferenceMapPrivate();
int parse_attribs(TiXmlElement* element,
std::map<std::string, std::string> &attribs);
std::map<std::string, qi::Value> parse(TiXmlNode* parent);
void getKeys(std::vector<std::string> &key,
qi::Value values,
const std::string &prefix);
void saveKeys(const std::string &tag,
const qi::Value &value,
int indent);
public:
std::map<std::string, qi::Value> _values;
std::stringstream _ss;
protected:
private:
qi::Value xmlToValue(const std::string &type,
const std::string &value);
std::string getType(const qi::Value &value);
std::string getValue(const std::string &type,
qi::Value value);
};
PreferenceMapPrivate::PreferenceMapPrivate()
{
}
PreferenceMapPrivate::~PreferenceMapPrivate()
{
}
int PreferenceMapPrivate::parse_attribs(TiXmlElement* element,
std::map<std::string, std::string> &attribs)
{
if (!element)
return 0;
TiXmlAttribute* attrib = element->FirstAttribute();
std::map<std::string, std::string> att;
int i = 0;
while (attrib)
{
std::stringstream ss;
ss << attrib->Name();
std::stringstream ss1;
ss1 << attrib->Value();
attribs[ss.str()] = ss1.str();
attrib = attrib->Next();
++i;
}
return i;
}
qi::Value PreferenceMapPrivate::xmlToValue(const std::string &type,
const std::string &value)
{
if (type == "bool")
{
if (value == "true")
{
qi::Value v(true);
return v;
}
else if (value == "false")
{
qi::Value v(false);
return v;
}
}
if (type == "char")
{
std::stringstream ss;
ss << value;
char res;
ss >> res;
qi::Value v(res);
return v;
}
if (type == "int")
{
std::stringstream ss;
ss << value;
int res;
ss >> res;
qi::Value v(res);
return v;
}
if (type == "unsigned int")
{
std::stringstream ss;
ss << value;
unsigned int res;
ss >> res;
qi::Value v(res);
return v;
}
if (type == "long long")
{
std::stringstream ss;
ss << value;
long long res;
ss >> res;
qi::Value v(res);
return v;
}
if (type == "unsigned long long")
{
std::stringstream ss;
ss << value;
unsigned long long res;
ss >> res;
qi::Value v(res);
return v;
}
if (type == "float")
{
std::stringstream ss;
ss << value;
float res;
ss >> res;
qi::Value v(res);
return v;
}
if (type == "double")
{
std::stringstream ss;
ss << value;
double res;
ss >> res;
qi::Value v(res);
return v;
}
if (type == "string")
{
qi::Value v(value);
return v;
}
}
std::map<std::string, qi::Value> PreferenceMapPrivate::parse(TiXmlNode* parent)
{
if (!parent)
{
std::cerr << "Invalid node!" << std::endl;
return qi::ValueMap();
}
TiXmlNode* child;
int num = 0;
std::map<std::string, std::string> attribs;
int t = parent->Type();
switch (t)
{
case TiXmlNode::DOCUMENT:
break;
case TiXmlNode::ELEMENT:
num = parse_attribs(parent->ToElement(), attribs);
break;
case TiXmlNode::COMMENT:
break;
case TiXmlNode::UNKNOWN:
break;
case TiXmlNode::TEXT:
break;
case TiXmlNode::DECLARATION:
break;
default:
break;
}
if (attribs.find("name") != attribs.end() &&
attribs.find("type") != attribs.end() &&
attribs.find("value") != attribs.end())
{
qi::ValueMap mValue;
qi::Value v = xmlToValue(attribs.find("type")->second,
attribs.find("value")->second);
mValue[attribs.find("name")->second] = v;
return mValue;
}
else if (attribs.find("name") != attribs.end() &&
attribs.find("type") != attribs.end())
{
if (attribs.find("type")->second == "array")
{
qi::Value v(qi::Value::Map);
qi::ValueMap mValue;
for (child = parent->FirstChild(); child != 0; child = child->NextSibling())
{
qi::ValueMap mTmpValue;
mTmpValue = parse(child);
v.value<qi::ValueMap>()[(mTmpValue.begin())->first] = (mTmpValue.begin())->second;
}
mValue[attribs.find("name")->second] = v;
return mValue;
}
}
else if (attribs.find("name") != attribs.end())
{
qi::Value v(qi::Value::Map);
qi::ValueMap mValue;
for (child = parent->FirstChild(); child != 0; child = child->NextSibling())
{
qi::ValueMap mTmpValue;
mTmpValue = parse(child);
v.value<qi::ValueMap>()[(mTmpValue.begin())->first] = (mTmpValue.begin())->second;
}
mValue[attribs.find("name")->second] = v;
return mValue;
}
qi::ValueMap mTmpValue;
for (child = parent->FirstChild(); child != 0; child = child->NextSibling())
{
mTmpValue = parse(child);
}
return mTmpValue;
}
PreferenceMap::PreferenceMap()
{
_private = new PreferenceMapPrivate;
}
PreferenceMap::~PreferenceMap()
{
delete _private;
}
void PreferenceMap::load(const std::string &file)
{
TiXmlDocument doc(file.c_str());
if(doc.LoadFile())
_private->_values = _private->parse(&doc);
else
printf("Cannot open file!\n");
}
std::string PreferenceMapPrivate::getType(const qi::Value &value)
{
if (value._private.type == qi::Value::Bool)
return "bool";
if (value._private.type == qi::Value::Char)
return "char";
if (value._private.type == qi::Value::Int32)
return "int";
if (value._private.type == qi::Value::UInt32)
return "unsigned int";
if (value._private.type == qi::Value::Int64)
return "long long";
if (value._private.type == qi::Value::UInt64)
return "unsigned long long";
if (value._private.type == qi::Value::Float)
return "float";
if (value._private.type == qi::Value::Double)
return "double";
if (value._private.type == qi::Value::String)
return "string";
if (value._private.type == qi::Value::Map)
return "array";
return "";
}
std::string PreferenceMapPrivate::getValue(const std::string &type,
qi::Value value)
{
std::stringstream ss;
if (type == "bool")
{
if (value.toBool())
ss << "true";
else
ss << "false";
}
if (type == "char")
ss << value.toChar();
if (type == "int")
ss << value.toInt32();
if (type == "unsigned int")
ss << value.toUInt32();
if (type == "long long")
ss << value.toInt64();
if (type == "unsigned long long")
ss << value.toUInt64();
if (type == "float")
ss << value.toFloat();
if (type == "double")
ss << value.toDouble();
if (type == "string")
ss << value.toString();
return ss.str();
}
void PreferenceMapPrivate::saveKeys(const std::string &tag,
const qi::Value &value,
int indent)
{
qi::Value v = value;
qi::ValueMap vm = v.toMap();
qi::ValueMap::iterator it = vm.begin();
for (; it != vm.end(); ++it)
{
for (int i = 0; i < indent; ++i)
_ss << "\t";
std::string type = getType(it->second);
_ss << "<" << tag
<< " type=\"" << type << "\" "
<< "name=\"" << it->first << "\" ";
if (type == "array")
{
_ss << ">" << std::endl;
saveKeys(tag, it->second, indent + 1);
for (int i = 0; i < indent; ++i)
_ss << "\t";
_ss << "</" << tag << ">" << std::endl;
}
else
{
_ss << "value=\"" << getValue(type, it->second) << "\" />" << std::endl;
}
}
return;
}
// FIXME
void PreferenceMap::save(const std::string &file)
{
std::filebuf fb;
fb.open(file.c_str(), std::ios::out);
std::ostream _os(&fb);
qi::ValueMap::iterator it = _private->_values.begin();
std::string s = it->first;
_private->_ss << "<?xml version = '1.0' encoding = 'UTF-8'?>" << std::endl;
_private->_ss << "<ModulePreference xmlns=" << "\"\" "
<< "schemaLocation=" << "\"\" "
<< "name=\"" << s << "\" >" << std::endl;
if (it->second._private.type == qi::Value::Map)
_private->saveKeys("Preference", it->second, 1);
_private->_ss << "</ModulePreference>" << std::endl;
_os << _private->_ss.str();
fb.close();
}
// get a value
const qi::Value &PreferenceMap::get(const std::string &name)
{
int start = 0;
int end = name.find("/");
if (end == 0)
{
start++;
end = name.find("/", start);
}
std::vector<std::string> vect;
for (; end != std::string::npos ; start = end + 1, end = name.find("/", start))
vect.push_back(name.substr(start, end - start));
if (start < name.size())
vect.push_back(name.substr(start, end));
if (vect.empty())
return qi::Value();
qi::ValueMap vm = _private->_values;
qi::ValueMap::iterator it;
for (int i = 0; i < vect.size(); ++i)
{
it = vm.find(vect[i]);
if (it == vm.end())
break;
else if (i != vect.size() - 1)
{
qi::Value v = (it->second);
if (v._private.type == qi::Value::Map)
{
vm = (it->second).value<qi::ValueMap>();
}
else
{
break;
}
}
else
return (it->second);
}
return qi::Value();
}
void PreferenceMap::set(const std::string &name,
const qi::Value &val)
{
int start = 0;
int end = name.find("/");
qi::Value v = val;
if (end == 0)
{
start++;
end = name.find("/", start);
}
std::vector<std::string> vect;
for (; end != std::string::npos ; start = end + 1, end = name.find("/", start))
vect.push_back(name.substr(start, end - start));
if (start < name.size())
vect.push_back(name.substr(start, end));
if (vect.empty())
return;
qi::ValueMap *vm = &_private->_values;
qi::ValueMap::iterator it;
for (int i = 0; i < vect.size(); ++i)
{
it = vm->find(vect[i]);
if (it == vm->end())
break;
else if (i != vect.size() - 1)
{
qi::Value v = (it->second);
if (v._private.type == qi::Value::Map)
{
vm = &(it->second).value<qi::ValueMap>();
}
else
{
break;
}
}
else
{
(*vm)[it->first] = v;
break;
}
}
return;
}
// delete a preference entry
void PreferenceMap::remove(const std::string &name)
{
int start = 0;
int end = name.find("/");
if (end == 0)
{
start++;
end = name.find("/", start);
}
std::vector<std::string> vect;
for (; end != std::string::npos ; start = end + 1, end = name.find("/", start))
vect.push_back(name.substr(start, end - start));
if (start < name.size())
vect.push_back(name.substr(start, end));
if (vect.empty())
return;
qi::ValueMap *vm = &_private->_values;
qi::ValueMap::iterator it;
for (int i = 0; i < vect.size(); ++i)
{
it = vm->find(vect[i]);
if (it == vm->end())
break;
else if (i != vect.size() - 1)
{
qi::Value v = (it->second);
if (v._private.type == qi::Value::Map)
{
vm = &(it->second).value<qi::ValueMap>();
}
else
{
break;
}
}
else
{
vm->erase(it);
break;
}
}
return;
}
void PreferenceMapPrivate::getKeys(std::vector<std::string> &key,
qi::Value values,
const std::string &prefix)
{
qi::ValueMap vm = values.toMap();
qi::ValueMap::iterator it = vm.begin();
for (; it != vm.end(); ++it)
{
std::string s = prefix + "/" + it->first;
key.push_back(s);
if (it->second._private.type == qi::Value::Map)
getKeys(key, it->second, s);
}
return;
}
// find existing keys, which names start with `prefix'
std::vector<std::string> PreferenceMap::keys(const std::string &prefix)
{
std::vector<std::string> k;
qi::ValueMap::iterator it = _private->_values.begin();
std::string s = it->first;
k.push_back(s);
if (it->second._private.type == qi::Value::Map)
_private->getKeys(k, it->second, s);
if (prefix.empty())
return k;
else
{
std::vector<std::string> res;
for (int i = 0; i < k.size(); ++i)
{
if (prefix[0] == '/')
{
if (k[i].find(&prefix[1]) == 0)
{
res.push_back("/" + k[i]);
}
}
else
{
if (k[i].find(prefix) == 0)
{
res.push_back(k[i]);
}
}
}
return res;
}
}
// return all values
std::map<std::string, qi::Value> PreferenceMap::values()
{
return _private->_values;
}
} // !pref
} // !qi
<commit_msg>qipreference: clean qipreference source code.<commit_after>/*
**
** Author(s):
** - Herve Cuche <hcuche@aldebaran-robotics.com>
**
** Copyright (C) 2011 Aldebaran Robotics
*/
#include <string>
#include <sstream>
#include <iostream>
#include <map>
#include <vector>
#include <fstream>
#include <tinyxml/tinyxml.h>
#include <qimessaging/value.hpp>
#include <qimessaging/signature.hpp>
#include <qipreference/preference.hpp>
namespace qi {
namespace pref {
class PreferenceMapPrivate
{
public:
PreferenceMapPrivate();
~PreferenceMapPrivate();
void parse_attribs(TiXmlElement* element,
std::map<std::string, std::string> &attribs);
std::map<std::string, qi::Value> parse(TiXmlNode* parent);
void getAllKeys(std::vector<std::string> &key,
const qi::Value &values,
const std::string &prefix);
void saveKeys(const std::string &tag,
const qi::Value &value,
int indent);
public:
std::map<std::string, qi::Value> _values;
std::stringstream _ss;
protected:
private:
qi::Value xmlToValue(const std::string &type,
const std::string &value);
std::string getType(const qi::Value &value);
std::string getValueToString(const std::string &type,
const qi::Value &value);
template <typename T>
qi::Value typeToValue(const std::string &value);
};
PreferenceMapPrivate::PreferenceMapPrivate()
{
}
PreferenceMapPrivate::~PreferenceMapPrivate()
{
}
void PreferenceMapPrivate::parse_attribs(TiXmlElement* element,
std::map<std::string, std::string> &attribs)
{
if (!element)
return;
TiXmlAttribute* attrib = element->FirstAttribute();
std::map<std::string, std::string> att;
for (; attrib != NULL; attrib = attrib->Next())
attribs[std::string(attrib->Name())] = std::string(attrib->Value());
}
template <typename T>
qi::Value PreferenceMapPrivate::typeToValue(const std::string &value)
{
std::stringstream ss;
ss << value;
T res;
ss >> res;
return qi::Value(res);
}
qi::Value PreferenceMapPrivate::xmlToValue(const std::string &type,
const std::string &value)
{
if (type == "bool")
{
if (value == "true")
return qi::Value(true);
else
return qi::Value(false);
}
if (type == "char")
return typeToValue<char>(value);
if (type == "int")
return typeToValue<int>(value);
if (type == "unsigned int")
return typeToValue<unsigned int>(value);
if (type == "long long")
return typeToValue<long long>(value);
if (type == "unsigned long long")
return typeToValue<unsigned long long>(value);
if (type == "float")
return typeToValue<float>(value);
if (type == "double")
return typeToValue<double>(value);
if (type == "string")
return qi::Value(value);
}
std::map<std::string, qi::Value> PreferenceMapPrivate::parse(TiXmlNode* parent)
{
if (!parent)
{
std::cerr << "Invalid node!" << std::endl;
return qi::ValueMap();
}
TiXmlNode* child;
std::map<std::string, std::string> attribs;
int t = parent->Type();
switch (t)
{
case TiXmlNode::DOCUMENT:
break;
case TiXmlNode::ELEMENT:
parse_attribs(parent->ToElement(), attribs);
break;
case TiXmlNode::COMMENT:
break;
case TiXmlNode::UNKNOWN:
break;
case TiXmlNode::TEXT:
break;
case TiXmlNode::DECLARATION:
break;
default:
break;
}
std::map<std::string, std::string>::iterator name = attribs.find("name");
std::map<std::string, std::string>::iterator type = attribs.find("type");
std::map<std::string, std::string>::iterator value = attribs.find("value");
if (name != attribs.end() &&
type != attribs.end() &&
value != attribs.end())
{
qi::ValueMap mValue;
mValue[name->second] = xmlToValue(type->second, value->second);
return mValue;
}
else if (name != attribs.end() &&
type != attribs.end())
{
if (type->second == "array")
{
qi::Value v(qi::Value::Map);
qi::ValueMap mValue;
for (child = parent->FirstChild(); child != 0; child = child->NextSibling())
{
qi::ValueMap mTmpValue;
mTmpValue = parse(child);
v.value<qi::ValueMap>()[(mTmpValue.begin())->first] = (mTmpValue.begin())->second;
}
mValue[name->second] = v;
return mValue;
}
}
else if (name != attribs.end())
{
qi::Value v(qi::Value::Map);
qi::ValueMap mValue;
for (child = parent->FirstChild(); child != 0; child = child->NextSibling())
{
qi::ValueMap mTmpValue;
mTmpValue = parse(child);
v.value<qi::ValueMap>()[(mTmpValue.begin())->first] = (mTmpValue.begin())->second;
}
mValue[name->second] = v;
return mValue;
}
qi::ValueMap mTmpValue;
for (child = parent->FirstChild(); child != 0; child = child->NextSibling())
{
mTmpValue = parse(child);
}
return mTmpValue;
}
PreferenceMap::PreferenceMap()
{
_private = new PreferenceMapPrivate;
}
PreferenceMap::~PreferenceMap()
{
delete _private;
}
void PreferenceMap::load(const std::string &file)
{
TiXmlDocument doc(file.c_str());
if(doc.LoadFile())
_private->_values = _private->parse(&doc);
else
printf("Cannot open file!\n");
}
std::string PreferenceMapPrivate::getType(const qi::Value &value)
{
if (value.type() == qi::Value::Bool)
return "bool";
if (value.type() == qi::Value::Char)
return "char";
if (value.type() == qi::Value::Int32)
return "int";
if (value.type() == qi::Value::UInt32)
return "unsigned int";
if (value.type() == qi::Value::Int64)
return "long long";
if (value.type() == qi::Value::UInt64)
return "unsigned long long";
if (value.type() == qi::Value::Float)
return "float";
if (value.type() == qi::Value::Double)
return "double";
if (value.type() == qi::Value::String)
return "string";
if (value.type() == qi::Value::Map)
return "array";
return "";
}
std::string PreferenceMapPrivate::getValueToString(const std::string &type,
const qi::Value &value)
{
std::stringstream ss;
if (type == "bool")
{
if (value.toBool())
ss << "true";
else
ss << "false";
}
if (type == "char")
ss << value.toChar();
if (type == "int")
ss << value.toInt32();
if (type == "unsigned int")
ss << value.toUInt32();
if (type == "long long")
ss << value.toInt64();
if (type == "unsigned long long")
ss << value.toUInt64();
if (type == "float")
ss << value.toFloat();
if (type == "double")
ss << value.toDouble();
if (type == "string")
ss << value.toString();
return ss.str();
}
void PreferenceMapPrivate::saveKeys(const std::string &tag,
const qi::Value &value,
int indent)
{
qi::ValueMap vm = value.toMap();
for (qi::ValueMap::iterator it = vm.begin(); it != vm.end(); ++it)
{
for (int i = 0; i < indent; ++i)
_ss << "\t";
std::string type = getType(it->second);
_ss << "<" << tag
<< " type=\"" << type << "\" "
<< "name=\"" << it->first << "\" ";
if (type == "array")
{
_ss << ">" << std::endl;
saveKeys(tag, it->second, indent + 1);
for (int i = 0; i < indent; ++i)
_ss << "\t";
_ss << "</" << tag << ">" << std::endl;
}
else
{
_ss << "value=\"" << getValueToString(type, it->second) << "\" />" << std::endl;
}
}
}
void PreferenceMap::save(const std::string &file)
{
std::ofstream f;
f.open(file.c_str());
_private->_ss.clear();
qi::ValueMap::iterator it = _private->_values.begin();
std::string s = it->first;
_private->_ss << "<?xml version = '1.0' encoding = 'UTF-8'?>" << std::endl;
_private->_ss << "<ModulePreference xmlns=" << "\"\" "
<< "schemaLocation=" << "\"\" "
<< "name=\"" << s << "\" >" << std::endl;
if (it->second.type() == qi::Value::Map)
_private->saveKeys("Preference", it->second, 1);
_private->_ss << "</ModulePreference>" << std::endl;
f << _private->_ss.str();
f.close();
}
std::vector<std::string> getVectorPath(const std::string& path)
{
int start = 0;
int end = path.find("/");
if (end == 0)
{
start++;
end = path.find("/", start);
}
std::vector<std::string> vect;
for (; end != std::string::npos ; start = end + 1, end = path.find("/", start))
vect.push_back(path.substr(start, end - start));
if (start < path.size())
vect.push_back(path.substr(start, end));
return vect;
}
const qi::Value &PreferenceMap::get(const std::string &name)
{
std::vector<std::string> vect = getVectorPath(name);
if (vect.empty())
return qi::Value();
qi::ValueMap vm = _private->_values;
qi::ValueMap::iterator it;
for (int i = 0; i < vect.size(); ++i)
{
it = vm.find(vect[i]);
if (it == vm.end())
break;
else if (i != vect.size() - 1)
{
if ((it->second).type() == qi::Value::Map)
{
vm = (it->second).value<qi::ValueMap>();
}
else
{
break;
}
}
else
return (it->second);
}
return qi::Value();
}
void PreferenceMap::set(const std::string &name,
const qi::Value &val)
{
std::vector<std::string> vect = getVectorPath(name);
if (vect.empty())
return;
qi::ValueMap *vm = &_private->_values;
qi::ValueMap::iterator it;
for (int i = 0; i < vect.size(); ++i)
{
it = vm->find(vect[i]);
if (it == vm->end())
break;
else if (i != vect.size() - 1)
{
if ((it->second).type() == qi::Value::Map)
{
vm = &(it->second).value<qi::ValueMap>();
}
else
{
break;
}
}
else
{
(*vm)[it->first] = val;
break;
}
}
return;
}
void PreferenceMap::remove(const std::string &name)
{
std::vector<std::string> vect = getVectorPath(name);
if (vect.empty())
return;
qi::ValueMap *vm = &_private->_values;
qi::ValueMap::iterator it;
for (int i = 0; i < vect.size(); ++i)
{
it = vm->find(vect[i]);
if (it == vm->end())
break;
else if (i != vect.size() - 1)
{
if ((it->second).type() == qi::Value::Map)
{
vm = &(it->second).value<qi::ValueMap>();
}
else
{
break;
}
}
else
{
vm->erase(it);
break;
}
}
return;
}
void PreferenceMapPrivate::getAllKeys(std::vector<std::string> &key,
const qi::Value &values,
const std::string &prefix)
{
qi::ValueMap vm = values.toMap();
qi::ValueMap::iterator it = vm.begin();
for (; it != vm.end(); ++it)
{
std::string s = prefix + "/" + it->first;
key.push_back(s);
if (it->second.type() == qi::Value::Map)
getAllKeys(key, it->second, s);
}
return;
}
std::vector<std::string> PreferenceMap::keys(const std::string &prefix)
{
std::vector<std::string> allKeys;
std::vector<std::string> key;
qi::ValueMap::iterator it = _private->_values.begin();
// Get all keys for the map
allKeys.push_back(it->first);
if (it->second.type() == qi::Value::Map)
_private->getAllKeys(allKeys, it->second, it->first);
if (prefix.empty())
return allKeys;
else
{
// Only return keys with prefix
for (int i = 0; i < allKeys.size(); ++i)
{
// Check first char
if (prefix[0] == '/' && allKeys[i].find(&prefix[1]) == 0)
key.push_back("/" + allKeys[i]);
else if (allKeys[i].find(prefix) == 0)
key.push_back(allKeys[i]);
}
}
return key;
}
std::map<std::string, qi::Value> PreferenceMap::values()
{
return _private->_values;
}
} // !pref
} // !qi
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
// Tests for the UdpSocketManager interface.
// Note: This tests UdpSocketManager together with UdpSocketWrapper,
// due to the way the code is full of static-casts to the platform dependent
// subtypes.
// It also uses the static UdpSocketManager object.
// The most important property of these tests is that they do not leak memory.
#include "udp_socket_wrapper.h"
#include "udp_socket_manager_wrapper.h"
#include "gtest/gtest.h"
TEST(UdpSocketManager, CreateCallsInitAndDoesNotLeakMemory) {
WebRtc_Word32 id = 42;
WebRtc_UWord8 threads = 1;
webrtc::UdpSocketManager* mgr = webrtc::UdpSocketManager::Create(id, threads);
// Create is supposed to have called init on the object.
EXPECT_EQ(false, mgr->Init(id, threads))
<< "Init should return false since Create is supposed to call it.";
webrtc::UdpSocketManager::Return();
}
// Creates a socket and adds it to the socket manager, and then removes it
// before destroying the socket manager.
TEST(UdpSocketManager, AddAndRemoveSocketDoesNotLeakMemory) {
WebRtc_Word32 id = 42;
WebRtc_UWord8 threads = 1;
webrtc::UdpSocketManager* mgr = webrtc::UdpSocketManager::Create(id, threads);
webrtc::UdpSocketWrapper* socket
= webrtc::UdpSocketWrapper::CreateSocket(id,
mgr,
NULL, // CallbackObj
NULL, // IncomingSocketCallback
false, // ipV6Enable
false); // disableGQOS
// The constructor will do AddSocket on the manager.
EXPECT_EQ(true, mgr->RemoveSocket(socket));
webrtc::UdpSocketManager::Return();
}
// Creates a socket and add it to the socket manager, but does not remove it
// before destroying the socket manager.
// This should also destroy the socket.
TEST(UdpSocketManager, UnremovedSocketsGetCollectedAtManagerDeletion) {
WebRtc_Word32 id = 42;
WebRtc_UWord8 threads = 1;
webrtc::UdpSocketManager* mgr = webrtc::UdpSocketManager::Create(id, threads);
webrtc::UdpSocketWrapper* unused_socket
= webrtc::UdpSocketWrapper::CreateSocket(id,
mgr,
NULL, // CallbackObj
NULL, // IncomingSocketCallback
false, // ipV6Enable
false); // disableGQOS
// The constructor will do AddSocket on the manager.
unused_socket = NULL;
webrtc::UdpSocketManager::Return();
}
<commit_msg>Disabled UnremovedSocketsGetCollectedAtManagerDeletion in UdpSocketManager unittest.<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
// Tests for the UdpSocketManager interface.
// Note: This tests UdpSocketManager together with UdpSocketWrapper,
// due to the way the code is full of static-casts to the platform dependent
// subtypes.
// It also uses the static UdpSocketManager object.
// The most important property of these tests is that they do not leak memory.
#include "udp_socket_wrapper.h"
#include "udp_socket_manager_wrapper.h"
#include "gtest/gtest.h"
TEST(UdpSocketManager, CreateCallsInitAndDoesNotLeakMemory) {
WebRtc_Word32 id = 42;
WebRtc_UWord8 threads = 1;
webrtc::UdpSocketManager* mgr = webrtc::UdpSocketManager::Create(id, threads);
// Create is supposed to have called init on the object.
EXPECT_EQ(false, mgr->Init(id, threads))
<< "Init should return false since Create is supposed to call it.";
webrtc::UdpSocketManager::Return();
}
// Creates a socket and adds it to the socket manager, and then removes it
// before destroying the socket manager.
TEST(UdpSocketManager, AddAndRemoveSocketDoesNotLeakMemory) {
WebRtc_Word32 id = 42;
WebRtc_UWord8 threads = 1;
webrtc::UdpSocketManager* mgr = webrtc::UdpSocketManager::Create(id, threads);
webrtc::UdpSocketWrapper* socket
= webrtc::UdpSocketWrapper::CreateSocket(id,
mgr,
NULL, // CallbackObj
NULL, // IncomingSocketCallback
false, // ipV6Enable
false); // disableGQOS
// The constructor will do AddSocket on the manager.
EXPECT_EQ(true, mgr->RemoveSocket(socket));
webrtc::UdpSocketManager::Return();
}
// Creates a socket and add it to the socket manager, but does not remove it
// before destroying the socket manager.
// This should also destroy the socket.
TEST(UdpSocketManager, DISABLED_UnremovedSocketsGetCollectedAtManagerDeletion) {
WebRtc_Word32 id = 42;
WebRtc_UWord8 threads = 1;
webrtc::UdpSocketManager* mgr = webrtc::UdpSocketManager::Create(id, threads);
webrtc::UdpSocketWrapper* unused_socket
= webrtc::UdpSocketWrapper::CreateSocket(id,
mgr,
NULL, // CallbackObj
NULL, // IncomingSocketCallback
false, // ipV6Enable
false); // disableGQOS
// The constructor will do AddSocket on the manager.
unused_socket = NULL;
webrtc::UdpSocketManager::Return();
}
<|endoftext|>
|
<commit_before>#include <cmath>
#include <ctime>
#include <iostream>
#include <random>
#include <set>
#include <vector>
#include <unordered_map>
namespace {
inline size_t GenerateMaskWithRightOnes(size_t onesCount) {
return (1ull << onesCount) - 1ull;
}
class TCacheSet {
public:
TCacheSet(size_t waysCount)
: TicksTimer(0)
, CacheWays(waysCount)
{}
bool Touch(size_t cacheLineNum) {
++TicksTimer;
// CacheLine2LastTouch[cacheLineNum] = TicksTimer;
TCacheLine* minTickLine = nullptr;
size_t minTickTime = TicksTimer;
for (auto& activeLine : CacheWays) {
if (activeLine.LineNum != cacheLineNum) {
if (activeLine.LineNum == -1) {
activeLine.TouchTick = TicksTimer;
activeLine.LineNum = cacheLineNum;
return false;
}
if (activeLine.TouchTick < minTickTime) {
minTickTime = activeLine.TouchTick;
minTickLine = &activeLine;
}
} else {
activeLine.TouchTick = TicksTimer;
++CacheHits;
return true;
}
}
minTickLine->LineNum = cacheLineNum;
minTickLine->TouchTick = TicksTimer;
return false;
}
size_t GetCacheHits() const {
return CacheHits;
}
size_t GetCacheMisses() const {
return TicksTimer - CacheHits;
}
private:
struct TCacheLine {
size_t LineNum = -1;
size_t TouchTick = 0;
};
private:
size_t TicksTimer;
std::vector<TCacheLine> CacheWays; // Contains LineNum == -1 if free
// std::unordered_map<size_t, size_t> CacheLine2LastTouch;
size_t CacheHits;
};
class TCache {
public:
TCache(size_t cacheSize, size_t cacheLineSize, size_t waysCount)
: CacheSize(cacheSize)
, CacheLineSize(cacheLineSize)
, WaysCount(waysCount)
, BlocksCount(CacheSize / CacheLineSize)
, SetsCount(BlocksCount / WaysCount)
, BlockOffsetSize(static_cast<size_t>(log2(CacheLineSize)))
, ShiftedIndexMask(GenerateMaskWithRightOnes(static_cast<size_t>(log2(SetsCount))))
, InvBlockMask(~GenerateMaskWithRightOnes(BlockOffsetSize))
, CacheSets(SetsCount, {WaysCount})
{}
/// @return true if needed cache line is in cache
bool Touch(const void* ptr) {
// std::cerr << std::oct << GetIndexFromPtr(ptr) << "\t->\t" << GetCacheLineNumFromPtr(ptr) << std::endl;
return CacheSets[GetIndexFromPtr(ptr)].Touch(GetCacheLineNumFromPtr(ptr));
}
std::vector<size_t> GetCacheMisses() const {
std::vector<size_t> result;
result.reserve(SetsCount);
for (const auto& cacheSet : CacheSets) {
result.push_back(cacheSet.GetCacheMisses());
}
return result;
}
private:
size_t GetIndexFromPtr(const void* ptr) {
return ((size_t)ptr >> BlockOffsetSize) & ShiftedIndexMask;
}
size_t GetCacheLineNumFromPtr(const void* ptr) {
return (size_t)ptr & InvBlockMask;
}
private:
const size_t CacheSize;
const size_t CacheLineSize;
const size_t WaysCount;
const size_t BlocksCount;
const size_t SetsCount;
const size_t BlockOffsetSize;
const size_t ShiftedIndexMask;
const size_t InvBlockMask;
std::vector<TCacheSet> CacheSets;
};
void PrintStats(const TCache& cache) {
auto misses = cache.GetCacheMisses();
// auto hits = cache.GetCacheHits();
for (size_t i = 0; i < misses.size(); ++i) {
std::cerr << i << ")\t" << misses[i] << std::endl;
}
}
void MultSimpleTooled(TCache& cache,
const float* __restrict a,
const float* __restrict b,
float* __restrict c,
int n)
{
for (int i = 0; i < n; ++i) {
if (i == 0) {
//>-- i = 0
cache.Touch(&i);
//<-- i = 0
//>-- i < n
cache.Touch(&i);
cache.Touch(&n);
//<-- i < n
}
for (int j = 0; j < n; ++j) {
if (j == 0) {
//>-- j = 0
cache.Touch(&j);
//<-- j = 0
//>-- j < n
cache.Touch(&j);
cache.Touch(&n);
//<-- j < n
}
//>-- c[i * n + j]
cache.Touch(&i);
cache.Touch(&j);
cache.Touch(&n);
cache.Touch(&c);
cache.Touch(&c[i * n + j]);
//<-- c[i * n + j]
c[i * n + j] = 0.f;
for (int k = 0; k < n; ++k) {
if (k == 0) {
//>-- k = 0
cache.Touch(&k);
//<-- k = 0
//>-- k < n
cache.Touch(&k);
cache.Touch(&n);
//<-- k < n
}
cache.Touch(&i);
cache.Touch(&j);
cache.Touch(&k);
cache.Touch(&n);
cache.Touch(&a);
cache.Touch(&b);
cache.Touch(&c);
cache.Touch(&a[i * n + k]);
cache.Touch(&b[k * n + j]);
cache.Touch(&c[i * n + j]);
c[i * n + j] += a[i * n + k] * b[k * n + j];
//>-- ++k
cache.Touch(&k);
//<-- ++k
//>-- k < n
cache.Touch(&k);
cache.Touch(&n);
//<-- k < n
}
//>-- ++j
cache.Touch(&j);
//<-- ++j
//>-- j < n
cache.Touch(&j);
cache.Touch(&n);
//<-- j < n
}
//>-- ++i
cache.Touch(&i);
//<-- ++i
//>-- i < n
cache.Touch(&i);
cache.Touch(&n);
//<-- i < n
}
}
void MultSimple(const float* __restrict a, const float* __restrict b, float* __restrict c, int n)
{
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
c[i * n + j] = 0.f;
for (int k = 0; k < n; ++k) {
c[i * n + j] += a[i * n + k] * b[k * n + j];
}
}
}
}
void FillRandom(float* a, int n)
{
std::default_random_engine eng;
std::uniform_real_distribution<float> dist;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
a[i * n + j] = dist(eng);
}
}
}
}
int main(int argc, char* argv[])
{
const int n = atoi(argv[1]);
std::cerr << "n = " << n << std::endl;
float* a = new float[n * n];
float* b = new float[n * n];
float* c = new float[n * n];
FillRandom(a, n);
FillRandom(b, n);
TCache cache(3*1024*1024 /* 32kb */, 64 /* 64b */, 12 /* ways */);
{
const auto startTime = std::clock();
MultSimpleTooled(cache, a, b, c, n);
const auto endTime = std::clock();
std::cerr << "timeSimple: " << double(endTime - startTime) / CLOCKS_PER_SEC << '\n';
}
PrintStats(cache);
delete[] a;
delete[] b;
delete[] c;
}
<commit_msg>Parametrize.<commit_after>#include <cmath>
#include <ctime>
#include <iostream>
#include <random>
#include <set>
#include <vector>
#include <unordered_map>
namespace {
inline size_t GenerateMaskWithRightOnes(size_t onesCount) {
return (1ull << onesCount) - 1ull;
}
class TCacheSet {
public:
TCacheSet(size_t waysCount)
: TicksTimer(0)
, CacheWays(waysCount)
{}
bool Touch(size_t cacheLineNum) {
++TicksTimer;
// CacheLine2LastTouch[cacheLineNum] = TicksTimer;
TCacheLine* minTickLine = nullptr;
size_t minTickTime = TicksTimer;
for (auto& activeLine : CacheWays) {
if (activeLine.LineNum != cacheLineNum) {
if (activeLine.LineNum == -1) {
activeLine.TouchTick = TicksTimer;
activeLine.LineNum = cacheLineNum;
return false;
}
if (activeLine.TouchTick < minTickTime) {
minTickTime = activeLine.TouchTick;
minTickLine = &activeLine;
}
} else {
activeLine.TouchTick = TicksTimer;
++CacheHits;
return true;
}
}
minTickLine->LineNum = cacheLineNum;
minTickLine->TouchTick = TicksTimer;
return false;
}
size_t GetCacheHits() const {
return CacheHits;
}
size_t GetCacheMisses() const {
return TicksTimer - CacheHits;
}
double GetCacheMissRate() const {
return GetCacheMisses() / (TicksTimer * 1.0);
}
private:
struct TCacheLine {
size_t LineNum = -1;
size_t TouchTick = 0;
};
private:
size_t TicksTimer;
std::vector<TCacheLine> CacheWays; // Contains LineNum == -1 if free
// std::unordered_map<size_t, size_t> CacheLine2LastTouch;
size_t CacheHits;
};
class TCache {
public:
TCache(size_t cacheSize, size_t cacheLineSize, size_t waysCount)
: CacheSize(cacheSize)
, CacheLineSize(cacheLineSize)
, WaysCount(waysCount)
, BlocksCount(CacheSize / CacheLineSize)
, SetsCount(BlocksCount / WaysCount)
, BlockOffsetSize(static_cast<size_t>(log2(CacheLineSize)))
, ShiftedIndexMask(GenerateMaskWithRightOnes(static_cast<size_t>(log2(SetsCount))))
, InvBlockMask(~GenerateMaskWithRightOnes(BlockOffsetSize))
, CacheSets(SetsCount, {WaysCount})
{}
/// @return true if needed cache line is in cache
bool Touch(const void* ptr) {
return CacheSets[GetIndexFromPtr(ptr)].Touch(GetCacheLineNumFromPtr(ptr));
}
void PrintStats() const {
size_t cacheSetIdx = 0;
for (const auto& cacheSet : CacheSets) {
std::cout << cacheSetIdx << ")\t"
<< cacheSet.GetCacheMisses() << "\t"
<< cacheSet.GetCacheMissRate() << std::endl;
++cacheSetIdx;
}
}
private:
size_t GetIndexFromPtr(const void* ptr) {
return ((size_t)ptr >> BlockOffsetSize) & ShiftedIndexMask;
}
size_t GetCacheLineNumFromPtr(const void* ptr) {
return (size_t)ptr & InvBlockMask;
}
private:
const size_t CacheSize;
const size_t CacheLineSize;
const size_t WaysCount;
const size_t BlocksCount;
const size_t SetsCount;
const size_t BlockOffsetSize;
const size_t ShiftedIndexMask;
const size_t InvBlockMask;
std::vector<TCacheSet> CacheSets;
};
void MultSimpleTooled(TCache& cache,
const float* __restrict a,
const float* __restrict b,
float* __restrict c,
int n)
{
for (int i = 0; i < n; ++i) {
if (i == 0) {
//>-- i = 0
cache.Touch(&i);
//<-- i = 0
//>-- i < n
cache.Touch(&i);
cache.Touch(&n);
//<-- i < n
}
for (int j = 0; j < n; ++j) {
if (j == 0) {
//>-- j = 0
cache.Touch(&j);
//<-- j = 0
//>-- j < n
cache.Touch(&j);
cache.Touch(&n);
//<-- j < n
}
//>-- c[i * n + j]
cache.Touch(&i);
cache.Touch(&j);
cache.Touch(&n);
cache.Touch(&c);
cache.Touch(&c[i * n + j]);
//<-- c[i * n + j]
c[i * n + j] = 0.f;
for (int k = 0; k < n; ++k) {
if (k == 0) {
//>-- k = 0
cache.Touch(&k);
//<-- k = 0
//>-- k < n
cache.Touch(&k);
cache.Touch(&n);
//<-- k < n
}
cache.Touch(&i);
cache.Touch(&j);
cache.Touch(&k);
cache.Touch(&n);
cache.Touch(&a);
cache.Touch(&b);
cache.Touch(&c);
cache.Touch(&a[i * n + k]);
cache.Touch(&b[k * n + j]);
cache.Touch(&c[i * n + j]);
c[i * n + j] += a[i * n + k] * b[k * n + j];
//>-- ++k
cache.Touch(&k);
//<-- ++k
//>-- k < n
cache.Touch(&k);
cache.Touch(&n);
//<-- k < n
}
//>-- ++j
cache.Touch(&j);
//<-- ++j
//>-- j < n
cache.Touch(&j);
cache.Touch(&n);
//<-- j < n
}
//>-- ++i
cache.Touch(&i);
//<-- ++i
//>-- i < n
cache.Touch(&i);
cache.Touch(&n);
//<-- i < n
}
}
void MultSimple(const float* __restrict a, const float* __restrict b, float* __restrict c, int n)
{
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
c[i * n + j] = 0.f;
for (int k = 0; k < n; ++k) {
c[i * n + j] += a[i * n + k] * b[k * n + j];
}
}
}
}
void FillRandom(float* a, int n)
{
std::default_random_engine eng;
std::uniform_real_distribution<float> dist;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
a[i * n + j] = dist(eng);
}
}
}
}
int main(int argc, char* argv[])
{
const int n = atoi(argv[1]);
const size_t cacheSizeKB = atoi(argv[2]);
const size_t cacheLineSizeB = atoi(argv[3]);
const size_t waysCount = atoi(argv[4]);
std::cout << "n = " << n << std::endl;
std::cout << "Cache: " << cacheSizeKB << "KB, "
<< waysCount << " ways with "
<< cacheLineSizeB << "b cache line." << std::endl;
float* a = new float[n * n];
float* b = new float[n * n];
float* c = new float[n * n];
FillRandom(a, n);
FillRandom(b, n);
TCache cache(cacheSizeKB * 1024 /* kb */, cacheLineSizeB /* b */, waysCount /* ways */);
{
const auto startTime = std::clock();
MultSimpleTooled(cache, a, b, c, n);
const auto endTime = std::clock();
std::cout << "timeSimple: " << double(endTime - startTime) / CLOCKS_PER_SEC << '\n';
}
cache.PrintStats();
delete[] a;
delete[] b;
delete[] c;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: cmdmailmsg.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2004-06-17 11:34:14 $
*
* 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): _______________________________________
*
*
************************************************************************/
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _CMDMAILMSG_HXX_
#include "cmdmailmsg.hxx"
#endif
#ifndef _COM_SUN_STAR_URI_XEXTERNALURIREFERENCETRANSLATOR_HPP_
#include <com/sun/star/uri/XExternalUriReferenceTranslator.hpp>
#endif
#ifndef _COM_SUN_STAR_URI_EXTERNALURIREFERENCETRANSLATOR_HPP_
#include <com/sun/star/uri/ExternalUriReferenceTranslator.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
//------------------------------------------------------------------------
// namespace directives
//------------------------------------------------------------------------
using com::sun::star::lang::IllegalArgumentException;
using com::sun::star::lang::WrappedTargetException;
using com::sun::star::container::NoSuchElementException;
using com::sun::star::container::XNameAccess;
using rtl::OUString;
using osl::MutexGuard;
using namespace cppu;
using namespace com::sun::star::uno;
//------------------------------------------------
//
//------------------------------------------------
void SAL_CALL CmdMailMsg::setRecipient( const ::rtl::OUString& aRecipient )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
m_aRecipient = aRecipient;
}
//------------------------------------------------
//
//------------------------------------------------
::rtl::OUString SAL_CALL CmdMailMsg::getRecipient( )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
return m_aRecipient;
}
//------------------------------------------------
//
//------------------------------------------------
void SAL_CALL CmdMailMsg::setCcRecipient( const Sequence< OUString >& aCcRecipient )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
m_CcRecipients = aCcRecipient;
}
//------------------------------------------------
//
//------------------------------------------------
Sequence< OUString > SAL_CALL CmdMailMsg::getCcRecipient( )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
return m_CcRecipients;
}
//------------------------------------------------
//
//------------------------------------------------
void SAL_CALL CmdMailMsg::setBccRecipient( const Sequence< OUString >& aBccRecipient )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
m_BccRecipients = aBccRecipient;
}
//------------------------------------------------
//
//------------------------------------------------
Sequence< OUString > SAL_CALL CmdMailMsg::getBccRecipient( )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
return m_BccRecipients;
}
//------------------------------------------------
//
//------------------------------------------------
void SAL_CALL CmdMailMsg::setOriginator( const OUString& aOriginator )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
m_aOriginator = aOriginator;
}
//------------------------------------------------
//
//------------------------------------------------
OUString SAL_CALL CmdMailMsg::getOriginator( )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
return m_aOriginator;
}
//------------------------------------------------
//
//------------------------------------------------
void SAL_CALL CmdMailMsg::setSubject( const OUString& aSubject )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
m_aSubject = aSubject;
}
//------------------------------------------------
//
//------------------------------------------------
OUString SAL_CALL CmdMailMsg::getSubject( )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
return m_aSubject;
}
//------------------------------------------------
//
//------------------------------------------------
void SAL_CALL CmdMailMsg::setAttachement( const Sequence< ::rtl::OUString >& aAttachment )
throw (IllegalArgumentException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
m_Attachments = aAttachment;
sal_Int32 n = m_Attachments.getLength();
if (n > 0) {
Reference< com::sun::star::uri::XExternalUriReferenceTranslator >
translator(
com::sun::star::uri::ExternalUriReferenceTranslator::create(
m_xContext));
for (sal_Int32 i = 0; i < n; ++i) {
OUString external(
translator->translateToExternal(m_Attachments[i]));
if (external.getLength() == 0
&& m_Attachments[i].getLength() != 0)
{
throw RuntimeException(
(OUString(
RTL_CONSTASCII_USTRINGPARAM(
"Cannot translate URI reference to external"
" format: "))
+ m_Attachments[i]),
static_cast< cppu::OWeakObject * >(this));
}
m_Attachments[i] = external;
}
}
}
//------------------------------------------------
//
//------------------------------------------------
Sequence< OUString > SAL_CALL CmdMailMsg::getAttachement( )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
return m_Attachments;
}
//------------------------------------------------
//
//------------------------------------------------
Any SAL_CALL CmdMailMsg::getByName( const OUString& aName )
throw (NoSuchElementException, WrappedTargetException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
if( 0 == aName.compareToAscii( "from" ) && m_aOriginator.getLength() )
return makeAny( m_aOriginator );
else if( 0 == aName.compareToAscii( "to" ) && m_aRecipient.getLength() )
return makeAny( m_aRecipient );
else if( 0 == aName.compareToAscii( "cc" ) && m_CcRecipients.getLength() )
return makeAny( m_CcRecipients );
else if( 0 == aName.compareToAscii( "bcc" ) && m_BccRecipients.getLength() )
return makeAny( m_BccRecipients );
else if( 0 == aName.compareToAscii( "subject" ) && m_aSubject.getLength() )
return makeAny( m_aSubject );
else if( 0 == aName.compareToAscii( "attachment" ) && m_Attachments.getLength() )
return makeAny( m_Attachments );
throw NoSuchElementException( OUString::createFromAscii( "key not found: ") + aName,
static_cast < XNameAccess * > (this) );
}
//------------------------------------------------
//
//------------------------------------------------
Sequence< OUString > SAL_CALL CmdMailMsg::getElementNames( )
throw (::com::sun::star::uno::RuntimeException)
{
MutexGuard aGuard( m_aMutex );
sal_Int32 nItems = 0;
Sequence< OUString > aRet( 6 );
if( m_aOriginator.getLength() )
aRet[nItems++] = OUString::createFromAscii( "from" );
if( m_aRecipient.getLength() )
aRet[nItems++] = OUString::createFromAscii( "to" );
if( m_CcRecipients.getLength() )
aRet[nItems++] = OUString::createFromAscii( "cc" );
if( m_BccRecipients.getLength() )
aRet[nItems++] = OUString::createFromAscii( "bcc" );
if( m_aSubject.getLength() )
aRet[nItems++] = OUString::createFromAscii( "subject" );
if( m_Attachments.getLength() )
aRet[nItems++] = OUString::createFromAscii( "attachment" );
aRet.realloc( nItems );
return aRet;
}
//------------------------------------------------
//
//------------------------------------------------
sal_Bool SAL_CALL CmdMailMsg::hasByName( const ::rtl::OUString& aName )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
if( 0 == aName.compareToAscii( "from" ) && m_aOriginator.getLength() )
return sal_True;
else if( 0 == aName.compareToAscii( "to" ) && m_aRecipient.getLength() )
return sal_True;
else if( 0 == aName.compareToAscii( "cc" ) && m_CcRecipients.getLength() )
return sal_True;
else if( 0 == aName.compareToAscii( "bcc" ) && m_BccRecipients.getLength() )
return sal_True;
else if( 0 == aName.compareToAscii( "subject" ) && m_aSubject.getLength() )
return sal_True;
else if( 0 == aName.compareToAscii( "attachment" ) && m_Attachments.getLength() )
return sal_True;
return sal_False;
}
//------------------------------------------------
//
//------------------------------------------------
Type SAL_CALL CmdMailMsg::getElementType( )
throw (RuntimeException)
{
// returning void for multi type container
return Type();
}
//------------------------------------------------
//
//------------------------------------------------
sal_Bool SAL_CALL CmdMailMsg::hasElements( )
throw (RuntimeException)
{
return 0 != getElementNames().getLength();
}
<commit_msg>INTEGRATION: CWS shellfix01 (1.3.30); FILE MERGED 2004/09/14 07:06:16 obr 1.3.30.1: #i30170# attachments now passed as system paths<commit_after>/*************************************************************************
*
* $RCSfile: cmdmailmsg.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2004-10-22 08:14:19 $
*
* 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): _______________________________________
*
*
************************************************************************/
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _CMDMAILMSG_HXX_
#include "cmdmailmsg.hxx"
#endif
#ifndef _COM_SUN_STAR_URI_XEXTERNALURIREFERENCETRANSLATOR_HPP_
#include <com/sun/star/uri/XExternalUriReferenceTranslator.hpp>
#endif
#ifndef _COM_SUN_STAR_URI_EXTERNALURIREFERENCETRANSLATOR_HPP_
#include <com/sun/star/uri/ExternalUriReferenceTranslator.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
//------------------------------------------------------------------------
// namespace directives
//------------------------------------------------------------------------
using com::sun::star::lang::IllegalArgumentException;
using com::sun::star::lang::WrappedTargetException;
using com::sun::star::container::NoSuchElementException;
using com::sun::star::container::XNameAccess;
using rtl::OUString;
using osl::MutexGuard;
using namespace cppu;
using namespace com::sun::star::uno;
//------------------------------------------------
//
//------------------------------------------------
void SAL_CALL CmdMailMsg::setRecipient( const ::rtl::OUString& aRecipient )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
m_aRecipient = aRecipient;
}
//------------------------------------------------
//
//------------------------------------------------
::rtl::OUString SAL_CALL CmdMailMsg::getRecipient( )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
return m_aRecipient;
}
//------------------------------------------------
//
//------------------------------------------------
void SAL_CALL CmdMailMsg::setCcRecipient( const Sequence< OUString >& aCcRecipient )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
m_CcRecipients = aCcRecipient;
}
//------------------------------------------------
//
//------------------------------------------------
Sequence< OUString > SAL_CALL CmdMailMsg::getCcRecipient( )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
return m_CcRecipients;
}
//------------------------------------------------
//
//------------------------------------------------
void SAL_CALL CmdMailMsg::setBccRecipient( const Sequence< OUString >& aBccRecipient )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
m_BccRecipients = aBccRecipient;
}
//------------------------------------------------
//
//------------------------------------------------
Sequence< OUString > SAL_CALL CmdMailMsg::getBccRecipient( )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
return m_BccRecipients;
}
//------------------------------------------------
//
//------------------------------------------------
void SAL_CALL CmdMailMsg::setOriginator( const OUString& aOriginator )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
m_aOriginator = aOriginator;
}
//------------------------------------------------
//
//------------------------------------------------
OUString SAL_CALL CmdMailMsg::getOriginator( )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
return m_aOriginator;
}
//------------------------------------------------
//
//------------------------------------------------
void SAL_CALL CmdMailMsg::setSubject( const OUString& aSubject )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
m_aSubject = aSubject;
}
//------------------------------------------------
//
//------------------------------------------------
OUString SAL_CALL CmdMailMsg::getSubject( )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
return m_aSubject;
}
//------------------------------------------------
//
//------------------------------------------------
void SAL_CALL CmdMailMsg::setAttachement( const Sequence< ::rtl::OUString >& aAttachment )
throw (IllegalArgumentException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
m_Attachments = aAttachment;
}
//------------------------------------------------
//
//------------------------------------------------
Sequence< OUString > SAL_CALL CmdMailMsg::getAttachement( )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
return m_Attachments;
}
//------------------------------------------------
//
//------------------------------------------------
Any SAL_CALL CmdMailMsg::getByName( const OUString& aName )
throw (NoSuchElementException, WrappedTargetException, RuntimeException)
{
MutexGuard aGuard( m_aMutex );
if( 0 == aName.compareToAscii( "from" ) && m_aOriginator.getLength() )
return makeAny( m_aOriginator );
else if( 0 == aName.compareToAscii( "to" ) && m_aRecipient.getLength() )
return makeAny( m_aRecipient );
else if( 0 == aName.compareToAscii( "cc" ) && m_CcRecipients.getLength() )
return makeAny( m_CcRecipients );
else if( 0 == aName.compareToAscii( "bcc" ) && m_BccRecipients.getLength() )
return makeAny( m_BccRecipients );
else if( 0 == aName.compareToAscii( "subject" ) && m_aSubject.getLength() )
return makeAny( m_aSubject );
else if( 0 == aName.compareToAscii( "attachment" ) && m_Attachments.getLength() )
return makeAny( m_Attachments );
throw NoSuchElementException( OUString::createFromAscii( "key not found: ") + aName,
static_cast < XNameAccess * > (this) );
}
//------------------------------------------------
//
//------------------------------------------------
Sequence< OUString > SAL_CALL CmdMailMsg::getElementNames( )
throw (::com::sun::star::uno::RuntimeException)
{
MutexGuard aGuard( m_aMutex );
sal_Int32 nItems = 0;
Sequence< OUString > aRet( 6 );
if( m_aOriginator.getLength() )
aRet[nItems++] = OUString::createFromAscii( "from" );
if( m_aRecipient.getLength() )
aRet[nItems++] = OUString::createFromAscii( "to" );
if( m_CcRecipients.getLength() )
aRet[nItems++] = OUString::createFromAscii( "cc" );
if( m_BccRecipients.getLength() )
aRet[nItems++] = OUString::createFromAscii( "bcc" );
if( m_aSubject.getLength() )
aRet[nItems++] = OUString::createFromAscii( "subject" );
if( m_Attachments.getLength() )
aRet[nItems++] = OUString::createFromAscii( "attachment" );
aRet.realloc( nItems );
return aRet;
}
//------------------------------------------------
//
//------------------------------------------------
sal_Bool SAL_CALL CmdMailMsg::hasByName( const ::rtl::OUString& aName )
throw (RuntimeException)
{
MutexGuard aGuard( m_aMutex );
if( 0 == aName.compareToAscii( "from" ) && m_aOriginator.getLength() )
return sal_True;
else if( 0 == aName.compareToAscii( "to" ) && m_aRecipient.getLength() )
return sal_True;
else if( 0 == aName.compareToAscii( "cc" ) && m_CcRecipients.getLength() )
return sal_True;
else if( 0 == aName.compareToAscii( "bcc" ) && m_BccRecipients.getLength() )
return sal_True;
else if( 0 == aName.compareToAscii( "subject" ) && m_aSubject.getLength() )
return sal_True;
else if( 0 == aName.compareToAscii( "attachment" ) && m_Attachments.getLength() )
return sal_True;
return sal_False;
}
//------------------------------------------------
//
//------------------------------------------------
Type SAL_CALL CmdMailMsg::getElementType( )
throw (RuntimeException)
{
// returning void for multi type container
return Type();
}
//------------------------------------------------
//
//------------------------------------------------
sal_Bool SAL_CALL CmdMailMsg::hasElements( )
throw (RuntimeException)
{
return 0 != getElementNames().getLength();
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 Vasily i. Redkin <vir@ctm.ru>
* License: MIT (See LICENSE.txt or http://www.opensource.org/licenses/MIT)
*/
#ifndef CHILDPROCESS_HPP_INCLUDED
#define CHILDPROCESS_HPP_INCLUDED
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h> // for strerror
#include <stdlib.h> // for exit
#include <string>
#include "eventdispatcher.hpp"
class ReadBuffer
{
private:
std::string m_buf;
int m_fd;
public:
int fd() const { return m_fd; }
bool fd(int fd) {
m_fd = fd;
// Set non-blocking
long arg;
if( (arg = fcntl(m_fd, F_GETFL, NULL)) < 0) {
fprintf(stderr, "Error fcntl(..., F_GETFL) (%s)\n", strerror(errno));
exit(0);
}
arg |= O_NONBLOCK;
if( fcntl(m_fd, F_SETFL, arg) < 0) {
fprintf(stderr, "Error fcntl(..., F_SETFL) (%s)\n", strerror(errno));
exit(0);
}
return true;
}
int do_read();
bool readline(std::string & s);
};
class Family;
class ChildProcess:public AsyncReader, public ChildProc
{
private:
int m_pid;
int m_fdo;
int m_fde;
Family * m_family;
ReadBuffer m_bufo;
ReadBuffer m_bufe;
public:
ChildProcess(Family * f):m_family(f) { }
virtual ~ChildProcess() { }
int pid() const { return m_pid; }
bool start();
virtual int can_read(int fd);
virtual void dead(int status);
virtual int kill(int signal);
};
#endif /* CHILDPROCESS_HPP_INCLUDED */
<commit_msg>Fixed header for Linux<commit_after>/*
* Copyright (c) 2012 Vasily i. Redkin <vir@ctm.ru>
* License: MIT (See LICENSE.txt or http://www.opensource.org/licenses/MIT)
*/
#ifndef CHILDPROCESS_HPP_INCLUDED
#define CHILDPROCESS_HPP_INCLUDED
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h> // for strerror
#include <stdlib.h> // for exit
#include <string>
#include "eventdispatcher.hpp"
class ReadBuffer
{
private:
std::string m_buf;
int m_fd;
public:
int fd() const { return m_fd; }
bool fd(int fd) {
m_fd = fd;
// Set non-blocking
long arg;
if( (arg = fcntl(m_fd, F_GETFL, NULL)) < 0) {
fprintf(stderr, "Error fcntl(..., F_GETFL) (%s)\n", strerror(errno));
exit(0);
}
arg |= O_NONBLOCK;
if( fcntl(m_fd, F_SETFL, arg) < 0) {
fprintf(stderr, "Error fcntl(..., F_SETFL) (%s)\n", strerror(errno));
exit(0);
}
return true;
}
int do_read();
bool readline(std::string & s);
};
class Family;
class ChildProcess:public AsyncReader, public ChildProc
{
private:
int m_pid;
int m_fdo;
int m_fde;
Family * m_family;
ReadBuffer m_bufo;
ReadBuffer m_bufe;
public:
ChildProcess(Family * f):m_family(f) { }
virtual ~ChildProcess() { }
int pid() const { return m_pid; }
bool start();
virtual int can_read(int fd);
virtual void dead(int status);
virtual int kill(int signal);
};
#endif /* CHILDPROCESS_HPP_INCLUDED */
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2012-2014 The SSDB 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 <pthread.h>
#include <time.h>
#include "../include.h"
#include "../util/log.h"
#include "ttl.h"
#define EXPIRATION_LIST_KEY "\xff\xff\xff\xff\xff|EXPIRE_LIST|KV"
#define BATCH_SIZE 1000
ExpirationHandler::ExpirationHandler(SSDB *ssdb){
this->ssdb = ssdb;
this->thread_quit = false;
this->list_name = EXPIRATION_LIST_KEY;
this->first_timeout = INT64_MAX;
this->start();
}
ExpirationHandler::~ExpirationHandler(){
Locking l(&this->mutex);
this->stop();
ssdb = NULL;
}
void ExpirationHandler::start(){
thread_quit = false;
pthread_t tid;
int err = pthread_create(&tid, NULL, &ExpirationHandler::thread_func, this);
if(err != 0){
log_fatal("can't create thread: %s", strerror(err));
exit(0);
}
}
void ExpirationHandler::stop(){
thread_quit = true;
for(int i=0; i<100; i++){
if(!thread_quit){
break;
}
usleep(10 * 1000);
}
}
int ExpirationHandler::set_ttl(const Bytes &key, int64_t ttl){
int64_t expired = time_ms() + ttl * 1000;
char data[30];
int size = snprintf(data, sizeof(data), "%" PRId64, expired);
if(size <= 0){
log_error("snprintf return error!");
return -1;
}
int ret = ssdb->zset(this->list_name, key, Bytes(data, size));
if(ret == -1){
return -1;
}
if(expired < first_timeout){
first_timeout = expired;
}
std::string s_key = key.String();
if(!fast_keys.empty() && expired <= fast_keys.max_score()){
fast_keys.add(s_key, expired);
if(fast_keys.size() > BATCH_SIZE){
log_debug("pop_back");
fast_keys.pop_back();
}
}else{
fast_keys.del(s_key);
//log_debug("don't put in fast_keys");
}
return 0;
}
int ExpirationHandler::del_ttl(const Bytes &key){
// 这样用是有 bug 的, 虽然 fast_keys 为空, 不代表整个 ttl 队列为空
// if(!this->fast_keys.empty()){
if(first_timeout != INT64_MAX){
fast_keys.del(key.String());
ssdb->zdel(this->list_name, key);
}
return 0;
}
int64_t ExpirationHandler::get_ttl(const Bytes &key){
std::string score;
if(ssdb->zget(this->list_name, key, &score) == 1){
int64_t ex = str_to_int64(score);
return (ex - time_ms())/1000;
}
return -1;
}
void ExpirationHandler::load_expiration_keys_from_db(int num){
ZIterator *it;
it = ssdb->zscan(this->list_name, "", "", "", num);
int n = 0;
while(it->next()){
n ++;
std::string &key = it->key;
int64_t score = str_to_int64(it->score);
if(score < 2000000000){
// older version compatible
score *= 1000;
}
fast_keys.add(key, score);
}
delete it;
log_debug("load %d keys into fast_keys", n);
}
void ExpirationHandler::expire_loop(){
Locking l(&this->mutex);
if(!this->ssdb){
return;
}
if(this->fast_keys.empty()){
this->load_expiration_keys_from_db(BATCH_SIZE);
if(this->fast_keys.empty()){
this->first_timeout = INT64_MAX;
return;
}
}
int64_t score;
std::string key;
if(this->fast_keys.front(&key, &score)){
this->first_timeout = score;
if(score <= time_ms()){
log_debug("expired %s", key.c_str());
ssdb->del(key);
ssdb->zdel(this->list_name, key);
this->fast_keys.pop_front();
}
}
}
void* ExpirationHandler::thread_func(void *arg){
ExpirationHandler *handler = (ExpirationHandler *)arg;
while(!handler->thread_quit){
if(handler->first_timeout > time_ms()){
usleep(10 * 1000);
continue;
}
handler->expire_loop();
}
log_debug("ExpirationHandler thread quit");
handler->thread_quit = false;
return (void *)NULL;
}
<commit_msg>update<commit_after>/*
Copyright (c) 2012-2014 The SSDB 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 <pthread.h>
#include <time.h>
#include "../include.h"
#include "../util/log.h"
#include "ttl.h"
#define EXPIRATION_LIST_KEY "\xff\xff\xff\xff\xff|EXPIRE_LIST|KV"
#define BATCH_SIZE 1000
ExpirationHandler::ExpirationHandler(SSDB *ssdb){
this->ssdb = ssdb;
this->thread_quit = false;
this->list_name = EXPIRATION_LIST_KEY;
this->first_timeout = 0;
this->start();
}
ExpirationHandler::~ExpirationHandler(){
Locking l(&this->mutex);
this->stop();
ssdb = NULL;
}
void ExpirationHandler::start(){
thread_quit = false;
pthread_t tid;
int err = pthread_create(&tid, NULL, &ExpirationHandler::thread_func, this);
if(err != 0){
log_fatal("can't create thread: %s", strerror(err));
exit(0);
}
}
void ExpirationHandler::stop(){
thread_quit = true;
for(int i=0; i<100; i++){
if(!thread_quit){
break;
}
usleep(10 * 1000);
}
}
int ExpirationHandler::set_ttl(const Bytes &key, int64_t ttl){
int64_t expired = time_ms() + ttl * 1000;
char data[30];
int size = snprintf(data, sizeof(data), "%" PRId64, expired);
if(size <= 0){
log_error("snprintf return error!");
return -1;
}
int ret = ssdb->zset(this->list_name, key, Bytes(data, size));
if(ret == -1){
return -1;
}
if(expired < first_timeout){
first_timeout = expired;
}
std::string s_key = key.String();
if(!fast_keys.empty() && expired <= fast_keys.max_score()){
fast_keys.add(s_key, expired);
if(fast_keys.size() > BATCH_SIZE){
log_debug("pop_back");
fast_keys.pop_back();
}
}else{
fast_keys.del(s_key);
//log_debug("don't put in fast_keys");
}
return 0;
}
int ExpirationHandler::del_ttl(const Bytes &key){
// 这样用是有 bug 的, 虽然 fast_keys 为空, 不代表整个 ttl 队列为空
// if(!this->fast_keys.empty()){
if(first_timeout != INT64_MAX){
fast_keys.del(key.String());
ssdb->zdel(this->list_name, key);
}
return 0;
}
int64_t ExpirationHandler::get_ttl(const Bytes &key){
std::string score;
if(ssdb->zget(this->list_name, key, &score) == 1){
int64_t ex = str_to_int64(score);
return (ex - time_ms())/1000;
}
return -1;
}
void ExpirationHandler::load_expiration_keys_from_db(int num){
ZIterator *it;
it = ssdb->zscan(this->list_name, "", "", "", num);
int n = 0;
while(it->next()){
n ++;
std::string &key = it->key;
int64_t score = str_to_int64(it->score);
if(score < 2000000000){
// older version compatible
score *= 1000;
}
fast_keys.add(key, score);
}
delete it;
log_debug("load %d keys into fast_keys", n);
}
void ExpirationHandler::expire_loop(){
Locking l(&this->mutex);
if(!this->ssdb){
return;
}
if(this->fast_keys.empty()){
this->load_expiration_keys_from_db(BATCH_SIZE);
if(this->fast_keys.empty()){
this->first_timeout = INT64_MAX;
return;
}
}
int64_t score;
std::string key;
if(this->fast_keys.front(&key, &score)){
this->first_timeout = score;
if(score <= time_ms()){
log_debug("expired %s", key.c_str());
ssdb->del(key);
ssdb->zdel(this->list_name, key);
this->fast_keys.pop_front();
}
}
}
void* ExpirationHandler::thread_func(void *arg){
ExpirationHandler *handler = (ExpirationHandler *)arg;
while(!handler->thread_quit){
if(handler->first_timeout > time_ms()){
usleep(10 * 1000);
continue;
}
handler->expire_loop();
}
log_debug("ExpirationHandler thread quit");
handler->thread_quit = false;
return (void *)NULL;
}
<|endoftext|>
|
<commit_before>/* author: @gwzz
*
*/
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <map>
#include "graph.h"
#include "support.h"
#include "sctfile.h"
using namespace std;
// Pre-define hierarchy array
// CUI: array of top nodes concept id of each hierarchy
// ConName: array of the name of each hierarchy
const long long CUI[19] = {123037004, 404684003, 308916002, 272379006, 363787002, 410607006, 373873005, 78621006, 260787004, 71388002, 362981000, 419891008, 243796009, 900000000000441003, 48176007, 370115009, 123038009, 254291000, 105590001};
const string ConName[19] = {"Body_structure", "Clinical_finding", "Environment_or_geographical_location", "Event", "Observable_entity", "Organism", "Pharmaceutical_biologic_product", "Physical_force", "Physical_object", "Procedure", "Qualifier_value", "Record_artifact", "Situation_with_explicit_context", "SNOMED_CT_Model_Component", "Social_context", "Special_Concept", "Specimen", "Staging_and_scales", "Substance"};
// define global variables
// node_map: store all the concepts [key,value]
// reversed_node_map: store reversed node_map [value,key]
// nodeFile, relationFile, out_put_file, as variable name
string nodeFile = "2016nodes.txt";
string relationFile = "2016relation.txt";
int main(int argc, char* argv[])
{
if (argc < 2)
{
std::cerr << "Usage: " << argv[0] << " SNOMED_CT_FILE_PATH" << std::endl;
return 1;
}
string out_put_folder = "/Users/zhuwei/Desktop/sct_nodes_within_hierarchy/";
std::cout<< argc << " " << argv[1] << endl;
SctFile sf(argv[1]);
long long top_node;
std::map<long long, int> node_map;
std::map<int, long long> reversed_node_map;
std::vector<long long> output_vector;
std::string sline;
std::vector<std::string> relation;
std::vector<std::string> nodes;
// Read in node file
fstream fin;
fin.open(nodeFile,ios::in);
while (getline(fin, sline)){
nodes.push_back(sline);
}
fin.close();
for (int i = 0; i < nodes.size(); ++i){
node_map[std::stoll(nodes[i])] = i;
}
for (map<long long, int>::iterator i = node_map.begin(); i != node_map.end(); ++i)
reversed_node_map[i->second] = i->first;
int nodeSize = node_map.size();
fin.open(relationFile,ios::in);
while (getline(fin, sline)){
relation.push_back(sline);
}
fin.close();
// initialize graph g
Graph g(nodeSize);
std::vector<long long> is_a_relationship;
for (auto i : relation){
is_a_relationship.clear();
is_a_relationship = Split(i, ',');
g.addEdge(node_map[is_a_relationship[1]],node_map[is_a_relationship[0]]);
}
string out_put_file;
for (int i = 0; i < 19; ++i){
output_vector.clear();
out_put_file.clear();
out_put_file = out_put_folder + ConName[i];
top_node = CUI[i];
output_vector = g.DFS(node_map[top_node]);
fstream fout;
fout.open(out_put_file,ios::app);
for (auto o : output_vector){
fout << reversed_node_map[o] << endl;
}
fout.close();
}
return 0;
}<commit_msg>minor!<commit_after>/* author: @gwzz
*
*/
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <map>
#include "graph.h"
#include "support.h"
#include "sctfile.h"
using namespace std;
// Pre-define hierarchy array
// CUI: array of top nodes concept id of each hierarchy
// ConName: array of the name of each hierarchy
const long long CUI[19] = {123037004, 404684003, 308916002, 272379006, 363787002, 410607006, 373873005, 78621006, 260787004, 71388002, 362981000, 419891008, 243796009, 900000000000441003, 48176007, 370115009, 123038009, 254291000, 105590001};
const string ConName[19] = {"Body_structure", "Clinical_finding", "Environment_or_geographical_location", "Event", "Observable_entity", "Organism", "Pharmaceutical_biologic_product", "Physical_force", "Physical_object", "Procedure", "Qualifier_value", "Record_artifact", "Situation_with_explicit_context", "SNOMED_CT_Model_Component", "Social_context", "Special_Concept", "Specimen", "Staging_and_scales", "Substance"};
// define global variables
// node_map: store all the concepts [key,value]
// reversed_node_map: store reversed node_map [value,key]
// nodeFile, relationFile, out_put_file, as variable name
string nodeFile = "2016nodes.txt";
string relationFile = "2016relation.txt";
int main(int argc, char* argv[])
{
if (argc < 2)
{
std::cerr << "Usage: " << argv[0] << " SNOMED_CT_FILE_PATH" << std::endl;
return 1;
}
string out_put_folder = "/Users/zhuwei/Desktop/sct_nodes_within_hierarchy/";
SctFile sf(argv[1]);
long long top_node;
std::map<long long, int> node_map;
std::map<int, long long> reversed_node_map;
std::vector<long long> output_vector;
std::string sline;
std::vector<std::string> relation;
std::vector<std::string> nodes;
// Read in node file
fstream fin;
fin.open(nodeFile,ios::in);
while (getline(fin, sline)){
nodes.push_back(sline);
}
fin.close();
for (int i = 0; i < nodes.size(); ++i){
node_map[std::stoll(nodes[i])] = i;
}
for (map<long long, int>::iterator i = node_map.begin(); i != node_map.end(); ++i)
reversed_node_map[i->second] = i->first;
int nodeSize = node_map.size();
fin.open(relationFile,ios::in);
while (getline(fin, sline)){
relation.push_back(sline);
}
fin.close();
// initialize graph g
Graph g(nodeSize);
std::vector<long long> is_a_relationship;
for (auto i : relation){
is_a_relationship.clear();
is_a_relationship = Split(i, ',');
g.addEdge(node_map[is_a_relationship[1]],node_map[is_a_relationship[0]]);
}
string out_put_file;
for (int i = 0; i < 19; ++i){
output_vector.clear();
out_put_file.clear();
out_put_file = out_put_folder + ConName[i];
top_node = CUI[i];
output_vector = g.DFS(node_map[top_node]);
fstream fout;
fout.open(out_put_file,ios::app);
for (auto o : output_vector){
fout << reversed_node_map[o] << endl;
}
fout.close();
}
return 0;
}<|endoftext|>
|
<commit_before>// -*- Mode:C++ -*-
/**************************************************************************************************/
/* */
/* Copyright (C) 2016 University of Hull */
/* */
/**************************************************************************************************/
/* */
/* module : hugh/field/base.cpp */
/* project : */
/* description: */
/* */
/**************************************************************************************************/
// include i/f header
#include "hugh/field/base.hpp"
// includes, system
#include <algorithm> // std::find<>
#include <boost/io/ios_state.hpp> // boost::io::ios_all_saver
#include <iomanip> // std::dec, std::hex, std::right, std::setw, std::showbase
#include <ostream> // std::ostream
#include <stdexcept> // std::logic_error
// includes, project
#include <hugh/field/connection/manager.hpp>
#include <hugh/field/container.hpp>
#include <hugh/support/io_utils.hpp>
#define HUGH_USE_TRACE
#undef HUGH_USE_TRACE
#include <hugh/support/trace.hpp>
// internal unnamed namespace
namespace {
// types, internal (class, enum, struct, union, typedef)
// variables, internal
// functions, internal
} // namespace {
namespace hugh {
namespace field {
// variables, exported
// functions, exported
container const&
base::container() const
{
TRACE("hugh::field::base::container(get)");
return container_;
}
std::string const&
base::name() const
{
TRACE("hugh::field::base::name(get)");
return name_;
}
support::clock::time_point const&
base::last_change() const
{
TRACE("hugh::field::base::last_change(get)");
return last_change_;
}
void
base::touch()
{
TRACE("hugh::field::base::touch");
changed();
}
/* virtual */ void
base::print_on(std::ostream& os) const
{
TRACE_NEVER("hugh::field::base::print_on");
using support::ostream::operator<<;
boost::io::ios_all_saver const ias(os);
os << '['
<< std::right << std::setw(19) << name_
<< '@'
<< std::hex << std::showbase << this
<< "->c@"
<< std::hex << std::showbase << &container_
<< ':'
<< std::dec << last_change_
<< ']';
}
/* explicit */
base::base(container_type& a, std::string const& b)
: container_ (a),
name_ (b),
last_change_(support::clock::now())
{
TRACE("hugh::field::base::base");
if (name_.empty()) {
throw std::logic_error("hugh::field::base::base: field names cannot be empty!");
}
container_.add(this);
}
/* virtual */
base::~base()
{
TRACE("hugh::field::base::~base");
connection::manager::instance->disconnect(this);
container_.sub(this);
}
void
base::changed()
{
TRACE("hugh::field::base::changed");
last_change_ = support::clock::now();
container_.changed(*this);
notify();
}
void
base::notify()
{
TRACE("hugh::field::base::notify");
connection::manager::instance->update(this);
}
} // namespace field {
} // namespace hugh {
<commit_msg>cleanup: header inclusion<commit_after>// -*- Mode:C++ -*-
/**************************************************************************************************/
/* */
/* Copyright (C) 2016 University of Hull */
/* */
/**************************************************************************************************/
/* */
/* module : hugh/field/base.cpp */
/* project : */
/* description: */
/* */
/**************************************************************************************************/
// include i/f header
#include "hugh/field/base.hpp"
// includes, system
#include <boost/io/ios_state.hpp> // boost::io::ios_all_saver
#include <iomanip> // std::dec, std::hex, std::right, std::setw, std::showbase
#include <ostream> // std::ostream
#include <stdexcept> // std::logic_error
// includes, project
#include <hugh/field/connection/manager.hpp>
#include <hugh/field/container.hpp>
#include <hugh/support/io_utils.hpp>
#define HUGH_USE_TRACE
#undef HUGH_USE_TRACE
#include <hugh/support/trace.hpp>
// internal unnamed namespace
namespace {
// types, internal (class, enum, struct, union, typedef)
// variables, internal
// functions, internal
} // namespace {
namespace hugh {
namespace field {
// variables, exported
// functions, exported
container const&
base::container() const
{
TRACE("hugh::field::base::container(get)");
return container_;
}
std::string const&
base::name() const
{
TRACE("hugh::field::base::name(get)");
return name_;
}
support::clock::time_point const&
base::last_change() const
{
TRACE("hugh::field::base::last_change(get)");
return last_change_;
}
void
base::touch()
{
TRACE("hugh::field::base::touch");
changed();
}
/* virtual */ void
base::print_on(std::ostream& os) const
{
TRACE_NEVER("hugh::field::base::print_on");
using support::ostream::operator<<;
boost::io::ios_all_saver const ias(os);
os << '['
<< std::right << std::setw(19) << name_
<< '@'
<< std::hex << std::showbase << this
<< "->c@"
<< std::hex << std::showbase << &container_
<< ':'
<< std::dec << last_change_
<< ']';
}
/* explicit */
base::base(container_type& a, std::string const& b)
: container_ (a),
name_ (b),
last_change_(support::clock::now())
{
TRACE("hugh::field::base::base");
if (name_.empty()) {
throw std::logic_error("hugh::field::base::base: field names cannot be empty!");
}
container_.add(this);
}
/* virtual */
base::~base()
{
TRACE("hugh::field::base::~base");
connection::manager::instance->disconnect(this);
container_.sub(this);
}
void
base::changed()
{
TRACE("hugh::field::base::changed");
last_change_ = support::clock::now();
container_.changed(*this);
notify();
}
void
base::notify()
{
TRACE("hugh::field::base::notify");
connection::manager::instance->update(this);
}
} // namespace field {
} // namespace hugh {
<|endoftext|>
|
<commit_before>/**
* elf-loader.cpp: loader of elf files to guest memory
* @author Pavel Kryukov
* Copyright 2018 uArchSim iLab project
*/
#include "elf_loader.h"
#include <elfio/elfio.hpp>
#include <memory/memory.h>
#include <string>
struct InvalidElfSection : Exception
{
explicit InvalidElfSection(const std::string& section_name) :
Exception("Malformed ELF section", section_name) { }
};
static void load_elf_section( WriteableMemory* memory, const ELFIO::section& section, AddrDiff offset)
{
using namespace std::literals::string_literals;
if ( section.get_address() == 0 || section.get_data() == nullptr)
throw InvalidElfSection( "\""s + section.get_name() + "\""s);
memory->memcpy_host_to_guest( section.get_address() + offset, byte_cast( section.get_data()), section.get_size());
}
ElfLoader::ElfLoader( const std::string& filename, AddrDiff offset)
: reader( std::make_unique<ELFIO::elfio>())
, offset( offset)
{
if ( !reader->load( filename))
throw InvalidElfFile( filename);
}
void ElfLoader::load_to( WriteableMemory *memory) const
{
for ( const auto& section : reader->sections)
if ( ( section->get_flags() & SHF_ALLOC) != 0)
load_elf_section( memory, *section, offset);
}
Addr ElfLoader::get_startPC() const
{
using namespace ELFIO;
for ( const auto& section : reader->sections) {
if ( section->get_type() != SHT_SYMTAB)
continue;
symbol_section_accessor symbols(*reader, section);
for ( unsigned int j = 0; j < symbols.get_symbols_num(); ++j ) {
std::string name;
Elf64_Addr value = 0;
Elf_Xword size;
unsigned char bind;
unsigned char type;
Elf_Half section_index;
unsigned char other;
symbols.get_symbol( j, name, value, size, bind, type, section_index, other );
if ( name == "_start")
return offset + value;
}
}
if ( reader->sections[ ".text"] != nullptr) {
std::cout << "Warning: no _start label found, defaulting to '.text' section\n";
return offset + reader->sections[ ".text"]->get_address();
}
std::cout << "Warning: no entry point found, returning 0x0\n";
return offset;
}
ElfLoader::~ElfLoader() = default;
<commit_msg>Fix Clang-Tidy warnings (#981)<commit_after>/**
* elf-loader.cpp: loader of elf files to guest memory
* @author Pavel Kryukov
* Copyright 2018 uArchSim iLab project
*/
#include "elf_loader.h"
#include <elfio/elfio.hpp>
#include <memory/memory.h>
#include <string>
struct InvalidElfSection : Exception
{
explicit InvalidElfSection(const std::string& section_name) :
Exception("Malformed ELF section", section_name) { }
};
static void load_elf_section( WriteableMemory* memory, const ELFIO::section& section, AddrDiff offset)
{
using namespace std::literals::string_literals;
if ( section.get_address() == 0 || section.get_data() == nullptr)
throw InvalidElfSection( "\""s + section.get_name() + "\""s);
memory->memcpy_host_to_guest( section.get_address() + offset, byte_cast( section.get_data()), section.get_size());
}
ElfLoader::ElfLoader( const std::string& filename, AddrDiff offset)
: reader( std::make_unique<ELFIO::elfio>())
, offset( offset)
{
if ( !reader->load( filename))
throw InvalidElfFile( filename);
}
void ElfLoader::load_to( WriteableMemory *memory) const
{
for ( const auto& section : reader->sections)
if ( ( section->get_flags() & SHF_ALLOC) != 0)
load_elf_section( memory, *section, offset);
}
Addr ElfLoader::get_startPC() const
{
for ( const auto& section : reader->sections) {
if ( section->get_type() != SHT_SYMTAB)
continue;
ELFIO::symbol_section_accessor symbols(*reader, section);
for ( ELFIO::Elf_Xword j = 0; j < symbols.get_symbols_num(); ++j ) {
std::string name;
ELFIO::Elf64_Addr value = 0;
ELFIO::Elf_Xword size;
unsigned char bind;
unsigned char type;
ELFIO::Elf_Half section_index;
unsigned char other;
symbols.get_symbol( j, name, value, size, bind, type, section_index, other );
if ( name == "_start")
return offset + value;
}
}
if ( reader->sections[ ".text"] != nullptr) {
std::cout << "Warning: no _start label found, defaulting to '.text' section\n";
return offset + reader->sections[ ".text"]->get_address();
}
std::cout << "Warning: no entry point found, returning 0x0\n";
return offset;
}
ElfLoader::~ElfLoader() = default;
<|endoftext|>
|
<commit_before>// \file standard.cpp
// Implementation of some standard lisp operations
//
#include "yacas/yacasprivate.h"
#include "yacas/standard.h"
#include "yacas/lispatom.h"
#include "yacas/lisperror.h"
#include "yacas/lispenvironment.h"
#include "yacas/lispio.h"
#include "yacas/platfileio.h"
#include "yacas/lispenvironment.h"
#include "yacas/tokenizer.h"
#include "yacas/infixparser.h"
#include "yacas/lispeval.h"
#include "yacas/stringio.h"
#include "yacas/numbers.h"
bool InternalIsList(const LispPtr& aPtr)
{
if (!aPtr)
return false;
if (!aPtr->SubList())
return false;
if (!(*aPtr->SubList()))
return false;
// The following happens with IsList(UnList({foo(x), a, b}))
if ((*aPtr->SubList())->String()->c_str() == nullptr)
return false;
//TODO this StrEqual is far from perfect. We could pass in a LispEnvironment object...
if (std::strcmp((*aPtr->SubList())->String()->c_str(), "List"))
return false;
return true;
}
bool InternalIsString(LispString * aOriginal)
{
if (aOriginal)
if ((*aOriginal)[0] == '\"')
if ((*aOriginal)[aOriginal->size()-1] == '\"')
return true;
return false;
}
/* TODO: in documenting the choices made in the C++ engine, perhaps document why I pass objects that should contain the
result by reference. Result string passed in by reference to avoid copy-constructors etcetera (allowing
the code to share the same LispString in different places).
*/
void InternalUnstringify(LispString& aResult, const LispString * aOriginal)
{
/*TODO: should these not be checked also higher up, and should this not be an assert at this level?
* ideally this function should be as efficient as possible (allowing for a code generator to generate
* compiled code that calls this function immediately. The compiler could prove that the input is valid,
* so the checks would not be needed here in a non-debug run).
*
* Also do not forget to make the change in the Java version then, and find the other places where this is relevant.
*/
if (!aOriginal || (*aOriginal)[0] != '\"')
throw LispErrInvalidArg();
LispInt nrc = aOriginal->size()-1;
if (!aOriginal || (*aOriginal)[nrc] != '\"')
throw LispErrInvalidArg();
aResult.resize(nrc);
for (LispInt i = 1; i < nrc; i++)
aResult[i-1] = (*aOriginal)[i];
}
void InternalStringify(LispString& aResult, const LispString* aOriginal)
{
if (!aOriginal)
throw LispErrInvalidArg();
LispInt nrc=aOriginal->size()-1;
aResult.resize(nrc+3);
LispInt i;
aResult[0] = '\"';
for (i=0;i<nrc;i++)
aResult[i+1] = (*aOriginal)[i];
aResult[nrc+1] = '\"';
aResult[nrc+2] = '\0';
}
void InternalIntToAscii(LispChar * aTrg,LispInt aInt)
{
LispInt ind=0;
if (aInt < 0)
{
*aTrg++ = '-';
aInt = -aInt;
}
while (aInt != 0)
{
aTrg[ind] = '0'+(aInt%10);
ind++;
aInt/=10;
}
//zero
if (ind == 0)
{
aTrg[0] = '0';
ind++;
}
aTrg[ind]='\0';
LispInt i;
for (i=0;i<(ind>>1);i++)
{
LispChar swap=aTrg[i];
aTrg[i] = aTrg[ind-i-1];
aTrg[ind-i-1] = swap;
}
}
LispInt InternalAsciiToInt(const LispString& aString)
{
const LispChar* ptr = aString.c_str();
if (!IsNumber(ptr, false))
throw LispErrInvalidArg();
return std::atoi(ptr);
}
bool IsNumber(const LispChar * ptr,bool aAllowFloat)
{
if (*ptr == '-' || *ptr == '+')
ptr++;
LispInt nrDigits=0;
LispInt index=0;
while(ptr[index] >= '0' && ptr[index] <= '9')
{
nrDigits++;
index++;
}
if (ptr[index] == '.')
{
if (!aAllowFloat)
return false;
index++;
while(ptr[index] >= '0' && ptr[index] <= '9')
{
nrDigits++;
index++;
}
}
if (nrDigits == 0)
return false;
if (ptr[index] == 'e' || ptr[index] == 'E')
{
if (!aAllowFloat)
return false;
if (!NumericSupportForMantissa())
return false;
index++;
if (ptr[index] == '-' || ptr[index] == '+') index++;
while(ptr[index] >= '0' && ptr[index] <= '9') index++;
}
if (ptr[index] != '\0') return false;
return true;
}
void InternalNth(LispPtr& aResult, const LispPtr& aArg, LispInt n)
{
if (n < 0 || !aArg || !aArg->SubList())
throw LispErrInvalidArg();
LispIterator iter(*aArg->SubList());
while (n>0)
{
if (!iter.getObj())
throw LispErrInvalidArg();
++iter;
n--;
}
if (!iter.getObj())
throw LispErrInvalidArg();
aResult = (iter.getObj()->Copy());
}
void InternalTail(LispPtr& aResult, const LispPtr& aArg)
{
if (!aArg)
throw LispErrInvalidArg();
LispPtr* iter = aArg->SubList();
if (!iter || !*iter)
throw LispErrInvalidArg();
aResult = (LispSubList::New((*iter)->Nixed()));
}
void InternalReverseList(LispPtr& aResult, const LispPtr& aOriginal)
{
LispPtr iter(aOriginal);
LispPtr previous;
LispPtr tail(aOriginal);
while (!!iter)
{
tail = iter->Nixed();
iter->Nixed() = (previous);
previous = iter;
iter = tail;
}
aResult = previous;
}
void InternalFlatCopy(LispPtr& aResult, const LispPtr& aOriginal)
{
LispConstIterator orig(aOriginal);
LispIterator res(aResult);
while (orig.getObj())
{
(*res) = (orig.getObj()->Copy());
++orig;
++res;
}
}
LispInt InternalListLength(const LispPtr& aOriginal)
{
LispConstIterator iter(aOriginal);
LispInt length = 0;
while (iter.getObj())
{
/*
if (iter()->String())
printf("%s ",iter()->String()->c_str());
*/
++iter;
length++;
}
return length;
}
bool InternalEquals(LispEnvironment& aEnvironment,
const LispPtr& aExpression1,
const LispPtr& aExpression2)
{
// Handle pointers to same, or nullptr
if (aExpression1.ptr() == aExpression2.ptr()) // compare pointers to LispObject
{
return true;
}
/*TODO This code would be better, if BigNumber::Equals works*/
BigNumber *n1 = aExpression1->Number(aEnvironment.Precision());
BigNumber *n2 = aExpression2->Number(aEnvironment.Precision());
if (!(!n1 && !n2) )
{
if (n1 == n2)
{
return true;
}
if (!n1) return false;
if (!n2) return false;
if (n1->Equals(*n2)) return true;
//this should be enabled
return false;
}
//Pointers to strings should be the same
if (aExpression1->String() != aExpression2->String())
{
return false;
}
// Handle same sublists, or nullptr
if (aExpression1->SubList() == aExpression2->SubList())
{
return true;
}
// Now check the sublists
if (aExpression1->SubList())
{
if (!aExpression2->SubList())
{
return false;
}
LispIterator iter1(*aExpression1->SubList());
LispIterator iter2(*aExpression2->SubList());
while (iter1.getObj() && iter2.getObj())
{
// compare two list elements
if (!InternalEquals(aEnvironment, *iter1, *iter2))
{
return false;
}
// Step to next
++iter1;
++iter2;
}
// Lists don't have the same length
if (iter1.getObj() != iter2.getObj())
return false;
// Same!
return true;
}
// expressions sublists are not the same!
return false;
}
void DoInternalLoad(LispEnvironment& aEnvironment,LispInput* aInput)
{
LispLocalInput localInput(aEnvironment, aInput);
// TODO make "EndOfFile" a global thing
// read-parse-eval to the end of file
LispString * eof = aEnvironment.HashTable().LookUp("EndOfFile");
bool endoffile = false;
LispTokenizer tok;
InfixParser parser(tok,
*aEnvironment.CurrentInput(),
aEnvironment,
aEnvironment.PreFix(),
aEnvironment.InFix(),
aEnvironment.PostFix(),
aEnvironment.Bodied());
while (!endoffile)
{
LispPtr readIn;
// Read expression
parser.Parse(readIn);
if (!readIn)
throw LispErrReadingFile();
// Check for end of file
if (readIn->String() == eof)
{
endoffile = true;
}
// Else evaluate
else
{
LispPtr result;
aEnvironment.iEvaluator->Eval(aEnvironment, result, readIn);
}
}
}
void InternalLoad(LispEnvironment& aEnvironment, const LispString* aFileName)
{
LispString oper;
InternalUnstringify(oper, aFileName);
LispString * contents = aEnvironment.FindCachedFile(oper.c_str());
LispString * hashedname = aEnvironment.HashTable().LookUp(oper.c_str());
InputStatus oldstatus = aEnvironment.iInputStatus;
aEnvironment.iInputStatus.SetTo(hashedname->c_str());
if (contents)
{
StringInput newInput(*contents,aEnvironment.iInputStatus);
DoInternalLoad(aEnvironment,&newInput);
delete contents;
}
else
{
//TODO make the file api platform independent!!!!
// Open file
LispLocalFile localFP(aEnvironment, hashedname->c_str(),true,
aEnvironment.iInputDirectories);
if (!localFP.stream.is_open())
throw LispErrFileNotFound();
CachedStdFileInput newInput(localFP,aEnvironment.iInputStatus);
DoInternalLoad(aEnvironment,&newInput);
}
aEnvironment.iInputStatus.RestoreFrom(oldstatus);
}
void InternalUse(LispEnvironment& aEnvironment,LispString * aFileName)
{
LispDefFile* def = aEnvironment.DefFiles().File(aFileName);
if (!def->IsLoaded())
{
def->SetLoaded();
InternalLoad(aEnvironment,aFileName);
}
}
void InternalApplyString(LispEnvironment& aEnvironment, LispPtr& aResult,
LispString * aOperator,LispPtr& aArgs)
{
if (!InternalIsString(aOperator))
throw LispErrNotString();
LispObject *head =
LispAtom::New(aEnvironment,SymbolName(aEnvironment, aOperator->c_str())->c_str());
head->Nixed() = (aArgs);
LispPtr body(LispSubList::New(head));
aEnvironment.iEvaluator->Eval(aEnvironment, aResult, body);
}
void InternalApplyPure(LispPtr& oper,LispPtr& args2,LispPtr& aResult,LispEnvironment& aEnvironment)
{
LispPtr * chk1 = oper->SubList();
if (!chk1)
throw LispErrInvalidArg();
LispPtr oper2((*chk1)->Nixed());
if (!oper2)
throw LispErrInvalidArg();
LispPtr body(oper2->Nixed());
if (!body)
throw LispErrInvalidArg();
LispPtr * chk2 = oper2->SubList();
if (!chk2 || !*chk2)
throw LispErrInvalidArg();
oper2 = ((*chk2)->Nixed());
LispLocalFrame frame(aEnvironment,false);
while (!!oper2) {
if (!args2)
throw LispErrInvalidArg();
LispString* var = oper2->String();
if (!var)
throw LispErrInvalidArg();
LispPtr newly(args2->Copy());
aEnvironment.NewLocal(var,newly);
oper2 = (oper2->Nixed());
args2 = (args2->Nixed());
}
if (args2)
throw LispErrInvalidArg();
aEnvironment.iEvaluator->Eval(aEnvironment, aResult, body);
}
void InternalEvalString(LispEnvironment& aEnvironment, LispPtr& aResult,
const LispChar* aString)
{
LispString full(aString);
full.push_back(';');
StringInput input(full,aEnvironment.iInputStatus);
LispPtr lispexpr;
LispTokenizer &tok = *aEnvironment.iCurrentTokenizer;
InfixParser parser(tok, input,
aEnvironment,
aEnvironment.PreFix(),
aEnvironment.InFix(),
aEnvironment.PostFix(),
aEnvironment.Bodied());
parser.Parse(lispexpr);
aEnvironment.iEvaluator->Eval(aEnvironment, aResult, lispexpr);
}
LispObject* operator+(const LispObjectAdder& left, const LispObjectAdder& right)
{
LispObject* trav = left.iPtr;
while (!!trav->Nixed())
{
trav = trav->Nixed();
}
trav->Nixed() = (right.iPtr);
return left.iPtr;
}
void ParseExpression(LispPtr& aResult, const LispChar* aString,LispEnvironment& aEnvironment)
{
LispString full(aString);
full.push_back(';');
StringInput input(full,aEnvironment.iInputStatus);
aEnvironment.iInputStatus.SetTo("String");
LispTokenizer &tok = *aEnvironment.iCurrentTokenizer;
InfixParser parser(tok,
input,
aEnvironment,
aEnvironment.PreFix(),
aEnvironment.InFix(),
aEnvironment.PostFix(),
aEnvironment.Bodied());
parser.Parse(aResult);
}
void ReturnUnEvaluated(LispPtr& aResult,LispPtr& aArguments,
LispEnvironment& aEnvironment)
{
LispPtr full(aArguments->Copy());
aResult = (LispSubList::New(full));
LispIterator iter(aArguments);
++iter;
while (iter.getObj())
{
LispPtr next;
aEnvironment.iEvaluator->Eval(aEnvironment, next, *iter);
full->Nixed() = (next);
full = (next);
++iter;
}
full->Nixed() = (nullptr);
}
void PrintExpression(LispString& aResult,
LispPtr& aExpression,
LispEnvironment& aEnvironment,
std::size_t aMaxChars)
{
aResult.clear();
StringOutput newOutput(aResult);
InfixPrinter infixprinter(aEnvironment.PreFix(),
aEnvironment.InFix(),
aEnvironment.PostFix(),
aEnvironment.Bodied());
infixprinter.Print(aExpression, newOutput, aEnvironment);
if (aMaxChars > 0 && aResult.size()>aMaxChars)
{
aResult.resize(aMaxChars - 3);
aResult += "...";
}
}
LispString* SymbolName(LispEnvironment& aEnvironment,
const LispChar * aSymbol)
{
if (aSymbol[0] == '\"')
return aEnvironment.HashTable().LookUpCounted(aSymbol + 1, std::strlen(aSymbol) - 2);
else
return aEnvironment.HashTable().LookUp(aSymbol);
}
<commit_msg>adjustments to correct string semantics<commit_after>// \file standard.cpp
// Implementation of some standard lisp operations
//
#include "yacas/yacasprivate.h"
#include "yacas/standard.h"
#include "yacas/lispatom.h"
#include "yacas/lisperror.h"
#include "yacas/lispenvironment.h"
#include "yacas/lispio.h"
#include "yacas/platfileio.h"
#include "yacas/lispenvironment.h"
#include "yacas/tokenizer.h"
#include "yacas/infixparser.h"
#include "yacas/lispeval.h"
#include "yacas/stringio.h"
#include "yacas/numbers.h"
bool InternalIsList(const LispPtr& aPtr)
{
if (!aPtr)
return false;
if (!aPtr->SubList())
return false;
if (!(*aPtr->SubList()))
return false;
// The following happens with IsList(UnList({foo(x), a, b}))
if ((*aPtr->SubList())->String()->c_str() == nullptr)
return false;
//TODO this StrEqual is far from perfect. We could pass in a LispEnvironment object...
if (std::strcmp((*aPtr->SubList())->String()->c_str(), "List"))
return false;
return true;
}
bool InternalIsString(LispString * aOriginal)
{
if (aOriginal)
if ((*aOriginal)[0] == '\"')
if ((*aOriginal)[aOriginal->size()-1] == '\"')
return true;
return false;
}
/* TODO: in documenting the choices made in the C++ engine, perhaps document why I pass objects that should contain the
result by reference. Result string passed in by reference to avoid copy-constructors etcetera (allowing
the code to share the same LispString in different places).
*/
void InternalUnstringify(LispString& aResult, const LispString * aOriginal)
{
/*TODO: should these not be checked also higher up, and should this not be an assert at this level?
* ideally this function should be as efficient as possible (allowing for a code generator to generate
* compiled code that calls this function immediately. The compiler could prove that the input is valid,
* so the checks would not be needed here in a non-debug run).
*
* Also do not forget to make the change in the Java version then, and find the other places where this is relevant.
*/
if (!aOriginal || aOriginal->size() < 2 || aOriginal->front() != '\"' || aOriginal->back() != '\"')
throw LispErrInvalidArg();
aResult.assign(aOriginal->c_str() + 1, aOriginal->size() - 2);
}
void InternalStringify(LispString& aResult, const LispString* aOriginal)
{
if (!aOriginal)
throw LispErrInvalidArg();
LispInt nrc=aOriginal->size()-1;
aResult.resize(nrc+3);
LispInt i;
aResult[0] = '\"';
for (i=0;i<nrc;i++)
aResult[i+1] = (*aOriginal)[i];
aResult[nrc+1] = '\"';
aResult[nrc+2] = '\0';
}
void InternalIntToAscii(LispChar * aTrg,LispInt aInt)
{
LispInt ind=0;
if (aInt < 0)
{
*aTrg++ = '-';
aInt = -aInt;
}
while (aInt != 0)
{
aTrg[ind] = '0'+(aInt%10);
ind++;
aInt/=10;
}
//zero
if (ind == 0)
{
aTrg[0] = '0';
ind++;
}
aTrg[ind]='\0';
LispInt i;
for (i=0;i<(ind>>1);i++)
{
LispChar swap=aTrg[i];
aTrg[i] = aTrg[ind-i-1];
aTrg[ind-i-1] = swap;
}
}
LispInt InternalAsciiToInt(const LispString& aString)
{
const LispChar* ptr = aString.c_str();
if (!IsNumber(ptr, false))
throw LispErrInvalidArg();
return std::atoi(ptr);
}
bool IsNumber(const LispChar * ptr,bool aAllowFloat)
{
if (*ptr == '-' || *ptr == '+')
ptr++;
LispInt nrDigits=0;
LispInt index=0;
while(ptr[index] >= '0' && ptr[index] <= '9')
{
nrDigits++;
index++;
}
if (ptr[index] == '.')
{
if (!aAllowFloat)
return false;
index++;
while(ptr[index] >= '0' && ptr[index] <= '9')
{
nrDigits++;
index++;
}
}
if (nrDigits == 0)
return false;
if (ptr[index] == 'e' || ptr[index] == 'E')
{
if (!aAllowFloat)
return false;
if (!NumericSupportForMantissa())
return false;
index++;
if (ptr[index] == '-' || ptr[index] == '+') index++;
while(ptr[index] >= '0' && ptr[index] <= '9') index++;
}
if (ptr[index] != '\0') return false;
return true;
}
void InternalNth(LispPtr& aResult, const LispPtr& aArg, LispInt n)
{
if (n < 0 || !aArg || !aArg->SubList())
throw LispErrInvalidArg();
LispIterator iter(*aArg->SubList());
while (n>0)
{
if (!iter.getObj())
throw LispErrInvalidArg();
++iter;
n--;
}
if (!iter.getObj())
throw LispErrInvalidArg();
aResult = (iter.getObj()->Copy());
}
void InternalTail(LispPtr& aResult, const LispPtr& aArg)
{
if (!aArg)
throw LispErrInvalidArg();
LispPtr* iter = aArg->SubList();
if (!iter || !*iter)
throw LispErrInvalidArg();
aResult = (LispSubList::New((*iter)->Nixed()));
}
void InternalReverseList(LispPtr& aResult, const LispPtr& aOriginal)
{
LispPtr iter(aOriginal);
LispPtr previous;
LispPtr tail(aOriginal);
while (!!iter)
{
tail = iter->Nixed();
iter->Nixed() = (previous);
previous = iter;
iter = tail;
}
aResult = previous;
}
void InternalFlatCopy(LispPtr& aResult, const LispPtr& aOriginal)
{
LispConstIterator orig(aOriginal);
LispIterator res(aResult);
while (orig.getObj())
{
(*res) = (orig.getObj()->Copy());
++orig;
++res;
}
}
LispInt InternalListLength(const LispPtr& aOriginal)
{
LispConstIterator iter(aOriginal);
LispInt length = 0;
while (iter.getObj())
{
/*
if (iter()->String())
printf("%s ",iter()->String()->c_str());
*/
++iter;
length++;
}
return length;
}
bool InternalEquals(LispEnvironment& aEnvironment,
const LispPtr& aExpression1,
const LispPtr& aExpression2)
{
// Handle pointers to same, or nullptr
if (aExpression1.ptr() == aExpression2.ptr()) // compare pointers to LispObject
{
return true;
}
/*TODO This code would be better, if BigNumber::Equals works*/
BigNumber *n1 = aExpression1->Number(aEnvironment.Precision());
BigNumber *n2 = aExpression2->Number(aEnvironment.Precision());
if (!(!n1 && !n2) )
{
if (n1 == n2)
{
return true;
}
if (!n1) return false;
if (!n2) return false;
if (n1->Equals(*n2)) return true;
//this should be enabled
return false;
}
//Pointers to strings should be the same
if (aExpression1->String() != aExpression2->String())
{
return false;
}
// Handle same sublists, or nullptr
if (aExpression1->SubList() == aExpression2->SubList())
{
return true;
}
// Now check the sublists
if (aExpression1->SubList())
{
if (!aExpression2->SubList())
{
return false;
}
LispIterator iter1(*aExpression1->SubList());
LispIterator iter2(*aExpression2->SubList());
while (iter1.getObj() && iter2.getObj())
{
// compare two list elements
if (!InternalEquals(aEnvironment, *iter1, *iter2))
{
return false;
}
// Step to next
++iter1;
++iter2;
}
// Lists don't have the same length
if (iter1.getObj() != iter2.getObj())
return false;
// Same!
return true;
}
// expressions sublists are not the same!
return false;
}
void DoInternalLoad(LispEnvironment& aEnvironment,LispInput* aInput)
{
LispLocalInput localInput(aEnvironment, aInput);
// TODO make "EndOfFile" a global thing
// read-parse-eval to the end of file
LispString * eof = aEnvironment.HashTable().LookUp("EndOfFile");
bool endoffile = false;
LispTokenizer tok;
InfixParser parser(tok,
*aEnvironment.CurrentInput(),
aEnvironment,
aEnvironment.PreFix(),
aEnvironment.InFix(),
aEnvironment.PostFix(),
aEnvironment.Bodied());
while (!endoffile)
{
LispPtr readIn;
// Read expression
parser.Parse(readIn);
if (!readIn)
throw LispErrReadingFile();
// Check for end of file
if (readIn->String() == eof)
{
endoffile = true;
}
// Else evaluate
else
{
LispPtr result;
aEnvironment.iEvaluator->Eval(aEnvironment, result, readIn);
}
}
}
void InternalLoad(LispEnvironment& aEnvironment, const LispString* aFileName)
{
LispString oper;
InternalUnstringify(oper, aFileName);
LispString * contents = aEnvironment.FindCachedFile(oper.c_str());
LispString * hashedname = aEnvironment.HashTable().LookUp(oper.c_str());
InputStatus oldstatus = aEnvironment.iInputStatus;
aEnvironment.iInputStatus.SetTo(hashedname->c_str());
if (contents)
{
StringInput newInput(*contents,aEnvironment.iInputStatus);
DoInternalLoad(aEnvironment,&newInput);
delete contents;
}
else
{
//TODO make the file api platform independent!!!!
// Open file
LispLocalFile localFP(aEnvironment, hashedname->c_str(),true,
aEnvironment.iInputDirectories);
if (!localFP.stream.is_open())
throw LispErrFileNotFound();
CachedStdFileInput newInput(localFP,aEnvironment.iInputStatus);
DoInternalLoad(aEnvironment,&newInput);
}
aEnvironment.iInputStatus.RestoreFrom(oldstatus);
}
void InternalUse(LispEnvironment& aEnvironment,LispString * aFileName)
{
LispDefFile* def = aEnvironment.DefFiles().File(aFileName);
if (!def->IsLoaded())
{
def->SetLoaded();
InternalLoad(aEnvironment,aFileName);
}
}
void InternalApplyString(LispEnvironment& aEnvironment, LispPtr& aResult,
LispString * aOperator,LispPtr& aArgs)
{
if (!InternalIsString(aOperator))
throw LispErrNotString();
LispObject *head =
LispAtom::New(aEnvironment,SymbolName(aEnvironment, aOperator->c_str())->c_str());
head->Nixed() = (aArgs);
LispPtr body(LispSubList::New(head));
aEnvironment.iEvaluator->Eval(aEnvironment, aResult, body);
}
void InternalApplyPure(LispPtr& oper,LispPtr& args2,LispPtr& aResult,LispEnvironment& aEnvironment)
{
LispPtr * chk1 = oper->SubList();
if (!chk1)
throw LispErrInvalidArg();
LispPtr oper2((*chk1)->Nixed());
if (!oper2)
throw LispErrInvalidArg();
LispPtr body(oper2->Nixed());
if (!body)
throw LispErrInvalidArg();
LispPtr * chk2 = oper2->SubList();
if (!chk2 || !*chk2)
throw LispErrInvalidArg();
oper2 = ((*chk2)->Nixed());
LispLocalFrame frame(aEnvironment,false);
while (!!oper2) {
if (!args2)
throw LispErrInvalidArg();
LispString* var = oper2->String();
if (!var)
throw LispErrInvalidArg();
LispPtr newly(args2->Copy());
aEnvironment.NewLocal(var,newly);
oper2 = (oper2->Nixed());
args2 = (args2->Nixed());
}
if (args2)
throw LispErrInvalidArg();
aEnvironment.iEvaluator->Eval(aEnvironment, aResult, body);
}
void InternalEvalString(LispEnvironment& aEnvironment, LispPtr& aResult,
const LispChar* aString)
{
LispString full(aString);
full.push_back(';');
StringInput input(full,aEnvironment.iInputStatus);
LispPtr lispexpr;
LispTokenizer &tok = *aEnvironment.iCurrentTokenizer;
InfixParser parser(tok, input,
aEnvironment,
aEnvironment.PreFix(),
aEnvironment.InFix(),
aEnvironment.PostFix(),
aEnvironment.Bodied());
parser.Parse(lispexpr);
aEnvironment.iEvaluator->Eval(aEnvironment, aResult, lispexpr);
}
LispObject* operator+(const LispObjectAdder& left, const LispObjectAdder& right)
{
LispObject* trav = left.iPtr;
while (!!trav->Nixed())
{
trav = trav->Nixed();
}
trav->Nixed() = (right.iPtr);
return left.iPtr;
}
void ParseExpression(LispPtr& aResult, const LispChar* aString,LispEnvironment& aEnvironment)
{
LispString full(aString);
full.push_back(';');
StringInput input(full,aEnvironment.iInputStatus);
aEnvironment.iInputStatus.SetTo("String");
LispTokenizer &tok = *aEnvironment.iCurrentTokenizer;
InfixParser parser(tok,
input,
aEnvironment,
aEnvironment.PreFix(),
aEnvironment.InFix(),
aEnvironment.PostFix(),
aEnvironment.Bodied());
parser.Parse(aResult);
}
void ReturnUnEvaluated(LispPtr& aResult,LispPtr& aArguments,
LispEnvironment& aEnvironment)
{
LispPtr full(aArguments->Copy());
aResult = (LispSubList::New(full));
LispIterator iter(aArguments);
++iter;
while (iter.getObj())
{
LispPtr next;
aEnvironment.iEvaluator->Eval(aEnvironment, next, *iter);
full->Nixed() = (next);
full = (next);
++iter;
}
full->Nixed() = (nullptr);
}
void PrintExpression(LispString& aResult,
LispPtr& aExpression,
LispEnvironment& aEnvironment,
std::size_t aMaxChars)
{
aResult.clear();
StringOutput newOutput(aResult);
InfixPrinter infixprinter(aEnvironment.PreFix(),
aEnvironment.InFix(),
aEnvironment.PostFix(),
aEnvironment.Bodied());
infixprinter.Print(aExpression, newOutput, aEnvironment);
if (aMaxChars > 0 && aResult.size()>aMaxChars)
{
aResult.resize(aMaxChars - 3);
aResult += "...";
}
}
LispString* SymbolName(LispEnvironment& aEnvironment,
const LispChar * aSymbol)
{
if (aSymbol[0] == '\"')
return aEnvironment.HashTable().LookUpCounted(aSymbol + 1, std::strlen(aSymbol) - 2);
else
return aEnvironment.HashTable().LookUp(aSymbol);
}
<|endoftext|>
|
<commit_before>#include <v8.h>
#include "macros.h"
#include "gc.h"
#ifdef windows
# include <my_global.h>
#endif
#include <mysql.h>
#include <stdlib.h>
#include <string>
#define MYSQL_ERROR mysql_error(conn)
#define ASSERT_CONNECTED if (!conn) { return JS_EXCEPTION("No connection established yet."); }
#define MYSQL_PTR MYSQL * conn = LOAD_PTR(0, MYSQL *)
namespace {
v8::Persistent<v8::FunctionTemplate> rest;
void destroy(v8::Handle<v8::Object> obj) {
v8::Handle<v8::Function> fun = v8::Handle<v8::Function>::Cast(obj->Get(JS_STR("close")));
fun->Call(obj, 0, NULL);
}
v8::Handle<v8::Value> createResult(MYSQL * conn) {
MYSQL_RES * res = mysql_store_result(conn);
if (res) {
v8::Handle<v8::Value> resargs[] = { v8::External::New((void *) res) };
return rest->GetFunction()->NewInstance(1, resargs);
} else {
if (mysql_field_count(conn)) {
return JS_EXCEPTION(MYSQL_ERROR);
} else {
return JS_BOOL(true);
}
}
}
/**
* MySQL constructor does basically nothing. It just adds "this.close()" method to global GC
*/
JS_METHOD(_mysql) {
ASSERT_CONSTRUCTOR;
SAVE_PTR(0, NULL);
GC * gc = GC_PTR;
gc->add(args.This(), destroy);
return args.This();
}
/**
* Close DB connection
*/
JS_METHOD(_close) {
MYSQL_PTR;
if (conn) {
mysql_close(conn);
SAVE_PTR(0, NULL);
}
return args.This();
}
/**
* Should be called ASAP: new MySQL().connect("host", "user", "pass", "db")
*/
JS_METHOD(_connect) {
if (args.Length() < 4) {
return JS_EXCEPTION("Invalid call format. Use 'mysql.connect(host, user, pass, db)'");
}
MYSQL * conn;
v8::String::Utf8Value host(args[0]);
v8::String::Utf8Value user(args[1]);
v8::String::Utf8Value pass(args[2]);
v8::String::Utf8Value db(args[3]);
conn = mysql_init(NULL);
if (!mysql_real_connect(conn, *host, *user, *pass, *db, 0, NULL, CLIENT_MULTI_STATEMENTS)) {
return JS_EXCEPTION(MYSQL_ERROR);
} else {
mysql_query(conn, "SET NAMES 'utf8'");
SAVE_PTR(0, conn);
return args.This();
}
}
/**
* Query takes a string argument and returns an instance of Result object
*/
JS_METHOD(_query) {
MYSQL_PTR;
ASSERT_CONNECTED;
if (args.Length() < 1) {
return JS_EXCEPTION("No query specified");
}
v8::String::Utf8Value q(args[0]);
int code = mysql_real_query(conn, *q, q.length());
if (code != 0) { return JS_EXCEPTION(MYSQL_ERROR); }
int qc = args.This()->Get(JS_STR("queryCount"))->ToInteger()->Int32Value();
args.This()->Set(JS_STR("queryCount"), JS_INT(qc+1));
return createResult(conn);
}
/**
* Fetch next result from a multi-result set
*/
JS_METHOD(_nextresult) {
MYSQL_PTR;
ASSERT_CONNECTED;
int status = mysql_next_result(conn);
if (status == -1) { return JS_NULL; }
if (status > 0) { return JS_EXCEPTION(MYSQL_ERROR); }
return createResult(conn);
}
JS_METHOD(_affectedrows) {
MYSQL_PTR;
ASSERT_CONNECTED;
return JS_INT(mysql_affected_rows(conn));
}
JS_METHOD(_insertid) {
MYSQL_PTR;
ASSERT_CONNECTED;
return JS_INT(mysql_insert_id(conn));
}
JS_METHOD(_escape) {
MYSQL_PTR;
ASSERT_CONNECTED;
if (args.Length() < 1) {
return JS_EXCEPTION("Nothing to escape");
}
v8::String::Utf8Value str(args[0]);
int len = args[0]->ToString()->Utf8Length();
char * result = new char[2*len + 1];
int length = mysql_real_escape_string(conn, result, *str, len);
v8::Handle<v8::Value> output = JS_STR(result, length);
delete[] result;
return output;
}
JS_METHOD(_qualify) {
if (args.Length() < 1) {
return JS_EXCEPTION("Nothing to qualify");
}
v8::String::Utf8Value str(args[0]);
std::string result = "`";
result += *str;
result += "`";
v8::Handle<v8::Value> output = JS_STR(result.c_str());
return output;
}
JS_METHOD(_result) {
SAVE_VALUE(0, args[0]);
return args.This();
}
JS_METHOD(_numrows) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
return JS_INT(mysql_num_rows(res));
}
JS_METHOD(_numfields) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
return JS_INT(mysql_num_fields(res));
}
JS_METHOD(_fetchnames) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
int cnt = mysql_num_fields(res);
MYSQL_FIELD * fields = mysql_fetch_fields(res);
v8::Handle<v8::Array> result = v8::Array::New(cnt);
for(int i = 0; i < cnt; i++) {
result->Set(JS_INT(i), JS_STR(fields[i].name));
}
return result;
}
/**
* Return result data as an array of JS arrays
*/
JS_METHOD(_fetcharrays) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
mysql_data_seek(res, 0);
int x = mysql_num_fields(res);
int y = mysql_num_rows(res);
MYSQL_ROW row;
v8::Handle<v8::Array> result = v8::Array::New(y);
for (int i = 0; i < y; i++) {
row = mysql_fetch_row(res);
v8::Handle<v8::Array> item = v8::Array::New(x);
result->Set(JS_INT(i), item);
for (int j=0; j<x; j++) {
if (row[j] == NULL) {
item->Set(JS_INT(j), v8::Null());
} else {
item->Set(JS_INT(j), JS_STR(row[j]));
}
}
}
return result;
}
/**
* Return result data as an array of JS objects, indexed with column names
*/
JS_METHOD(_fetchobjects) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
mysql_data_seek(res, 0);
int x = mysql_num_fields(res);
int y = mysql_num_rows(res);
MYSQL_FIELD * fields = mysql_fetch_fields(res);
MYSQL_ROW row;
v8::Handle<v8::Array> result = v8::Array::New(y);
for (int i = 0; i < y; i++) {
row = mysql_fetch_row(res);
v8::Handle<v8::Object> item = v8::Object::New();
result->Set(JS_INT(i), item);
for (int j=0; j<x; j++) {
if (row[j] == NULL) {
item->Set(JS_STR(fields[j].name), v8::Null());
} else {
item->Set(JS_STR(fields[j].name), JS_STR(row[j]));
}
}
}
return result;
}
} /* end namespace */
SHARED_INIT() {
v8::HandleScope handle_scope;
v8::Handle<v8::FunctionTemplate> ft = v8::FunctionTemplate::New(_mysql);
ft->SetClassName(JS_STR("MySQL"));
v8::Handle<v8::ObjectTemplate> ot = ft->InstanceTemplate();
ot->SetInternalFieldCount(1); /* connection */
/**
* Static property, useful for stats gathering
*/
ot->Set(JS_STR("queryCount"), JS_INT(0));
v8::Handle<v8::ObjectTemplate> pt = ft->PrototypeTemplate();
/**
* MySQL prototype methods (new MySQL().*)
*/
pt->Set(JS_STR("connect"), v8::FunctionTemplate::New(_connect));
pt->Set(JS_STR("close"), v8::FunctionTemplate::New(_close));
pt->Set(JS_STR("query"), v8::FunctionTemplate::New(_query));
pt->Set(JS_STR("nextResult"), v8::FunctionTemplate::New(_nextresult));
pt->Set(JS_STR("affectedRows"), v8::FunctionTemplate::New(_affectedrows));
pt->Set(JS_STR("escape"), v8::FunctionTemplate::New(_escape));
pt->Set(JS_STR("qualify"), v8::FunctionTemplate::New(_qualify));
pt->Set(JS_STR("insertId"), v8::FunctionTemplate::New(_insertid));
rest = v8::Persistent<v8::FunctionTemplate>::New(v8::FunctionTemplate::New(_result));
rest->SetClassName(JS_STR("Result"));
v8::Handle<v8::ObjectTemplate> resinst = rest->InstanceTemplate();
resinst->SetInternalFieldCount(1);
v8::Handle<v8::ObjectTemplate> resproto = rest->PrototypeTemplate();
/**
* Result prototype methods (new MySQL().query().*)
*/
resproto->Set(JS_STR("numRows"), v8::FunctionTemplate::New(_numrows));
resproto->Set(JS_STR("numFields"), v8::FunctionTemplate::New(_numfields));
resproto->Set(JS_STR("fetchNames"), v8::FunctionTemplate::New(_fetchnames));
resproto->Set(JS_STR("fetchArrays"), v8::FunctionTemplate::New(_fetcharrays));
resproto->Set(JS_STR("fetchObjects"), v8::FunctionTemplate::New(_fetchobjects));
exports->Set(JS_STR("MySQL"), ft->GetFunction());
}
<commit_msg>mysql result close()<commit_after>#include <v8.h>
#include "macros.h"
#include "gc.h"
#ifdef windows
# include <my_global.h>
#endif
#include <mysql.h>
#include <stdlib.h>
#include <string>
#define MYSQL_ERROR mysql_error(conn)
#define ASSERT_CONNECTED if (!conn) { return JS_EXCEPTION("No connection established yet."); }
#define MYSQL_PTR MYSQL * conn = LOAD_PTR(0, MYSQL *)
namespace {
v8::Persistent<v8::FunctionTemplate> rest;
void destroy(v8::Handle<v8::Object> obj) {
v8::Handle<v8::Function> fun = v8::Handle<v8::Function>::Cast(obj->Get(JS_STR("close")));
fun->Call(obj, 0, NULL);
}
v8::Handle<v8::Value> createResult(MYSQL * conn) {
MYSQL_RES * res = mysql_store_result(conn);
if (res) {
v8::Handle<v8::Value> resargs[] = { v8::External::New((void *) res) };
return rest->GetFunction()->NewInstance(1, resargs);
} else {
if (mysql_field_count(conn)) {
return JS_EXCEPTION(MYSQL_ERROR);
} else {
return JS_BOOL(true);
}
}
}
/**
* MySQL constructor does basically nothing. It just adds "this.close()" method to global GC
*/
JS_METHOD(_mysql) {
ASSERT_CONSTRUCTOR;
SAVE_PTR(0, NULL);
GC * gc = GC_PTR;
gc->add(args.This(), destroy);
return args.This();
}
/**
* Close DB connection
*/
JS_METHOD(_close) {
MYSQL_PTR;
if (conn) {
mysql_close(conn);
SAVE_PTR(0, NULL);
}
return args.This();
}
/**
* Should be called ASAP: new MySQL().connect("host", "user", "pass", "db")
*/
JS_METHOD(_connect) {
if (args.Length() < 4) {
return JS_EXCEPTION("Invalid call format. Use 'mysql.connect(host, user, pass, db)'");
}
MYSQL * conn;
v8::String::Utf8Value host(args[0]);
v8::String::Utf8Value user(args[1]);
v8::String::Utf8Value pass(args[2]);
v8::String::Utf8Value db(args[3]);
conn = mysql_init(NULL);
if (!mysql_real_connect(conn, *host, *user, *pass, *db, 0, NULL, CLIENT_MULTI_STATEMENTS)) {
return JS_EXCEPTION(MYSQL_ERROR);
} else {
mysql_query(conn, "SET NAMES 'utf8'");
SAVE_PTR(0, conn);
return args.This();
}
}
/**
* Query takes a string argument and returns an instance of Result object
*/
JS_METHOD(_query) {
MYSQL_PTR;
ASSERT_CONNECTED;
if (args.Length() < 1) {
return JS_EXCEPTION("No query specified");
}
v8::String::Utf8Value q(args[0]);
int code = mysql_real_query(conn, *q, q.length());
if (code != 0) { return JS_EXCEPTION(MYSQL_ERROR); }
int qc = args.This()->Get(JS_STR("queryCount"))->ToInteger()->Int32Value();
args.This()->Set(JS_STR("queryCount"), JS_INT(qc+1));
return createResult(conn);
}
/**
* Fetch next result from a multi-result set
*/
JS_METHOD(_nextresult) {
MYSQL_PTR;
ASSERT_CONNECTED;
int status = mysql_next_result(conn);
if (status == -1) { return JS_NULL; }
if (status > 0) { return JS_EXCEPTION(MYSQL_ERROR); }
return createResult(conn);
}
JS_METHOD(_affectedrows) {
MYSQL_PTR;
ASSERT_CONNECTED;
return JS_INT(mysql_affected_rows(conn));
}
JS_METHOD(_insertid) {
MYSQL_PTR;
ASSERT_CONNECTED;
return JS_INT(mysql_insert_id(conn));
}
JS_METHOD(_escape) {
MYSQL_PTR;
ASSERT_CONNECTED;
if (args.Length() < 1) {
return JS_EXCEPTION("Nothing to escape");
}
v8::String::Utf8Value str(args[0]);
int len = args[0]->ToString()->Utf8Length();
char * result = new char[2*len + 1];
int length = mysql_real_escape_string(conn, result, *str, len);
v8::Handle<v8::Value> output = JS_STR(result, length);
delete[] result;
return output;
}
JS_METHOD(_qualify) {
if (args.Length() < 1) {
return JS_EXCEPTION("Nothing to qualify");
}
v8::String::Utf8Value str(args[0]);
std::string result = "`";
result += *str;
result += "`";
v8::Handle<v8::Value> output = JS_STR(result.c_str());
return output;
}
JS_METHOD(_result) {
SAVE_VALUE(0, args[0]);
return args.This();
}
JS_METHOD(_numrows) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
return JS_INT(mysql_num_rows(res));
}
JS_METHOD(_numfields) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
return JS_INT(mysql_num_fields(res));
}
JS_METHOD(_fetchnames) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
int cnt = mysql_num_fields(res);
MYSQL_FIELD * fields = mysql_fetch_fields(res);
v8::Handle<v8::Array> result = v8::Array::New(cnt);
for(int i = 0; i < cnt; i++) {
result->Set(JS_INT(i), JS_STR(fields[i].name));
}
return result;
}
/**
* Return result data as an array of JS arrays
*/
JS_METHOD(_fetcharrays) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
mysql_data_seek(res, 0);
int x = mysql_num_fields(res);
int y = mysql_num_rows(res);
MYSQL_ROW row;
v8::Handle<v8::Array> result = v8::Array::New(y);
for (int i = 0; i < y; i++) {
row = mysql_fetch_row(res);
v8::Handle<v8::Array> item = v8::Array::New(x);
result->Set(JS_INT(i), item);
for (int j=0; j<x; j++) {
if (row[j] == NULL) {
item->Set(JS_INT(j), v8::Null());
} else {
item->Set(JS_INT(j), JS_STR(row[j]));
}
}
}
return result;
}
/**
* Return result data as an array of JS objects, indexed with column names
*/
JS_METHOD(_fetchobjects) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
mysql_data_seek(res, 0);
int x = mysql_num_fields(res);
int y = mysql_num_rows(res);
MYSQL_FIELD * fields = mysql_fetch_fields(res);
MYSQL_ROW row;
v8::Handle<v8::Array> result = v8::Array::New(y);
for (int i = 0; i < y; i++) {
row = mysql_fetch_row(res);
v8::Handle<v8::Object> item = v8::Object::New();
result->Set(JS_INT(i), item);
for (int j=0; j<x; j++) {
if (row[j] == NULL) {
item->Set(JS_STR(fields[j].name), v8::Null());
} else {
item->Set(JS_STR(fields[j].name), JS_STR(row[j]));
}
}
}
return result;
}
JS_METHOD(_result_close) {
MYSQL_RES * res = LOAD_PTR(0, MYSQL_RES *);
if (res) {
mysql_free_result(res);
SAVE_PTR(0, NULL);
return JS_BOOL(true);
} else {
return JS_BOOL(false);
}
}
} /* end namespace */
SHARED_INIT() {
v8::HandleScope handle_scope;
v8::Handle<v8::FunctionTemplate> ft = v8::FunctionTemplate::New(_mysql);
ft->SetClassName(JS_STR("MySQL"));
v8::Handle<v8::ObjectTemplate> ot = ft->InstanceTemplate();
ot->SetInternalFieldCount(1); /* connection */
/**
* Static property, useful for stats gathering
*/
ot->Set(JS_STR("queryCount"), JS_INT(0));
v8::Handle<v8::ObjectTemplate> pt = ft->PrototypeTemplate();
/**
* MySQL prototype methods (new MySQL().*)
*/
pt->Set(JS_STR("connect"), v8::FunctionTemplate::New(_connect));
pt->Set(JS_STR("close"), v8::FunctionTemplate::New(_close));
pt->Set(JS_STR("query"), v8::FunctionTemplate::New(_query));
pt->Set(JS_STR("nextResult"), v8::FunctionTemplate::New(_nextresult));
pt->Set(JS_STR("affectedRows"), v8::FunctionTemplate::New(_affectedrows));
pt->Set(JS_STR("escape"), v8::FunctionTemplate::New(_escape));
pt->Set(JS_STR("qualify"), v8::FunctionTemplate::New(_qualify));
pt->Set(JS_STR("insertId"), v8::FunctionTemplate::New(_insertid));
rest = v8::Persistent<v8::FunctionTemplate>::New(v8::FunctionTemplate::New(_result));
rest->SetClassName(JS_STR("Result"));
v8::Handle<v8::ObjectTemplate> resinst = rest->InstanceTemplate();
resinst->SetInternalFieldCount(1);
v8::Handle<v8::ObjectTemplate> resproto = rest->PrototypeTemplate();
/**
* Result prototype methods (new MySQL().query().*)
*/
resproto->Set(JS_STR("numRows"), v8::FunctionTemplate::New(_numrows));
resproto->Set(JS_STR("numFields"), v8::FunctionTemplate::New(_numfields));
resproto->Set(JS_STR("fetchNames"), v8::FunctionTemplate::New(_fetchnames));
resproto->Set(JS_STR("fetchArrays"), v8::FunctionTemplate::New(_fetcharrays));
resproto->Set(JS_STR("fetchObjects"), v8::FunctionTemplate::New(_fetchobjects));
resproto->Set(JS_STR("close"), v8::FunctionTemplate::New(_result_close));
exports->Set(JS_STR("MySQL"), ft->GetFunction());
}
<|endoftext|>
|
<commit_before>#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "naivebayes.h"
std::tuple<std::vector<NB::Event>, std::vector<NB::label_t>>
load_data(const std::string &filename, const std::size_t num_features) {
std::vector<NB::Event> events;
std::vector<NB::label_t> labels;
std::vector<NB::number_t> features(num_features);
NB::label_t label;
std::ifstream ifs(filename);
while (ifs.good()) {
for (std::size_t f = 0; f < num_features; f++) {
ifs >> features[f];
}
ifs >> label;
events.push_back(NB::Event{features});
labels.push_back(label);
}
ifs.close();
return std::make_tuple(events, labels);
}
int main(int argc, char *argv[]) {
if (argc < 4) {
std::cerr << "Usage: " << argv[0] << " N train predict" << std::endl
<< " N - number of features" << std::endl
<< " train - path to the training data sample" << std::endl
<< " predict - path to the data sample to be predicted"
<< std::endl;
return EXIT_FAILURE;
}
const size_t num_features = std::stoul(argv[1]);
const std::string filename_train = std::string(argv[2]),
filename_predict = std::string(argv[3]);
NB::NaiveBayes nb(num_features);
std::vector<NB::Event> events;
std::vector<NB::label_t> labels;
// Training
std::tie(events, labels) = load_data(filename_train, num_features);
nb.train(events, labels);
// Testing (write results to file, actual evaluation is done via Python)
std::tie(events, labels) = load_data(filename_predict, num_features);
for (const auto &e : events) {
std::cout << nb.predict(e) << std::endl;
}
}
<commit_msg>Update main.cc<commit_after>#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "naivebayes.h"
std::tuple<std::vector<NB::Event>, std::vector<NB::label_t>>
load_data(const std::string &filename, const std::size_t num_features) {
std::vector<NB::Event> events;
std::vector<NB::label_t> labels;
std::vector<NB::number_t> features(num_features);
NB::label_t label;
std::ifstream ifs(filename);
while (ifs.good()) {
for (std::size_t f = 0; f < num_features; f++) {
ifs >> features[f];
}
ifs >> label;
events.push_back(NB::Event{features});
labels.push_back(label);
}
ifs.close();
return std::make_tuple(events, labels);
}
int main(int argc, char *argv[]) {
if (argc < 4) {
std::cerr << "Usage: " << argv[0] << " N train predict" << std::endl
<< " N - number of features" << std::endl
<< " train - path to the training data sample" << std::endl
<< " predict - path to the data sample to be predicted"
<< std::endl;
return EXIT_FAILURE;
}
const size_t num_features = std::stoul(argv[1]);
const std::string filename_train = std::string(argv[2]),
filename_predict = std::string(argv[3]);
NB::NaiveBayes nb(num_features);
std::vector<NB::Event> events;
std::vector<NB::label_t> labels;
// Training
std::tie(events, labels) = load_data(filename_train, num_features);
nb.train(events, labels);
// Prediction
std::tie(events, labels) = load_data(filename_predict, num_features);
for (const auto &e : events) {
std::cout << nb.predict(e) << std::endl;
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by MIT license that can be found in the
// LICENSE file.
#include <string.h>
#include <stdlib.h>
#include "rescle.h"
bool print_error(const char* message) {
fprintf(stderr, "Fatal error: %s\n", message);
return 1;
}
bool parse_version_string(const wchar_t* str, int *v1, int *v2, int *v3, int *v4) {
*v1 = *v2 = *v3 = *v4 = 0;
if (swscanf_s(str, L"%d.%d.%d.%d", v1, v2, v3, v4) == 4)
return true;
if (swscanf_s(str, L"%d.%d.%d", v1, v2, v3) == 3)
return true;
if (swscanf_s(str, L"%d.%d", v1, v2) == 2)
return true;
if (swscanf_s(str, L"%d", v1) == 1)
return true;
return false;
}
int wmain(int argc, const wchar_t* argv[]) {
bool loaded = false;
rescle::ResourceUpdater updater;
for (int i = 1; i < argc; ++i) {
if (wcscmp(argv[i], L"--set-version-string") == 0 ||
wcscmp(argv[i], L"-svs") == 0) {
if (argc - i < 3)
return print_error("--set-version-string requires 'Key' and 'Value'");
const wchar_t* key = argv[++i];
const wchar_t* value = argv[++i];
if (!updater.ChangeVersionString(key, value))
return print_error("Unable to change version string");
} else if (wcscmp(argv[i], L"--set-file-version") == 0 ||
wcscmp(argv[i], L"-sfv") == 0) {
if (argc - i < 2)
return print_error("--set-file-version requires a version string");
int v1, v2, v3, v4;
if (!parse_version_string(argv[++i], &v1, &v2, &v3, &v4))
return print_error("Unable to parse version string");
if (!updater.ChangeVersionFileVersion(v1, v2, v3, v4))
return print_error("Unable to change file version");
} else if (wcscmp(argv[i], L"--set-product-version") == 0 ||
wcscmp(argv[i], L"-spv") == 0) {
if (argc - i < 2)
return print_error("--set-product-version requires a version string");
int v1, v2, v3, v4;
if (!parse_version_string(argv[++i], &v1, &v2, &v3, &v4))
return print_error("Unable to parse version string");
if (!updater.ChangeVersionProductVersion(v1, v2, v3, v4))
return print_error("Unable to change product version");
} else {
if (loaded)
return print_error("Unexpected trailing arguments");
loaded = true;
if (!updater.Load(argv[i]))
return print_error("Unable to load file");
}
}
if (!loaded)
return print_error("You should specify a exe/dll file");
if (!updater.Commit())
return print_error("Unable to commit changes");
return 0;
}
<commit_msg>Also set version string when setting file version and product version.<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by MIT license that can be found in the
// LICENSE file.
#include <string.h>
#include <stdlib.h>
#include "rescle.h"
bool print_error(const char* message) {
fprintf(stderr, "Fatal error: %s\n", message);
return 1;
}
bool parse_version_string(const wchar_t* str, int *v1, int *v2, int *v3, int *v4) {
*v1 = *v2 = *v3 = *v4 = 0;
if (swscanf_s(str, L"%d.%d.%d.%d", v1, v2, v3, v4) == 4)
return true;
if (swscanf_s(str, L"%d.%d.%d", v1, v2, v3) == 3)
return true;
if (swscanf_s(str, L"%d.%d", v1, v2) == 2)
return true;
if (swscanf_s(str, L"%d", v1) == 1)
return true;
return false;
}
int wmain(int argc, const wchar_t* argv[]) {
bool loaded = false;
rescle::ResourceUpdater updater;
for (int i = 1; i < argc; ++i) {
if (wcscmp(argv[i], L"--set-version-string") == 0 ||
wcscmp(argv[i], L"-svs") == 0) {
if (argc - i < 3)
return print_error("--set-version-string requires 'Key' and 'Value'");
const wchar_t* key = argv[++i];
const wchar_t* value = argv[++i];
if (!updater.ChangeVersionString(key, value))
return print_error("Unable to change version string");
} else if (wcscmp(argv[i], L"--set-file-version") == 0 ||
wcscmp(argv[i], L"-sfv") == 0) {
if (argc - i < 2)
return print_error("--set-file-version requires a version string");
int v1, v2, v3, v4;
if (!parse_version_string(argv[++i], &v1, &v2, &v3, &v4))
return print_error("Unable to parse version string");
if (!updater.ChangeVersionFileVersion(v1, v2, v3, v4))
return print_error("Unable to change file version");
if (!updater.ChangeVersionString(L"FileVersion", argv[i]))
return print_error("Unable to change FileVersion string");
} else if (wcscmp(argv[i], L"--set-product-version") == 0 ||
wcscmp(argv[i], L"-spv") == 0) {
if (argc - i < 2)
return print_error("--set-product-version requires a version string");
int v1, v2, v3, v4;
if (!parse_version_string(argv[++i], &v1, &v2, &v3, &v4))
return print_error("Unable to parse version string");
if (!updater.ChangeVersionFileVersion(v1, v2, v3, v4))
return print_error("Unable to change file version");
if (!updater.ChangeVersionString(L"ProductVersion", argv[i]))
return print_error("Unable to change ProductVersion string");
} else {
if (loaded)
return print_error("Unexpected trailing arguments");
loaded = true;
if (!updater.Load(argv[i]))
return print_error("Unable to load file");
}
}
if (!loaded)
return print_error("You should specify a exe/dll file");
if (!updater.Commit())
return print_error("Unable to commit changes");
return 0;
}
<|endoftext|>
|
<commit_before>// RUN: %clang_cc1 -fsyntax-only -verify -Wno-array-bounds %s -fpascal-strings
void consume(const char* c) {}
void consume(const unsigned char* c) {}
void consume(const wchar_t* c) {}
void consumeChar(char c) {}
enum MyEnum {
kMySmallEnum = 1,
kMyEnum = 5
};
enum OperatorOverloadEnum {
kMyOperatorOverloadedEnum = 5
};
const char* operator+(const char* c, OperatorOverloadEnum e) {
return "yo";
}
const char* operator+(OperatorOverloadEnum e, const char* c) {
return "yo";
}
void f(int index) {
// Should warn.
consume("foo" + 5); // expected-warning {{adding 'int' to a string does not append to the string}} expected-note {{use array indexing to silence this warning}}
consume("foo" + index); // expected-warning {{adding 'int' to a string does not append to the string}} expected-note {{use array indexing to silence this warning}}
consume("foo" + kMyEnum); // expected-warning {{adding 'MyEnum' to a string does not append to the string}} expected-note {{use array indexing to silence this warning}}
consume(5 + "foo"); // expected-warning {{adding 'int' to a string does not append to the string}} expected-note {{use array indexing to silence this warning}}
consume(index + "foo"); // expected-warning {{adding 'int' to a string does not append to the string}} expected-note {{use array indexing to silence this warning}}
consume(kMyEnum + "foo"); // expected-warning {{adding 'MyEnum' to a string does not append to the string}} expected-note {{use array indexing to silence this warning}}
// FIXME: suggest replacing with "foo"[5]
consumeChar(*("foo" + 5)); // expected-warning {{adding 'int' to a string does not append to the string}} expected-note {{use array indexing to silence this warning}}
consumeChar(*(5 + "foo")); // expected-warning {{adding 'int' to a string does not append to the string}} expected-note {{use array indexing to silence this warning}}
consume(L"foo" + 5); // expected-warning {{adding 'int' to a string does not append to the string}} expected-note {{use array indexing to silence this warning}}
// Should not warn.
consume(&("foo"[3]));
consume(&("foo"[index]));
consume(&("foo"[kMyEnum]));
consume("foo" + kMySmallEnum);
consume(kMySmallEnum + "foo");
consume(L"foo" + 2);
consume("foo" + 3); // Points at the \0
consume("foo" + 4); // Points 1 past the \0, which is legal too.
consume("\pfoo" + 4); // Pascal strings don't have a trailing \0, but they
// have a leading length byte, so this is fine too.
consume("foo" + kMyOperatorOverloadedEnum);
consume(kMyOperatorOverloadedEnum + "foo");
#define A "foo"
#define B "bar"
consume(A B + sizeof(A) - 1);
}
<commit_msg>Add a test for the -Wstring-plus-int fixit note.<commit_after>// RUN: %clang_cc1 -fsyntax-only -verify -Wno-array-bounds %s -fpascal-strings
// RUN: %clang_cc1 -fdiagnostics-parseable-fixits -x c++ %s 2>&1 -Wno-array-bounds -fpascal-strings | FileCheck %s
void consume(const char* c) {}
void consume(const unsigned char* c) {}
void consume(const wchar_t* c) {}
void consumeChar(char c) {}
enum MyEnum {
kMySmallEnum = 1,
kMyEnum = 5
};
enum OperatorOverloadEnum {
kMyOperatorOverloadedEnum = 5
};
const char* operator+(const char* c, OperatorOverloadEnum e) {
return "yo";
}
const char* operator+(OperatorOverloadEnum e, const char* c) {
return "yo";
}
void f(int index) {
// Should warn.
// CHECK: fix-it:"{{.*}}":{31:11-31:11}:"&"
// CHECK: fix-it:"{{.*}}":{31:17-31:18}:"["
// CHECK: fix-it:"{{.*}}":{31:20-31:20}:"]"
consume("foo" + 5); // expected-warning {{adding 'int' to a string does not append to the string}} expected-note {{use array indexing to silence this warning}}
consume("foo" + index); // expected-warning {{adding 'int' to a string does not append to the string}} expected-note {{use array indexing to silence this warning}}
consume("foo" + kMyEnum); // expected-warning {{adding 'MyEnum' to a string does not append to the string}} expected-note {{use array indexing to silence this warning}}
consume(5 + "foo"); // expected-warning {{adding 'int' to a string does not append to the string}} expected-note {{use array indexing to silence this warning}}
consume(index + "foo"); // expected-warning {{adding 'int' to a string does not append to the string}} expected-note {{use array indexing to silence this warning}}
consume(kMyEnum + "foo"); // expected-warning {{adding 'MyEnum' to a string does not append to the string}} expected-note {{use array indexing to silence this warning}}
// FIXME: suggest replacing with "foo"[5]
consumeChar(*("foo" + 5)); // expected-warning {{adding 'int' to a string does not append to the string}} expected-note {{use array indexing to silence this warning}}
consumeChar(*(5 + "foo")); // expected-warning {{adding 'int' to a string does not append to the string}} expected-note {{use array indexing to silence this warning}}
consume(L"foo" + 5); // expected-warning {{adding 'int' to a string does not append to the string}} expected-note {{use array indexing to silence this warning}}
// Should not warn.
consume(&("foo"[3]));
consume(&("foo"[index]));
consume(&("foo"[kMyEnum]));
consume("foo" + kMySmallEnum);
consume(kMySmallEnum + "foo");
consume(L"foo" + 2);
consume("foo" + 3); // Points at the \0
consume("foo" + 4); // Points 1 past the \0, which is legal too.
consume("\pfoo" + 4); // Pascal strings don't have a trailing \0, but they
// have a leading length byte, so this is fine too.
consume("foo" + kMyOperatorOverloadedEnum);
consume(kMyOperatorOverloadedEnum + "foo");
#define A "foo"
#define B "bar"
consume(A B + sizeof(A) - 1);
}
<|endoftext|>
|
<commit_before>#include "gtest/gtest.h"
#include "DiceRoll/Operations/RollResult.h"
#include "DiceRoll/Operations/RepeatOperation.h"
#include "DiceRoll/Operations/RandomOperation.hpp"
class MockOperation : public IOperation
{
std::unique_ptr<RollResult> execute()
{ return std::make_unique<RollResult>(); }
public:
static int count;
MockOperation(): IOperation(nullptr){};
// For each evaluate() static int count is incrementing.
std::unique_ptr<RollResult> evaluate()
{
auto result = std::make_unique<RollResult>();
result->setFullResult(std::to_string(++count));
result->setShortResult(count);
return result;
}
};
int MockOperation::count = 0;
MockOperation baseOp;
// Test to check if repeating even works (without the same result).
TEST(RepeatOperationTest, EvaluateWithPositiveCount)
{
MockOperation::count = 0;
RepeatOperation repeatOp(&baseOp , 3);
auto result = repeatOp.evaluate();
EXPECT_EQ("(1 2 3)", result->getFullResult());
EXPECT_EQ(std::vector<int>({1, 2, 3}), result->getShortResult());
EXPECT_FALSE(result->hasErrors());
}
TEST(RepeatOperationTest, CantInitializeWithCountLowerThan2)
{
MockOperation::count = 0;
ASSERT_ANY_THROW(RepeatOperation(&baseOp, 1));
ASSERT_ANY_THROW(RepeatOperation(&baseOp, -1));
}
TEST(RepeatOperationTest, RepeatRandomOperation)
{
RandomOperation op(10);
RepeatOperation repeatOp(&op, 100);
auto result = repeatOp.evaluate();
ASSERT_EQ(100, result->getShortResultSize());
for(auto item: result->getShortResult()) {
EXPECT_GE(item, 1);
EXPECT_LE(item, 10);
}
}
//TODO: Add test that makes sure that RepeatOperation won't work on
// multiple value operation, just singular value.
TEST(RepeatOperationTest, CanRepeatRepeatOperation)
{
MockOperation::count = 0;
RepeatOperation repOp(&baseOp, 3);
ASSERT_NO_THROW(RepeatOperation(&repOp, 3));
RepeatOperation repOpFinal = RepeatOperation(&repOp, 3);
auto result = repOpFinal.evaluate();
EXPECT_EQ(result->getFullResult(), "((1 2 3) (4 5 6) (7 8 9))");
EXPECT_EQ(result->getShortResult(),
std::vector<int>({1, 2, 3, 4, 5, 6, 7, 8, 9}));
}
<commit_msg>Removed obsolete comment.<commit_after>#include "gtest/gtest.h"
#include "DiceRoll/Operations/RollResult.h"
#include "DiceRoll/Operations/RepeatOperation.h"
#include "DiceRoll/Operations/RandomOperation.hpp"
class MockOperation : public IOperation
{
std::unique_ptr<RollResult> execute()
{ return std::make_unique<RollResult>(); }
public:
static int count;
MockOperation(): IOperation(nullptr){};
// For each evaluate() static int count is incrementing.
std::unique_ptr<RollResult> evaluate()
{
auto result = std::make_unique<RollResult>();
result->setFullResult(std::to_string(++count));
result->setShortResult(count);
return result;
}
};
int MockOperation::count = 0;
MockOperation baseOp;
// Test to check if repeating even works (without the same result).
TEST(RepeatOperationTest, EvaluateWithPositiveCount)
{
MockOperation::count = 0;
RepeatOperation repeatOp(&baseOp , 3);
auto result = repeatOp.evaluate();
EXPECT_EQ("(1 2 3)", result->getFullResult());
EXPECT_EQ(std::vector<int>({1, 2, 3}), result->getShortResult());
EXPECT_FALSE(result->hasErrors());
}
TEST(RepeatOperationTest, CantInitializeWithCountLowerThan2)
{
MockOperation::count = 0;
ASSERT_ANY_THROW(RepeatOperation(&baseOp, 1));
ASSERT_ANY_THROW(RepeatOperation(&baseOp, -1));
}
TEST(RepeatOperationTest, RepeatRandomOperation)
{
RandomOperation op(10);
RepeatOperation repeatOp(&op, 100);
auto result = repeatOp.evaluate();
ASSERT_EQ(100, result->getShortResultSize());
for(auto item: result->getShortResult()) {
EXPECT_GE(item, 1);
EXPECT_LE(item, 10);
}
}
TEST(RepeatOperationTest, CanRepeatRepeatOperation)
{
MockOperation::count = 0;
RepeatOperation repOp(&baseOp, 3);
ASSERT_NO_THROW(RepeatOperation(&repOp, 3));
RepeatOperation repOpFinal = RepeatOperation(&repOp, 3);
auto result = repOpFinal.evaluate();
EXPECT_EQ(result->getFullResult(), "((1 2 3) (4 5 6) (7 8 9))");
EXPECT_EQ(result->getShortResult(),
std::vector<int>({1, 2, 3, 4, 5, 6, 7, 8, 9}));
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2016 Nu-book Inc.
* Copyright 2017 Axel Waggershauser
*
* 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 "ByteArray.h"
#include "BlackboxTestRunner.h"
#include "ImageLoader.h"
#include "MultiFormatReader.h"
#include "Result.h"
#include "BinaryBitmap.h"
#include "ImageLoader.h"
#include "DecodeHints.h"
#include "TextUtfEncoding.h"
#include "ZXContainerAlgorithms.h"
#include "ZXFilesystem.h"
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <fstream>
#include <set>
using namespace ZXing;
using namespace ZXing::Test;
int getEnv(const char* name, int fallback = 0)
{
auto var = getenv(name);
return var ? atoi(var) : fallback;
}
int main(int argc, char** argv)
{
if (argc <= 1) {
std::cout << "Usage: " << argv[0] << " <test_path_prefix>" << std::endl;
return 0;
}
fs::path pathPrefix = argv[1];
if (Contains({".png", ".jpg", ".pgm", ".gif"}, pathPrefix.extension())) {
auto hints = DecodeHints().setTryHarder(true).setTryRotate(true).setIsPure(getEnv("IS_PURE"));
// hints.setFormats(BarcodeFormat::QR_CODE);
MultiFormatReader reader(hints);
int rotation = getEnv("ROTATION");
for (int i = 1; i < argc; ++i) {
Result result = reader.read(*ImageLoader::load(argv[i]).rotated(rotation));
std::cout << argv[i] << ": ";
if (result.isValid())
std::cout << ToString(result.format()) << ": " << TextUtfEncoding::ToUtf8(result.text()) << " " << metadataToUtf8(result) << "\n";
else
std::cout << "FAILED\n";
if (result.isValid() && getenv("WRITE_TEXT")) {
std::ofstream f(fs::path(argv[i]).replace_extension(".txt"));
f << TextUtfEncoding::ToUtf8(result.text());
}
}
return 0;
} else {
std::set<std::string> includedTests;
for (int i = 2; i < argc; ++i) {
if (std::strlen(argv[i]) > 2 && argv[i][0] == '-' && argv[i][1] == 't') {
includedTests.insert(argv[i] + 2);
}
}
return runBlackBoxTests(pathPrefix, includedTests);
}
}
<commit_msg>TestReader: allow setting Formats from environment variable<commit_after>/*
* Copyright 2016 Nu-book Inc.
* Copyright 2017 Axel Waggershauser
*
* 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 "ByteArray.h"
#include "BlackboxTestRunner.h"
#include "ImageLoader.h"
#include "MultiFormatReader.h"
#include "Result.h"
#include "BinaryBitmap.h"
#include "ImageLoader.h"
#include "DecodeHints.h"
#include "TextUtfEncoding.h"
#include "ZXContainerAlgorithms.h"
#include "ZXFilesystem.h"
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <fstream>
#include <set>
using namespace ZXing;
using namespace ZXing::Test;
int getEnv(const char* name, int fallback = 0)
{
auto var = getenv(name);
return var ? atoi(var) : fallback;
}
int main(int argc, char** argv)
{
if (argc <= 1) {
std::cout << "Usage: " << argv[0] << " <test_path_prefix>" << std::endl;
return 0;
}
fs::path pathPrefix = argv[1];
if (Contains({".png", ".jpg", ".pgm", ".gif"}, pathPrefix.extension())) {
auto hints = DecodeHints().setTryHarder(true).setTryRotate(true).setIsPure(getEnv("IS_PURE"));
if (getenv("FORMATS"))
hints.setFormats(BarcodeFormatsFromString(getenv("FORMATS")));
MultiFormatReader reader(hints);
int rotation = getEnv("ROTATION");
for (int i = 1; i < argc; ++i) {
Result result = reader.read(*ImageLoader::load(argv[i]).rotated(rotation));
std::cout << argv[i] << ": ";
if (result.isValid())
std::cout << ToString(result.format()) << ": " << TextUtfEncoding::ToUtf8(result.text()) << " " << metadataToUtf8(result) << "\n";
else
std::cout << "FAILED\n";
if (result.isValid() && getenv("WRITE_TEXT")) {
std::ofstream f(fs::path(argv[i]).replace_extension(".txt"));
f << TextUtfEncoding::ToUtf8(result.text());
}
}
return 0;
} else {
std::set<std::string> includedTests;
for (int i = 2; i < argc; ++i) {
if (std::strlen(argv[i]) > 2 && argv[i][0] == '-' && argv[i][1] == 't') {
includedTests.insert(argv[i] + 2);
}
}
return runBlackBoxTests(pathPrefix, includedTests);
}
}
<|endoftext|>
|
<commit_before>//===-- ipcd.cpp ----------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implements IPCD interface, communicates with ipcd via control socket
//
//===----------------------------------------------------------------------===//
#include "ipcd.h"
#include "debug.h"
#include "real.h"
#include "rename_fd.h"
#include "magic_socket_nums.h"
#include "lock.h"
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
static int ipcd_socket = 0;
static int mypid = 0;
// Must match that used by server,
// currently defined in ipcd/clients.go
const char *SOCK_PATH = "/tmp/ipcd.sock";
const char *IPCD_BIN_PATH = "/bin/ipcd";
const useconds_t SLEEP_AFTER_IPCD_START_INTERVAL = 10 * 1000; // 10ms?
SimpleLock &getConnectLock() {
static SimpleLock ConnectLock;
return ConnectLock;
}
bool we_are_ipcd;
void check_if_we_are_ipcd() {
// man 3 program_invocation_name
extern char *program_invocation_short_name;
assert(program_invocation_short_name);
ipclog("program_invocation_short_name: %s\n", program_invocation_short_name);
we_are_ipcd = strcmp("ipcd", program_invocation_short_name) == 0;
}
void start_ipcd() {
int d = daemon(0, 0);
if (d == -1) {
perror("Failed to daemonize");
exit(1);
}
execl(IPCD_BIN_PATH, IPCD_BIN_PATH, (char *)NULL);
perror("Failed to exec ipcd");
exit(1);
}
void fork_ipcd() {
switch (__real_fork()) {
case -1:
break;
case 0:
// Child
start_ipcd();
assert(0 && "Exec failed?");
break;
default:
// Wait for ipcd to start :P
ipclog("Starting ipcd...\n");
}
}
void connect_to_ipcd() {
int s, len;
struct sockaddr_un remote;
if ((s = __real_socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)) == -1) {
perror("socket");
exit(1);
}
bool rename_success = rename_fd(s, MAGIC_SOCKET_FD, /* cloexec */ true);
assert(rename_success);
s = MAGIC_SOCKET_FD;
remote.sun_family = AF_UNIX;
strcpy(remote.sun_path, SOCK_PATH);
len = strlen(remote.sun_path) + sizeof(remote.sun_family);
if (__real_connect(s, (struct sockaddr *)&remote, len) == -1) {
// XXX: Super kludge!
// If we can't connect to daemon, assume it hasn't been
// started yet and attempt to run it ourselves.
// This code is terrible, and is likely to break
// badly in many situations, but works for now.
if (errno == ENOENT || errno == ECONNREFUSED) {
fork_ipcd();
int attempts = 0;
const int MAX_ATTEMPTS = 10;
while (attempts < MAX_ATTEMPTS) {
usleep(SLEEP_AFTER_IPCD_START_INTERVAL);
if (__real_connect(s, (struct sockaddr *)&remote, len) != -1)
break;
++attempts;
}
if (attempts == MAX_ATTEMPTS) {
perror("Unable to connect to ipcd after attempting to start it");
exit(1);
}
} else {
perror("connect");
ipclog("Error connecting to ipcd?\n");
exit(1);
}
}
ipclog("Connected to IPCD, fd=%d\n", s);
mypid = getpid();
ipcd_socket = s;
}
void __ipcd_init() {
assert(ipcd_socket == 0);
check_if_we_are_ipcd();
if (ipcd_enabled())
connect_to_ipcd();
}
void __attribute__((destructor)) ipcd_dtor() {
if (ipcd_socket == 0) {
ipclog("Exiting without establishing connection to ipcd...\n");
return;
}
assert(ipcd_socket != 0);
assert(mypid != 0);
// TODO: REMOVEALL is goodness, but we don't presently
// correctly associate PID's with endpoints they own in ipcd.
// Partially due to the mechanism for REREGISTER being
// performed 'eagerly' before the child PID is known,
// and partially due to a need to update ipcd's datastructures.
// This needs to be done eventually anyway, to provide
// access control restrictions on who can unregister,
// optimize, etc. a given endpoint.
// For now, explicitly unregister all endpoints we know we own.
// XXX: This is done in ipcopt.cpp since this code
// doesn't have access to our state table, just ipcd.
// Return instead of REMOVEALL to avoid
// duplicate UNREGISTER.
return;
char buf[100];
int len = sprintf(buf, "REMOVEALL %d\n", mypid);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
ipclog("Error sending ipcd REMOVEALL command in dtor: %s\n",
strerror(errno));
return;
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
const char *match = "200 REMOVED ";
size_t matchlen = strlen(match);
if (size_t(err) < matchlen) {
ipclog("Error receiving response from ipcd in dtor: %s\n", strerror(errno));
return;
}
bool success = (strncmp(buf, "200 REMOVED ", matchlen) == 0);
if (!success) {
ipclog("Failure, response=%s\n", buf);
}
if (success)
ipclog("Successfully unregistered all fd's\n");
else
ipclog("Failed to remove all fd's\n");
}
void connect_if_needed() {
if (mypid == getpid())
return;
ipclog("Reconnecting to ipcd in child...\n");
__real_close(ipcd_socket);
connect_to_ipcd();
}
endpoint ipcd_register_socket(int fd) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "REGISTER %d %d\n", getpid(), fd);
assert(len > 5);
assert(ipcd_socket);
// ipclog("REGISTER %d -->\n", fd);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
// ipclog("REGISTER %d <--\n", fd);
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
buf[err] = 0;
int id;
int n = sscanf(buf, "200 ID %d\n", &id);
assert(n == 1);
// ipclog("Registered and got endpoint id=%d\n", id);
return id;
}
bool ipcd_localize(endpoint local, endpoint remote) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "LOCALIZE %d %d\n", local, remote);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
return strncmp(buf, "200 OK\n", err) == 0;
}
// GETLOCALFD
int ipcd_getlocalfd(endpoint local) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "GETLOCALFD %d\n", local);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
int fd;
{
// Lots of magic
const size_t CONTROLLEN = CMSG_LEN(sizeof(int));
struct iovec iov[1];
struct msghdr msg;
struct cmsghdr *cmsg;
char cmsg_buf[CONTROLLEN];
cmsg = (struct cmsghdr *)cmsg_buf;
memset(&msg, 0, sizeof(msg));
iov[0].iov_base = buf;
iov[0].iov_len = sizeof(buf);
msg.msg_iov = iov;
msg.msg_iovlen = 1;
msg.msg_control = cmsg;
msg.msg_controllen = CONTROLLEN;
int ret = recvmsg(ipcd_socket, &msg, MSG_NOSIGNAL);
if (ret <= 0) {
perror("recvmsg");
exit(1);
}
// TODO: Understand and fix mismatch between
// CONTROLLEN and msg.msg_controllen after recvmsg()!
memcpy(&fd, CMSG_DATA(cmsg), sizeof(int));
ipclog("received local fd %d for endpoint %d\n", fd, local);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
bool success = strncmp(buf, "200 OK\n", err) == 0;
assert(success);
return fd;
}
// UNREGISTER
bool ipcd_unregister_socket(endpoint ep) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "UNREGISTER %d\n", ep);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
return strncmp(buf, "200 OK\n", err) == 0;
}
// REREGISTER
bool ipcd_reregister_socket(endpoint ep, int fd) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "REREGISTER %d %d %d\n", ep, getpid(), fd);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
return strncmp(buf, "200 OK\n", err) == 0;
}
endpoint ipcd_endpoint_kludge(endpoint local) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "ENDPOINT_KLUDGE %d\n", local);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
buf[err] = 0;
int id;
ipclog("endpoint_kludge(%d) = %s\n", local, buf);
int n = sscanf(buf, "200 PAIR %d\n", &id);
if (n == 1) {
return id;
}
return EP_INVALID;
}
endpoint ipcd_crc_kludge(endpoint local, uint32_t s_crc, uint32_t r_crc) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "THRESH_CRC_KLUDGE %d %d %d\n", local, s_crc, r_crc);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
buf[err] = 0;
int id;
ipclog("crc_kludge(%d, %d, %d) = %s\n", local, s_crc, r_crc, buf);
int n = sscanf(buf, "200 PAIR %d\n", &id);
if (n == 1) {
return id;
}
return EP_INVALID;
}
bool ipcd_is_protected(int fd) {
return fd == ipcd_socket;
}
bool ipcd_enabled() {
static bool disabled = getenv("IPCD_DISABLE") || we_are_ipcd;
return !disabled;
}
<commit_msg>libipc/ipcd: Be sure to call unwrapped version of recvmsg.<commit_after>//===-- ipcd.cpp ----------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implements IPCD interface, communicates with ipcd via control socket
//
//===----------------------------------------------------------------------===//
#include "ipcd.h"
#include "debug.h"
#include "real.h"
#include "rename_fd.h"
#include "magic_socket_nums.h"
#include "lock.h"
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
static int ipcd_socket = 0;
static int mypid = 0;
// Must match that used by server,
// currently defined in ipcd/clients.go
const char *SOCK_PATH = "/tmp/ipcd.sock";
const char *IPCD_BIN_PATH = "/bin/ipcd";
const useconds_t SLEEP_AFTER_IPCD_START_INTERVAL = 10 * 1000; // 10ms?
SimpleLock &getConnectLock() {
static SimpleLock ConnectLock;
return ConnectLock;
}
bool we_are_ipcd;
void check_if_we_are_ipcd() {
// man 3 program_invocation_name
extern char *program_invocation_short_name;
assert(program_invocation_short_name);
ipclog("program_invocation_short_name: %s\n", program_invocation_short_name);
we_are_ipcd = strcmp("ipcd", program_invocation_short_name) == 0;
}
void start_ipcd() {
int d = daemon(0, 0);
if (d == -1) {
perror("Failed to daemonize");
exit(1);
}
execl(IPCD_BIN_PATH, IPCD_BIN_PATH, (char *)NULL);
perror("Failed to exec ipcd");
exit(1);
}
void fork_ipcd() {
switch (__real_fork()) {
case -1:
break;
case 0:
// Child
start_ipcd();
assert(0 && "Exec failed?");
break;
default:
// Wait for ipcd to start :P
ipclog("Starting ipcd...\n");
}
}
void connect_to_ipcd() {
int s, len;
struct sockaddr_un remote;
if ((s = __real_socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)) == -1) {
perror("socket");
exit(1);
}
bool rename_success = rename_fd(s, MAGIC_SOCKET_FD, /* cloexec */ true);
assert(rename_success);
s = MAGIC_SOCKET_FD;
remote.sun_family = AF_UNIX;
strcpy(remote.sun_path, SOCK_PATH);
len = strlen(remote.sun_path) + sizeof(remote.sun_family);
if (__real_connect(s, (struct sockaddr *)&remote, len) == -1) {
// XXX: Super kludge!
// If we can't connect to daemon, assume it hasn't been
// started yet and attempt to run it ourselves.
// This code is terrible, and is likely to break
// badly in many situations, but works for now.
if (errno == ENOENT || errno == ECONNREFUSED) {
fork_ipcd();
int attempts = 0;
const int MAX_ATTEMPTS = 10;
while (attempts < MAX_ATTEMPTS) {
usleep(SLEEP_AFTER_IPCD_START_INTERVAL);
if (__real_connect(s, (struct sockaddr *)&remote, len) != -1)
break;
++attempts;
}
if (attempts == MAX_ATTEMPTS) {
perror("Unable to connect to ipcd after attempting to start it");
exit(1);
}
} else {
perror("connect");
ipclog("Error connecting to ipcd?\n");
exit(1);
}
}
ipclog("Connected to IPCD, fd=%d\n", s);
mypid = getpid();
ipcd_socket = s;
}
void __ipcd_init() {
assert(ipcd_socket == 0);
check_if_we_are_ipcd();
if (ipcd_enabled())
connect_to_ipcd();
}
void __attribute__((destructor)) ipcd_dtor() {
if (ipcd_socket == 0) {
ipclog("Exiting without establishing connection to ipcd...\n");
return;
}
assert(ipcd_socket != 0);
assert(mypid != 0);
// TODO: REMOVEALL is goodness, but we don't presently
// correctly associate PID's with endpoints they own in ipcd.
// Partially due to the mechanism for REREGISTER being
// performed 'eagerly' before the child PID is known,
// and partially due to a need to update ipcd's datastructures.
// This needs to be done eventually anyway, to provide
// access control restrictions on who can unregister,
// optimize, etc. a given endpoint.
// For now, explicitly unregister all endpoints we know we own.
// XXX: This is done in ipcopt.cpp since this code
// doesn't have access to our state table, just ipcd.
// Return instead of REMOVEALL to avoid
// duplicate UNREGISTER.
return;
char buf[100];
int len = sprintf(buf, "REMOVEALL %d\n", mypid);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
ipclog("Error sending ipcd REMOVEALL command in dtor: %s\n",
strerror(errno));
return;
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
const char *match = "200 REMOVED ";
size_t matchlen = strlen(match);
if (size_t(err) < matchlen) {
ipclog("Error receiving response from ipcd in dtor: %s\n", strerror(errno));
return;
}
bool success = (strncmp(buf, "200 REMOVED ", matchlen) == 0);
if (!success) {
ipclog("Failure, response=%s\n", buf);
}
if (success)
ipclog("Successfully unregistered all fd's\n");
else
ipclog("Failed to remove all fd's\n");
}
void connect_if_needed() {
if (mypid == getpid())
return;
ipclog("Reconnecting to ipcd in child...\n");
__real_close(ipcd_socket);
connect_to_ipcd();
}
endpoint ipcd_register_socket(int fd) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "REGISTER %d %d\n", getpid(), fd);
assert(len > 5);
assert(ipcd_socket);
// ipclog("REGISTER %d -->\n", fd);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
// ipclog("REGISTER %d <--\n", fd);
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
buf[err] = 0;
int id;
int n = sscanf(buf, "200 ID %d\n", &id);
assert(n == 1);
// ipclog("Registered and got endpoint id=%d\n", id);
return id;
}
bool ipcd_localize(endpoint local, endpoint remote) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "LOCALIZE %d %d\n", local, remote);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
return strncmp(buf, "200 OK\n", err) == 0;
}
// GETLOCALFD
int ipcd_getlocalfd(endpoint local) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "GETLOCALFD %d\n", local);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
int fd;
{
// Lots of magic
const size_t CONTROLLEN = CMSG_LEN(sizeof(int));
struct iovec iov[1];
struct msghdr msg;
struct cmsghdr *cmsg;
char cmsg_buf[CONTROLLEN];
cmsg = (struct cmsghdr *)cmsg_buf;
memset(&msg, 0, sizeof(msg));
iov[0].iov_base = buf;
iov[0].iov_len = sizeof(buf);
msg.msg_iov = iov;
msg.msg_iovlen = 1;
msg.msg_control = cmsg;
msg.msg_controllen = CONTROLLEN;
int ret = __real_recvmsg(ipcd_socket, &msg, MSG_NOSIGNAL);
if (ret <= 0) {
perror("recvmsg");
exit(1);
}
// TODO: Understand and fix mismatch between
// CONTROLLEN and msg.msg_controllen after recvmsg()!
memcpy(&fd, CMSG_DATA(cmsg), sizeof(int));
ipclog("received local fd %d for endpoint %d\n", fd, local);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
bool success = strncmp(buf, "200 OK\n", err) == 0;
assert(success);
return fd;
}
// UNREGISTER
bool ipcd_unregister_socket(endpoint ep) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "UNREGISTER %d\n", ep);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
return strncmp(buf, "200 OK\n", err) == 0;
}
// REREGISTER
bool ipcd_reregister_socket(endpoint ep, int fd) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "REREGISTER %d %d %d\n", ep, getpid(), fd);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
return strncmp(buf, "200 OK\n", err) == 0;
}
endpoint ipcd_endpoint_kludge(endpoint local) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "ENDPOINT_KLUDGE %d\n", local);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
buf[err] = 0;
int id;
ipclog("endpoint_kludge(%d) = %s\n", local, buf);
int n = sscanf(buf, "200 PAIR %d\n", &id);
if (n == 1) {
return id;
}
return EP_INVALID;
}
endpoint ipcd_crc_kludge(endpoint local, uint32_t s_crc, uint32_t r_crc) {
ScopedLock L(getConnectLock());
connect_if_needed();
char buf[100];
int len = sprintf(buf, "THRESH_CRC_KLUDGE %d %d %d\n", local, s_crc, r_crc);
assert(len > 5);
int err = __real_send(ipcd_socket, buf, len, MSG_NOSIGNAL);
if (err < 0) {
perror("write");
exit(1);
}
err = __real_recv(ipcd_socket, buf, 50, MSG_NOSIGNAL);
assert(err > 5);
buf[err] = 0;
int id;
ipclog("crc_kludge(%d, %d, %d) = %s\n", local, s_crc, r_crc, buf);
int n = sscanf(buf, "200 PAIR %d\n", &id);
if (n == 1) {
return id;
}
return EP_INVALID;
}
bool ipcd_is_protected(int fd) {
return fd == ipcd_socket;
}
bool ipcd_enabled() {
static bool disabled = getenv("IPCD_DISABLE") || we_are_ipcd;
return !disabled;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 "testuriresolver.h"
#include <zorba/zorba.h>
#include <zorbautils/strutil.h>
#include <cassert>
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
using namespace zorba;
zorba::TestSchemaURIResolverResult::~TestSchemaURIResolverResult()
{}
Item zorba::TestSchemaURIResolverResult::getSchema () const
{
return theSchema;
}
zorba::TestSchemaURIResolver::TestSchemaURIResolver( const char * file ) :
map_file ( file )
{}
zorba::TestSchemaURIResolver::~TestSchemaURIResolver() {}
void zorba::TestSchemaURIResolver::initialize ()
{
std::string path ( map_file );
for (int i = 0; i < 2; i++) {
std::string::size_type slash = path.find_last_of ( '/' );
assert (slash != std::string::npos);
path.erase ( slash );
}
path += "/";
std::string url ( "file://" );
url += path;
std::ifstream urifile ( map_file.c_str() );
if ( urifile.good () == false ) return;
std::string uris;
while (std::getline (urifile, uris)) {
std::string::size_type eq = uris.find ('=');
String uri (uris.substr (0, eq));
String file (url + uris.substr (eq+1).c_str());
std::cout << "uri_map: " << uri << " -> " << file << std::endl;
uri_map [uri] = file;
}
urifile.close();
}
std::auto_ptr<SchemaURIResolverResult>
zorba::TestSchemaURIResolver::resolve ( const Item & aURI,
const std::vector <Item> & aLocationHint,
StaticContext * aStaticContext )
{
if ( uri_map.empty () ) {
initialize ();
}
std::auto_ptr<TestSchemaURIResolverResult>
result ( new TestSchemaURIResolverResult () );
String request = aURI.getStringValue ();
std::map <String, String >::iterator it = uri_map.find ( request );
if ( it != uri_map.end () ) {
const String target = uri_map [ request ];
Zorba * zorba = Zorba::getInstance ( 0 );
ItemFactory * factory = zorba -> getItemFactory ();
Item item = factory -> createAnyURI ( target );
result -> theSchema = item;
} else {
result -> setError ( URIResolverResult::UR_XQST0059 );
std::stringstream lErrorStream;
lErrorStream << "Schema not found " << aURI.getStringValue();
std::cout << "Schema not found " << aURI.getStringValue() << std::endl;
result->setErrorDescription(lErrorStream.str());
}
std::cout << "Resolved schema " << aURI.getStringValue () << " -> " << result->theSchema.getStringValue () << std::endl;
return std::auto_ptr<SchemaURIResolverResult> ( result );
}
std::istream *
zorba::TestModuleURIResolverResult::getModule () const
{
return theModule;
}
zorba::TestModuleURIResolver::TestModuleURIResolver (const char * file, const std::string &test_)
: map_file (file), theTest (test_)
{}
void zorba::TestModuleURIResolver::initialize ()
{
std::string::size_type pos = theTest.find_first_of ('/');
if (pos != std::string::npos && theTest.substr (0, pos) == "w3c_testsuite")
pos = theTest.find_first_of ('/', pos + 1);
else {
return;
}
std::string pfx = theTest.substr (0, pos) + "/";
std::string path ( map_file );
std::string::size_type slash = path.find_last_of ( '/' );
path.erase ( slash );
slash = path.find_last_of ( '/' );
path.erase ( slash );
std::string url ( "file://" );
std::ifstream urifile ( map_file.c_str() );
std::string uris;
while (std::getline ( urifile, uris )) {
uris = pfx + uris;
pos = uris.find_first_of (':');
assert (pos != std::string::npos);
if (uris.substr (0, pos) != theTest) continue;
uris = uris.substr (pos + 1);
std::string::size_type eq = uris.find ('=');
String uri (uris.substr (0, eq));
String file ( path );
file.append ("/");
file.append (uris.substr (eq+1).c_str());
file.append (".xqi");
uri_map [uri] = file;
}
urifile.close();
}
zorba::TestModuleURIResolver::~TestModuleURIResolver ()
{}
std::auto_ptr < ModuleURIResolverResult >
zorba::TestModuleURIResolver::
resolve ( const Item & aURI, StaticContext* aStaticContext )
{
if ( uri_map.empty () ) {
initialize ();
}
std::auto_ptr < TestModuleURIResolverResult >
lResult ( new TestModuleURIResolverResult () );
String request = aURI.getStringValue ();
std::map < String, String > :: iterator it = uri_map.find ( request );
if ( it != uri_map.end () ) {
const String target = uri_map [ request ];
const char * file = target.c_str();
std::cout << "Resolved module " << aURI.getStringValue() << " -> " << file << std::endl;
lResult -> theModule = new std::ifstream ( file );
lResult -> setError ( URIResolverResult::UR_NOERROR );
} else {
lResult -> setError ( URIResolverResult::UR_XQST0059 );
std::stringstream lErrorStream;
lErrorStream << "Module not found " << aURI.getStringValue();
std::cout << "Module not found " << aURI.getStringValue() << std::endl;
lResult->setErrorDescription(lErrorStream.str());
}
return std::auto_ptr<ModuleURIResolverResult>(lResult.release());
}
// Collection Resolver
Collection_t
zorba::TestCollectionURIResolverResult::getCollection () const
{
return theCollection;
}
zorba::TestCollectionURIResolver::TestCollectionURIResolver ( const char * file, const std::string& rbkt_src_dir ) :
map_file ( file ),
rbkt_src ( rbkt_src_dir )
{}
void
std_string_tokenize(const std::string& aStr, const std::string& aDelims, std::vector<std::string>& aTokens, const std::string& rbkt_src)
{
std::string::size_type lastPos = aStr.find_first_not_of(aDelims, 0);
std::string::size_type pos = aStr.find_first_of(aDelims, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos) {
// Found a token, add it to the vector.
aTokens.push_back(aStr.substr(lastPos, pos - lastPos));
zorba::str_replace_all(aTokens.back(), "$RBKT_SRC_DIR", rbkt_src);
lastPos = aStr.find_first_not_of(aDelims, pos);
pos = aStr.find_first_of(aDelims, lastPos);
}
}
void zorba::TestCollectionURIResolver::trim(std::string& str)
{
std::string::size_type pos = str.find_last_not_of(' ');
if(pos != std::string::npos) {
str.erase(pos + 1);
pos = str.find_first_not_of(' ');
if(pos != std::string::npos) str.erase(0, pos);
}
else str.erase(str.begin(), str.end());
}
void zorba::TestCollectionURIResolver::initialize ()
{
std::ifstream urifile ( map_file.c_str() );
if ( urifile.bad() ) return;
while ( !urifile.eof() ) {
std::string lCollectionMapping;
std::getline( urifile, lCollectionMapping );
if (lCollectionMapping.size() == 0) continue;
std::string::size_type eq = lCollectionMapping.find ( '=' );
assert(eq != std::string::npos);
std::string id ( lCollectionMapping.substr ( 0, eq ) );
trim(id);
std::vector<std::string>& lCollections = uri_map[id];
std_string_tokenize(lCollectionMapping.substr(eq+1), ";", lCollections, rbkt_src);
}
}
zorba::TestCollectionURIResolver::~TestCollectionURIResolver ()
{}
std::auto_ptr < CollectionURIResolverResult >
zorba::TestCollectionURIResolver::
resolve ( const Item & aURI, StaticContext* aStaticContext, XmlDataManager* aXmlDataManager )
{
if ( uri_map.empty () ) {
initialize ();
}
std::auto_ptr < TestCollectionURIResolverResult >
lResult ( new TestCollectionURIResolverResult () );
std::string request = aURI.getStringValue ().c_str();
std::string search = request.substr(request.find_last_of('/')+1);
std::map < std::string, std::vector<std::string> > :: iterator it = uri_map.find ( search );
if ( it != uri_map.end () ) {
const std::vector<std::string>& target = it->second;
Collection_t lCol = aXmlDataManager->getCollection(request);
if (lCol.isNull()) {
lCol = aXmlDataManager->createCollection(request);
for (std::vector<std::string>::const_iterator lIter = target.begin();
lIter != target.end(); ++lIter) {
std::ifstream lIn(lIter->c_str());
assert(lIn.good());
lCol->addDocument(lIn);
}
}
lResult -> theCollection = lCol;
lResult -> setError ( URIResolverResult::UR_NOERROR );
} else {
lResult -> setError ( URIResolverResult::UR_FODC0004 );
std::stringstream lErrorStream;
lErrorStream << "Collection not found " << aURI.getStringValue();
lResult->setErrorDescription(lErrorStream.str());
}
return std::auto_ptr<CollectionURIResolverResult>(lResult.release());
}
<commit_msg>Removed debugging output, fixed segfault in testdriver resolver<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 "testuriresolver.h"
#include <zorba/zorba.h>
#include <zorbautils/strutil.h>
#include <cassert>
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
using namespace zorba;
zorba::TestSchemaURIResolverResult::~TestSchemaURIResolverResult()
{}
Item zorba::TestSchemaURIResolverResult::getSchema () const
{
return theSchema;
}
zorba::TestSchemaURIResolver::TestSchemaURIResolver( const char * file ) :
map_file ( file )
{}
zorba::TestSchemaURIResolver::~TestSchemaURIResolver() {}
void zorba::TestSchemaURIResolver::initialize ()
{
std::string path ( map_file );
for (int i = 0; i < 2; i++) {
std::string::size_type slash = path.find_last_of ( '/' );
assert (slash != std::string::npos);
path.erase ( slash );
}
path += "/";
std::string url ( "file://" );
url += path;
std::ifstream urifile ( map_file.c_str() );
if ( urifile.good () == false ) return;
std::string uris;
while (std::getline (urifile, uris)) {
std::string::size_type eq = uris.find ('=');
String uri (uris.substr (0, eq));
String file (url + uris.substr (eq+1).c_str());
uri_map [uri] = file;
}
urifile.close();
}
std::auto_ptr<SchemaURIResolverResult>
zorba::TestSchemaURIResolver::resolve ( const Item & aURI,
const std::vector <Item> & aLocationHint,
StaticContext * aStaticContext )
{
if ( uri_map.empty () ) {
initialize ();
}
std::auto_ptr<TestSchemaURIResolverResult>
result ( new TestSchemaURIResolverResult () );
String request = aURI.getStringValue ();
std::map <String, String >::iterator it = uri_map.find ( request );
if ( it != uri_map.end () ) {
const String target = uri_map [ request ];
Zorba * zorba = Zorba::getInstance ( 0 );
ItemFactory * factory = zorba -> getItemFactory ();
Item item = factory -> createAnyURI ( target );
result -> theSchema = item;
std::cout << "Resolved schema " << aURI.getStringValue () << " -> " << result->theSchema.getStringValue () << std::endl;
} else {
result -> setError ( URIResolverResult::UR_XQST0059 );
std::stringstream lErrorStream;
lErrorStream << "Schema not found " << aURI.getStringValue();
std::cout << "Schema not found " << aURI.getStringValue() << std::endl;
result->setErrorDescription(lErrorStream.str());
}
return std::auto_ptr<SchemaURIResolverResult> ( result );
}
std::istream *
zorba::TestModuleURIResolverResult::getModule () const
{
return theModule;
}
zorba::TestModuleURIResolver::TestModuleURIResolver (const char * file, const std::string &test_)
: map_file (file), theTest (test_)
{}
void zorba::TestModuleURIResolver::initialize ()
{
std::string::size_type pos = theTest.find_first_of ('/');
if (pos != std::string::npos && theTest.substr (0, pos) == "w3c_testsuite")
pos = theTest.find_first_of ('/', pos + 1);
else {
return;
}
std::string pfx = theTest.substr (0, pos) + "/";
std::string path ( map_file );
std::string::size_type slash = path.find_last_of ( '/' );
path.erase ( slash );
slash = path.find_last_of ( '/' );
path.erase ( slash );
std::string url ( "file://" );
std::ifstream urifile ( map_file.c_str() );
std::string uris;
while (std::getline ( urifile, uris )) {
uris = pfx + uris;
pos = uris.find_first_of (':');
assert (pos != std::string::npos);
if (uris.substr (0, pos) != theTest) continue;
uris = uris.substr (pos + 1);
std::string::size_type eq = uris.find ('=');
String uri (uris.substr (0, eq));
String file ( path );
file.append ("/");
file.append (uris.substr (eq+1).c_str());
file.append (".xqi");
uri_map [uri] = file;
}
urifile.close();
}
zorba::TestModuleURIResolver::~TestModuleURIResolver ()
{}
std::auto_ptr < ModuleURIResolverResult >
zorba::TestModuleURIResolver::
resolve ( const Item & aURI, StaticContext* aStaticContext )
{
if ( uri_map.empty () ) {
initialize ();
}
std::auto_ptr < TestModuleURIResolverResult >
lResult ( new TestModuleURIResolverResult () );
String request = aURI.getStringValue ();
std::map < String, String > :: iterator it = uri_map.find ( request );
if ( it != uri_map.end () ) {
const String target = uri_map [ request ];
const char * file = target.c_str();
std::cout << "Resolved module " << aURI.getStringValue() << " -> " << file << std::endl;
lResult -> theModule = new std::ifstream ( file );
lResult -> setError ( URIResolverResult::UR_NOERROR );
} else {
lResult -> setError ( URIResolverResult::UR_XQST0059 );
std::stringstream lErrorStream;
lErrorStream << "Module not found " << aURI.getStringValue();
std::cout << "Module not found " << aURI.getStringValue() << std::endl;
lResult->setErrorDescription(lErrorStream.str());
}
return std::auto_ptr<ModuleURIResolverResult>(lResult.release());
}
// Collection Resolver
Collection_t
zorba::TestCollectionURIResolverResult::getCollection () const
{
return theCollection;
}
zorba::TestCollectionURIResolver::TestCollectionURIResolver ( const char * file, const std::string& rbkt_src_dir ) :
map_file ( file ),
rbkt_src ( rbkt_src_dir )
{}
void
std_string_tokenize(const std::string& aStr, const std::string& aDelims, std::vector<std::string>& aTokens, const std::string& rbkt_src)
{
std::string::size_type lastPos = aStr.find_first_not_of(aDelims, 0);
std::string::size_type pos = aStr.find_first_of(aDelims, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos) {
// Found a token, add it to the vector.
aTokens.push_back(aStr.substr(lastPos, pos - lastPos));
zorba::str_replace_all(aTokens.back(), "$RBKT_SRC_DIR", rbkt_src);
lastPos = aStr.find_first_not_of(aDelims, pos);
pos = aStr.find_first_of(aDelims, lastPos);
}
}
void zorba::TestCollectionURIResolver::trim(std::string& str)
{
std::string::size_type pos = str.find_last_not_of(' ');
if(pos != std::string::npos) {
str.erase(pos + 1);
pos = str.find_first_not_of(' ');
if(pos != std::string::npos) str.erase(0, pos);
}
else str.erase(str.begin(), str.end());
}
void zorba::TestCollectionURIResolver::initialize ()
{
std::ifstream urifile ( map_file.c_str() );
if ( urifile.bad() ) return;
while ( !urifile.eof() ) {
std::string lCollectionMapping;
std::getline( urifile, lCollectionMapping );
if (lCollectionMapping.size() == 0) continue;
std::string::size_type eq = lCollectionMapping.find ( '=' );
assert(eq != std::string::npos);
std::string id ( lCollectionMapping.substr ( 0, eq ) );
trim(id);
std::vector<std::string>& lCollections = uri_map[id];
std_string_tokenize(lCollectionMapping.substr(eq+1), ";", lCollections, rbkt_src);
}
}
zorba::TestCollectionURIResolver::~TestCollectionURIResolver ()
{}
std::auto_ptr < CollectionURIResolverResult >
zorba::TestCollectionURIResolver::
resolve ( const Item & aURI, StaticContext* aStaticContext, XmlDataManager* aXmlDataManager )
{
if ( uri_map.empty () ) {
initialize ();
}
std::auto_ptr < TestCollectionURIResolverResult >
lResult ( new TestCollectionURIResolverResult () );
std::string request = aURI.getStringValue ().c_str();
std::string search = request.substr(request.find_last_of('/')+1);
std::map < std::string, std::vector<std::string> > :: iterator it = uri_map.find ( search );
if ( it != uri_map.end () ) {
const std::vector<std::string>& target = it->second;
Collection_t lCol = aXmlDataManager->getCollection(request);
if (lCol.isNull()) {
lCol = aXmlDataManager->createCollection(request);
for (std::vector<std::string>::const_iterator lIter = target.begin();
lIter != target.end(); ++lIter) {
std::ifstream lIn(lIter->c_str());
assert(lIn.good());
lCol->addDocument(lIn);
}
}
lResult -> theCollection = lCol;
lResult -> setError ( URIResolverResult::UR_NOERROR );
} else {
lResult -> setError ( URIResolverResult::UR_FODC0004 );
std::stringstream lErrorStream;
lErrorStream << "Collection not found " << aURI.getStringValue();
lResult->setErrorDescription(lErrorStream.str());
}
return std::auto_ptr<CollectionURIResolverResult>(lResult.release());
}
<|endoftext|>
|
<commit_before>#include <catch.hpp>
#include <rapidcheck-catch.h>
#include "util/Generators.h"
#include "util/TemplateProps.h"
using namespace rc;
using namespace rc::detail;
TEST_CASE("TestCase") {
SECTION("operator==/operator!=") {
propConformsToEquals<TestCase>();
PROP_REPLACE_MEMBER_INEQUAL(TestCase, size);
PROP_REPLACE_MEMBER_INEQUAL(TestCase, seed);
}
SECTION("operator<<") {
propConformsToOutputOperator<TestCase>();
}
}
TEST_CASE("CaseResult") {
SECTION("operator==/operator!=") {
propConformsToEquals<CaseResult>();
PROP_REPLACE_MEMBER_INEQUAL(CaseResult, type);
PROP_REPLACE_MEMBER_INEQUAL(CaseResult, description);
}
SECTION("operator<<") {
propConformsToOutputOperator<CaseResult>();
}
}
TEST_CASE("SuccessResult") {
SECTION("operator==/operator!=") {
propConformsToEquals<SuccessResult>();
PROP_REPLACE_MEMBER_INEQUAL(SuccessResult, numSuccess);
}
SECTION("operator<<") {
propConformsToOutputOperator<SuccessResult>();
}
}
TEST_CASE("FailureResult") {
SECTION("operator==/operator!=") {
propConformsToEquals<FailureResult>();
PROP_REPLACE_MEMBER_INEQUAL(FailureResult, numSuccess);
PROP_REPLACE_MEMBER_INEQUAL(FailureResult, failingCase);
PROP_REPLACE_MEMBER_INEQUAL(FailureResult, description);
PROP_REPLACE_MEMBER_INEQUAL(FailureResult, numShrinks);
PROP_REPLACE_MEMBER_INEQUAL(FailureResult, counterExample);
}
SECTION("operator<<") {
propConformsToOutputOperator<FailureResult>();
}
}
TEST_CASE("GaveUpResult") {
SECTION("operator==/operator!=") {
propConformsToEquals<GaveUpResult>();
PROP_REPLACE_MEMBER_INEQUAL(GaveUpResult, numSuccess);
PROP_REPLACE_MEMBER_INEQUAL(GaveUpResult, description);
}
SECTION("operator<<") {
propConformsToOutputOperator<GaveUpResult>();
}
}
<commit_msg>Move ResultTests to new framework<commit_after>#include <catch.hpp>
#include <rapidcheck-catch.h>
#include "util/Generators.h"
#include "util/TemplateProps.h"
using namespace rc;
using namespace rc::detail;
TEST_CASE("TestCase") {
SECTION("operator==/operator!=") {
newpropConformsToEquals<TestCase>();
NEWPROP_REPLACE_MEMBER_INEQUAL(TestCase, size);
NEWPROP_REPLACE_MEMBER_INEQUAL(TestCase, seed);
}
SECTION("operator<<") {
newpropConformsToOutputOperator<TestCase>();
}
}
TEST_CASE("CaseResult") {
SECTION("operator==/operator!=") {
newpropConformsToEquals<CaseResult>();
NEWPROP_REPLACE_MEMBER_INEQUAL(CaseResult, type);
NEWPROP_REPLACE_MEMBER_INEQUAL(CaseResult, description);
}
SECTION("operator<<") {
newpropConformsToOutputOperator<CaseResult>();
}
}
TEST_CASE("SuccessResult") {
SECTION("operator==/operator!=") {
newpropConformsToEquals<SuccessResult>();
NEWPROP_REPLACE_MEMBER_INEQUAL(SuccessResult, numSuccess);
}
SECTION("operator<<") {
newpropConformsToOutputOperator<SuccessResult>();
}
}
TEST_CASE("FailureResult") {
SECTION("operator==/operator!=") {
newpropConformsToEquals<FailureResult>();
NEWPROP_REPLACE_MEMBER_INEQUAL(FailureResult, numSuccess);
NEWPROP_REPLACE_MEMBER_INEQUAL(FailureResult, failingCase);
NEWPROP_REPLACE_MEMBER_INEQUAL(FailureResult, description);
NEWPROP_REPLACE_MEMBER_INEQUAL(FailureResult, numShrinks);
NEWPROP_REPLACE_MEMBER_INEQUAL(FailureResult, counterExample);
}
SECTION("operator<<") {
newpropConformsToOutputOperator<FailureResult>();
}
}
TEST_CASE("GaveUpResult") {
SECTION("operator==/operator!=") {
newpropConformsToEquals<GaveUpResult>();
NEWPROP_REPLACE_MEMBER_INEQUAL(GaveUpResult, numSuccess);
NEWPROP_REPLACE_MEMBER_INEQUAL(GaveUpResult, description);
}
SECTION("operator<<") {
newpropConformsToOutputOperator<GaveUpResult>();
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <utility>
#include <cassert>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include "glt/tex_util.h"
//Swap rows of n bytes pointed to by a with those pointed to by b
//for use in doing the y-flip for images so OpenGL has them right-side up
void swap_row(unsigned char *a, unsigned char *b, size_t n){
for (size_t i = 0; i < n; ++i){
std::swap(a[i], b[i]);
}
}
GLint glt::load_texture_2d(const std::string &file, int *width, int *height){
int x, y, n;
unsigned char *img = stbi_load(file.c_str(), &x, &y, &n, 0);
if (!img){
std::cout << "load_texture_2d error loading " << file
<< " - " << stbi_failure_reason() << std::endl;
return -1;
}
if (width){
*width = x;
}
if (height){
*height = y;
}
GLenum format;
switch (n){
case 1:
format = GL_RED;
break;
case 2:
format = GL_RG;
break;
case 3:
format = GL_RGB;
break;
case 4:
format = GL_RGBA;
break;
}
for (int i = 0; i < y / 2; ++i){
swap_row(&img[i * x * n], &img[(y - i - 1) * x * n], x * n);
}
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, format, x, y, 0, format, GL_UNSIGNED_BYTE, img);
glGenerateMipmap(GL_TEXTURE_2D);
stbi_image_free(img);
return tex;
}
GLint glt::load_texture_2d_array(const std::vector<std::string> &files, int *width, int *height){
assert(!files.empty());
int x, y, n;
std::vector<unsigned char*> images;
//We need to load the first image to get the dimensions and format we're loading
images.push_back(stbi_load(files.front().c_str(), &x, &y, &n, 0));
for (const auto &f : files){
int ix, iy, in;
unsigned char *im = stbi_load(f.c_str(), &ix, &iy, &in, 0);
bool error = false;
if (!im){
std::cout << "load_texture_2d_array error loading " << f
<< " - " << stbi_failure_reason() << std::endl;
error = true;
}
if (x != ix || y != iy || n != in){
std::cout << "load_texture_2d_array error: incompatible file types found on "
<< f << std::endl;
error = true;
}
if (error){
for (auto i : images){
stbi_image_free(i);
}
return -1;
}
images.push_back(im);
}
if (width){
*width = x;
}
if (height){
*height = y;
}
//Perform y-swap on each loaded image
for (auto img : images){
for (int i = 0; i < y / 2; ++i){
swap_row(&img[i * x * n], &img[(y - i - 1) * x * n], x * n);
}
}
GLenum format;
switch (n){
case 1:
format = GL_RED;
break;
case 2:
format = GL_RG;
break;
case 3:
format = GL_RGB;
break;
case 4:
format = GL_RGBA;
break;
}
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D_ARRAY, tex);
glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, format, x, y, images.size(), 0, format, GL_UNSIGNED_BYTE, NULL);
//Upload all the textures in the array
for (size_t i = 0; i < images.size(); ++i){
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, i, x, y, 1, format, GL_UNSIGNED_BYTE, images.at(i));
}
glGenerateMipmap(GL_TEXTURE_2D_ARRAY);
//Clean up all the image data
for (auto i : images){
stbi_image_free(i);
}
return tex;
}
GLint glt::load_cubemap(const std::vector<std::string> &files, int *width, int *height){
assert(files.size() == 6);
int x, y, n;
std::vector<unsigned char*> images;
//We need to load the first image to get the dimensions and format we're loading
images.push_back(stbi_load(files.front().c_str(), &x, &y, &n, 0));
for (const auto &f : files){
int ix, iy, in;
unsigned char *im = stbi_load(f.c_str(), &ix, &iy, &in, 0);
bool error = false;
if (!im){
std::cout << "load_cubemap error loading " << f
<< " - " << stbi_failure_reason() << std::endl;
error = true;
}
if (x != ix || y != iy || n != in){
std::cout << "load_cubemap error: incompatible file types found on "
<< f << std::endl;
error = true;
}
if (error){
for (auto i : images){
stbi_image_free(i);
}
return -1;
}
images.push_back(im);
}
if (width){
*width = x;
}
if (height){
*height = y;
}
//Perform y-swap on each loaded image
for (auto img : images){
for (int i = 0; i < y / 2; ++i){
swap_row(&img[i * x * n], &img[(y - i - 1) * x * n], x * n);
}
}
GLenum format;
switch (n){
case 1:
format = GL_RED;
break;
case 2:
format = GL_RG;
break;
case 3:
format = GL_RGB;
break;
case 4:
format = GL_RGBA;
break;
}
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_CUBE_MAP, tex);
//Upload all the textures in the array
for (size_t i = 0; i < images.size(); ++i){
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, format, x, y, 0, format,
GL_UNSIGNED_BYTE, images[i]);
}
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
//Clean up all the image data
for (auto i : images){
stbi_image_free(i);
}
return tex;
}
<commit_msg>Error checking on loading the first cubemap face too<commit_after>#include <iostream>
#include <utility>
#include <cassert>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include "glt/tex_util.h"
//Swap rows of n bytes pointed to by a with those pointed to by b
//for use in doing the y-flip for images so OpenGL has them right-side up
void swap_row(unsigned char *a, unsigned char *b, size_t n){
for (size_t i = 0; i < n; ++i){
std::swap(a[i], b[i]);
}
}
GLint glt::load_texture_2d(const std::string &file, int *width, int *height){
int x, y, n;
unsigned char *img = stbi_load(file.c_str(), &x, &y, &n, 0);
if (!img){
std::cout << "load_texture_2d error loading " << file
<< " - " << stbi_failure_reason() << std::endl;
return -1;
}
if (width){
*width = x;
}
if (height){
*height = y;
}
GLenum format;
switch (n){
case 1:
format = GL_RED;
break;
case 2:
format = GL_RG;
break;
case 3:
format = GL_RGB;
break;
case 4:
format = GL_RGBA;
break;
}
for (int i = 0; i < y / 2; ++i){
swap_row(&img[i * x * n], &img[(y - i - 1) * x * n], x * n);
}
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, format, x, y, 0, format, GL_UNSIGNED_BYTE, img);
glGenerateMipmap(GL_TEXTURE_2D);
stbi_image_free(img);
return tex;
}
GLint glt::load_texture_2d_array(const std::vector<std::string> &files, int *width, int *height){
assert(!files.empty());
int x, y, n;
std::vector<unsigned char*> images;
//We need to load the first image to get the dimensions and format we're loading
images.push_back(stbi_load(files.front().c_str(), &x, &y, &n, 0));
for (const auto &f : files){
int ix, iy, in;
unsigned char *im = stbi_load(f.c_str(), &ix, &iy, &in, 0);
bool error = false;
if (!im){
std::cout << "load_texture_2d_array error loading " << f
<< " - " << stbi_failure_reason() << std::endl;
error = true;
}
if (x != ix || y != iy || n != in){
std::cout << "load_texture_2d_array error: incompatible file types found on "
<< f << std::endl;
error = true;
}
if (error){
for (auto i : images){
stbi_image_free(i);
}
return -1;
}
images.push_back(im);
}
if (width){
*width = x;
}
if (height){
*height = y;
}
//Perform y-swap on each loaded image
for (auto img : images){
for (int i = 0; i < y / 2; ++i){
swap_row(&img[i * x * n], &img[(y - i - 1) * x * n], x * n);
}
}
GLenum format;
switch (n){
case 1:
format = GL_RED;
break;
case 2:
format = GL_RG;
break;
case 3:
format = GL_RGB;
break;
case 4:
format = GL_RGBA;
break;
}
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D_ARRAY, tex);
glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, format, x, y, images.size(), 0, format, GL_UNSIGNED_BYTE, NULL);
//Upload all the textures in the array
for (size_t i = 0; i < images.size(); ++i){
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, i, x, y, 1, format, GL_UNSIGNED_BYTE, images.at(i));
}
glGenerateMipmap(GL_TEXTURE_2D_ARRAY);
//Clean up all the image data
for (auto i : images){
stbi_image_free(i);
}
return tex;
}
GLint glt::load_cubemap(const std::vector<std::string> &files, int *width, int *height){
assert(files.size() == 6);
int x, y, n;
std::vector<unsigned char*> images;
//We need to load the first image to get the dimensions and format we're loading
unsigned char *im = stbi_load(files.front().c_str(), &x, &y, &n, 0);
if (!im){
std::cout << "load_cubemap error loading " << files.front()
<< " - " << stbi_failure_reason() << std::endl;
return -1;
}
images.push_back(im);
for (const auto &f : files){
int ix, iy, in;
unsigned char *im = stbi_load(f.c_str(), &ix, &iy, &in, 0);
bool error = false;
if (!im){
std::cout << "load_cubemap error loading " << f
<< " - " << stbi_failure_reason() << std::endl;
error = true;
}
if (x != ix || y != iy || n != in){
std::cout << "load_cubemap error: incompatible file types found on "
<< f << std::endl;
error = true;
}
if (error){
for (auto i : images){
stbi_image_free(i);
}
return -1;
}
images.push_back(im);
}
if (width){
*width = x;
}
if (height){
*height = y;
}
//Perform y-swap on each loaded image
for (auto img : images){
for (int i = 0; i < y / 2; ++i){
swap_row(&img[i * x * n], &img[(y - i - 1) * x * n], x * n);
}
}
GLenum format;
switch (n){
case 1:
format = GL_RED;
break;
case 2:
format = GL_RG;
break;
case 3:
format = GL_RGB;
break;
case 4:
format = GL_RGBA;
break;
}
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_CUBE_MAP, tex);
//Upload all the textures in the array
for (size_t i = 0; i < images.size(); ++i){
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, format, x, y, 0, format,
GL_UNSIGNED_BYTE, images[i]);
}
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
//Clean up all the image data
for (auto i : images){
stbi_image_free(i);
}
return tex;
}
<|endoftext|>
|
<commit_before>#include <archive.h>
#include <archive_entry.h>
#include "serialise.hh"
#include "tarfile.hh"
namespace nix {
static int callback_open(struct archive *, void * self)
{
return ARCHIVE_OK;
}
static ssize_t callback_read(struct archive * archive, void * _self, const void * * buffer)
{
auto self = (TarArchive *) _self;
*buffer = self->buffer.data();
try {
return self->source->read((char *) self->buffer.data(), 4096);
} catch (EndOfFile &) {
return 0;
} catch (std::exception & err) {
archive_set_error(archive, EIO, "Source threw exception: %s", err.what());
return -1;
}
}
static int callback_close(struct archive *, void * self)
{
return ARCHIVE_OK;
}
void TarArchive::check(int err, const std::string & reason)
{
if (err == ARCHIVE_EOF)
throw EndOfFile("reached end of archive");
else if (err != ARCHIVE_OK)
throw Error(reason, archive_error_string(this->archive));
}
TarArchive::TarArchive(Source & source, bool raw)
: source(&source), buffer(4096)
{
init();
if (!raw)
archive_read_support_format_all(archive);
else
archive_read_support_format_raw(archive);
check(archive_read_open(archive, (void *)this, callback_open, callback_read, callback_close), "Failed to open archive (%s)");
}
TarArchive::TarArchive(const Path & path)
{
init();
archive_read_support_format_all(archive);
check(archive_read_open_filename(archive, path.c_str(), 16384), "failed to open archive: %s");
}
void TarArchive::init()
{
archive = archive_read_new();
archive_read_support_filter_all(archive);
}
void TarArchive::close()
{
check(archive_read_close(this->archive), "Failed to close archive (%s)");
}
TarArchive::~TarArchive()
{
if (this->archive) archive_read_free(this->archive);
}
static void extract_archive(TarArchive & archive, const Path & destDir)
{
int flags = ARCHIVE_EXTRACT_FFLAGS
| ARCHIVE_EXTRACT_PERM
| ARCHIVE_EXTRACT_TIME
| ARCHIVE_EXTRACT_SECURE_SYMLINKS
| ARCHIVE_EXTRACT_SECURE_NODOTDOT;
for (;;) {
struct archive_entry * entry;
int r = archive_read_next_header(archive.archive, &entry);
if (r == ARCHIVE_EOF) break;
auto name = archive_entry_pathname(entry);
if (!name)
throw Error("cannot get archive member name: %s", archive_error_string(archive.archive));
if (r == ARCHIVE_WARN)
warn(archive_error_string(archive.archive));
else
archive.check(r);
archive_entry_set_pathname(entry,
(destDir + "/" + name).c_str());
archive.check(archive_read_extract(archive.archive, entry, flags));
}
archive.close();
}
void unpackTarfile(Source & source, const Path & destDir)
{
auto archive = TarArchive(source);
createDirs(destDir);
extract_archive(archive, destDir);
}
void unpackTarfile(const Path & tarFile, const Path & destDir)
{
auto archive = TarArchive(tarFile);
createDirs(destDir);
extract_archive(archive, destDir);
}
}
<commit_msg>extract_archive: use copy_pathname instead of set_pathname.<commit_after>#include <archive.h>
#include <archive_entry.h>
#include "serialise.hh"
#include "tarfile.hh"
namespace nix {
static int callback_open(struct archive *, void * self)
{
return ARCHIVE_OK;
}
static ssize_t callback_read(struct archive * archive, void * _self, const void * * buffer)
{
auto self = (TarArchive *) _self;
*buffer = self->buffer.data();
try {
return self->source->read((char *) self->buffer.data(), 4096);
} catch (EndOfFile &) {
return 0;
} catch (std::exception & err) {
archive_set_error(archive, EIO, "Source threw exception: %s", err.what());
return -1;
}
}
static int callback_close(struct archive *, void * self)
{
return ARCHIVE_OK;
}
void TarArchive::check(int err, const std::string & reason)
{
if (err == ARCHIVE_EOF)
throw EndOfFile("reached end of archive");
else if (err != ARCHIVE_OK)
throw Error(reason, archive_error_string(this->archive));
}
TarArchive::TarArchive(Source & source, bool raw)
: source(&source), buffer(4096)
{
init();
if (!raw)
archive_read_support_format_all(archive);
else
archive_read_support_format_raw(archive);
check(archive_read_open(archive, (void *)this, callback_open, callback_read, callback_close), "Failed to open archive (%s)");
}
TarArchive::TarArchive(const Path & path)
{
init();
archive_read_support_format_all(archive);
check(archive_read_open_filename(archive, path.c_str(), 16384), "failed to open archive: %s");
}
void TarArchive::init()
{
archive = archive_read_new();
archive_read_support_filter_all(archive);
}
void TarArchive::close()
{
check(archive_read_close(this->archive), "Failed to close archive (%s)");
}
TarArchive::~TarArchive()
{
if (this->archive) archive_read_free(this->archive);
}
static void extract_archive(TarArchive & archive, const Path & destDir)
{
int flags = ARCHIVE_EXTRACT_FFLAGS
| ARCHIVE_EXTRACT_PERM
| ARCHIVE_EXTRACT_TIME
| ARCHIVE_EXTRACT_SECURE_SYMLINKS
| ARCHIVE_EXTRACT_SECURE_NODOTDOT;
for (;;) {
struct archive_entry * entry;
int r = archive_read_next_header(archive.archive, &entry);
if (r == ARCHIVE_EOF) break;
auto name = archive_entry_pathname(entry);
if (!name)
throw Error("cannot get archive member name: %s", archive_error_string(archive.archive));
if (r == ARCHIVE_WARN)
warn(archive_error_string(archive.archive));
else
archive.check(r);
archive_entry_copy_pathname(entry,
(destDir + "/" + name).c_str());
archive.check(archive_read_extract(archive.archive, entry, flags));
}
archive.close();
}
void unpackTarfile(Source & source, const Path & destDir)
{
auto archive = TarArchive(source);
createDirs(destDir);
extract_archive(archive, destDir);
}
void unpackTarfile(const Path & tarFile, const Path & destDir)
{
auto archive = TarArchive(tarFile);
createDirs(destDir);
extract_archive(archive, destDir);
}
}
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// functions_test.cpp
//
// Identification: test/function/functions_test.cpp
//
// Copyright (c) 2015-2017, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "common/harness.h"
#include "sql/testing_sql_util.h"
#include "concurrency/transaction_manager_factory.h"
#include "catalog/catalog.h"
#include "catalog/proc_catalog.h"
#include "catalog/language_catalog.h"
#include "type/ephemeral_pool.h"
namespace peloton {
namespace test {
class FunctionsTests : public PelotonTest {
public:
static type::Value TestFunc(UNUSED_ATTRIBUTE const std::vector<type::Value>& args) {
return type::ValueFactory::GetIntegerValue(0);
}
};
TEST_F(FunctionsTests, CatalogTest) {
auto catalog = catalog::Catalog::GetInstance();
catalog->Bootstrap();
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto pg_language = catalog::LanguageCatalog::GetInstance();
// test "internal" language
auto txn = txn_manager.BeginTransaction();
auto internal_oid = pg_language->GetLanguageOid("internal", txn);
EXPECT_NE(INVALID_OID, internal_oid);
auto name = pg_language->GetLanguageName(internal_oid, txn);
EXPECT_EQ("internal", name);
// test add/del language
type::EphemeralPool pool;
std::string lanname = "foo_lang";
pg_language->InsertLanguage(lanname, &pool, txn);
auto oid = pg_language->GetLanguageOid(lanname, txn);
EXPECT_NE(INVALID_OID, oid);
name = pg_language->GetLanguageName(oid, txn);
EXPECT_EQ(lanname, name);
pg_language->DeleteLanguage(lanname, txn);
oid = pg_language->GetLanguageOid(lanname, txn);
EXPECT_EQ(INVALID_OID, oid);
txn_manager.CommitTransaction(txn);
auto pg_proc = catalog::ProcCatalog::GetInstance();
// test pg_proc
txn = txn_manager.BeginTransaction();
std::string func_name = "test_func";
std::vector<type::TypeId> arg_types{type::TypeId::VARCHAR, type::TypeId::INTEGER};
catalog->AddFunction(func_name, arg_types, type::TypeId::INTEGER,
internal_oid, "TestFunc", TestFunc, txn);
oid_t prolang = pg_proc->GetProLang(func_name, arg_types, txn);
EXPECT_EQ(internal_oid, prolang);
type::TypeId ret_type = pg_proc->GetProRetType(func_name, arg_types, txn);
EXPECT_EQ(type::TypeId::INTEGER, ret_type);
std::string func = pg_proc->GetProSrc(func_name, arg_types, txn);
EXPECT_EQ("TestFunc", func);
txn_manager.CommitTransaction(txn);
auto func_data = catalog->GetFunction(func_name, arg_types);
EXPECT_EQ(ret_type, func_data.return_type_);
EXPECT_EQ(TestFunc, func_data.func_ptr_);
}
TEST_F(FunctionsTests, FuncCallTest) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);
txn_manager.CommitTransaction(txn);
TestingSQLUtil::ExecuteSQLQuery(
"CREATE TABLE test(a DECIMAL, s VARCHAR);");
TestingSQLUtil::ExecuteSQLQuery(
"INSERT INTO test VALUES (4.0, 'abc');");
std::vector<StatementResult> result;
std::vector<FieldInfo> tuple_descriptor;
std::string error_message;
int rows_affected;
TestingSQLUtil::ExecuteSQLQuery(
"SELECT SQRT(a), SUBSTR(s,1,2) FROM test;", result,
tuple_descriptor, rows_affected, error_message);
EXPECT_EQ(1, result[0].second.size());
EXPECT_EQ('2', result[0].second[0]);
EXPECT_EQ(2, result[1].second.size());
EXPECT_EQ(result[1].second[0], 'a');
EXPECT_EQ(result[1].second[1], 'b');
TestingSQLUtil::ExecuteSQLQuery(
"SELECT ASCII(s) FROM test;", result,
tuple_descriptor, rows_affected, error_message);
EXPECT_EQ(2, result[0].second.size());
EXPECT_EQ('9', result[0].second[0]);
EXPECT_EQ('7', result[0].second[1]);
// free the database just created
txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);
txn_manager.CommitTransaction(txn);
}
} // namespace test
} // namespace peloton
<commit_msg>pointer comparision in test<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// functions_test.cpp
//
// Identification: test/function/functions_test.cpp
//
// Copyright (c) 2015-2017, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "common/harness.h"
#include "sql/testing_sql_util.h"
#include "concurrency/transaction_manager_factory.h"
#include "catalog/catalog.h"
#include "catalog/proc_catalog.h"
#include "catalog/language_catalog.h"
#include "type/ephemeral_pool.h"
namespace peloton {
namespace test {
class FunctionsTests : public PelotonTest {
public:
static type::Value TestFunc(UNUSED_ATTRIBUTE const std::vector<type::Value>& args) {
return type::ValueFactory::GetIntegerValue(0);
}
};
TEST_F(FunctionsTests, CatalogTest) {
auto catalog = catalog::Catalog::GetInstance();
catalog->Bootstrap();
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto pg_language = catalog::LanguageCatalog::GetInstance();
// test "internal" language
auto txn = txn_manager.BeginTransaction();
auto internal_oid = pg_language->GetLanguageOid("internal", txn);
EXPECT_NE(INVALID_OID, internal_oid);
auto name = pg_language->GetLanguageName(internal_oid, txn);
EXPECT_EQ("internal", name);
// test add/del language
type::EphemeralPool pool;
std::string lanname = "foo_lang";
pg_language->InsertLanguage(lanname, &pool, txn);
auto oid = pg_language->GetLanguageOid(lanname, txn);
EXPECT_NE(INVALID_OID, oid);
name = pg_language->GetLanguageName(oid, txn);
EXPECT_EQ(lanname, name);
pg_language->DeleteLanguage(lanname, txn);
oid = pg_language->GetLanguageOid(lanname, txn);
EXPECT_EQ(INVALID_OID, oid);
txn_manager.CommitTransaction(txn);
auto pg_proc = catalog::ProcCatalog::GetInstance();
// test pg_proc
txn = txn_manager.BeginTransaction();
std::string func_name = "test_func";
std::vector<type::TypeId> arg_types{type::TypeId::VARCHAR, type::TypeId::INTEGER};
catalog->AddFunction(func_name, arg_types, type::TypeId::INTEGER,
internal_oid, "TestFunc", TestFunc, txn);
oid_t prolang = pg_proc->GetProLang(func_name, arg_types, txn);
EXPECT_EQ(internal_oid, prolang);
type::TypeId ret_type = pg_proc->GetProRetType(func_name, arg_types, txn);
EXPECT_EQ(type::TypeId::INTEGER, ret_type);
std::string func = pg_proc->GetProSrc(func_name, arg_types, txn);
EXPECT_EQ("TestFunc", func);
txn_manager.CommitTransaction(txn);
auto func_data = catalog->GetFunction(func_name, arg_types);
EXPECT_EQ(ret_type, func_data.return_type_);
EXPECT_EQ((int64_t)TestFunc, (int64_t)func_data.func_ptr_);
}
TEST_F(FunctionsTests, FuncCallTest) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);
txn_manager.CommitTransaction(txn);
TestingSQLUtil::ExecuteSQLQuery(
"CREATE TABLE test(a DECIMAL, s VARCHAR);");
TestingSQLUtil::ExecuteSQLQuery(
"INSERT INTO test VALUES (4.0, 'abc');");
std::vector<StatementResult> result;
std::vector<FieldInfo> tuple_descriptor;
std::string error_message;
int rows_affected;
TestingSQLUtil::ExecuteSQLQuery(
"SELECT SQRT(a), SUBSTR(s,1,2) FROM test;", result,
tuple_descriptor, rows_affected, error_message);
EXPECT_EQ(1, result[0].second.size());
EXPECT_EQ('2', result[0].second[0]);
EXPECT_EQ(2, result[1].second.size());
EXPECT_EQ(result[1].second[0], 'a');
EXPECT_EQ(result[1].second[1], 'b');
TestingSQLUtil::ExecuteSQLQuery(
"SELECT ASCII(s) FROM test;", result,
tuple_descriptor, rows_affected, error_message);
EXPECT_EQ(2, result[0].second.size());
EXPECT_EQ('9', result[0].second[0]);
EXPECT_EQ('7', result[0].second[1]);
// free the database just created
txn = txn_manager.BeginTransaction();
catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);
txn_manager.CommitTransaction(txn);
}
} // namespace test
} // namespace peloton
<|endoftext|>
|
<commit_before>#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "GraphDirected.h"
#include <map>
#include <utility>
using namespace std;
TEST_CASE( "GraphDirected", "[GraphDirected]" ) {
GraphDirected<int> _Optimizer;
map< pair< int, int >, int > _Connections;
_Connections.emplace( std::pair<int,int>(0,1), 1 );
_Connections.emplace( std::pair<int,int>(1,2), 1 );
_Connections.emplace( std::pair<int,int>(2,0), 1 );
_Connections.emplace( std::pair<int,int>(0,3), 1 );
_Connections.emplace( std::pair<int,int>(3,4), 1 );
_Connections.emplace( std::pair<int,int>(4,1), 1 );
_Connections.emplace( std::pair<int,int>(1,0), 1 );
_Connections.emplace( std::pair<int,int>(1,0), 1 );
_Connections.emplace( std::pair<int,int>(2,6), 1 );
_Connections.emplace( std::pair<int,int>(1,6), 1 );
_Connections.emplace( std::pair<int,int>(6,6), 0 );
_Connections.emplace( std::pair<int,int>(7,4), 0 );
_Optimizer.GenerateGraphFromWeightMap( _Connections );
SECTION( "Shortest Path" ) {
vector< int > _Path;
int _Dist;
_Optimizer.GetShortestPath( 0, 6, _Path, _Dist );
REQUIRE( 3 == _Path.size() );
CHECK( 2 == _Dist );
CHECK( 0 == _Path[0] );
CHECK( 1 == _Path[1] );
CHECK( 6 == _Path[2] );
}
SECTION( "Cycle" ) {
vector< int > _Path;
int _Dist;
bool bRet = _Optimizer.GetShortestPath( 4, 4, _Path, _Dist );
REQUIRE( true == bRet );
REQUIRE( 5 == _Path.size() );
CHECK( 4 == _Dist );
CHECK( 4 == _Path[0] );
CHECK( 1 == _Path[1] );
CHECK( 0 == _Path[2] );
CHECK( 3 == _Path[3] );
CHECK( 4 == _Path[4] );
}
SECTION( "Self" ) {
vector< int > _Path;
int _Dist;
bool bRet = _Optimizer.GetShortestPath( 6, 6, _Path, _Dist );
REQUIRE( true == bRet );
REQUIRE( 1 == _Path.size() );
CHECK( 0 == _Dist );
CHECK( 6 == _Path[0] );
}
}
<commit_msg>replace emplace with insert<commit_after>#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "GraphDirected.h"
#include <map>
#include <utility>
using namespace std;
TEST_CASE( "GraphDirected", "[GraphDirected]" ) {
GraphDirected<int> _Optimizer;
map< pair< int, int >, int > _Connections;
_Connections.insert( make_pair( std::pair<int,int>(0,1), 1 ) );
_Connections.insert( make_pair( std::pair<int,int>(1,2), 1 ) );
_Connections.insert( make_pair( std::pair<int,int>(2,0), 1 ) );
_Connections.insert( make_pair( std::pair<int,int>(0,3), 1 ) );
_Connections.insert( make_pair( std::pair<int,int>(3,4), 1 ) );
_Connections.insert( make_pair( std::pair<int,int>(4,1), 1 ) );
_Connections.insert( make_pair( std::pair<int,int>(1,0), 1 ) );
_Connections.insert( make_pair( std::pair<int,int>(1,0), 1 ) );
_Connections.insert( make_pair( std::pair<int,int>(2,6), 1 ) );
_Connections.insert( make_pair( std::pair<int,int>(1,6), 1 ) );
_Connections.insert( make_pair( std::pair<int,int>(6,6), 0 ) );
_Connections.insert( make_pair( std::pair<int,int>(7,4), 0 ) );
_Optimizer.GenerateGraphFromWeightMap( _Connections );
SECTION( "Shortest Path" ) {
vector< int > _Path;
int _Dist;
_Optimizer.GetShortestPath( 0, 6, _Path, _Dist );
REQUIRE( 3 == _Path.size() );
CHECK( 2 == _Dist );
CHECK( 0 == _Path[0] );
CHECK( 1 == _Path[1] );
CHECK( 6 == _Path[2] );
}
SECTION( "Cycle" ) {
vector< int > _Path;
int _Dist;
bool bRet = _Optimizer.GetShortestPath( 4, 4, _Path, _Dist );
REQUIRE( true == bRet );
REQUIRE( 5 == _Path.size() );
CHECK( 4 == _Dist );
CHECK( 4 == _Path[0] );
CHECK( 1 == _Path[1] );
CHECK( 0 == _Path[2] );
CHECK( 3 == _Path[3] );
CHECK( 4 == _Path[4] );
}
SECTION( "Self" ) {
vector< int > _Path;
int _Dist;
bool bRet = _Optimizer.GetShortestPath( 6, 6, _Path, _Dist );
REQUIRE( true == bRet );
REQUIRE( 1 == _Path.size() );
CHECK( 0 == _Dist );
CHECK( 6 == _Path[0] );
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <thread>
#include <iomanip>
#include <chrono>
#include <vision/nxtcam.h>
#include "stereo_config.h"
#include "delta_robot_args.h"
using namespace ev3dev;
using namespace std;
static cl::arg<vector3i> pid(
vector3i(5000, 5000, 100),
cl::name("pid"),
cl::desc("PID parameters Kp, Ki, Kd."));
static delta_robot_args delta_geometry("", "Delta robot geometry");
static stereo_config stereo;
static cl::arg<float> sample_rate(
30.0f,
cl::name("sample-rate"),
cl::desc("Frequency of camera observation samples, in Hz."));
static cl::arg<float> scale(
1.0f,
cl::name("scale"),
cl::desc("Ratio of robot movement to object movement."));
int main(int argc, const char **argv) {
cl::parse(argv[0], argc - 1, argv + 1);
// Reduce clutter of insignificant digits.
cout << fixed << showpoint << setprecision(3);
cerr << fixed << showpoint << setprecision(3);
nxtcam nxtcam0(port_to_i2c_path(stereo.cam0.port));
nxtcam nxtcam1(port_to_i2c_path(stereo.cam1.port));
cout << "Cameras:" << endl;
cout << nxtcam0.device_id() << " " << nxtcam0.version() << " (" << nxtcam0.vendor_id() << ")" << endl;
cout << nxtcam1.device_id() << " " << nxtcam1.version() << " (" << nxtcam1.vendor_id() << ")" << endl;
thread nxtcam_init_thread([&] () {
nxtcam0.track_objects();
nxtcam1.track_objects();
cout << "Tracking objects..." << endl;
});
// Initialize the delta robot.
delta_robot delta(delta_geometry.geometry());
if (scale > 0.0f) {
// Set the motor parameters.
delta.set_pid(pid->x, pid->y, pid->z);
delta.init();
// Bask in the glory of the calibration result for a moment.
this_thread::sleep_for(chrono::milliseconds(500));
}
nxtcam_init_thread.join();
pair<vector3f, float> volume = delta.get_volume();
cameraf cam0, cam1;
tie(cam0, cam1) = stereo.cameras();
float baseline = abs(cam1.x - cam0.x);
if (baseline < 1e-6f)
throw runtime_error("camera baseline is zero");
vector3f b = unit(cam1.x - cam0.x);
// t will increment in regular intervals of T.
typedef chrono::high_resolution_clock clock;
auto t = clock::now();
chrono::microseconds T(static_cast<int>(1e6f/sample_rate + 0.5f));
vector3f origin(0.0f, 0.0f, 0.0f);
string eraser;
while (true) {
nxtcam::blob_list blobs0 = nxtcam0.blobs();
nxtcam::blob_list blobs1 = nxtcam1.blobs();
if (blobs0.size() == 1 && blobs1.size() == 1) {
const nxtcam::blob &b0 = blobs0.front();
const nxtcam::blob &b1 = blobs1.front();
vector3f x0 = cam0.sensor_to_projection(b0.center(), 1.0f) - cam0.x;
vector3f x1 = cam1.sensor_to_projection(b1.center(), 1.0f) - cam1.x;
// z is determined by the stereo disparity.
float z = baseline/(dot(x0, b) - dot(x1, b));
// Move the points from the focal plane to the (parallel) plane containing z and add the camera origins.
x0 = x0*z + cam0.x;
x1 = x1*z + cam1.x;
vector3f x = (x0 + x1)/2;
stringstream ss;
ss << fixed << showpoint << setprecision(3);
ss << "x=" << x << ", ||x0 - x1||=" << abs(x0 - x1);
string msg = ss.str();
if (msg.length() > eraser.length())
eraser = string(msg.length(), ' ');
cout << msg << string(eraser.size() - msg.size(), ' ');
if (dot(origin, origin) == 0.0f)
origin = x*scale - volume.first;
x = x*scale - origin;
if (scale > 0.0f) {
try {
// Move to the position.
delta.set_position_setpoint(x);
} catch(runtime_error &) {
}
}
} else {
cout << eraser;
}
cout << "\r";
cout.flush();
t += T;
this_thread::sleep_until(t);
}
return 0;
}<commit_msg>More precise delta robot volume<commit_after>#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <thread>
#include <iomanip>
#include <chrono>
#include <vision/nxtcam.h>
#include "stereo_config.h"
#include "delta_robot_args.h"
using namespace ev3dev;
using namespace std;
static cl::arg<vector3i> pid(
vector3i(5000, 5000, 100),
cl::name("pid"),
cl::desc("PID parameters Kp, Ki, Kd."));
static delta_robot_args delta_geometry("", "Delta robot geometry");
static stereo_config stereo;
static cl::arg<float> sample_rate(
30.0f,
cl::name("sample-rate"),
cl::desc("Frequency of camera observation samples, in Hz."));
static cl::arg<float> scale(
1.0f,
cl::name("scale"),
cl::desc("Ratio of robot movement to object movement."));
int main(int argc, const char **argv) {
cl::parse(argv[0], argc - 1, argv + 1);
// Reduce clutter of insignificant digits.
cout << fixed << showpoint << setprecision(3);
cerr << fixed << showpoint << setprecision(3);
nxtcam nxtcam0(port_to_i2c_path(stereo.cam0.port));
nxtcam nxtcam1(port_to_i2c_path(stereo.cam1.port));
cout << "Cameras:" << endl;
cout << nxtcam0.device_id() << " " << nxtcam0.version() << " (" << nxtcam0.vendor_id() << ")" << endl;
cout << nxtcam1.device_id() << " " << nxtcam1.version() << " (" << nxtcam1.vendor_id() << ")" << endl;
thread nxtcam_init_thread([&] () {
nxtcam0.track_objects();
nxtcam1.track_objects();
cout << "Tracking objects..." << endl;
});
// Initialize the delta robot.
delta_robot delta(delta_geometry.geometry());
if (scale > 0.0f) {
// Set the motor parameters.
delta.set_pid(pid->x, pid->y, pid->z);
delta.init();
// Bask in the glory of the calibration result for a moment.
this_thread::sleep_for(chrono::milliseconds(500));
}
nxtcam_init_thread.join();
delta_robot::ellipse volume = delta.volume();
cameraf cam0, cam1;
tie(cam0, cam1) = stereo.cameras();
float baseline = abs(cam1.x - cam0.x);
if (baseline < 1e-6f)
throw runtime_error("camera baseline is zero");
vector3f b = unit(cam1.x - cam0.x);
// t will increment in regular intervals of T.
typedef chrono::high_resolution_clock clock;
auto t = clock::now();
chrono::microseconds T(static_cast<int>(1e6f/sample_rate + 0.5f));
vector3f origin(0.0f, 0.0f, 0.0f);
string eraser;
while (true) {
nxtcam::blob_list blobs0 = nxtcam0.blobs();
nxtcam::blob_list blobs1 = nxtcam1.blobs();
if (blobs0.size() == 1 && blobs1.size() == 1) {
const nxtcam::blob &b0 = blobs0.front();
const nxtcam::blob &b1 = blobs1.front();
vector3f x0 = cam0.sensor_to_projection(b0.center(), 1.0f) - cam0.x;
vector3f x1 = cam1.sensor_to_projection(b1.center(), 1.0f) - cam1.x;
// z is determined by the stereo disparity.
float z = baseline/(dot(x0, b) - dot(x1, b));
// Move the points from the focal plane to the (parallel) plane containing z and add the camera origins.
x0 = x0*z + cam0.x;
x1 = x1*z + cam1.x;
vector3f x = (x0 + x1)/2;
stringstream ss;
ss << fixed << showpoint << setprecision(3);
ss << "x=" << x << ", ||x0 - x1||=" << abs(x0 - x1) << ", z=" << z;
string msg = ss.str();
if (msg.length() > eraser.length())
eraser = string(msg.length(), ' ');
cout << msg << string(eraser.size() - msg.size(), ' ');
if (dot(origin, origin) == 0.0f)
origin = x*scale - volume.origin;
x = x*scale - origin;
if (scale > 0.0f) {
try {
// Move to the position.
delta.set_position_setpoint(x);
} catch(runtime_error &) {
}
}
} else {
cout << eraser;
}
cout << "\r";
cout.flush();
t += T;
this_thread::sleep_until(t);
}
return 0;
}<|endoftext|>
|
<commit_before>/* MergeSort.c
Este programa realiza el algoritmo paralelizado del MergeSort para ordenar una lista desordenada, el cual consiste en:
Dividir la lista recursivamente en sublistas de aproximadamente la mitad del tamano hasta que su tamano sea 1
Ordenar cada sublista recursivamente usando este algoritmo
Mezclar cada sublista hasta que se forme una sola
El programa ordena con p procesos una lista de n valores entre 0 y m, donde
p es el numero de procesos, lo define el usuario en "mpiexcec". Debe de ser potencia de 2
n es el tamaño de la lista a ordenas, se los pide al usuario el proceso raiz. Debe de se divisible por p
m es el rango de posibles valores que pueden aparecer en la lista, se los pide al usuario el proceso raiz. Debe ser <=60
Al final se despliega
Lista ordenada, si el usuario lo desea
Tiempo que tardo el ordenamieto
Valores de p, n y m
Numero de veces que aparecia en la lista cada uno de los posibles valores del 0 a m
*/
#include <stdio.h>
#include "mpi.h"
#include <stdlib.h>
#include<iostream>
#include <chrono>
#include <ctime>
using namespace std;
int main( int argc, char *argv[] )
{
int* lista; /* Lista que debe ser ordenada*/
int* lista_cantidadMenor;
int* lista_local;
int n; /* Dimension de los 2 vectores dada por el usuario */
int m; /* Limite de numeros aleatorios de la lista */
int p; /* Numero de procesos que corren */
int my_rank; /* Identificacion de cada proceso*/
int r;
int t;
int cantidadMenorTag = 11011;
void Genera_vector(int lista[], int n, int m); /* Genera valores aleatorios para n vector de enteros*/
MPI_Init(&argc, &argv); /* Inicializacion del ambiente para MPI. */
MPI_Comm_size(MPI_COMM_WORLD, &p); //Cantidad de procesos inicializados.
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); //El rango del proceso "local".
MPI_Comm balancer_comm; //Este comunicador sirve entre procesos que tengan el mísmo número de items.
MPI_Group original_group;
MPI_Comm_group(MPI_COMM_WORLD, &original_group); //
if (my_rank == 0) { /* LO QUE SIGUE LO REALIZA UNICAMENTE EL PROCESO 0 (PROCESO RAIZ o PRINCIPAL) */
std::cout << "Digite el tamano de la lista\n" << endl;
std::cin >> n;
std::cout << "Digite el limite de valores aleatorios en la lista" << endl;
std::cin >> m;
lista = (int *)malloc(n*sizeof(int));
if(lista==NULL){
std::cout << "Error al asignar memoria a la lista" << endl;
return 0;
}
Genera_vector(lista, n, m);
for(int i=0; i < n; i++) {
std::cout <<"parent WORLD: " << lista[i] << " ";
}
r = n % p; //Restante de la division de items en la lista entre los procesos.
//También indica los r primero procesos a recibir t+1 items.
t = (n - r)/p; //Cuantos items por proceso para que tengan el mismo número de procesos (no contando los restantes).
lista_cantidadMenor = lista+r;
if(r != 0){
MPI_Send (lista_cantidadMenor,n-r,MPI_INT,r,cantidadMenorTag, MPI_COMM_WORLD); //Mandamos la lista de cantidades menores al pocesador que se convertira
//en la raiz de su comunicador que se crea al hacer el split después.
std::cout << "0 is done sending lista_cantidadMenor" << std::endl;
}
free(lista_cantidadMenor);
}
MPI_Bcast(&t, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&r, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
if(my_rank == r-1)//Soy el proceso raíz del segundo subgrupo de comm.
{
MPI_Recv(lista,n-r,MPI_INT,r-1,cantidadMenorTag,MPI_COMM_WORLD,MPI_STATUS_IGNORE); //Recibir la lista de cantidades menores
}
//Vamos a dividir los procesos en dos sub comunicadores. El de color 1 que recibe t+1 items en sus listas.
//El de color 2 que recibe t items. Esto para garantizar una manera de recibir cualquier cantidad de n de items.
int color = my_rank < r ? 1 : 0; //Esto es para calcular el color (identificar procesos de un comunicador) del proceso.
//Aquí es donde se reparte los procesos según color y se identifican con el COMM handler balancer_comm.
MPI_Comm_split(MPI_COMM_WORLD, color, my_rank, &balancer_comm);
//Ahora, dependiendo del color, la lista será del tamaño t+1, o t.
lista_local = (int *)malloc((t+color)*sizeof(int));
if(r > 0){
//Vamos a repartir la lista. Para los procesos en COMM_WORLD con rank menor a r, esto reciben t+1, para los otro t.
MPI_Scatter(lista, t + 1, MPI_INT, lista_local, t + 1, MPI_INT, 0, balancer_comm);
MPI_Scatter(lista, t, MPI_INT, lista_local, t, MPI_INT, r-1, balancer_comm);
}else{
lista_local = lista;
}
std::cout << "Yo soy el proceso " << my_rank << " del comunicador: "<< balancer_comm << " first: " << lista_local[0] << std::endl;
if(my_rank == 0 || my_rank == r-1){
free(lista);
}
free(lista_local);
MPI_Finalize();
return 0;
}
void Genera_vector(int lista[], int n, int m)
{
int i;
for (i = 0; i < n; i++) {
//lista[i]= 0 + rand()%(m+1-0);
lista[i]= i;
}
}
<commit_msg>added necessary barriers<commit_after>/* MergeSort.c
Este programa realiza el algoritmo paralelizado del MergeSort para ordenar una lista desordenada, el cual consiste en:
Dividir la lista recursivamente en sublistas de aproximadamente la mitad del tamano hasta que su tamano sea 1
Ordenar cada sublista recursivamente usando este algoritmo
Mezclar cada sublista hasta que se forme una sola
El programa ordena con p procesos una lista de n valores entre 0 y m, donde
p es el numero de procesos, lo define el usuario en "mpiexcec". Debe de ser potencia de 2
n es el tamaño de la lista a ordenas, se los pide al usuario el proceso raiz. Debe de se divisible por p
m es el rango de posibles valores que pueden aparecer en la lista, se los pide al usuario el proceso raiz. Debe ser <=60
Al final se despliega
Lista ordenada, si el usuario lo desea
Tiempo que tardo el ordenamieto
Valores de p, n y m
Numero de veces que aparecia en la lista cada uno de los posibles valores del 0 a m
*/
#include <stdio.h>
#include "mpi.h"
#include <stdlib.h>
#include<iostream>
#include <chrono>
#include <ctime>
using namespace std;
int main( int argc, char *argv[] )
{
int* lista; /* Lista que debe ser ordenada*/
int* lista_cantidadMenor;
int* lista_local;
int n; /* Dimension de los 2 vectores dada por el usuario */
int m; /* Limite de numeros aleatorios de la lista */
int p; /* Numero de procesos que corren */
int my_rank; /* Identificacion de cada proceso*/
int r;
int t;
int cantidadMenorTag = 11011;
void Genera_vector(int lista[], int n, int m); /* Genera valores aleatorios para n vector de enteros*/
MPI_Init(&argc, &argv); /* Inicializacion del ambiente para MPI. */
MPI_Comm_size(MPI_COMM_WORLD, &p); //Cantidad de procesos inicializados.
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); //El rango del proceso "local".
MPI_Comm balancer_comm; //Este comunicador sirve entre procesos que tengan el mísmo número de items.
MPI_Group original_group;
MPI_Comm_group(MPI_COMM_WORLD, &original_group); //
if (my_rank == 0) { /* LO QUE SIGUE LO REALIZA UNICAMENTE EL PROCESO 0 (PROCESO RAIZ o PRINCIPAL) */
std::cout << "Digite el tamano de la lista\n" << endl;
std::cin >> n;
std::cout << "Digite el limite de valores aleatorios en la lista" << endl;
std::cin >> m;
lista = (int *)malloc(n*sizeof(int));
if(lista==NULL){
std::cout << "Error al asignar memoria a la lista" << endl;
return 0;
}
Genera_vector(lista, n, m);
for(int i=0; i < n; i++) {
std::cout <<"parent WORLD: " << lista[i] << " ";
}
r = n % p; //Restante de la division de items en la lista entre los procesos.
//También indica los r primero procesos a recibir t+1 items.
t = (n - r)/p; //Cuantos items por proceso para que tengan el mismo número de procesos (no contando los restantes).
int num_elementos_to_send = n - (2*r);
lista_cantidadMenor = lista+2*r;
for(int i = 0; i < num_elementos_to_send; i++){
std::cout <<"tesnting lista cantidad menor: " << lista_cantidadMenor[i] << std::endl;
}
if(r != 0){
std::cout << "About to send lista_cantidadMenor to process " << r << std::endl;
//MPI_Send (&buf,count,datatype,dest,tag,comm)
MPI_Send (lista_cantidadMenor,num_elementos_to_send,MPI_INT,r,cantidadMenorTag, MPI_COMM_WORLD); //Mandamos la lista de cantidades menores al pocesador que se convertira
//en la raiz de su comunicador que se crea al hacer el split después.
std::cout << "0 is done sending lista_cantidadMenor" << std::endl;
}
//free(lista_cantidadMenor);
lista_cantidadMenor = NULL;
}
MPI_Bcast(&t, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&r, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
if(my_rank == 0 ){std::cout << "Donde broadcasting with r = "<< r << std::endl; }
if(my_rank == r)//Soy el proceso raíz del segundo subgrupo de comm.
{
std::cout << "preparing list with n = " << n << std::endl;
int num_elementos_to_rcv = n - 2*r;
lista = (int *)malloc(num_elementos_to_rcv*sizeof(int));
if(lista==NULL){
std::cout << "Error al asignar memoria a la lista" << endl;
return 0;
}
std::cout << my_rank << " is bout to receive " << std::endl;
//MPI_Recv (&buf,count,datatype,source,tag,comm,&status)
MPI_Recv(lista,n-2*r,MPI_INT,0,cantidadMenorTag,MPI_COMM_WORLD,MPI_STATUS_IGNORE); //Recibir la lista de cantidades menores
std::cout << "Done receiving, starting testing: ";
for(int i = 0; i < n - 2*r; i++){
std::cout << "--" << lista[i] << std::endl;
}
std::cout << "la lista está terminada" <<std::endl;
}
//Vamos a dividir los procesos en dos sub comunicadores. El de color 1 que recibe t+1 items en sus listas.
//El de color 2 que recibe t items. Esto para garantizar una manera de recibir cualquier cantidad de n de items.
// std::cout << "Starting to calculate color for "<< my_rank <<std::endl;
int color = my_rank < r ? 1 : 0; //Esto es para calcular el color (identificar procesos de un comunicador) del proceso.
std::cout << " pro "<< my_rank << "with color "<< color << std::endl;
MPI_Barrier(MPI_COMM_WORLD);
//Aquí es donde se reparte los procesos según color y se identifican con el COMM handler balancer_comm.
MPI_Comm_split(MPI_COMM_WORLD, color, my_rank, &balancer_comm);
std::cout << "After Splitiing about to allocate "<< my_rank << " with balancer: "<< balancer_comm <<std::endl;
//Ahora, dependiendo del color, la lista será del tamaño t+1, o t.
lista_local = (int *)malloc((t+color)*sizeof(int));
std::cout << "Done allocating "<< my_rank <<std::endl;
MPI_Barrier(MPI_COMM_WORLD);
if(r > 0){
//Vamos a repartir la lista. Para los procesos en COMM_WORLD con rank menor a r, esto reciben t+1, para los otro t.
// MPI_Scatter (&sendbuf,sendcnt,sendtype,&recvbuf,recvcnt,recvtype,root,comm)
MPI_Scatter(lista, t + 1, MPI_INT, lista_local, t + 1, MPI_INT, 0, balancer_comm);
MPI_Scatter(lista, t, MPI_INT, lista_local, t, MPI_INT, 0, balancer_comm);
}else{
lista_local = lista;
}
MPI_Barrier(MPI_COMM_WORLD);
std::cout << "Yo soy el proceso " << my_rank << " first: " << lista_local[0] << std::endl;
if(my_rank == 0 || my_rank == r){
free(lista);
}
free(lista_local);
MPI_Finalize();
return 0;
}
void Genera_vector(int lista[], int n, int m)
{
int i;
for (i = 0; i < n; i++) {
//lista[i]= 0 + rand()%(m+1-0);
lista[i]= i;
}
}
<|endoftext|>
|
<commit_before>// Copyright 2014 BVLC and contributors.
#ifndef CAFFE_LAYER_H_
#define CAFFE_LAYER_H_
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/proto/caffe.pb.h"
using std::vector;
namespace caffe {
template <typename Dtype>
class Layer {
public:
// You should not implement your own constructor. Any set up code should go
// to SetUp(), where the dimensions of the bottom blobs are provided to the
// layer.
explicit Layer(const LayerParameter& param)
: layer_param_(param) {
// The only thing we do is to copy blobs if there are any.
if (layer_param_.blobs_size() > 0) {
blobs_.resize(layer_param_.blobs_size());
for (int i = 0; i < layer_param_.blobs_size(); ++i) {
blobs_[i].reset(new Blob<Dtype>());
blobs_[i]->FromProto(layer_param_.blobs(i));
}
}
}
virtual ~Layer() {}
// SetUp: your function should implement this.
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) = 0;
// Forward and backward wrappers. You should implement the cpu and
// gpu specific implementations instead, and should not change these
// functions.
inline Dtype Forward(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
inline void Backward(const vector<Blob<Dtype>*>& top,
const bool propagate_down,
vector<Blob<Dtype>*>* bottom);
// Returns the vector of blobs.
vector<shared_ptr<Blob<Dtype> > >& blobs() {
return blobs_;
}
// Returns the layer parameter
const LayerParameter& layer_param() { return layer_param_; }
// Writes the layer parameter to a protocol buffer
virtual void ToProto(LayerParameter* param, bool write_diff = false);
protected:
// The protobuf that stores the layer parameters
LayerParameter layer_param_;
// The vector that stores the parameters as a set of blobs.
vector<shared_ptr<Blob<Dtype> > > blobs_;
// Forward functions
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) = 0;
// If no gpu code is provided, we will simply use cpu code.
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {
// LOG(WARNING) << "Using CPU code as backup.";
return Forward_cpu(bottom, top);
}
// Backward functions: the backward function will compute the gradients for
// any parameters and also for the bottom blobs if propagate_down is true.
// It will return the loss produced from this layer.
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const bool propagate_down,
vector<Blob<Dtype>*>* bottom) = 0;
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const bool propagate_down,
vector<Blob<Dtype>*>* bottom) {
// LOG(WARNING) << "Using CPU code as backup.";
Backward_cpu(top, propagate_down, bottom);
}
DISABLE_COPY_AND_ASSIGN(Layer);
}; // class Layer
// Forward and backward wrappers. You should implement the cpu and
// gpu specific implementations instead, and should not change these
// functions.
template <typename Dtype>
inline Dtype Layer<Dtype>::Forward(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {
switch (Caffe::mode()) {
case Caffe::CPU:
return Forward_cpu(bottom, top);
case Caffe::GPU:
return Forward_gpu(bottom, top);
default:
LOG(FATAL) << "Unknown caffe mode.";
return Dtype(0);
}
}
template <typename Dtype>
inline void Layer<Dtype>::Backward(const vector<Blob<Dtype>*>& top,
const bool propagate_down,
vector<Blob<Dtype>*>* bottom) {
switch (Caffe::mode()) {
case Caffe::CPU:
Backward_cpu(top, propagate_down, bottom);
break;
case Caffe::GPU:
Backward_gpu(top, propagate_down, bottom);
break;
default:
LOG(FATAL) << "Unknown caffe mode.";
}
}
template <typename Dtype>
void Layer<Dtype>::ToProto(LayerParameter* param, bool write_diff) {
param->Clear();
param->CopyFrom(layer_param_);
param->clear_blobs();
for (int i = 0; i < blobs_.size(); ++i) {
blobs_[i]->ToProto(param->add_blobs(), write_diff);
}
}
// The layer factory function
template <typename Dtype>
Layer<Dtype>* GetLayer(const LayerParameter& param);
} // namespace caffe
#endif // CAFFE_LAYER_H_
<commit_msg>Comment current forward/backward responsibilities<commit_after>// Copyright 2014 BVLC and contributors.
#ifndef CAFFE_LAYER_H_
#define CAFFE_LAYER_H_
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/proto/caffe.pb.h"
using std::vector;
namespace caffe {
template <typename Dtype>
class Layer {
public:
// You should not implement your own constructor. Any set up code should go
// to SetUp(), where the dimensions of the bottom blobs are provided to the
// layer.
explicit Layer(const LayerParameter& param)
: layer_param_(param) {
// The only thing we do is to copy blobs if there are any.
if (layer_param_.blobs_size() > 0) {
blobs_.resize(layer_param_.blobs_size());
for (int i = 0; i < layer_param_.blobs_size(); ++i) {
blobs_[i].reset(new Blob<Dtype>());
blobs_[i]->FromProto(layer_param_.blobs(i));
}
}
}
virtual ~Layer() {}
// SetUp: your function should implement this.
virtual void SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) = 0;
// Forward and backward wrappers. You should implement the cpu and
// gpu specific implementations instead, and should not change these
// functions.
inline Dtype Forward(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
inline void Backward(const vector<Blob<Dtype>*>& top,
const bool propagate_down,
vector<Blob<Dtype>*>* bottom);
// Returns the vector of blobs.
vector<shared_ptr<Blob<Dtype> > >& blobs() {
return blobs_;
}
// Returns the layer parameter
const LayerParameter& layer_param() { return layer_param_; }
// Writes the layer parameter to a protocol buffer
virtual void ToProto(LayerParameter* param, bool write_diff = false);
protected:
// The protobuf that stores the layer parameters
LayerParameter layer_param_;
// The vector that stores the parameters as a set of blobs.
vector<shared_ptr<Blob<Dtype> > > blobs_;
// Forward functions: compute the layer output
// (and loss layers return the loss; other layers return the dummy value 0.)
virtual Dtype Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) = 0;
// If no gpu code is provided, we will simply use cpu code.
virtual Dtype Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {
// LOG(WARNING) << "Using CPU code as backup.";
return Forward_cpu(bottom, top);
}
// Backward functions: compute the gradients for any parameters and
// for the bottom blobs if propagate_down is true.
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const bool propagate_down,
vector<Blob<Dtype>*>* bottom) = 0;
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const bool propagate_down,
vector<Blob<Dtype>*>* bottom) {
// LOG(WARNING) << "Using CPU code as backup.";
Backward_cpu(top, propagate_down, bottom);
}
DISABLE_COPY_AND_ASSIGN(Layer);
}; // class Layer
// Forward and backward wrappers. You should implement the cpu and
// gpu specific implementations instead, and should not change these
// functions.
template <typename Dtype>
inline Dtype Layer<Dtype>::Forward(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {
switch (Caffe::mode()) {
case Caffe::CPU:
return Forward_cpu(bottom, top);
case Caffe::GPU:
return Forward_gpu(bottom, top);
default:
LOG(FATAL) << "Unknown caffe mode.";
return Dtype(0);
}
}
template <typename Dtype>
inline void Layer<Dtype>::Backward(const vector<Blob<Dtype>*>& top,
const bool propagate_down,
vector<Blob<Dtype>*>* bottom) {
switch (Caffe::mode()) {
case Caffe::CPU:
Backward_cpu(top, propagate_down, bottom);
break;
case Caffe::GPU:
Backward_gpu(top, propagate_down, bottom);
break;
default:
LOG(FATAL) << "Unknown caffe mode.";
}
}
// Serialize LayerParameter to protocol buffer
template <typename Dtype>
void Layer<Dtype>::ToProto(LayerParameter* param, bool write_diff) {
param->Clear();
param->CopyFrom(layer_param_);
param->clear_blobs();
for (int i = 0; i < blobs_.size(); ++i) {
blobs_[i]->ToProto(param->add_blobs(), write_diff);
}
}
// The layer factory function
template <typename Dtype>
Layer<Dtype>* GetLayer(const LayerParameter& param);
} // namespace caffe
#endif // CAFFE_LAYER_H_
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include "config.h"
#include <cassert>
#include "stored-value.hh"
#ifndef DEFAULT_HT_SIZE
#define DEFAULT_HT_SIZE 12582917
#endif
size_t HashTable::defaultNumBuckets = DEFAULT_HT_SIZE;
size_t HashTable::defaultNumLocks = 193;
enum stored_value_type HashTable::defaultStoredValueType = featured;
static inline size_t getDefault(size_t x, size_t d) {
return x == 0 ? d : x;
}
/**
* Get the number of buckets for a hash table.
*
* @param n the desired number of buckets, if 0, use the default
*
* @return the number of buckets to create
*/
size_t HashTable::getNumBuckets(size_t n = 0) {
return getDefault(n, defaultNumBuckets);
}
/**
* Get the number of locks for a hash table.
*
* @param n the desired number of locks, if 0, use the default
*
* @return the number of locks to create
*/
size_t HashTable::getNumLocks(size_t n = 0) {
return getDefault(n, defaultNumLocks);
}
/**
* Set the default number of hashtable buckets.
*/
void HashTable::setDefaultNumBuckets(size_t to) {
if (to != 0) {
defaultNumBuckets = to;
}
}
/**
* Set the default number of hashtable locks.
*/
void HashTable::setDefaultNumLocks(size_t to) {
if (to != 0) {
defaultNumLocks = to;
}
}
size_t HashTable::clear(bool deactivate) {
size_t rv = 0;
if (!deactivate) {
// If not deactivating, assert we're already active.
assert(active());
}
MultiLockHolder(mutexes, n_locks);
if (deactivate) {
active(false);
}
for (int i = 0; i < (int)size; i++) {
while (values[i]) {
++rv;
StoredValue *v = values[i];
values[i] = v->next;
delete v;
}
}
numItems.set(0);
return rv;
}
void HashTable::visit(HashTableVisitor &visitor) {
if (!active()) {
return;
}
VisitorTracker vt(&visitors);
bool aborted = !visitor.shouldContinue();
size_t visited = 0;
for (int l = 0; active() && !aborted && l < static_cast<int>(n_locks); l++) {
LockHolder lh(getMutex(l));
for (int i = l; i < static_cast<int>(size); i+= n_locks) {
assert(l == mutexForBucket(i));
StoredValue *v = values[i];
while (v) {
visitor.visit(v);
v = v->next;
}
++visited;
}
lh.unlock();
aborted = !visitor.shouldContinue();
}
assert(aborted || visited == size);
}
void HashTable::visitDepth(HashTableDepthVisitor &visitor) {
if (!active()) {
return;
}
size_t visited = 0;
VisitorTracker vt(&visitors);
for (int l = 0; l < static_cast<int>(n_locks); l++) {
LockHolder lh(getMutex(l));
for (int i = l; i < static_cast<int>(size); i+= n_locks) {
size_t depth = 0;
StoredValue *p = values[i];
while (p) {
depth++;
p = p->next;
}
visitor.visit(i, depth);
++visited;
}
}
assert(visited == size);
}
bool HashTable::setDefaultStorageValueType(const char *t) {
bool rv = false;
if (t && strcmp(t, "featured") == 0) {
setDefaultStorageValueType(featured);
rv = true;
} else if (t && strcmp(t, "small") == 0) {
setDefaultStorageValueType(small);
rv = true;
}
return rv;
}
void HashTable::setDefaultStorageValueType(enum stored_value_type t) {
defaultStoredValueType = t;
}
enum stored_value_type HashTable::getDefaultStorageValueType() {
return defaultStoredValueType;
}
const char* HashTable::getDefaultStorageValueTypeStr() {
const char *rv = "unknown";
switch(getDefaultStorageValueType()) {
case small: rv = "small"; break;
case featured: rv = "featured"; break;
default: abort();
}
return rv;
}
/**
* Get the maximum amount of memory available for storing data.
*
* @return the memory ceiling
*/
size_t StoredValue::getMaxDataSize(EPStats& st) {
return st.maxDataSize;
}
/**
* Set the default number of bytes available for stored values.
*/
void StoredValue::setMaxDataSize(EPStats &st, size_t to) {
if (to != 0) {
st.maxDataSize = to;
}
}
/**
* What's the total size of allocations?
*/
size_t StoredValue::getCurrentSize(EPStats &st) {
return st.currentSize.get() + st.memOverhead.get();
}
size_t StoredValue::getTotalCacheSize(EPStats &st) {
return st.totalCacheSize.get();
}
void StoredValue::increaseCurrentSize(EPStats &st, size_t by, bool residentOnly) {
if (!residentOnly) {
st.totalCacheSize.incr(by);
}
st.currentSize.incr(by);
assert(st.currentSize.get() < GIGANTOR);
}
void StoredValue::reduceCurrentSize(EPStats &st, size_t by, bool residentOnly) {
size_t val;
do {
val = st.currentSize.get();
assert(val >= by);
} while (!st.currentSize.cas(val, val - by));;
if (!residentOnly) {
st.totalCacheSize.decr(by);
}
}
/**
* Is there enough space for this thing?
*/
bool StoredValue::hasAvailableSpace(EPStats &st, const Item &item) {
return getCurrentSize(st) + sizeof(StoredValue) + item.getNKey() + item.getNBytes()
<= getMaxDataSize(st);
}
<commit_msg>Don't visit empty hash tables.<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include "config.h"
#include <cassert>
#include "stored-value.hh"
#ifndef DEFAULT_HT_SIZE
#define DEFAULT_HT_SIZE 12582917
#endif
size_t HashTable::defaultNumBuckets = DEFAULT_HT_SIZE;
size_t HashTable::defaultNumLocks = 193;
enum stored_value_type HashTable::defaultStoredValueType = featured;
static inline size_t getDefault(size_t x, size_t d) {
return x == 0 ? d : x;
}
/**
* Get the number of buckets for a hash table.
*
* @param n the desired number of buckets, if 0, use the default
*
* @return the number of buckets to create
*/
size_t HashTable::getNumBuckets(size_t n = 0) {
return getDefault(n, defaultNumBuckets);
}
/**
* Get the number of locks for a hash table.
*
* @param n the desired number of locks, if 0, use the default
*
* @return the number of locks to create
*/
size_t HashTable::getNumLocks(size_t n = 0) {
return getDefault(n, defaultNumLocks);
}
/**
* Set the default number of hashtable buckets.
*/
void HashTable::setDefaultNumBuckets(size_t to) {
if (to != 0) {
defaultNumBuckets = to;
}
}
/**
* Set the default number of hashtable locks.
*/
void HashTable::setDefaultNumLocks(size_t to) {
if (to != 0) {
defaultNumLocks = to;
}
}
size_t HashTable::clear(bool deactivate) {
size_t rv = 0;
if (!deactivate) {
// If not deactivating, assert we're already active.
assert(active());
}
MultiLockHolder(mutexes, n_locks);
if (deactivate) {
active(false);
}
for (int i = 0; i < (int)size; i++) {
while (values[i]) {
++rv;
StoredValue *v = values[i];
values[i] = v->next;
delete v;
}
}
numItems.set(0);
return rv;
}
void HashTable::visit(HashTableVisitor &visitor) {
if (numItems.get() == 0 || !active()) {
return;
}
VisitorTracker vt(&visitors);
bool aborted = !visitor.shouldContinue();
size_t visited = 0;
for (int l = 0; active() && !aborted && l < static_cast<int>(n_locks); l++) {
LockHolder lh(getMutex(l));
for (int i = l; i < static_cast<int>(size); i+= n_locks) {
assert(l == mutexForBucket(i));
StoredValue *v = values[i];
while (v) {
visitor.visit(v);
v = v->next;
}
++visited;
}
lh.unlock();
aborted = !visitor.shouldContinue();
}
assert(aborted || visited == size);
}
void HashTable::visitDepth(HashTableDepthVisitor &visitor) {
if (numItems.get() == 0 || !active()) {
return;
}
size_t visited = 0;
VisitorTracker vt(&visitors);
for (int l = 0; l < static_cast<int>(n_locks); l++) {
LockHolder lh(getMutex(l));
for (int i = l; i < static_cast<int>(size); i+= n_locks) {
size_t depth = 0;
StoredValue *p = values[i];
while (p) {
depth++;
p = p->next;
}
visitor.visit(i, depth);
++visited;
}
}
assert(visited == size);
}
bool HashTable::setDefaultStorageValueType(const char *t) {
bool rv = false;
if (t && strcmp(t, "featured") == 0) {
setDefaultStorageValueType(featured);
rv = true;
} else if (t && strcmp(t, "small") == 0) {
setDefaultStorageValueType(small);
rv = true;
}
return rv;
}
void HashTable::setDefaultStorageValueType(enum stored_value_type t) {
defaultStoredValueType = t;
}
enum stored_value_type HashTable::getDefaultStorageValueType() {
return defaultStoredValueType;
}
const char* HashTable::getDefaultStorageValueTypeStr() {
const char *rv = "unknown";
switch(getDefaultStorageValueType()) {
case small: rv = "small"; break;
case featured: rv = "featured"; break;
default: abort();
}
return rv;
}
/**
* Get the maximum amount of memory available for storing data.
*
* @return the memory ceiling
*/
size_t StoredValue::getMaxDataSize(EPStats& st) {
return st.maxDataSize;
}
/**
* Set the default number of bytes available for stored values.
*/
void StoredValue::setMaxDataSize(EPStats &st, size_t to) {
if (to != 0) {
st.maxDataSize = to;
}
}
/**
* What's the total size of allocations?
*/
size_t StoredValue::getCurrentSize(EPStats &st) {
return st.currentSize.get() + st.memOverhead.get();
}
size_t StoredValue::getTotalCacheSize(EPStats &st) {
return st.totalCacheSize.get();
}
void StoredValue::increaseCurrentSize(EPStats &st, size_t by, bool residentOnly) {
if (!residentOnly) {
st.totalCacheSize.incr(by);
}
st.currentSize.incr(by);
assert(st.currentSize.get() < GIGANTOR);
}
void StoredValue::reduceCurrentSize(EPStats &st, size_t by, bool residentOnly) {
size_t val;
do {
val = st.currentSize.get();
assert(val >= by);
} while (!st.currentSize.cas(val, val - by));;
if (!residentOnly) {
st.totalCacheSize.decr(by);
}
}
/**
* Is there enough space for this thing?
*/
bool StoredValue::hasAvailableSpace(EPStats &st, const Item &item) {
return getCurrentSize(st) + sizeof(StoredValue) + item.getNKey() + item.getNBytes()
<= getMaxDataSize(st);
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.