text
stringlengths
54
60.6k
<commit_before>/** * @file ActionSimulator.cpp * @author <a href="mailto:schlottb@informatik.hu-berlin.de">Benjamin Schlotter</a> * Implementation of class ActionSimulator */ #include "ActionSimulator.h" #include <algorithm> using namespace naoth; using namespace std; ActionSimulator::ActionSimulator() : // own goal ownGoalBackSides({ Math::LineSegment(getFieldInfo().ownGoalBackLeft, getFieldInfo().ownGoalBackRight), Math::LineSegment(getFieldInfo().ownGoalPostLeft, getFieldInfo().ownGoalBackLeft), Math::LineSegment(getFieldInfo().ownGoalPostRight, getFieldInfo().ownGoalBackRight) }), // opp goal oppGoalBackSides({ Math::LineSegment(getFieldInfo().oppGoalBackLeft , getFieldInfo().oppGoalBackRight), Math::LineSegment(getFieldInfo().opponentGoalPostLeft , getFieldInfo().oppGoalBackLeft), Math::LineSegment(getFieldInfo().opponentGoalPostRight, getFieldInfo().oppGoalBackRight)} ) { DEBUG_REQUEST_REGISTER("Simulation:draw_goal_collisions", "draw goal collisions", false); DEBUG_REQUEST_REGISTER("Simulation:draw_potential_field", "draw potential field", false); } ActionSimulator::~ActionSimulator(){} void ActionSimulator::execute() { }//end execute void ActionSimulator::simulateAction(const Action& action, ActionResults& result, size_t numParticles) const { // just as a safety measure //categorizedBallPositions.clear(); //categorizedBallPositions.reserve(static_cast<int>(theParameters.numParticles)); result.reset(); // current ball position Vector2d globalBallStartPosition = getRobotPose() * getBallModel().positionPreview; // now generate predictions and categorize for(size_t j=0; j < numParticles; ++j) { // predict and calculate shoot line Vector2d globalBallEndPosition = getRobotPose() * action.predict(getBallModel().positionPreview, true); // check if collision detection with goal has to be performed // if the ball start and end positions are inside of the field, you don't need to check if(!getFieldInfo().fieldRect.inside(globalBallEndPosition) || !getFieldInfo().fieldRect.inside(globalBallStartPosition)) { // calculate if there is a collision with the opponent goal and where the ball would stop bool collisionWithOppGoal = calculateCollision(oppGoalBackSides, globalBallStartPosition, globalBallEndPosition, globalBallEndPosition); bool collisionWithOwnGoal = calculateCollision(ownGoalBackSides, globalBallStartPosition, globalBallEndPosition, globalBallEndPosition); // draw balls and goal box if there are collisions DEBUG_REQUEST("Simulation:draw_goal_collisions", if (collisionWithOppGoal) { FIELD_DRAWING_CONTEXT; PEN("000000", 10); BOX(getFieldInfo().oppGoalRect.min().x, getFieldInfo().oppGoalRect.min().y, getFieldInfo().oppGoalRect.max().x, getFieldInfo().oppGoalRect.max().y); if (getFieldInfo().oppGoalRect.inside(globalBallEndPosition)) { PEN("0000AA66", 1); } else { PEN("FF00AA66", 1); } const double r = getFieldInfo().ballRadius; FILLOVAL(globalBallEndPosition.x, globalBallEndPosition.y, r, r); } else if (collisionWithOwnGoal){ FIELD_DRAWING_CONTEXT; PEN("000000", 10); BOX(getFieldInfo().ownGoalRect.min().x, getFieldInfo().ownGoalRect.min().y, getFieldInfo().ownGoalRect.max().x, getFieldInfo().ownGoalRect.max().y); if (getFieldInfo().ownGoalRect.inside(globalBallEndPosition)) { PEN("0000AA66", 1); } else { PEN("FF00AA66", 1); } const double r = getFieldInfo().ballRadius; FILLOVAL(globalBallEndPosition.x, globalBallEndPosition.y, r, r); } ); } // default category BallPositionCategory category = classifyBallPosition(globalBallEndPosition); result.add(getRobotPose() / globalBallEndPosition, category); } } bool ActionSimulator::calculateCollision(const vector<Math::LineSegment>& lines, const Vector2d& start, const Vector2d& end, Vector2d& result) const { Math::LineSegment motionLine(start, end); double t_min = motionLine.getLength(); bool collision = false; for(const Math::LineSegment& segment: lines) { const double t = motionLine.Line::intersection(segment); if(t >= 0 && t < t_min && segment.intersect(motionLine)) { t_min = t; collision = true; } } if(collision) { result = motionLine.point(t_min-getFieldInfo().ballRadius); } else { result = end; } return collision; } ActionSimulator::BallPositionCategory ActionSimulator::classifyBallPosition( const Vector2d& globalBallPosition ) const { BallPositionCategory category = INFIELD; // goal!! if(getFieldInfo().oppGoalRect.inside(globalBallPosition)) { category = OPPGOAL; } // own goal :( else if(getFieldInfo().ownGoalRect.inside(globalBallPosition)) { category = OWNGOAL; } // inside field // HACK: small gap between this and the borders of the goalbox //check y coordinates and else if(getFieldInfo().fieldRect.inside(globalBallPosition) || // TODO: do we really need it? (globalBallPosition.x <= getFieldInfo().opponentGoalPostRight.x && globalBallPosition.y > getFieldInfo().opponentGoalPostRight.y && globalBallPosition.y < getFieldInfo().opponentGoalPostLeft.y) ) { category = INFIELD; } // HHHHHHH FIXME //Opponent Groundline Out - Ball einen Meter hinter Roboter mind ansto hhe. jeweils seite wo ins ausgeht else if(globalBallPosition.x > getFieldInfo().xPosOpponentGroundline) { category = OPPOUT; } //Own Groundline out - an der seite wo raus geht else if(globalBallPosition.x < getFieldInfo().xPosOwnGroundline) { category = OWNOUT; } //an der linken Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter else if(globalBallPosition.y > getFieldInfo().yPosLeftSideline ) { category = LEFTOUT; } //an der rechten Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter else if(globalBallPosition.y < getFieldInfo().yPosRightSideline) { category = RIGHTOUT; } return category; } //correction of distance in percentage, angle in degrees // TODO unify with ballmodel Vector2d ActionSimulator::Action::predict(const Vector2d& ball, bool noise) const { double gforce = Math::g*1e3; // mm/s^2 double distance; double angle; if (noise){ double speed = Math::generateGaussianNoise(action_speed, action_speed_std); angle = Math::generateGaussianNoise(Math::fromDegrees(action_angle), Math::fromDegrees(action_angle_std)); distance = speed*speed / friction / gforce / 2.0; // friction*mass*gforce*distance = 1/2*mass*speed*speed } else { distance = action_speed*action_speed / friction / gforce / 2.0; // friction*mass*gforce*distance = 1/2*mass*speed*speed angle = Math::fromDegrees(action_angle); } Vector2d predictedAction(distance, 0.0); predictedAction.rotate(angle); return ball + predictedAction; } double ActionSimulator::evaluateAction(const Vector2d& a) const { double xPosOpponentGoal = getFieldInfo().xPosOpponentGoal; double yPosLeftSideline = getFieldInfo().yPosLeftSideline; double xPosOwnGoal = getFieldInfo().xPosOwnGoal; double sigmaX = xPosOpponentGoal/2.0; double sigmaY = yPosLeftSideline/2.5; double slopeX = -1.0/xPosOpponentGoal; double f = 0.0; f += slope(a.x, a.y, slopeX, 0.0); f -= gaussian(a.x, a.y, xPosOpponentGoal, 0.0, sigmaX, sigmaY); f += gaussian(a.x, a.y, xPosOwnGoal, 0.0, 1.5*sigmaX, sigmaY); return f; } double ActionSimulator::evaluateAction(const ActionResults& results) const { double sumPotential = 0.0; double numberOfActions = 0.0; for(ActionResults::Positions::const_iterator p = results.positions().begin(); p != results.positions().end(); ++p) { // assumes that the potential field is well defined inside the opponent goal if(p->cat() == INFIELD || p->cat() == OPPGOAL) { sumPotential += evaluateAction(getRobotPose() * p->pos()); numberOfActions++; } } ASSERT(numberOfActions > 0); sumPotential /= numberOfActions; return sumPotential; } void ActionSimulator::draw_potential_field() const { static const int ySize = 20; static const int xSize = 30; double yWidth = 0.5*getFieldInfo().yFieldLength/(double)ySize; double xWidth = 0.5*getFieldInfo().xFieldLength/(double)xSize; FIELD_DRAWING_CONTEXT; Color white(0.0,0.0,1.0,0.5); // transparent Color black(1.0,0.0,0.0,0.5); // create new sample set std::vector<double> potential(xSize*ySize); int idx = 0; for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { Vector2d point(xWidth*(2*x-xSize+1), yWidth*(2*y-ySize+1)); potential[idx] = evaluateAction(point); idx++; } } auto result = std::minmax_element(potential.begin(), potential.end()); double range = *result.second - *result.first; if(range == 0) { return; } idx = 0; for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { Vector2d point(xWidth*(2*x-xSize+1), yWidth*(2*y-ySize+1)); double t = (potential[idx++] - *result.first) / range; Color color = black*t + white*(1-t); PEN(color, 20); FILLBOX(point.x - xWidth, point.y - yWidth, point.x+xWidth, point.y+yWidth); } } }//end draw_closest_points <commit_msg>fix weird comments in ActionSimulator<commit_after>/** * @file ActionSimulator.cpp * @author <a href="mailto:schlottb@informatik.hu-berlin.de">Benjamin Schlotter</a> * Implementation of class ActionSimulator */ #include "ActionSimulator.h" #include <algorithm> using namespace naoth; using namespace std; ActionSimulator::ActionSimulator() : // own goal ownGoalBackSides({ Math::LineSegment(getFieldInfo().ownGoalBackLeft, getFieldInfo().ownGoalBackRight), Math::LineSegment(getFieldInfo().ownGoalPostLeft, getFieldInfo().ownGoalBackLeft), Math::LineSegment(getFieldInfo().ownGoalPostRight, getFieldInfo().ownGoalBackRight) }), // opp goal oppGoalBackSides({ Math::LineSegment(getFieldInfo().oppGoalBackLeft , getFieldInfo().oppGoalBackRight), Math::LineSegment(getFieldInfo().opponentGoalPostLeft , getFieldInfo().oppGoalBackLeft), Math::LineSegment(getFieldInfo().opponentGoalPostRight, getFieldInfo().oppGoalBackRight)} ) { DEBUG_REQUEST_REGISTER("Simulation:draw_goal_collisions", "draw goal collisions", false); DEBUG_REQUEST_REGISTER("Simulation:draw_potential_field", "draw potential field", false); } ActionSimulator::~ActionSimulator(){} void ActionSimulator::execute() { }//end execute void ActionSimulator::simulateAction(const Action& action, ActionResults& result, size_t numParticles) const { // just as a safety measure //categorizedBallPositions.clear(); //categorizedBallPositions.reserve(static_cast<int>(theParameters.numParticles)); result.reset(); // current ball position Vector2d globalBallStartPosition = getRobotPose() * getBallModel().positionPreview; // now generate predictions and categorize for(size_t j=0; j < numParticles; ++j) { // predict and calculate shoot line Vector2d globalBallEndPosition = getRobotPose() * action.predict(getBallModel().positionPreview, true); // check if collision detection with goal has to be performed // if the ball start and end positions are inside of the field, you don't need to check if(!getFieldInfo().fieldRect.inside(globalBallEndPosition) || !getFieldInfo().fieldRect.inside(globalBallStartPosition)) { // calculate if there is a collision with the opponent goal and where the ball would stop bool collisionWithOppGoal = calculateCollision(oppGoalBackSides, globalBallStartPosition, globalBallEndPosition, globalBallEndPosition); bool collisionWithOwnGoal = calculateCollision(ownGoalBackSides, globalBallStartPosition, globalBallEndPosition, globalBallEndPosition); // draw balls and goal box if there are collisions DEBUG_REQUEST("Simulation:draw_goal_collisions", if (collisionWithOppGoal) { FIELD_DRAWING_CONTEXT; PEN("000000", 10); BOX(getFieldInfo().oppGoalRect.min().x, getFieldInfo().oppGoalRect.min().y, getFieldInfo().oppGoalRect.max().x, getFieldInfo().oppGoalRect.max().y); if (getFieldInfo().oppGoalRect.inside(globalBallEndPosition)) { PEN("0000AA66", 1); } else { PEN("FF00AA66", 1); } const double r = getFieldInfo().ballRadius; FILLOVAL(globalBallEndPosition.x, globalBallEndPosition.y, r, r); } else if (collisionWithOwnGoal){ FIELD_DRAWING_CONTEXT; PEN("000000", 10); BOX(getFieldInfo().ownGoalRect.min().x, getFieldInfo().ownGoalRect.min().y, getFieldInfo().ownGoalRect.max().x, getFieldInfo().ownGoalRect.max().y); if (getFieldInfo().ownGoalRect.inside(globalBallEndPosition)) { PEN("0000AA66", 1); } else { PEN("FF00AA66", 1); } const double r = getFieldInfo().ballRadius; FILLOVAL(globalBallEndPosition.x, globalBallEndPosition.y, r, r); } ); } // default category BallPositionCategory category = classifyBallPosition(globalBallEndPosition); result.add(getRobotPose() / globalBallEndPosition, category); } } bool ActionSimulator::calculateCollision(const vector<Math::LineSegment>& lines, const Vector2d& start, const Vector2d& end, Vector2d& result) const { Math::LineSegment motionLine(start, end); double t_min = motionLine.getLength(); bool collision = false; for(const Math::LineSegment& segment: lines) { const double t = motionLine.Line::intersection(segment); if(t >= 0 && t < t_min && segment.intersect(motionLine)) { t_min = t; collision = true; } } if(collision) { result = motionLine.point(t_min-getFieldInfo().ballRadius); } else { result = end; } return collision; } ActionSimulator::BallPositionCategory ActionSimulator::classifyBallPosition( const Vector2d& globalBallPosition ) const { BallPositionCategory category = INFIELD; // goal!! if(getFieldInfo().oppGoalRect.inside(globalBallPosition)) { category = OPPGOAL; } // own goal :( else if(getFieldInfo().ownGoalRect.inside(globalBallPosition)) { category = OWNGOAL; } // inside field // HACK: small gap between this and the borders of the goalbox //check y coordinates and else if(getFieldInfo().fieldRect.inside(globalBallPosition) || // TODO: do we really need it? (globalBallPosition.x <= getFieldInfo().opponentGoalPostRight.x && globalBallPosition.y > getFieldInfo().opponentGoalPostRight.y && globalBallPosition.y < getFieldInfo().opponentGoalPostLeft.y) ) { category = INFIELD; } //Opponent Groundline Out else if(globalBallPosition.x > getFieldInfo().xPosOpponentGroundline) { category = OPPOUT; } //Own Groundline out else if(globalBallPosition.x < getFieldInfo().xPosOwnGroundline) { category = OWNOUT; } //an der linken Seite raus else if(globalBallPosition.y > getFieldInfo().yPosLeftSideline ) { category = LEFTOUT; } //an der rechten Seite raus else if(globalBallPosition.y < getFieldInfo().yPosRightSideline) { category = RIGHTOUT; } return category; } //correction of distance in percentage, angle in degrees // TODO unify with ballmodel Vector2d ActionSimulator::Action::predict(const Vector2d& ball, bool noise) const { double gforce = Math::g*1e3; // mm/s^2 double distance; double angle; if (noise){ double speed = Math::generateGaussianNoise(action_speed, action_speed_std); angle = Math::generateGaussianNoise(Math::fromDegrees(action_angle), Math::fromDegrees(action_angle_std)); distance = speed*speed / friction / gforce / 2.0; // friction*mass*gforce*distance = 1/2*mass*speed*speed } else { distance = action_speed*action_speed / friction / gforce / 2.0; // friction*mass*gforce*distance = 1/2*mass*speed*speed angle = Math::fromDegrees(action_angle); } Vector2d predictedAction(distance, 0.0); predictedAction.rotate(angle); return ball + predictedAction; } double ActionSimulator::evaluateAction(const Vector2d& a) const { double xPosOpponentGoal = getFieldInfo().xPosOpponentGoal; double yPosLeftSideline = getFieldInfo().yPosLeftSideline; double xPosOwnGoal = getFieldInfo().xPosOwnGoal; double sigmaX = xPosOpponentGoal/2.0; double sigmaY = yPosLeftSideline/2.5; double slopeX = -1.0/xPosOpponentGoal; double f = 0.0; f += slope(a.x, a.y, slopeX, 0.0); f -= gaussian(a.x, a.y, xPosOpponentGoal, 0.0, sigmaX, sigmaY); f += gaussian(a.x, a.y, xPosOwnGoal, 0.0, 1.5*sigmaX, sigmaY); return f; } double ActionSimulator::evaluateAction(const ActionResults& results) const { double sumPotential = 0.0; double numberOfActions = 0.0; for(ActionResults::Positions::const_iterator p = results.positions().begin(); p != results.positions().end(); ++p) { // assumes that the potential field is well defined inside the opponent goal if(p->cat() == INFIELD || p->cat() == OPPGOAL) { sumPotential += evaluateAction(getRobotPose() * p->pos()); numberOfActions++; } } ASSERT(numberOfActions > 0); sumPotential /= numberOfActions; return sumPotential; } void ActionSimulator::draw_potential_field() const { static const int ySize = 20; static const int xSize = 30; double yWidth = 0.5*getFieldInfo().yFieldLength/(double)ySize; double xWidth = 0.5*getFieldInfo().xFieldLength/(double)xSize; FIELD_DRAWING_CONTEXT; Color white(0.0,0.0,1.0,0.5); // transparent Color black(1.0,0.0,0.0,0.5); // create new sample set std::vector<double> potential(xSize*ySize); int idx = 0; for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { Vector2d point(xWidth*(2*x-xSize+1), yWidth*(2*y-ySize+1)); potential[idx] = evaluateAction(point); idx++; } } auto result = std::minmax_element(potential.begin(), potential.end()); double range = *result.second - *result.first; if(range == 0) { return; } idx = 0; for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { Vector2d point(xWidth*(2*x-xSize+1), yWidth*(2*y-ySize+1)); double t = (potential[idx++] - *result.first) / range; Color color = black*t + white*(1-t); PEN(color, 20); FILLBOX(point.x - xWidth, point.y - yWidth, point.x+xWidth, point.y+yWidth); } } }//end draw_closest_points <|endoftext|>
<commit_before><commit_msg>remove extraneous log<commit_after><|endoftext|>
<commit_before>/* * Source/sersic.cpp * * Created on: Feb 28, 2010 * Author: R.B. Metcalf */ #include "slsimlib.h" SersicSource::SersicSource( double my_mag /// Total magnitude ,double my_Reff /// Bulge half light radius (arcs) ,double my_PA /// Position angle (radians) ,double my_index /// Sersic index ,double my_q // axes ratio ,double my_z /// optional redshift ,const double *my_theta /// optional angular position on the sky ) : Source(), mag(my_mag), Reff(my_Reff*pi/180/60/60), PA(my_PA), index(my_index), q(my_q) { setZ(my_z); if(my_theta) setX(my_theta[0], my_theta[1]); setInternals(); } SersicSource::~SersicSource() { } void SersicSource::getParameters(Parameters& p) const { // base class serialization Source::getParameters(p); p << Reff << mag << PA << index << bn << q << Ieff << flux; } void SersicSource::setParameters(Parameters& p) { // base class deserialization Source::setParameters(p); p >> Reff >> mag >> PA >> index >> bn >> q >> Ieff >> flux; } void SersicSource::randomize(double step, long* seed) { // half light radius Reff += step*pi/180/60/60*gasdev(seed); // magnitude mag += step*gasdev(seed); // position angle //PA += step*pi*gasdev(seed); // Sersic index index += step*gasdev(seed); // axes ratio //q += step*gasdev(seed); // redshift? // position source_x[0] += step*pi/180/60/60*gasdev(seed); source_x[1] += step*pi/180/60/60*gasdev(seed); // update setInternals(); } void SersicSource::setInternals() { // approximation valid for 0.5 < n < 8 bn = 1.9992*index - 0.3271; flux = pow(10,-0.4*(mag+48.6)); Ieff = flux/2./pi/Reff/Reff/exp(bn)/index*pow(bn,2*index)/tgamma(2*index)/q; // radius in Source // approximation of the radius that encloses 99% of the flux setRadius((3.73 - 0.926*index + 1.164*index*index)*Reff); } double SersicSource::SurfaceBrightness( double *x /// position in radians relative to center of source ){ double x_new[2]; x_new[0] = (x[0]-source_x[0])*cos(PA)-(x[1]-source_x[1])*sin(PA); x_new[1] = (x[0]-source_x[0])*sin(PA)+(x[1]-source_x[1])*cos(PA); double r = sqrt(x_new[0]*x_new[0]+x_new[1]*x_new[1]/q/q); double sb = Ieff * exp(-bn*(pow(r/Reff,1./index)-1.))*inv_hplanck; if (sb < sb_limit) return 0.; return sb; } void SersicSource::printSource(){} void SersicSource::assignParams(InputParams& /* params */){} <commit_msg>Made clockwise rotation for SersicSources in cpp<commit_after>/* * Source/sersic.cpp * * Created on: Feb 28, 2010 * Author: R.B. Metcalf */ #include "slsimlib.h" SersicSource::SersicSource( double my_mag /// Total magnitude ,double my_Reff /// Bulge half light radius (arcs) ,double my_PA /// Position angle (radians) ,double my_index /// Sersic index ,double my_q // axes ratio ,double my_z /// optional redshift ,const double *my_theta /// optional angular position on the sky ) : Source(), mag(my_mag), Reff(my_Reff*pi/180/60/60), PA(my_PA), index(my_index), q(my_q) { setZ(my_z); if(my_theta) setX(my_theta[0], my_theta[1]); setInternals(); } SersicSource::~SersicSource() { } void SersicSource::getParameters(Parameters& p) const { // base class serialization Source::getParameters(p); p << Reff << mag << PA << index << bn << q << Ieff << flux; } void SersicSource::setParameters(Parameters& p) { // base class deserialization Source::setParameters(p); p >> Reff >> mag >> PA >> index >> bn >> q >> Ieff >> flux; } void SersicSource::randomize(double step, long* seed) { // half light radius Reff += step*pi/180/60/60*gasdev(seed); // magnitude mag += step*gasdev(seed); // position angle //PA += step*pi*gasdev(seed); // Sersic index index += step*gasdev(seed); // axes ratio //q += step*gasdev(seed); // redshift? // position source_x[0] += step*pi/180/60/60*gasdev(seed); source_x[1] += step*pi/180/60/60*gasdev(seed); // update setInternals(); } void SersicSource::setInternals() { // approximation valid for 0.5 < n < 8 bn = 1.9992*index - 0.3271; flux = pow(10,-0.4*(mag+48.6)); Ieff = flux/2./pi/Reff/Reff/exp(bn)/index*pow(bn,2*index)/tgamma(2*index)/q; // radius in Source // approximation of the radius that encloses 99% of the flux setRadius((3.73 - 0.926*index + 1.164*index*index)*Reff); } double SersicSource::SurfaceBrightness( double *x /// position in radians relative to center of source ){ double x_new[2]; x_new[0] = (x[0]-source_x[0])*cos(PA)+(x[1]-source_x[1])*sin(PA); x_new[1] = (x[0]-source_x[0])*sin(PA)-(x[1]-source_x[1])*cos(PA); double r = sqrt(x_new[0]*x_new[0]+x_new[1]*x_new[1]/q/q); double sb = Ieff * exp(-bn*(pow(r/Reff,1./index)-1.))*inv_hplanck; if (sb < sb_limit) return 0.; return sb; } void SersicSource::printSource(){} void SersicSource::assignParams(InputParams& /* params */){} <|endoftext|>
<commit_before>#pragma once #include "Point.hpp" #include "Entity.hpp" #include "OnScreenComponent.hpp" namespace kengine { struct ViewportComponent : OnScreenComponent { using RenderTexture = void *; Entity::ID window = Entity::INVALID_ID; putils::Rect2f boundingBox = { { 0.f, 0.f }, { 1.f, 1.f } }; putils::Point2i resolution = { 1280, 720 }; float zOrder = 1.f; RenderTexture renderTexture = (RenderTexture)-1; ViewportComponent() noexcept { coordinateType = CoordinateType::ScreenPercentage; } putils_reflection_class_name(ViewportComponent); putils_reflection_attributes( putils_reflection_attribute(&ViewportComponent::window), putils_reflection_attribute(&ViewportComponent::boundingBox), putils_reflection_attribute(&ViewportComponent::resolution), putils_reflection_attribute(&ViewportComponent::zOrder) ); putils_reflection_parents( putils_reflection_type(OnScreenComponent) ); }; }<commit_msg>re-order ViewportComponent attributes<commit_after>#pragma once #include "Point.hpp" #include "Entity.hpp" #include "OnScreenComponent.hpp" namespace kengine { struct ViewportComponent : OnScreenComponent { using RenderTexture = void *; putils::Rect2f boundingBox = { { 0.f, 0.f }, { 1.f, 1.f } }; putils::Point2i resolution = { 1280, 720 }; float zOrder = 1.f; Entity::ID window = Entity::INVALID_ID; RenderTexture renderTexture = (RenderTexture)-1; ViewportComponent() noexcept { coordinateType = CoordinateType::ScreenPercentage; } putils_reflection_class_name(ViewportComponent); putils_reflection_attributes( putils_reflection_attribute(&ViewportComponent::window), putils_reflection_attribute(&ViewportComponent::boundingBox), putils_reflection_attribute(&ViewportComponent::resolution), putils_reflection_attribute(&ViewportComponent::zOrder) ); putils_reflection_parents( putils_reflection_type(OnScreenComponent) ); }; }<|endoftext|>
<commit_before>///====================================== TSContSchedule.cc =================/// /// A helper class used to test the API's exposed by Apache Traffic Server. #include <netinet/in.h> #include <cassert> #include <cstdlib> #include <string> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <iostream> #include <ts/ts.h> #include <ink_defs.h> // Status code for transactions. static const int TXN_SUCCESS = 10000; static const int TXN_FAILURE = 10001; static const int TXN_TIMEOUT = 10002; extern void *plugin_http_accept; class AutoAsyncRefresher; struct RefreshContData { TSAction firstRefreshAction; TSAction periodicRefreshAction; TSAction backupDataReadAction; std::string backupDataFilename; AutoAsyncRefresher *refresher; // Does not take ownership. RefreshContData(const std::string &backupDataFilename, AutoAsyncRefresher *refresher) : firstRefreshAction(NULL), periodicRefreshAction(NULL), backupDataReadAction(NULL), backupDataFilename(backupDataFilename), refresher(refresher) { } }; static int handleFetchEvents(TSCont cont, TSEvent event, void *edata) { if (event == TXN_SUCCESS) { // success. TSHttpTxn txn = static_cast<TSHttpTxn>(edata); int dataLen = 0; // The length of fetched data. // Get the starting position of fetched data. const char *dataStart = TSFetchRespGet(txn, &dataLen); const char *dataEnd = dataStart + dataLen; std::cout << dataStart; TSHttpParser parser = TSHttpParserCreate(); TSMBuffer buf = TSMBufferCreate(); TSMLoc hdrLoc = TSHttpHdrCreate(buf); TSHttpHdrTypeSet(buf, hdrLoc, TS_HTTP_TYPE_RESPONSE); if (TSHttpHdrParseResp(parser, buf, hdrLoc, &dataStart, dataEnd) == TS_PARSE_DONE) { TSHttpStatus status = TSHttpHdrStatusGet(buf, hdrLoc); if (!status) std::cout << dataStart << "\n"; // TODO: handle the fetched data here. } else { std::cout << "Fail to parse http response\n"; } TSHandleMLocRelease(buf, 0, hdrLoc); TSMBufferDestroy(buf); TSHttpParserDestroy(parser); } else if (event == TXN_FAILURE) { // failure. std::cout << "HTTP GET failure"; } else if (event == TXN_TIMEOUT) { // timeout std::cout << "HTTP GET timeout"; } else { std::cout << "Unrecognized status"; } return 0; } // Initialize the sockaddr_in with the target address and port. int initializeSockaddr(const char *ip, int port, struct sockaddr_in *addr) { if (inet_aton(ip, &addr->sin_addr) == 0) { std::cout << "Invalid IP address\n"; return -1; } addr->sin_family = AF_INET; // addr->sin_addr.s_addr = 0x0100007f /* 127.0.0.1 */; addr->sin_port = port /* 8080 */; return 0; } // Fetch an object through a URL and http 1.0. void fetchHttpUrl(const std::string &url) { std::string requestString("GET "); requestString.append(url); requestString.append(" HTTP/1.0\r\n\r\n"); // Create a continuation to handle the event when the fetch result arrives. TSCont fetchCont = TSContCreate(handleFetchEvents, TSMutexCreate()); TSFetchEvent eventIds; eventIds.success_event_id = TXN_SUCCESS; eventIds.failure_event_id = TXN_FAILURE; eventIds.timeout_event_id = TXN_TIMEOUT; struct sockaddr_in addr; //if (initializeSockaddr("172.20.200.150", 10126 /* port number*/, &addr) != 0) { if (initializeSockaddr("127.0.0.1", 8080 /* port number*/, &addr) != 0) { std::cout << "Error initializing sockaddr\n"; } TSFetchUrl(requestString.c_str(), requestString.size(), reinterpret_cast<struct sockaddr const *>(&addr), fetchCont, AFTER_BODY, eventIds); } class AutoAsyncRefresher { public: AutoAsyncRefresher(const std::string backupFilename, const std::string url) : url(url){ if (pthread_rwlock_init(&dataLock, 0)) { std::cout << "Failed to initialize dataLock\n"; exit(1); } if (pthread_mutex_init(&refreshLock, NULL)) { std::cout << "Failed to initialize refreshLock\n"; exit(1); } refreshFailureStat = TSStatCreate("refresh_failure_stat", TS_RECORDDATATYPE_INT, TS_STAT_PERSISTENT, TS_STAT_SYNC_COUNT); refreshCont = TSContCreate(handleRefreshContEvent, 0); RefreshContData *refreshContData = new RefreshContData(backupFilename, this); TSContDataSet(refreshCont, refreshContData); //refreshContData->periodicRefreshAction = TSContScheduleEvery(refreshCont, 5000 /* ms */, TS_THREAD_POOL_DEFAULT); refreshContData->periodicRefreshAction = TSContSchedule(refreshCont, 5000 /* ms */, TS_THREAD_POOL_DEFAULT); } static int handleRefreshContEvent(TSCont cont, TSEvent event, void *edata) { assert(event == TS_EVENT_TIMEOUT || event == TS_EVENT_IMMEDIATE); RefreshContData *refreshContData = static_cast<RefreshContData *>(TSContDataGet(cont)); refreshContData->refresher->refresh(refreshContData); // Reschedule itself here. refreshContData->periodicRefreshAction = TSContSchedule(cont, 5000 /* ms */, TS_THREAD_POOL_DEFAULT); return 0; } void refresh(RefreshContData *refreshContData) { if (refreshContData->backupDataReadAction) { refreshContData->backupDataReadAction = NULL; } else if (!plugin_http_accept){ refreshContData->firstRefreshAction = TSContSchedule(refreshCont, 1000 /* ms */, TS_THREAD_POOL_DEFAULT); } else { refreshContData->firstRefreshAction = 0; bool initiateRefresh = false; pthread_mutex_lock(&refreshLock); if (!refreshInProgress) { refreshInProgress = true; initiateRefresh = true; } pthread_mutex_unlock(&refreshLock); if (initiateRefresh) { fetchHttpUrl(url); refreshInProgress = false; } else { std::cout << "Refresh already in progress..."; } } } private: int refreshFailureStat; TSCont refreshCont; // The continuation used to fetch data. std::string url; // The url to fetch data from. pthread_rwlock_t dataLock; pthread_mutex_t refreshLock; bool refreshInProgress; }; void testAutoAsyncRefresher() { AutoAsyncRefresher *refresher = new AutoAsyncRefresher("/home/bzeng/web/ATS_plugins/test/backup.data" /* backup path */, "http://eat1-app533.stg.linkedin.com:10126/bwl-ds/rest/getbwl?name=CIPL" /* URL for the object*/); //"http://eat1-app533.stg.linkedin.com:10126/bwl-ds/rest/getbwl?name=CWLP&type=current"); //"www.google.com"); (void) refresher; } ///==========================================================================/// enum HOOK_TYPE { READ_RESPONSE, SEND_RESPONSE }; // A dummy transaction hook for testing whether a transaction hook will be hit // if the transaction is enabled with TSHttpTxnReenable(txn, TS_EVENT_HTTP_ERROR). static int transactionCont(TSCont cont, TSEvent event, void *edata) { TSHttpTxn txn = static_cast<TSHttpTxn>(edata); int * contData = static_cast<int *>(TSContDataGet(cont)); switch (*contData) { case READ_RESPONSE: std::cout << "transactionCont: read response \n"; break; case SEND_RESPONSE: std::cout << "transactionCont: send response \n"; break; default: std::cout << "Other hooks\n"; } delete contData; // You need to destroy the continuation. TSContDestroy(cont); TSHttpTxnReenable(txn, TS_EVENT_HTTP_CONTINUE); return 0; } // Test whether a transaction still hits handleReadResponseHeader after it is // called with TSHttpTxnReenable(txn, TS_EVENT_HTTP_ERROR). static int handleReadRequestHeader(TSCont cont, TSEvent event, void *edata) { TSHttpTxn txn = static_cast<TSHttpTxn>(edata); // Internal requests, do nothing. if (TSHttpIsInternalRequest(txn) == TS_SUCCESS) { TSHttpTxnReenable(txn, TS_EVENT_HTTP_CONTINUE); return 0; } // Schedule a continuation at read response header. TSCont readResponseCont = TSContCreate(transactionCont, 0); int *contData = new int(READ_RESPONSE); TSContDataSet(readResponseCont, contData); TSHttpTxnHookAdd(txn, TS_HTTP_READ_RESPONSE_HDR_HOOK, readResponseCont); // Schedule a continuation at send response header. TSCont sendResponseCont = TSContCreate(transactionCont, 0); int * data = new int(SEND_RESPONSE); TSContDataSet(sendResponseCont, data); TSHttpTxnHookAdd(txn, TS_HTTP_SEND_RESPONSE_HDR_HOOK, sendResponseCont); // Reenable with TS_EVENT_HTTP_ERROR. // TSHttpTxnReenable(txn, TS_EVENT_HTTP_ERROR); TSHttpTxnReenable(txn, TS_EVENT_HTTP_CONTINUE); return 0; } void startTestCont() { TSCont cont = TSContCreate(handleReadRequestHeader, 0); TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, cont); } ///==========================================================================/// void TSPluginInit(int argc, const char *argv[]) { // Register this plugin first. This is necessary since 5.2. Otherwise, ATS // will crash during the event handler. TSPluginRegistrationInfo info; info.plugin_name = (char *)"TSContSchedule"; info.vendor_name = (char *)"LinkedIn Inc."; info.support_email = (char *)"bzeng@linkedin.com"; if (!TSPluginRegister(TS_SDK_VERSION_2_0, &info)) { TSError("Plugin registration failed. \n"); } startTestCont(); //testAutoAsyncRefresher(); } <commit_msg>Test whether continuation data is freed if a transaction hook is not hit<commit_after>///====================================== TSContSchedule.cc =================/// /// A helper class used to test the API's exposed by Apache Traffic Server. #include <netinet/in.h> #include <cassert> #include <cstdlib> #include <string> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <iostream> #include <ts/ts.h> #include <ink_defs.h> // Status code for transactions. static const int TXN_SUCCESS = 10000; static const int TXN_FAILURE = 10001; static const int TXN_TIMEOUT = 10002; extern void *plugin_http_accept; class AutoAsyncRefresher; struct RefreshContData { TSAction firstRefreshAction; TSAction periodicRefreshAction; TSAction backupDataReadAction; std::string backupDataFilename; AutoAsyncRefresher *refresher; // Does not take ownership. RefreshContData(const std::string &backupDataFilename, AutoAsyncRefresher *refresher) : firstRefreshAction(NULL), periodicRefreshAction(NULL), backupDataReadAction(NULL), backupDataFilename(backupDataFilename), refresher(refresher) { } }; static int handleFetchEvents(TSCont cont, TSEvent event, void *edata) { if (event == TXN_SUCCESS) { // success. TSHttpTxn txn = static_cast<TSHttpTxn>(edata); int dataLen = 0; // The length of fetched data. // Get the starting position of fetched data. const char *dataStart = TSFetchRespGet(txn, &dataLen); const char *dataEnd = dataStart + dataLen; std::cout << dataStart; TSHttpParser parser = TSHttpParserCreate(); TSMBuffer buf = TSMBufferCreate(); TSMLoc hdrLoc = TSHttpHdrCreate(buf); TSHttpHdrTypeSet(buf, hdrLoc, TS_HTTP_TYPE_RESPONSE); if (TSHttpHdrParseResp(parser, buf, hdrLoc, &dataStart, dataEnd) == TS_PARSE_DONE) { TSHttpStatus status = TSHttpHdrStatusGet(buf, hdrLoc); if (!status) std::cout << dataStart << "\n"; // TODO: handle the fetched data here. } else { std::cout << "Fail to parse http response\n"; } TSHandleMLocRelease(buf, 0, hdrLoc); TSMBufferDestroy(buf); TSHttpParserDestroy(parser); } else if (event == TXN_FAILURE) { // failure. std::cout << "HTTP GET failure"; } else if (event == TXN_TIMEOUT) { // timeout std::cout << "HTTP GET timeout"; } else { std::cout << "Unrecognized status"; } return 0; } // Initialize the sockaddr_in with the target address and port. int initializeSockaddr(const char *ip, int port, struct sockaddr_in *addr) { if (inet_aton(ip, &addr->sin_addr) == 0) { std::cout << "Invalid IP address\n"; return -1; } addr->sin_family = AF_INET; // addr->sin_addr.s_addr = 0x0100007f /* 127.0.0.1 */; addr->sin_port = port /* 8080 */; return 0; } // Fetch an object through a URL and http 1.0. void fetchHttpUrl(const std::string &url) { std::string requestString("GET "); requestString.append(url); requestString.append(" HTTP/1.0\r\n\r\n"); // Create a continuation to handle the event when the fetch result arrives. TSCont fetchCont = TSContCreate(handleFetchEvents, TSMutexCreate()); TSFetchEvent eventIds; eventIds.success_event_id = TXN_SUCCESS; eventIds.failure_event_id = TXN_FAILURE; eventIds.timeout_event_id = TXN_TIMEOUT; struct sockaddr_in addr; //if (initializeSockaddr("172.20.200.150", 10126 /* port number*/, &addr) != 0) { if (initializeSockaddr("127.0.0.1", 8080 /* port number*/, &addr) != 0) { std::cout << "Error initializing sockaddr\n"; } TSFetchUrl(requestString.c_str(), requestString.size(), reinterpret_cast<struct sockaddr const *>(&addr), fetchCont, AFTER_BODY, eventIds); } class AutoAsyncRefresher { public: AutoAsyncRefresher(const std::string backupFilename, const std::string url) : url(url){ if (pthread_rwlock_init(&dataLock, 0)) { std::cout << "Failed to initialize dataLock\n"; exit(1); } if (pthread_mutex_init(&refreshLock, NULL)) { std::cout << "Failed to initialize refreshLock\n"; exit(1); } refreshFailureStat = TSStatCreate("refresh_failure_stat", TS_RECORDDATATYPE_INT, TS_STAT_PERSISTENT, TS_STAT_SYNC_COUNT); refreshCont = TSContCreate(handleRefreshContEvent, 0); RefreshContData *refreshContData = new RefreshContData(backupFilename, this); TSContDataSet(refreshCont, refreshContData); //refreshContData->periodicRefreshAction = TSContScheduleEvery(refreshCont, 5000 /* ms */, TS_THREAD_POOL_DEFAULT); refreshContData->periodicRefreshAction = TSContSchedule(refreshCont, 5000 /* ms */, TS_THREAD_POOL_DEFAULT); } static int handleRefreshContEvent(TSCont cont, TSEvent event, void *edata) { assert(event == TS_EVENT_TIMEOUT || event == TS_EVENT_IMMEDIATE); RefreshContData *refreshContData = static_cast<RefreshContData *>(TSContDataGet(cont)); refreshContData->refresher->refresh(refreshContData); // Reschedule itself here. refreshContData->periodicRefreshAction = TSContSchedule(cont, 5000 /* ms */, TS_THREAD_POOL_DEFAULT); return 0; } void refresh(RefreshContData *refreshContData) { if (refreshContData->backupDataReadAction) { refreshContData->backupDataReadAction = NULL; } else if (!plugin_http_accept){ refreshContData->firstRefreshAction = TSContSchedule(refreshCont, 1000 /* ms */, TS_THREAD_POOL_DEFAULT); } else { refreshContData->firstRefreshAction = 0; bool initiateRefresh = false; pthread_mutex_lock(&refreshLock); if (!refreshInProgress) { refreshInProgress = true; initiateRefresh = true; } pthread_mutex_unlock(&refreshLock); if (initiateRefresh) { fetchHttpUrl(url); refreshInProgress = false; } else { std::cout << "Refresh already in progress..."; } } } private: int refreshFailureStat; TSCont refreshCont; // The continuation used to fetch data. std::string url; // The url to fetch data from. pthread_rwlock_t dataLock; pthread_mutex_t refreshLock; bool refreshInProgress; }; void testAutoAsyncRefresher() { AutoAsyncRefresher *refresher = new AutoAsyncRefresher("/home/bzeng/web/ATS_plugins/test/backup.data" /* backup path */, "http://eat1-app533.stg.linkedin.com:10126/bwl-ds/rest/getbwl?name=CIPL" /* URL for the object*/); //"http://eat1-app533.stg.linkedin.com:10126/bwl-ds/rest/getbwl?name=CWLP&type=current"); //"www.google.com"); (void) refresher; } ///==========================================================================/// enum HOOK_TYPE { READ_RESPONSE, SEND_RESPONSE }; class PrintDtor { HOOK_TYPE Member; public: int member() { return Member; } PrintDtor(HOOK_TYPE hookType) : Member(hookType) {} ~PrintDtor() { std::cout << "~PrintDtor\n"; } }; // A dummy transaction hook for testing whether a transaction hook will be hit // if the transaction is enabled with TSHttpTxnReenable(txn, TS_EVENT_HTTP_ERROR). static int transactionCont(TSCont cont, TSEvent event, void *edata) { TSHttpTxn txn = static_cast<TSHttpTxn>(edata); PrintDtor *contData = static_cast<PrintDtor *>(TSContDataGet(cont)); switch (contData->member()) { case READ_RESPONSE: std::cout << "transactionCont: read response \n"; break; case SEND_RESPONSE: std::cout << "transactionCont: send response \n"; break; default: std::cout << "Other hooks\n"; } delete contData; // You need to destroy the continuation. TSContDestroy(cont); TSHttpTxnReenable(txn, TS_EVENT_HTTP_CONTINUE); return 0; } // Test whether a transaction still hits handleReadResponseHeader after it is // called with TSHttpTxnReenable(txn, TS_EVENT_HTTP_ERROR). static int handleReadRequestHeader(TSCont cont, TSEvent event, void *edata) { TSHttpTxn txn = static_cast<TSHttpTxn>(edata); // Internal requests, do nothing. if (TSHttpIsInternalRequest(txn) == TS_SUCCESS) { TSHttpTxnReenable(txn, TS_EVENT_HTTP_CONTINUE); return 0; } // Schedule a continuation at read response header. TSCont readResponseCont = TSContCreate(transactionCont, 0); PrintDtor *contData = new PrintDtor(READ_RESPONSE); TSContDataSet(readResponseCont, contData); TSHttpTxnHookAdd(txn, TS_HTTP_READ_RESPONSE_HDR_HOOK, readResponseCont); // Schedule a continuation at send response header. TSCont sendResponseCont = TSContCreate(transactionCont, 0); PrintDtor * data = new PrintDtor(SEND_RESPONSE); TSContDataSet(sendResponseCont, data); TSHttpTxnHookAdd(txn, TS_HTTP_SEND_RESPONSE_HDR_HOOK, sendResponseCont); // Reenable with TS_EVENT_HTTP_ERROR. TSHttpTxnReenable(txn, TS_EVENT_HTTP_ERROR); // TSHttpTxnReenable(txn, TS_EVENT_HTTP_CONTINUE); return 0; } void startTestCont() { TSCont cont = TSContCreate(handleReadRequestHeader, 0); TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, cont); } ///==========================================================================/// void TSPluginInit(int argc, const char *argv[]) { // Register this plugin first. This is necessary since 5.2. Otherwise, ATS // will crash during the event handler. TSPluginRegistrationInfo info; info.plugin_name = (char *)"TSContSchedule"; info.vendor_name = (char *)"LinkedIn Inc."; info.support_email = (char *)"bzeng@linkedin.com"; if (!TSPluginRegister(TS_SDK_VERSION_2_0, &info)) { TSError("Plugin registration failed. \n"); } startTestCont(); //testAutoAsyncRefresher(); } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions Inc. 1990-2014. All rights reserved */ // TEST Foundation::Containers::Stack // STATUS PRELIMINARY #include "Stroika/Foundation/StroikaPreComp.h" #include <iostream> #include <sstream> #include "Stroika/Foundation/Containers/Stack.h" #include "Stroika/Foundation/Containers/Concrete/Stack_LinkedList.h" #include "Stroika/Foundation/Debug/Assertions.h" #include "Stroika/Foundation/Debug/Trace.h" #include "../TestHarness/SimpleClass.h" #include "../TestHarness/TestHarness.h" using namespace Stroika; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using Concrete::Stack_LinkedList; namespace { template <typename StackOfT> void SimpleTest_1_ (StackOfT s) { StackOfT s2; StackOfT s3 = s; } } namespace { template <typename StackOfT> void SimpleTest_2_ (StackOfT s) { s.Push (1); VerifyTestResult (s.size () == 1); s.Push (1); VerifyTestResult (s.size () == 2); s.Pop (); VerifyTestResult (s.size () == 1); s.RemoveAll (); VerifyTestResult (s.size () == 0); } } namespace { template <typename StackOfT> void SimpleTest_3_Iteration_ (StackOfT s) { #if 0 m.Add (1, 2); VerifyTestResult (m.size () == 1); for (auto i : m) { VerifyTestResult (i.first == 1); VerifyTestResult (i.second == 2); } m.Add (1, 2); VerifyTestResult (m.size () == 1); for (auto i : m) { VerifyTestResult (i.first == 1); VerifyTestResult (i.second == 2); } m.Remove (1); VerifyTestResult (m.size () == 0); for (auto i : m) { VerifyTestResult (false); } m.Add (1, 2); m.Add (2, 3); m.Add (3, 4); unsigned int cnt = 0; for (auto i : m) { cnt++; if (cnt == 1) { VerifyTestResult (i.first == 1); VerifyTestResult (i.second == 2); } if (cnt == 2) { VerifyTestResult (i.first == 2); VerifyTestResult (i.second == 3); } if (cnt == 3) { VerifyTestResult (i.first == 3); VerifyTestResult (i.second == 4); } } VerifyTestResult (cnt == 3); #endif s.RemoveAll (); VerifyTestResult (s.size () == 0); } } namespace Test4_Equals { template <typename USING_STACK_CONTAINER, typename EQUALS_COMPARER> void DoAllTests_ () { USING_STACK_CONTAINER s; USING_STACK_CONTAINER s2 = s; s.Push (1); s.Push (2); VerifyTestResult (s.size () == 2); USING_STACK_CONTAINER s3 = s; //VerifyTestResult (s == s3); VerifyTestResult (s.Equals<EQUALS_COMPARER> (s3)); //VerifyTestResult (not (s != s3)); //VerifyTestResult (s != s2); VerifyTestResult (not s.Equals<EQUALS_COMPARER> (s2)); //VerifyTestResult (not (s == s2)); } } namespace { template <typename CONCRETE_SEQUENCE_TYPE, typename EQUALS_COMPARER> void Tests_All_For_Type_WhichDontRequireComparer_For_Type_ () { CONCRETE_SEQUENCE_TYPE s; SimpleTest_1_<CONCRETE_SEQUENCE_TYPE> (s); SimpleTest_2_<CONCRETE_SEQUENCE_TYPE> (s); SimpleTest_3_Iteration_<CONCRETE_SEQUENCE_TYPE> (s); } template <typename CONCRETE_SEQUENCE_TYPE, typename EQUALS_COMPARER> void Tests_All_For_Type_ () { Tests_All_For_Type_WhichDontRequireComparer_For_Type_<CONCRETE_SEQUENCE_TYPE, EQUALS_COMPARER> (); Test4_Equals::DoAllTests_<CONCRETE_SEQUENCE_TYPE, EQUALS_COMPARER> (); } } namespace { void DoRegressionTests_ () { using COMPARE_SIZET = Common::ComparerWithEquals<size_t>; using COMPARE_SimpleClass = Common::ComparerWithEquals<SimpleClass>; struct COMPARE_SimpleClassWithoutComparisonOperators { using ElementType = SimpleClassWithoutComparisonOperators; static bool Equals (ElementType v1, ElementType v2) { return v1.GetValue () == v2.GetValue (); } }; Tests_All_For_Type_<Stack<size_t>, COMPARE_SIZET> (); Tests_All_For_Type_<Stack<SimpleClass>, COMPARE_SimpleClass> (); Tests_All_For_Type_WhichDontRequireComparer_For_Type_<Stack<SimpleClassWithoutComparisonOperators>, COMPARE_SimpleClassWithoutComparisonOperators> (); Tests_All_For_Type_<Stack<SimpleClassWithoutComparisonOperators>, COMPARE_SimpleClassWithoutComparisonOperators> (); Tests_All_For_Type_<Stack_LinkedList<size_t>, COMPARE_SIZET> (); Tests_All_For_Type_<Stack_LinkedList<SimpleClass>, COMPARE_SimpleClass> (); Tests_All_For_Type_WhichDontRequireComparer_For_Type_<Stack_LinkedList<SimpleClassWithoutComparisonOperators>, COMPARE_SimpleClassWithoutComparisonOperators> (); Tests_All_For_Type_<Stack_LinkedList<SimpleClassWithoutComparisonOperators>, COMPARE_SimpleClassWithoutComparisonOperators> (); } } int main (int argc, const char* argv[]) { Stroika::TestHarness::Setup (); Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_); return EXIT_SUCCESS; } <commit_msg>gcc template cleanups<commit_after>/* * Copyright(c) Sophist Solutions Inc. 1990-2014. All rights reserved */ // TEST Foundation::Containers::Stack // STATUS PRELIMINARY #include "Stroika/Foundation/StroikaPreComp.h" #include <iostream> #include <sstream> #include "Stroika/Foundation/Containers/Stack.h" #include "Stroika/Foundation/Containers/Concrete/Stack_LinkedList.h" #include "Stroika/Foundation/Debug/Assertions.h" #include "Stroika/Foundation/Debug/Trace.h" #include "../TestHarness/SimpleClass.h" #include "../TestHarness/TestHarness.h" using namespace Stroika; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using Concrete::Stack_LinkedList; namespace { template <typename StackOfT> void SimpleTest_1_ (StackOfT s) { StackOfT s2; StackOfT s3 = s; } } namespace { template <typename StackOfT> void SimpleTest_2_ (StackOfT s) { s.Push (1); VerifyTestResult (s.size () == 1); s.Push (1); VerifyTestResult (s.size () == 2); s.Pop (); VerifyTestResult (s.size () == 1); s.RemoveAll (); VerifyTestResult (s.size () == 0); } } namespace { template <typename StackOfT> void SimpleTest_3_Iteration_ (StackOfT s) { #if 0 m.Add (1, 2); VerifyTestResult (m.size () == 1); for (auto i : m) { VerifyTestResult (i.first == 1); VerifyTestResult (i.second == 2); } m.Add (1, 2); VerifyTestResult (m.size () == 1); for (auto i : m) { VerifyTestResult (i.first == 1); VerifyTestResult (i.second == 2); } m.Remove (1); VerifyTestResult (m.size () == 0); for (auto i : m) { VerifyTestResult (false); } m.Add (1, 2); m.Add (2, 3); m.Add (3, 4); unsigned int cnt = 0; for (auto i : m) { cnt++; if (cnt == 1) { VerifyTestResult (i.first == 1); VerifyTestResult (i.second == 2); } if (cnt == 2) { VerifyTestResult (i.first == 2); VerifyTestResult (i.second == 3); } if (cnt == 3) { VerifyTestResult (i.first == 3); VerifyTestResult (i.second == 4); } } VerifyTestResult (cnt == 3); #endif s.RemoveAll (); VerifyTestResult (s.size () == 0); } } namespace Test4_Equals { template <typename USING_STACK_CONTAINER, typename EQUALS_COMPARER> void DoAllTests_ () { USING_STACK_CONTAINER s; USING_STACK_CONTAINER s2 = s; s.Push (1); s.Push (2); VerifyTestResult (s.size () == 2); USING_STACK_CONTAINER s3 = s; //VerifyTestResult (s == s3); VerifyTestResult (s.template Equals<EQUALS_COMPARER> (s3)); //VerifyTestResult (not (s != s3)); //VerifyTestResult (s != s2); VerifyTestResult (not s.template Equals<EQUALS_COMPARER> (s2)); //VerifyTestResult (not (s == s2)); } } namespace { template <typename CONCRETE_SEQUENCE_TYPE, typename EQUALS_COMPARER> void Tests_All_For_Type_WhichDontRequireComparer_For_Type_ () { CONCRETE_SEQUENCE_TYPE s; SimpleTest_1_<CONCRETE_SEQUENCE_TYPE> (s); SimpleTest_2_<CONCRETE_SEQUENCE_TYPE> (s); SimpleTest_3_Iteration_<CONCRETE_SEQUENCE_TYPE> (s); } template <typename CONCRETE_SEQUENCE_TYPE, typename EQUALS_COMPARER> void Tests_All_For_Type_ () { Tests_All_For_Type_WhichDontRequireComparer_For_Type_<CONCRETE_SEQUENCE_TYPE, EQUALS_COMPARER> (); Test4_Equals::DoAllTests_<CONCRETE_SEQUENCE_TYPE, EQUALS_COMPARER> (); } } namespace { void DoRegressionTests_ () { using COMPARE_SIZET = Common::ComparerWithEquals<size_t>; using COMPARE_SimpleClass = Common::ComparerWithEquals<SimpleClass>; struct COMPARE_SimpleClassWithoutComparisonOperators { using ElementType = SimpleClassWithoutComparisonOperators; static bool Equals (ElementType v1, ElementType v2) { return v1.GetValue () == v2.GetValue (); } }; Tests_All_For_Type_<Stack<size_t>, COMPARE_SIZET> (); Tests_All_For_Type_<Stack<SimpleClass>, COMPARE_SimpleClass> (); Tests_All_For_Type_WhichDontRequireComparer_For_Type_<Stack<SimpleClassWithoutComparisonOperators>, COMPARE_SimpleClassWithoutComparisonOperators> (); Tests_All_For_Type_<Stack<SimpleClassWithoutComparisonOperators>, COMPARE_SimpleClassWithoutComparisonOperators> (); Tests_All_For_Type_<Stack_LinkedList<size_t>, COMPARE_SIZET> (); Tests_All_For_Type_<Stack_LinkedList<SimpleClass>, COMPARE_SimpleClass> (); Tests_All_For_Type_WhichDontRequireComparer_For_Type_<Stack_LinkedList<SimpleClassWithoutComparisonOperators>, COMPARE_SimpleClassWithoutComparisonOperators> (); Tests_All_For_Type_<Stack_LinkedList<SimpleClassWithoutComparisonOperators>, COMPARE_SimpleClassWithoutComparisonOperators> (); } } int main (int argc, const char* argv[]) { Stroika::TestHarness::Setup (); Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_); return EXIT_SUCCESS; } <|endoftext|>
<commit_before><commit_msg>cosmetic<commit_after><|endoftext|>
<commit_before>#include "lobby_server.h" #include <network/network.h> #include <network/commands.h> #include <tinker/application.h> extern CNetworkCommand LobbyPlayerInfo; SERVER_COMMAND(JoinLobby) { if (pCmd->GetNumArguments() < 2) { TMsg("JoinLobby not enough arguments\n"); return; } CGameLobbyServer::JoinLobby(pCmd->ArgAsUInt(0), pCmd->ArgAsUInt(1)); } SERVER_COMMAND(UpdateInfo) { if (pCmd->GetNumArguments() < 2) { TMsg("UpdateInfo not enough arguments\n"); return; } CGameLobbyServer::UpdatePlayer(iClient, pCmd->Arg(0), pCmd->Arg(1)); } eastl::vector<CGameLobby> CGameLobbyServer::s_aLobbies; eastl::vector<size_t> CGameLobbyServer::s_iClientLobbies; size_t CGameLobbyServer::CreateLobby(size_t iPort) { if (s_iClientLobbies.size() == 0) { s_iClientLobbies.resize(NETWORK_MAX_CLIENTS); for (size_t i = 0; i < NETWORK_MAX_CLIENTS; i++) s_iClientLobbies[i] = ~0; } CGameLobby* pLobby = NULL; size_t iLobby; for (size_t i = 0; i < s_aLobbies.size(); i++) { if (!s_aLobbies[i].m_bActive) { pLobby = &s_aLobbies[i]; iLobby = i; break; } } if (!pLobby) { pLobby = &s_aLobbies.push_back(); iLobby = s_aLobbies.size()-1; } pLobby->Initialize(iPort); return iLobby; } void CGameLobbyServer::DestroyLobby(size_t iLobby) { if (iLobby >= s_aLobbies.size()) { assert(!"What lobby is this?"); return; } s_aLobbies[iLobby].Shutdown(); } void CGameLobbyServer::JoinLobby(size_t iLobby, size_t iClient) { if (iLobby >= s_aLobbies.size()) { assert(!"What lobby is this?"); return; } s_aLobbies[iLobby].AddPlayer(iClient); if (iClient != ~0) s_iClientLobbies[iClient] = iLobby; } void CGameLobbyServer::LeaveLobby(size_t iLobby, size_t iClient) { if (iLobby >= s_aLobbies.size()) { assert(!"What lobby is this?"); return; } s_aLobbies[iLobby].RemovePlayer(iClient); if (iClient != ~0) s_iClientLobbies[iClient] = ~0; } void CGameLobbyServer::UpdatePlayer(size_t iClient, const eastl::string16& sKey, const eastl::string16& sValue) { if (iClient != ~0 && s_iClientLobbies[iClient] == ~0) { TMsg(sprintf(L"Can't find lobby for client %d\n", iClient)); assert(!"Can't find lobby for client"); return; } size_t iLobby; if (iClient == ~0) iLobby = 0; else iLobby = s_iClientLobbies[iClient]; s_aLobbies[iLobby].UpdatePlayer(iClient, sKey, sValue); } void CGameLobbyServer::ClientConnect(class INetworkListener*, class CNetworkParameters* pParameters) { int iClient = pParameters->i1; JoinLobby(0, iClient); s_aLobbies[0].SendFullUpdate(iClient); } void CGameLobbyServer::ClientDisconnect(class INetworkListener*, class CNetworkParameters* pParameters) { int iClient = pParameters->i1; LeaveLobby(0, iClient); } CGameLobby::CGameLobby() { m_bActive = false; } void CGameLobby::Initialize(size_t iPort) { CNetwork::Disconnect(); CNetwork::SetCallbacks(NULL, CGameLobbyServer::ClientConnect, CGameLobbyServer::ClientDisconnect); CNetwork::CreateHost(iPort); m_bActive = true; } void CGameLobby::Shutdown() { CNetwork::Disconnect(); m_bActive = false; } size_t CGameLobby::GetNumPlayers() { return m_aClients.size(); } size_t CGameLobby::GetPlayerIndex(size_t iClient) { for (size_t i = 0; i < m_aClients.size(); i++) { if (m_aClients[i].iClient == iClient) return i; } return ~0; } CLobbyPlayer* CGameLobby::GetPlayer(size_t iIndex) { if (iIndex >= m_aClients.size()) return NULL; return &m_aClients[iIndex]; } CLobbyPlayer* CGameLobby::GetPlayerByClient(size_t iClient) { return GetPlayer(GetPlayerIndex(iClient)); } void CGameLobby::AddPlayer(size_t iClient) { if (GetPlayerByClient(iClient)) return; CLobbyPlayer* pPlayer = &m_aClients.push_back(); pPlayer->iClient = iClient; ::LobbyPlayerInfo.RunCommand(sprintf(L"%d active 1", iClient)); } void CGameLobby::RemovePlayer(size_t iClient) { size_t iPlayer = GetPlayerIndex(iClient); if (!GetPlayer(iPlayer)) return; m_aClients.erase(m_aClients.begin()+iPlayer); ::LobbyPlayerInfo.RunCommand(sprintf(L"%d active 0", iClient)); } void CGameLobby::UpdatePlayer(size_t iClient, const eastl::string16& sKey, const eastl::string16& sValue) { CLobbyPlayer* pPlayer = GetPlayerByClient(iClient); if (!pPlayer) return; pPlayer->asInfo[sKey] = sValue; eastl::string16 sCommand = sprintf(eastl::string16(L"%d ") + sKey + L" " + sValue, iClient); ::LobbyPlayerInfo.RunCommand(sCommand); } void CGameLobby::SendFullUpdate(size_t iClient) { for (size_t i = 0; i < m_aClients.size(); i++) { CLobbyPlayer* pPlayer = &m_aClients[i]; ::LobbyPlayerInfo.RunCommand(sprintf(L"%d active 1", pPlayer->iClient), pPlayer->iClient); for (eastl::map<eastl::string16, eastl::string16>::iterator it = pPlayer->asInfo.begin(); it != pPlayer->asInfo.end(); it++) { eastl::string16 sCommand = sprintf(eastl::string16(L"%d ") + it->first + L" " + it->second, iClient); ::LobbyPlayerInfo.RunCommand(sCommand, pPlayer->iClient); } } } <commit_msg>More lobby improvements<commit_after>#include "lobby_server.h" #include <network/network.h> #include <network/commands.h> #include <tinker/application.h> extern CNetworkCommand LobbyPlayerInfo; SERVER_COMMAND(JoinLobby) { if (pCmd->GetNumArguments() < 2) { TMsg("JoinLobby not enough arguments\n"); return; } CGameLobbyServer::JoinLobby(pCmd->ArgAsUInt(0), pCmd->ArgAsUInt(1)); } SERVER_COMMAND(UpdateInfo) { if (pCmd->GetNumArguments() < 2) { TMsg("UpdateInfo not enough arguments\n"); return; } CGameLobbyServer::UpdatePlayer(iClient, pCmd->Arg(0), pCmd->Arg(1)); } eastl::vector<CGameLobby> CGameLobbyServer::s_aLobbies; eastl::vector<size_t> CGameLobbyServer::s_iClientLobbies; size_t CGameLobbyServer::CreateLobby(size_t iPort) { if (s_iClientLobbies.size() == 0) { s_iClientLobbies.resize(NETWORK_MAX_CLIENTS); for (size_t i = 0; i < NETWORK_MAX_CLIENTS; i++) s_iClientLobbies[i] = ~0; } CGameLobby* pLobby = NULL; size_t iLobby; for (size_t i = 0; i < s_aLobbies.size(); i++) { if (!s_aLobbies[i].m_bActive) { pLobby = &s_aLobbies[i]; iLobby = i; break; } } if (!pLobby) { pLobby = &s_aLobbies.push_back(); iLobby = s_aLobbies.size()-1; } pLobby->Initialize(iPort); return iLobby; } void CGameLobbyServer::DestroyLobby(size_t iLobby) { if (iLobby >= s_aLobbies.size()) { assert(!"What lobby is this?"); return; } s_aLobbies[iLobby].Shutdown(); } void CGameLobbyServer::JoinLobby(size_t iLobby, size_t iClient) { if (iLobby >= s_aLobbies.size()) { assert(!"What lobby is this?"); return; } s_aLobbies[iLobby].AddPlayer(iClient); if (iClient != ~0) s_iClientLobbies[iClient] = iLobby; } void CGameLobbyServer::LeaveLobby(size_t iLobby, size_t iClient) { if (iLobby >= s_aLobbies.size()) { assert(!"What lobby is this?"); return; } s_aLobbies[iLobby].RemovePlayer(iClient); if (iClient != ~0) s_iClientLobbies[iClient] = ~0; } void CGameLobbyServer::UpdatePlayer(size_t iClient, const eastl::string16& sKey, const eastl::string16& sValue) { if (iClient != ~0 && s_iClientLobbies[iClient] == ~0) { TMsg(sprintf(L"Can't find lobby for client %d\n", iClient)); assert(!"Can't find lobby for client"); return; } size_t iLobby; if (iClient == ~0) iLobby = 0; else iLobby = s_iClientLobbies[iClient]; s_aLobbies[iLobby].UpdatePlayer(iClient, sKey, sValue); } void CGameLobbyServer::ClientConnect(class INetworkListener*, class CNetworkParameters* pParameters) { int iClient = pParameters->i1; JoinLobby(0, iClient); s_aLobbies[0].SendFullUpdate(iClient); } void CGameLobbyServer::ClientDisconnect(class INetworkListener*, class CNetworkParameters* pParameters) { int iClient = pParameters->i1; LeaveLobby(0, iClient); } CGameLobby::CGameLobby() { m_bActive = false; } void CGameLobby::Initialize(size_t iPort) { CNetwork::Disconnect(); CNetwork::SetCallbacks(NULL, CGameLobbyServer::ClientConnect, CGameLobbyServer::ClientDisconnect); CNetwork::CreateHost(iPort); m_bActive = true; } void CGameLobby::Shutdown() { CNetwork::Disconnect(); m_bActive = false; } size_t CGameLobby::GetNumPlayers() { return m_aClients.size(); } size_t CGameLobby::GetPlayerIndex(size_t iClient) { for (size_t i = 0; i < m_aClients.size(); i++) { if (m_aClients[i].iClient == iClient) return i; } return ~0; } CLobbyPlayer* CGameLobby::GetPlayer(size_t iIndex) { if (iIndex >= m_aClients.size()) return NULL; return &m_aClients[iIndex]; } CLobbyPlayer* CGameLobby::GetPlayerByClient(size_t iClient) { return GetPlayer(GetPlayerIndex(iClient)); } void CGameLobby::AddPlayer(size_t iClient) { if (GetPlayerByClient(iClient)) return; CLobbyPlayer* pPlayer = &m_aClients.push_back(); pPlayer->iClient = iClient; ::LobbyPlayerInfo.RunCommand(sprintf(L"%d active 1", iClient)); } void CGameLobby::RemovePlayer(size_t iClient) { size_t iPlayer = GetPlayerIndex(iClient); if (!GetPlayer(iPlayer)) return; m_aClients.erase(m_aClients.begin()+iPlayer); ::LobbyPlayerInfo.RunCommand(sprintf(L"%d active 0", iClient)); } void CGameLobby::UpdatePlayer(size_t iClient, const eastl::string16& sKey, const eastl::string16& sValue) { CLobbyPlayer* pPlayer = GetPlayerByClient(iClient); if (!pPlayer) return; pPlayer->asInfo[sKey] = sValue; eastl::string16 sCommand = sprintf(eastl::string16(L"%d ") + sKey + L" " + sValue, iClient); ::LobbyPlayerInfo.RunCommand(sCommand); } void CGameLobby::SendFullUpdate(size_t iClient) { for (size_t i = 0; i < m_aClients.size(); i++) { CLobbyPlayer* pPlayer = &m_aClients[i]; ::LobbyPlayerInfo.RunCommand(sprintf(L"%d active 1", pPlayer->iClient), iClient); for (eastl::map<eastl::string16, eastl::string16>::iterator it = pPlayer->asInfo.begin(); it != pPlayer->asInfo.end(); it++) { eastl::string16 sCommand = sprintf(eastl::string16(L"%d ") + it->first + L" " + it->second, pPlayer->iClient); ::LobbyPlayerInfo.RunCommand(sCommand, iClient); } } } <|endoftext|>
<commit_before>#include <yuni/yuni.h> #include <yuni/core/noncopyable.h> #include <yuni/io/file.h> #include <yuni/core/system/console.h> #include <yuni/core/getopt.h> #include <yuni/io/directory.h> #include <yuni/io/directory/info.h> #include <yuni/datetime/timestamp.h> #include <yuni/core/logs/logs.h> #include "nany/nany.h" #include <algorithm> #include <yuni/datetime/timestamp.h> #include <iostream> #include <vector> using namespace Yuni; namespace { struct Settings { //! List of filenames to verify std::vector<String> filenames; // no colors bool noColors = false; // Result expected from filename convention bool useFilenameConvention = false; }; template<class LeftType = Logs::NullDecorator> struct ParseVerbosity : public LeftType { template<class Handler, class VerbosityType, class O> void internalDecoratorAddPrefix(O& out, const AnyString& s) const { // Write the verbosity to the output if (VerbosityType::hasName) { AnyString name{VerbosityType::Name()}; if (s.empty()) { } else if (name == "info") { if (Handler::colorsAllowed) System::Console::TextColor<System::Console::yellow>::Set(out); #ifndef YUNI_OS_WINDOWS out << " \u2713 "; #else out << " > "; #endif if (Handler::colorsAllowed) System::Console::TextColor<System::Console::white>::Set(out); out << "parsing"; if (Handler::colorsAllowed) System::Console::ResetTextColor(out); } else if (name == "error") { if (Handler::colorsAllowed) System::Console::TextColor<System::Console::red>::Set(out); out << " FAILED "; if (Handler::colorsAllowed) System::Console::TextColor<System::Console::white>::Set(out); out << "parsing"; if (Handler::colorsAllowed) System::Console::ResetTextColor(out); } else if (name == "warning") { if (Handler::colorsAllowed) System::Console::TextColor<System::Console::yellow>::Set(out); out << " {warn} "; if (Handler::colorsAllowed) System::Console::TextColor<System::Console::white>::Set(out); out << "parsing"; if (Handler::colorsAllowed) System::Console::ResetTextColor(out); } else { // Set Color if (Handler::colorsAllowed && VerbosityType::color != System::Console::none) System::Console::TextColor<VerbosityType::color>::Set(out); // The verbosity VerbosityType::AppendName(out); // Reset Color if (Handler::colorsAllowed && VerbosityType::color != System::Console::none) System::Console::ResetTextColor(out); } } // Transmit the message to the next decorator LeftType::template internalDecoratorAddPrefix<Handler, VerbosityType,O>(out, s); } }; // struct VerbosityLevel using Logging = Logs::Logger<Logs::StdCout<>, ParseVerbosity<Logs::Message<>>>; static Logging logs; uint32_t findCommonFolderLength(const std::vector<String>& filenames) { if (filenames.empty()) return 0; uint32_t len = 0; auto& firstElement = filenames[0]; const char sep = IO::Separator; for (; ; ++len) { for (auto& filename: filenames) { if (len == firstElement.size()) return len; if (len < filename.size() and filename[len] != '\0' and filename[len] == firstElement[len]) continue; while (len > 0 and firstElement[--len] != sep) { // back to the last sep } return len; } } return len; } bool expandAndCanonicalizeFilenames(std::vector<String>& filenames) { std::vector<String> filelist; filelist.reserve(512); String currentfile; currentfile.reserve(4096); for (auto& filename: filenames) { IO::Canonicalize(currentfile, filename); switch (IO::TypeOf(currentfile)) { case IO::typeFile: { filelist.emplace_back(currentfile); break; } case IO::typeFolder: { ShortString16 ext; IO::Directory::Info info(currentfile); auto end = info.recursive_file_end(); for (auto i = info.recursive_file_begin(); i != end; ++i) { IO::ExtractExtension(ext, *i); if (ext == ".ny") filelist.emplace_back(i.filename()); } break; } default: { logs.error() << "impossible to find '" << currentfile << "'"; return false; } } } // for beauty in singled-threaded (and to always produce the same output) std::sort(filelist.begin(), filelist.end()); filenames.swap(filelist); return true; } template<class F> bool IterateThroughAllFiles(const std::vector<String>& filenames, const F& callback) { String currentfile; uint32_t testOK = 0; uint32_t testFAILED = 0; int64_t maxCheckDuration = 0; int64_t startTime = DateTime::NowMilliSeconds(); for (auto& filename: filenames) { int64_t duration = 0; if (callback(filename, duration)) ++testOK; else ++testFAILED; if (duration > maxCheckDuration) maxCheckDuration = duration; } int64_t endTime = DateTime::NowMilliSeconds(); uint32_t total = testOK + testFAILED; if (total > 0) { int64_t duration = (endTime - startTime); String durationStr; durationStr << " (in " << duration << "ms, max: " << maxCheckDuration << "ms)"; if (total > 1) { if (0 != testFAILED) { switch (total) { case 1: logs.warning() << "-- FAILED -- 1 file, +" << testOK << ", -" << testFAILED << durationStr; break; default: logs.warning() << "-- FAILED -- " << total << " files, +" << testOK << ", -" << testFAILED << durationStr; } } else { switch (total) { case 1: logs.info() << "success: 1 file, +" << testOK << ", -0" << durationStr; break; default: logs.info() << "success: " << total << " files, +" << testOK << ", -0" << durationStr; } } } } else logs.warning() << "no input file"; return (0 == testFAILED); } bool batchCheckIfFilenamesConformToGrammar(Settings& settings) { if (not expandAndCanonicalizeFilenames(settings.filenames)) return false; auto commonFolder = (settings.filenames.size() > 1 ? findCommonFolderLength(settings.filenames) : 0); if (0 != commonFolder) ++commonFolder; return IterateThroughAllFiles(settings.filenames, [&](const AnyString& file, int64_t& duration) -> bool { String barefile; IO::ExtractFileName(barefile, file); bool expected = true; bool canfail = false; if (settings.useFilenameConvention) { if (barefile.startsWith("ko-")) expected = false; if (barefile.find("-canfail-") < barefile.size()) canfail = true; } // PARSE int64_t start = DateTime::NowMilliSeconds(); bool success = (nytrue == nytry_parse_file_n(file.c_str(), file.size())); duration = DateTime::NowMilliSeconds() - start; success = (success == expected); if (success and duration < 300) { logs.info() << AnyString{file, commonFolder} << " [" << duration << "ms]"; } else { if (not success) { if (not canfail) logs.error() << AnyString{file, commonFolder} << " [" << duration << "ms]"; else logs.warning() << AnyString{file, commonFolder} << " [" << duration << "ms, can fail]"; } else logs.error() << AnyString{file, commonFolder} << " [" << duration << "ms - time limit reached]"; success = canfail; } return success; }); } } // namespace int main(int argc, char** argv) { try { Settings settings; // parse the command { // The command line options parser GetOpt::Parser options; // Input files options.add(settings.filenames, 'i', "input", "Input files (or folders)"); options.remainingArguments(settings.filenames); // --no-color options.addFlag(settings.noColors, ' ', "no-color", "Disable color output"); // use filename convention options.addFlag(settings.useFilenameConvention, ' ', "use-filename-convention", "Use the filename to determine if the test should succeed or not (should succeed if starting with 'ok-'"); // version bool optVersion = false; options.addFlag(optVersion, ' ', "version", "Display the version of the compiler and exit"); // Ask to the parser to parse the command line if (not options(argc, argv)) { // The program should not continue here // The user may have requested the help or an error has happened // If an error has happened, the exit status should be different from 0 if (options.errors()) { std::cerr << "Abort due to error\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } if (optVersion) { std::cout << "0.0\n"; return EXIT_SUCCESS; } if (settings.filenames.empty()) { std::cerr << argv[0] << ": no input file\n"; return EXIT_FAILURE; } } // Print AST or check for Nany Grammar bool success = batchCheckIfFilenamesConformToGrammar(settings); return success ? EXIT_SUCCESS : EXIT_FAILURE; } catch (const std::exception& e) { std::cerr << argv[0] << ": " << e.what() << '\n'; } return EXIT_FAILURE; } <commit_msg>check-syntax: bold instead of white color for logging<commit_after>#include <yuni/yuni.h> #include <yuni/core/noncopyable.h> #include <yuni/io/file.h> #include <yuni/core/system/console.h> #include <yuni/core/getopt.h> #include <yuni/io/directory.h> #include <yuni/io/directory/info.h> #include <yuni/datetime/timestamp.h> #include <yuni/core/logs/logs.h> #include "nany/nany.h" #include <algorithm> #include <yuni/datetime/timestamp.h> #include <iostream> #include <vector> using namespace Yuni; namespace { struct Settings { //! List of filenames to verify std::vector<String> filenames; // no colors bool noColors = false; // Result expected from filename convention bool useFilenameConvention = false; }; template<class LeftType = Logs::NullDecorator> struct ParseVerbosity : public LeftType { template<class Handler, class VerbosityType, class O> void internalDecoratorAddPrefix(O& out, const AnyString& s) const { // Write the verbosity to the output if (VerbosityType::hasName) { AnyString name{VerbosityType::Name()}; if (s.empty()) { } else if (name == "info") { if (Handler::colorsAllowed) System::Console::TextColor<System::Console::yellow>::Set(out); #ifndef YUNI_OS_WINDOWS out << " \u2713 "; #else out << " > "; #endif if (Handler::colorsAllowed) { System::Console::ResetTextColor(out); System::Console::TextColor<System::Console::bold>::Set(out); } out << "parsing"; if (Handler::colorsAllowed) System::Console::ResetTextColor(out); } else if (name == "error") { if (Handler::colorsAllowed) System::Console::TextColor<System::Console::red>::Set(out); out << " FAILED "; if (Handler::colorsAllowed) { System::Console::ResetTextColor(out); System::Console::TextColor<System::Console::bold>::Set(out); } out << "parsing"; if (Handler::colorsAllowed) System::Console::ResetTextColor(out); } else if (name == "warning") { if (Handler::colorsAllowed) System::Console::TextColor<System::Console::yellow>::Set(out); out << " {warn} "; if (Handler::colorsAllowed) { System::Console::ResetTextColor(out); System::Console::TextColor<System::Console::bold>::Set(out); } out << "parsing"; if (Handler::colorsAllowed) System::Console::ResetTextColor(out); } else { // Set Color if (Handler::colorsAllowed && VerbosityType::color != System::Console::none) System::Console::TextColor<VerbosityType::color>::Set(out); // The verbosity VerbosityType::AppendName(out); // Reset Color if (Handler::colorsAllowed && VerbosityType::color != System::Console::none) System::Console::ResetTextColor(out); } } // Transmit the message to the next decorator LeftType::template internalDecoratorAddPrefix<Handler, VerbosityType,O>(out, s); } }; // struct VerbosityLevel using Logging = Logs::Logger<Logs::StdCout<>, ParseVerbosity<Logs::Message<>>>; static Logging logs; uint32_t findCommonFolderLength(const std::vector<String>& filenames) { if (filenames.empty()) return 0; uint32_t len = 0; auto& firstElement = filenames[0]; const char sep = IO::Separator; for (; ; ++len) { for (auto& filename: filenames) { if (len == firstElement.size()) return len; if (len < filename.size() and filename[len] != '\0' and filename[len] == firstElement[len]) continue; while (len > 0 and firstElement[--len] != sep) { // back to the last sep } return len; } } return len; } bool expandAndCanonicalizeFilenames(std::vector<String>& filenames) { std::vector<String> filelist; filelist.reserve(512); String currentfile; currentfile.reserve(4096); for (auto& filename: filenames) { IO::Canonicalize(currentfile, filename); switch (IO::TypeOf(currentfile)) { case IO::typeFile: { filelist.emplace_back(currentfile); break; } case IO::typeFolder: { ShortString16 ext; IO::Directory::Info info(currentfile); auto end = info.recursive_file_end(); for (auto i = info.recursive_file_begin(); i != end; ++i) { IO::ExtractExtension(ext, *i); if (ext == ".ny") filelist.emplace_back(i.filename()); } break; } default: { logs.error() << "impossible to find '" << currentfile << "'"; return false; } } } // for beauty in singled-threaded (and to always produce the same output) std::sort(filelist.begin(), filelist.end()); filenames.swap(filelist); return true; } template<class F> bool IterateThroughAllFiles(const std::vector<String>& filenames, const F& callback) { String currentfile; uint32_t testOK = 0; uint32_t testFAILED = 0; int64_t maxCheckDuration = 0; int64_t startTime = DateTime::NowMilliSeconds(); for (auto& filename: filenames) { int64_t duration = 0; if (callback(filename, duration)) ++testOK; else ++testFAILED; if (duration > maxCheckDuration) maxCheckDuration = duration; } int64_t endTime = DateTime::NowMilliSeconds(); uint32_t total = testOK + testFAILED; if (total > 0) { int64_t duration = (endTime - startTime); String durationStr; durationStr << " (in " << duration << "ms, max: " << maxCheckDuration << "ms)"; if (total > 1) { if (0 != testFAILED) { switch (total) { case 1: logs.warning() << "-- FAILED -- 1 file, +" << testOK << ", -" << testFAILED << durationStr; break; default: logs.warning() << "-- FAILED -- " << total << " files, +" << testOK << ", -" << testFAILED << durationStr; } } else { switch (total) { case 1: logs.info() << "success: 1 file, +" << testOK << ", -0" << durationStr; break; default: logs.info() << "success: " << total << " files, +" << testOK << ", -0" << durationStr; } } } } else logs.warning() << "no input file"; return (0 == testFAILED); } bool batchCheckIfFilenamesConformToGrammar(Settings& settings) { if (not expandAndCanonicalizeFilenames(settings.filenames)) return false; auto commonFolder = (settings.filenames.size() > 1 ? findCommonFolderLength(settings.filenames) : 0); if (0 != commonFolder) ++commonFolder; return IterateThroughAllFiles(settings.filenames, [&](const AnyString& file, int64_t& duration) -> bool { String barefile; IO::ExtractFileName(barefile, file); bool expected = true; bool canfail = false; if (settings.useFilenameConvention) { if (barefile.startsWith("ko-")) expected = false; if (barefile.find("-canfail-") < barefile.size()) canfail = true; } // PARSE int64_t start = DateTime::NowMilliSeconds(); bool success = (nytrue == nytry_parse_file_n(file.c_str(), file.size())); duration = DateTime::NowMilliSeconds() - start; success = (success == expected); if (success and duration < 300) { logs.info() << AnyString{file, commonFolder} << " [" << duration << "ms]"; } else { if (not success) { if (not canfail) logs.error() << AnyString{file, commonFolder} << " [" << duration << "ms]"; else logs.warning() << AnyString{file, commonFolder} << " [" << duration << "ms, can fail]"; } else logs.error() << AnyString{file, commonFolder} << " [" << duration << "ms - time limit reached]"; success = canfail; } return success; }); } } // namespace int main(int argc, char** argv) { try { Settings settings; // parse the command { // The command line options parser GetOpt::Parser options; // Input files options.add(settings.filenames, 'i', "input", "Input files (or folders)"); options.remainingArguments(settings.filenames); // --no-color options.addFlag(settings.noColors, ' ', "no-color", "Disable color output"); // use filename convention options.addFlag(settings.useFilenameConvention, ' ', "use-filename-convention", "Use the filename to determine if the test should succeed or not (should succeed if starting with 'ok-'"); // version bool optVersion = false; options.addFlag(optVersion, ' ', "version", "Display the version of the compiler and exit"); // Ask to the parser to parse the command line if (not options(argc, argv)) { // The program should not continue here // The user may have requested the help or an error has happened // If an error has happened, the exit status should be different from 0 if (options.errors()) { std::cerr << "Abort due to error\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } if (optVersion) { std::cout << "0.0\n"; return EXIT_SUCCESS; } if (settings.filenames.empty()) { std::cerr << argv[0] << ": no input file\n"; return EXIT_FAILURE; } } // Print AST or check for Nany Grammar bool success = batchCheckIfFilenamesConformToGrammar(settings); return success ? EXIT_SUCCESS : EXIT_FAILURE; } catch (const std::exception& e) { std::cerr << argv[0] << ": " << e.what() << '\n'; } return EXIT_FAILURE; } <|endoftext|>
<commit_before>// Rhodes.cpp : Implementation of WinMain. #include "stdafx.h" #include "MainWindow.h" #include "common/RhodesApp.h" #include "common/StringConverter.h" #include "common/rhoparams.h" #include "rho/rubyext/GeoLocationImpl.h" #include "ruby/ext/rho/rhoruby.h" using namespace rho; using namespace rho::common; using namespace std; using namespace stdext; #ifndef RUBY_RUBY_H typedef unsigned long VALUE; #endif //!RUBY_RUBY_H #if defined(OS_WINDOWS) char* parseToken( const char* start, int len ); #endif extern "C" char* wce_wctomb(const wchar_t* w); extern "C" wchar_t* wce_mbtowc(const char* a); extern "C" void rho_ringtone_manager_stop(); #if defined(_WIN32_WCE) #include <regext.h> // Global Notification Handle HREGNOTIFY g_hNotify = NULL; // ConnectionsNetworkCount // Gets a value indicating the number of network connections that are currently connected. #define SN_CONNECTIONSNETWORKCOUNT_ROOT HKEY_LOCAL_MACHINE #define SN_CONNECTIONSNETWORKCOUNT_PATH TEXT("System\\State\\Connections\\Network") #define SN_CONNECTIONSNETWORKCOUNT_VALUE TEXT("Count") #endif //BOOL EnumRhodesWindowsProc(HWND hwnd,LPARAM lParam); extern "C" void rho_clientregister_create(const char* szDevicePin); class CRhodesModule : public CAtlExeModuleT< CRhodesModule > { public : bool ParseCommandLine(LPCTSTR lpCmdLine, HRESULT* pnRetCode ) throw( ) { m_nRestarting = 1; TCHAR szTokens[] = _T("-/"); LPCTSTR lpszToken = FindOneOf(lpCmdLine, szTokens); getRhoRootPath(); while (lpszToken != NULL) { if (WordCmpI(lpszToken, _T("Restarting"))==0) { m_nRestarting = 10; } #if defined(OS_WINDOWS) else if (wcsncmp(lpszToken, _T("approot"),7)==0) { char* token = wce_wctomb(lpszToken); //parseToken will allocate extra byte at the end of the returned token value char* path = parseToken( token, strlen(token) ); if (path) { int len = strlen(path); if (!(path[len]=='\\' || path[len]=='/')) { path[len] = '\\'; path[len+1] = 0; } m_strRootPath = path; free(path); } free(token); } #endif lpszToken = FindOneOf(lpszToken, szTokens); } return __super::ParseCommandLine(lpCmdLine, pnRetCode); } // This method is called immediately before entering the message loop. // It contains initialization code for the application. // Returns: // S_OK => Success. Continue with RunMessageLoop() and PostMessageLoop(). // S_FALSE => Skip RunMessageLoop(), call PostMessageLoop(). // error code => Failure. Skip both RunMessageLoop() and PostMessageLoop(). HRESULT PreMessageLoop(int nShowCmd) throw() { HRESULT hr = __super::PreMessageLoop(nShowCmd); if (FAILED(hr)) { return hr; } // Note: In this sample, we don't respond differently to different hr success codes. // Allow only one instance of the application. // the "| 0x01" activates the correct owned window of the previous instance's main window HWND hWnd = NULL; for (int wait = 0; wait < m_nRestarting; wait++) { hWnd = FindWindow(CMainWindow::GetWndClassInfo().m_wc.lpszClassName, NULL); if (hWnd && m_nRestarting > 1) { Sleep(1000); } else { break; } } //EnumWindows(EnumRhodesWindowsProc, (LPARAM)&hWnd); if (hWnd) { SetForegroundWindow( HWND( DWORD(hWnd) | 0x01 ) ); return S_FALSE; } rho_logconf_Init(m_strRootPath.c_str()); LOG(INFO) + "Rhodes started"; ::SetThreadPriority(GetCurrentThread(),10); //Check for bundle directory is exists. HANDLE hFind; WIN32_FIND_DATA wfd; hFind = FindFirstFile(convertToStringW(m_strRootPath.substr(0, m_strRootPath.find_last_of('/'))).c_str(), &wfd); if (INVALID_HANDLE_VALUE == hFind || !(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { LOG(INFO) + "Bundle directory is missing\n"; int last = 0, pre_last = 0; last = getRhoRootPath().find_last_of('\\'); pre_last = getRhoRootPath().substr(0, last).find_last_of('\\'); String appName = getRhoRootPath().substr(pre_last + 1, last - pre_last - 1); int msgboxID = MessageBox(NULL, _T("Bundle directory is missing."), convertToStringW(appName).c_str(), MB_ICONERROR | MB_OK); return S_FALSE; } // Create the main application window m_appWindow.Create(NULL, CWindow::rcDefault, TEXT("Rhodes"), WS_VISIBLE); if (NULL == m_appWindow.m_hWnd) { return S_FALSE; } rho::common::CRhodesApp::Create(m_strRootPath ); RHODESAPP().startApp(); // m_pServerHost = new CServerHost(); // Starting local server //m_pServerHost->Start(m_appWindow.m_hWnd); // Navigate to the "loading..." page m_appWindow.Navigate2(_T("about:blank")); // Show the main application window m_appWindow.ShowWindow(nShowCmd); #if defined(_WIN32_WCE) // Register for changes in the number of network connections hr = RegistryNotifyWindow(SN_CONNECTIONSNETWORKCOUNT_ROOT, SN_CONNECTIONSNETWORKCOUNT_PATH, SN_CONNECTIONSNETWORKCOUNT_VALUE, m_appWindow.m_hWnd, WM_CONNECTIONSNETWORKCOUNT, 0, NULL, &g_hNotify); #else rho_clientregister_create("win32_client"); #endif return S_OK; } HWND GetManWindow() { return m_appWindow.m_hWnd; } void RunMessageLoop( ) throw( ) { MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { if (!m_appWindow.TranslateAccelerator(&msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } // Stop local server //m_pServerHost->Stop(); //delete m_pServerHost; //m_pServerHost = NULL; #if defined(OS_WINCE) CGPSController* pGPS = CGPSController::Instance(); pGPS->DeleteInstance(); #endif rho_ringtone_manager_stop(); rho::common::CRhodesApp::Destroy(); } const rho::String& getRhoRootPath() { if ( m_strRootPath.length() == 0 ) { char rootpath[MAX_PATH]; int len; if ( (len = GetModuleFileNameA(NULL,rootpath,MAX_PATH)) == 0 ) strcpy(rootpath,"."); else { while( !(rootpath[len] == '\\' || rootpath[len] == '/') ) len--; rootpath[len+1]=0; } m_strRootPath = rootpath; m_strRootPath += "rho/"; } return m_strRootPath; } private: CMainWindow m_appWindow; //CServerHost* m_pServerHost; rho::String m_strRootPath; int m_nRestarting; }; CRhodesModule _AtlModule; // bool g_restartOnExit = false; // extern "C" int WINAPI _tWinMain(HINSTANCE /*hInstance*/, HINSTANCE /*hPrevInstance*/, LPTSTR /*lpCmdLine*/, int nShowCmd) { INITCOMMONCONTROLSEX ctrl; //Required to use datetime picker controls. ctrl.dwSize = sizeof(ctrl); ctrl.dwICC = ICC_DATE_CLASSES; InitCommonControlsEx(&ctrl); return _AtlModule.WinMain(nShowCmd); } extern "C" HWND getMainWnd() { return _AtlModule.GetManWindow(); } extern "C" const char* rho_native_rhopath() { return _AtlModule.getRhoRootPath().c_str(); } extern "C" void rho_conf_show_log() { ::PostMessage(getMainWnd(),WM_COMMAND,IDM_LOG,0); } //Hook for ruby call to refresh web view extern "C" void rho_net_impl_network_indicator(int active) { //TODO: rho_net_impl_network_indicator } extern "C" void create_nativebar(int bar_type, rho_param *p) { //TODO: Implement me! } extern "C" void remove_nativebar() { //TODO: Implement me! } extern "C" void nativebar_switch_tab(int index) { //TODO: Implement me! } extern "C" void mapview_create(rho_param *p) { //TODO: mapview_create } extern "C" void rho_map_location(char* query) { } extern "C" void rho_appmanager_load( void* httpContext, char* szQuery) { } extern "C" void Init_openssl(void) { } extern "C" void Init_digest(void) { } extern "C" void Init_fcntl(void) { } extern "C" void Init_NavBar(void) { } /*BOOL EnumRhodesWindowsProc(HWND hwnd,LPARAM lParam) { char buf[255] = {0}; static char current_path[255] = {0}; if ( strlen(current_path) == 0 ) GetWindowModuleFileName(getMainWnd(), current_path, 255); GetWindowModuleFileName(hwnd, buf, 255); if ( strncmp( buf, current_path, 255 ) == 0 ) { HWND* pWnd = (HWND*)lParam; *pWnd = hwnd; return FALSE; } return TRUE; }*/ #if defined(OS_WINDOWS) //parseToken will allocate extra byte at the end of the //returned token value char* parseToken( const char* start, int len ) { int nNameLen = 0; while(*start==' '){ start++; len--;} int i = 0; for( i = 0; i < len; i++ ){ if ( start[i] == '=' ){ if ( i > 0 ){ int s = i-1; for(; s >= 0 && start[s]==' '; s-- ); nNameLen = s+1; break; }else break; } } if ( nNameLen == 0 ) return NULL; const char* szValue = start + i+1; int nValueLen = len - (i+1); while(*szValue==' ' || *szValue=='\'' || *szValue=='"' && nValueLen >= 0 ){ szValue++; nValueLen--;} while(nValueLen > 0 && (szValue[nValueLen-1]==' ' || szValue[nValueLen-1]=='\'' || szValue[nValueLen-1]=='"')) nValueLen--; char* value = (char*) malloc(nValueLen+2); strncpy(value, szValue, nValueLen); value[nValueLen] = '\0'; return value; } // char -> wchar_t wchar_t* wce_mbtowc(const char* a) { int length; wchar_t *wbuf; length = MultiByteToWideChar(CP_ACP, 0, a, -1, NULL, 0); wbuf = (wchar_t*)malloc( (length+1)*sizeof(wchar_t) ); MultiByteToWideChar(CP_ACP, 0, a, -1, wbuf, length); return wbuf; } // wchar_t -> char char* wce_wctomb(const wchar_t* w) { DWORD charlength; char* pChar; charlength = WideCharToMultiByte(CP_ACP, 0, w, -1, NULL, 0, NULL, NULL); pChar = (char*)malloc(charlength+1); WideCharToMultiByte(CP_ACP, 0, w, -1, pChar, charlength, NULL, NULL); return pChar; } #endif <commit_msg>WM & Win32: - show rhobundle pathname while reporting about missing directory; - fix pathname checking for approot argument;<commit_after>// Rhodes.cpp : Implementation of WinMain. #include "stdafx.h" #include "MainWindow.h" #include "common/RhodesApp.h" #include "common/StringConverter.h" #include "common/rhoparams.h" #include "rho/rubyext/GeoLocationImpl.h" #include "ruby/ext/rho/rhoruby.h" using namespace rho; using namespace rho::common; using namespace std; using namespace stdext; #ifndef RUBY_RUBY_H typedef unsigned long VALUE; #endif //!RUBY_RUBY_H #if defined(OS_WINDOWS) char* parseToken( const char* start, int len ); #endif extern "C" char* wce_wctomb(const wchar_t* w); extern "C" wchar_t* wce_mbtowc(const char* a); extern "C" void rho_ringtone_manager_stop(); #if defined(_WIN32_WCE) #include <regext.h> // Global Notification Handle HREGNOTIFY g_hNotify = NULL; // ConnectionsNetworkCount // Gets a value indicating the number of network connections that are currently connected. #define SN_CONNECTIONSNETWORKCOUNT_ROOT HKEY_LOCAL_MACHINE #define SN_CONNECTIONSNETWORKCOUNT_PATH TEXT("System\\State\\Connections\\Network") #define SN_CONNECTIONSNETWORKCOUNT_VALUE TEXT("Count") #endif //BOOL EnumRhodesWindowsProc(HWND hwnd,LPARAM lParam); extern "C" void rho_clientregister_create(const char* szDevicePin); class CRhodesModule : public CAtlExeModuleT< CRhodesModule > { public : bool ParseCommandLine(LPCTSTR lpCmdLine, HRESULT* pnRetCode ) throw( ) { m_nRestarting = 1; TCHAR szTokens[] = _T("-/"); LPCTSTR lpszToken = FindOneOf(lpCmdLine, szTokens); getRhoRootPath(); while (lpszToken != NULL) { if (WordCmpI(lpszToken, _T("Restarting"))==0) { m_nRestarting = 10; } #if defined(OS_WINDOWS) else if (wcsncmp(lpszToken, _T("approot"),7)==0) { char* token = wce_wctomb(lpszToken); //parseToken will allocate extra byte at the end of the returned token value char* path = parseToken( token, strlen(token) ); if (path) { int len = strlen(path); if (!(path[len]=='\\' || path[len]=='/')) { path[len] = '\\'; path[len+1] = 0; } m_strRootPath = path; free(path); } free(token); } #endif lpszToken = FindOneOf(lpszToken, szTokens); } return __super::ParseCommandLine(lpCmdLine, pnRetCode); } // This method is called immediately before entering the message loop. // It contains initialization code for the application. // Returns: // S_OK => Success. Continue with RunMessageLoop() and PostMessageLoop(). // S_FALSE => Skip RunMessageLoop(), call PostMessageLoop(). // error code => Failure. Skip both RunMessageLoop() and PostMessageLoop(). HRESULT PreMessageLoop(int nShowCmd) throw() { HRESULT hr = __super::PreMessageLoop(nShowCmd); if (FAILED(hr)) { return hr; } // Note: In this sample, we don't respond differently to different hr success codes. // Allow only one instance of the application. // the "| 0x01" activates the correct owned window of the previous instance's main window HWND hWnd = NULL; for (int wait = 0; wait < m_nRestarting; wait++) { hWnd = FindWindow(CMainWindow::GetWndClassInfo().m_wc.lpszClassName, NULL); if (hWnd && m_nRestarting > 1) { Sleep(1000); } else { break; } } //EnumWindows(EnumRhodesWindowsProc, (LPARAM)&hWnd); if (hWnd) { SetForegroundWindow( HWND( DWORD(hWnd) | 0x01 ) ); return S_FALSE; } rho_logconf_Init(m_strRootPath.c_str()); LOG(INFO) + "Rhodes started"; ::SetThreadPriority(GetCurrentThread(),10); //Check for bundle directory is exists. HANDLE hFind; WIN32_FIND_DATA wfd; // rootpath + "rho/" if (m_strRootPath.at(m_strRootPath.length()-1) == '/') { hFind = FindFirstFile(convertToStringW(m_strRootPath.substr(0, m_strRootPath.find_last_of('/'))).c_str(), &wfd); } else if (m_strRootPath.at(m_strRootPath.length()-1) == '\\') { //delete all '\' from the end of the pathname int i = m_strRootPath.length(); for ( ; i != 1; i--) { if (m_strRootPath.at(i-1) != '\\') break; } hFind = FindFirstFile(convertToStringW(m_strRootPath.substr(0, i)).c_str(), &wfd); } if (INVALID_HANDLE_VALUE == hFind || !(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { int last = 0, pre_last = 0; last = getRhoRootPath().find_last_of('\\'); pre_last = getRhoRootPath().substr(0, last).find_last_of('\\'); String appName = getRhoRootPath().substr(pre_last + 1, last - pre_last - 1); String messageText = "Bundle directory \"" + m_strRootPath.substr(0, m_strRootPath.find_last_of('/')) + "\" is missing\n"; LOG(INFO) + messageText; int msgboxID = MessageBox(NULL, convertToStringW(messageText).c_str(), convertToStringW(appName).c_str(), MB_ICONERROR | MB_OK); return S_FALSE; } // Create the main application window m_appWindow.Create(NULL, CWindow::rcDefault, TEXT("Rhodes"), WS_VISIBLE); if (NULL == m_appWindow.m_hWnd) { return S_FALSE; } rho::common::CRhodesApp::Create(m_strRootPath ); RHODESAPP().startApp(); // m_pServerHost = new CServerHost(); // Starting local server //m_pServerHost->Start(m_appWindow.m_hWnd); // Navigate to the "loading..." page m_appWindow.Navigate2(_T("about:blank")); // Show the main application window m_appWindow.ShowWindow(nShowCmd); #if defined(_WIN32_WCE) // Register for changes in the number of network connections hr = RegistryNotifyWindow(SN_CONNECTIONSNETWORKCOUNT_ROOT, SN_CONNECTIONSNETWORKCOUNT_PATH, SN_CONNECTIONSNETWORKCOUNT_VALUE, m_appWindow.m_hWnd, WM_CONNECTIONSNETWORKCOUNT, 0, NULL, &g_hNotify); #else rho_clientregister_create("win32_client"); #endif return S_OK; } HWND GetManWindow() { return m_appWindow.m_hWnd; } void RunMessageLoop( ) throw( ) { MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { if (!m_appWindow.TranslateAccelerator(&msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } // Stop local server //m_pServerHost->Stop(); //delete m_pServerHost; //m_pServerHost = NULL; #if defined(OS_WINCE) CGPSController* pGPS = CGPSController::Instance(); pGPS->DeleteInstance(); #endif rho_ringtone_manager_stop(); rho::common::CRhodesApp::Destroy(); } const rho::String& getRhoRootPath() { if ( m_strRootPath.length() == 0 ) { char rootpath[MAX_PATH]; int len; if ( (len = GetModuleFileNameA(NULL,rootpath,MAX_PATH)) == 0 ) strcpy(rootpath,"."); else { while( !(rootpath[len] == '\\' || rootpath[len] == '/') ) len--; rootpath[len+1]=0; } m_strRootPath = rootpath; m_strRootPath += "rho/"; } return m_strRootPath; } private: CMainWindow m_appWindow; //CServerHost* m_pServerHost; rho::String m_strRootPath; int m_nRestarting; }; CRhodesModule _AtlModule; // bool g_restartOnExit = false; // extern "C" int WINAPI _tWinMain(HINSTANCE /*hInstance*/, HINSTANCE /*hPrevInstance*/, LPTSTR /*lpCmdLine*/, int nShowCmd) { INITCOMMONCONTROLSEX ctrl; //Required to use datetime picker controls. ctrl.dwSize = sizeof(ctrl); ctrl.dwICC = ICC_DATE_CLASSES; InitCommonControlsEx(&ctrl); return _AtlModule.WinMain(nShowCmd); } extern "C" HWND getMainWnd() { return _AtlModule.GetManWindow(); } extern "C" const char* rho_native_rhopath() { return _AtlModule.getRhoRootPath().c_str(); } extern "C" void rho_conf_show_log() { ::PostMessage(getMainWnd(),WM_COMMAND,IDM_LOG,0); } //Hook for ruby call to refresh web view extern "C" void rho_net_impl_network_indicator(int active) { //TODO: rho_net_impl_network_indicator } extern "C" void create_nativebar(int bar_type, rho_param *p) { //TODO: Implement me! } extern "C" void remove_nativebar() { //TODO: Implement me! } extern "C" void nativebar_switch_tab(int index) { //TODO: Implement me! } extern "C" void mapview_create(rho_param *p) { //TODO: mapview_create } extern "C" void rho_map_location(char* query) { } extern "C" void rho_appmanager_load( void* httpContext, char* szQuery) { } extern "C" void Init_openssl(void) { } extern "C" void Init_digest(void) { } extern "C" void Init_fcntl(void) { } extern "C" void Init_NavBar(void) { } /*BOOL EnumRhodesWindowsProc(HWND hwnd,LPARAM lParam) { char buf[255] = {0}; static char current_path[255] = {0}; if ( strlen(current_path) == 0 ) GetWindowModuleFileName(getMainWnd(), current_path, 255); GetWindowModuleFileName(hwnd, buf, 255); if ( strncmp( buf, current_path, 255 ) == 0 ) { HWND* pWnd = (HWND*)lParam; *pWnd = hwnd; return FALSE; } return TRUE; }*/ #if defined(OS_WINDOWS) //parseToken will allocate extra byte at the end of the //returned token value char* parseToken( const char* start, int len ) { int nNameLen = 0; while(*start==' '){ start++; len--;} int i = 0; for( i = 0; i < len; i++ ){ if ( start[i] == '=' ){ if ( i > 0 ){ int s = i-1; for(; s >= 0 && start[s]==' '; s-- ); nNameLen = s+1; break; }else break; } } if ( nNameLen == 0 ) return NULL; const char* szValue = start + i+1; int nValueLen = len - (i+1); while(*szValue==' ' || *szValue=='\'' || *szValue=='"' && nValueLen >= 0 ){ szValue++; nValueLen--;} while(nValueLen > 0 && (szValue[nValueLen-1]==' ' || szValue[nValueLen-1]=='\'' || szValue[nValueLen-1]=='"')) nValueLen--; char* value = (char*) malloc(nValueLen+2); strncpy(value, szValue, nValueLen); value[nValueLen] = '\0'; return value; } // char -> wchar_t wchar_t* wce_mbtowc(const char* a) { int length; wchar_t *wbuf; length = MultiByteToWideChar(CP_ACP, 0, a, -1, NULL, 0); wbuf = (wchar_t*)malloc( (length+1)*sizeof(wchar_t) ); MultiByteToWideChar(CP_ACP, 0, a, -1, wbuf, length); return wbuf; } // wchar_t -> char char* wce_wctomb(const wchar_t* w) { DWORD charlength; char* pChar; charlength = WideCharToMultiByte(CP_ACP, 0, w, -1, NULL, 0, NULL, NULL); pChar = (char*)malloc(charlength+1); WideCharToMultiByte(CP_ACP, 0, w, -1, pChar, charlength, NULL, NULL); return pChar; } #endif <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2012 Razor team * Authors: * Johannes Zellner <webmaster@nebulon.de> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "volumepopup.h" #include "pulseaudiodevice.h" #include <qtxdg/xdgicon.h> #include <QtGui/QSlider> #include <QtGui/QToolButton> #include <QtGui/QVBoxLayout> #include <QtGui/QApplication> #include <QtGui/QDesktopWidget> #include <QtCore/QProcess> VolumePopup::VolumePopup(QWidget* parent): QWidget(parent, Qt::Dialog | Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::X11BypassWindowManagerHint), m_pos(0,0), m_anchor(Qt::TopLeftCorner), m_device(0) { m_volumeSlider = new QSlider(Qt::Vertical, this); m_mixerButton = new QToolButton(this); m_mixerButton->setIcon(XdgIcon::fromTheme(QStringList() << "kmix")); m_volumeSlider->setSingleStep(m_volumeSlider->pageStep()); QVBoxLayout *l = new QVBoxLayout(this); l->setSpacing(0); l->setMargin(2); l->addWidget(m_volumeSlider, 0, Qt::AlignHCenter); l->addWidget(m_mixerButton); connect(m_mixerButton, SIGNAL(clicked()), this, SIGNAL(launchMixer())); connect(m_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(handleSliderValueChanged(int))); } VolumePopup::~VolumePopup() { } void VolumePopup::enterEvent(QEvent *event) { emit mouseEnter(); } void VolumePopup::leaveEvent(QEvent *event) { emit mouseExit(); } void VolumePopup::handleSliderValueChanged(int value) { if (!m_device) return; m_device->setVolume(value); } void VolumePopup::resizeEvent(QResizeEvent *event) { QWidget::resizeEvent(event); realign(); } void VolumePopup::open(QPoint pos, Qt::Corner anchor) { m_pos = pos; m_anchor = anchor; realign(); show(); } void VolumePopup::handleWheelEvent(QWheelEvent *event) { m_volumeSlider->event(reinterpret_cast<QEvent*>(event)); } void VolumePopup::setDevice(PulseAudioDevice *device) { if (device == m_device) return; // disconnect old device if (m_device) { disconnect(m_device, SIGNAL(volumeChanged(int)), m_volumeSlider, SLOT(setValue(int))); disconnect(m_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(handleSliderValueChanged(int))); } m_device = device; connect(m_device, SIGNAL(volumeChanged(int)), m_volumeSlider, SLOT(setValue(int))); connect(m_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(handleSliderValueChanged(int))); emit deviceChanged(); } void VolumePopup::realign() { QRect rect; rect.setSize(sizeHint()); switch (m_anchor) { case Qt::TopLeftCorner: rect.moveTopLeft(m_pos); break; case Qt::TopRightCorner: rect.moveTopRight(m_pos); break; case Qt::BottomLeftCorner: rect.moveBottomLeft(m_pos); break; case Qt::BottomRightCorner: rect.moveBottomRight(m_pos); break; } QRect screen = QApplication::desktop()->availableGeometry(m_pos); if (rect.right() > screen.right()) rect.moveRight(screen.right()); if (rect.bottom() > screen.bottom()) rect.moveBottom(screen.bottom()); move(rect.topLeft()); } <commit_msg>panel-volume: Set slider value for initial volume value whenever the managed device changes<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2012 Razor team * Authors: * Johannes Zellner <webmaster@nebulon.de> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "volumepopup.h" #include "pulseaudiodevice.h" #include <qtxdg/xdgicon.h> #include <QtGui/QSlider> #include <QtGui/QToolButton> #include <QtGui/QVBoxLayout> #include <QtGui/QApplication> #include <QtGui/QDesktopWidget> #include <QtCore/QProcess> VolumePopup::VolumePopup(QWidget* parent): QWidget(parent, Qt::Dialog | Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::X11BypassWindowManagerHint), m_pos(0,0), m_anchor(Qt::TopLeftCorner), m_device(0) { m_volumeSlider = new QSlider(Qt::Vertical, this); m_mixerButton = new QToolButton(this); m_mixerButton->setIcon(XdgIcon::fromTheme(QStringList() << "kmix")); m_volumeSlider->setSingleStep(m_volumeSlider->pageStep()); QVBoxLayout *l = new QVBoxLayout(this); l->setSpacing(0); l->setMargin(2); l->addWidget(m_volumeSlider, 0, Qt::AlignHCenter); l->addWidget(m_mixerButton); connect(m_mixerButton, SIGNAL(clicked()), this, SIGNAL(launchMixer())); connect(m_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(handleSliderValueChanged(int))); } VolumePopup::~VolumePopup() { } void VolumePopup::enterEvent(QEvent *event) { emit mouseEnter(); } void VolumePopup::leaveEvent(QEvent *event) { emit mouseExit(); } void VolumePopup::handleSliderValueChanged(int value) { if (!m_device) return; m_device->setVolume(value); } void VolumePopup::resizeEvent(QResizeEvent *event) { QWidget::resizeEvent(event); realign(); } void VolumePopup::open(QPoint pos, Qt::Corner anchor) { m_pos = pos; m_anchor = anchor; realign(); show(); } void VolumePopup::handleWheelEvent(QWheelEvent *event) { m_volumeSlider->event(reinterpret_cast<QEvent*>(event)); } void VolumePopup::setDevice(PulseAudioDevice *device) { if (device == m_device) return; // disconnect old device if (m_device) { disconnect(m_device, SIGNAL(volumeChanged(int)), m_volumeSlider, SLOT(setValue(int))); disconnect(m_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(handleSliderValueChanged(int))); } m_device = device; m_volumeSlider->setValue(m_device->volume()); connect(m_device, SIGNAL(volumeChanged(int)), m_volumeSlider, SLOT(setValue(int))); connect(m_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(handleSliderValueChanged(int))); emit deviceChanged(); } void VolumePopup::realign() { QRect rect; rect.setSize(sizeHint()); switch (m_anchor) { case Qt::TopLeftCorner: rect.moveTopLeft(m_pos); break; case Qt::TopRightCorner: rect.moveTopRight(m_pos); break; case Qt::BottomLeftCorner: rect.moveBottomLeft(m_pos); break; case Qt::BottomRightCorner: rect.moveBottomRight(m_pos); break; } QRect screen = QApplication::desktop()->availableGeometry(m_pos); if (rect.right() > screen.right()) rect.moveRight(screen.right()); if (rect.bottom() > screen.bottom()) rect.moveBottom(screen.bottom()); move(rect.topLeft()); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: unodtabl.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2004-11-09 12:38:22 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _COM_SUN_STAR_DRAWING_LINEDASH_HPP_ #include <com/sun/star/drawing/LineDash.hpp> #endif #ifndef _SFXITEMPOOL_HXX #include <svtools/itempool.hxx> #endif #ifndef _SFXITEMSET_HXX //autogen #include <svtools/itemset.hxx> #endif #include <vector> #ifndef _SVX_UNONAMEITEMTABLE_HXX_ #include "UnoNameItemTable.hxx" #endif #ifndef _SVX_XLNDSIT_HXX #include "xlndsit.hxx" #endif #ifndef _SVX_UNOMID_HXX #include "unomid.hxx" #endif #include "xdash.hxx" #include "svdmodel.hxx" using namespace ::com::sun::star; using namespace ::rtl; using namespace ::cppu; class SvxUnoDashTable : public SvxUnoNameItemTable { public: SvxUnoDashTable( SdrModel* pModel ) throw(); virtual ~SvxUnoDashTable() throw(); virtual NameOrIndex* createItem() const throw(); // XServiceInfo virtual OUString SAL_CALL getImplementationName( ) throw( uno::RuntimeException ); virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw( uno::RuntimeException); // XElementAccess virtual uno::Type SAL_CALL getElementType( ) throw( uno::RuntimeException); }; SvxUnoDashTable::SvxUnoDashTable( SdrModel* pModel ) throw() : SvxUnoNameItemTable( pModel, XATTR_LINEDASH, MID_LINEDASH ) { } SvxUnoDashTable::~SvxUnoDashTable() throw() { } OUString SAL_CALL SvxUnoDashTable::getImplementationName() throw( uno::RuntimeException ) { return OUString( RTL_CONSTASCII_USTRINGPARAM("SvxUnoDashTable") ); } uno::Sequence< OUString > SAL_CALL SvxUnoDashTable::getSupportedServiceNames( ) throw( uno::RuntimeException ) { uno::Sequence< OUString > aSNS( 1 ); aSNS.getArray()[0] = OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.DashTable" )); return aSNS; } NameOrIndex* SvxUnoDashTable::createItem() const throw() { XLineDashItem* pNewItem = new XLineDashItem(); pNewItem->SetWhich( XATTR_LINEDASH ); // set which id for pooling return pNewItem; } // XElementAccess uno::Type SAL_CALL SvxUnoDashTable::getElementType( ) throw( uno::RuntimeException ) { return ::getCppuType((const struct drawing::LineDash*)0); } /** * Create a gradienttable */ uno::Reference< uno::XInterface > SAL_CALL SvxUnoDashTable_createInstance( SdrModel* pModel ) { return *new SvxUnoDashTable(pModel); } <commit_msg>INTEGRATION: CWS visibility01 (1.8.854); FILE MERGED 2005/01/12 12:29:23 mnicel 1.8.854.2: RESYNC: (1.8-1.9); FILE MERGED 2004/12/06 08:11:28 mnicel 1.8.854.1: Part of symbol visibility markup - #i35758#<commit_after>/************************************************************************* * * $RCSfile: unodtabl.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: kz $ $Date: 2005-01-21 17:01:34 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _COM_SUN_STAR_DRAWING_LINEDASH_HPP_ #include <com/sun/star/drawing/LineDash.hpp> #endif #ifndef _SFXITEMPOOL_HXX #include <svtools/itempool.hxx> #endif #ifndef _SFXITEMSET_HXX //autogen #include <svtools/itemset.hxx> #endif #include <vector> #ifndef _SVX_UNONAMEITEMTABLE_HXX_ #include "UnoNameItemTable.hxx" #endif #ifndef _SVX_XLNDSIT_HXX #include "xlndsit.hxx" #endif #ifndef _SVX_UNOMID_HXX #include "unomid.hxx" #endif #include "xdash.hxx" #include "svdmodel.hxx" #include "unofill.hxx" using namespace ::com::sun::star; using namespace ::rtl; using namespace ::cppu; class SvxUnoDashTable : public SvxUnoNameItemTable { public: SvxUnoDashTable( SdrModel* pModel ) throw(); virtual ~SvxUnoDashTable() throw(); virtual NameOrIndex* createItem() const throw(); // XServiceInfo virtual OUString SAL_CALL getImplementationName( ) throw( uno::RuntimeException ); virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw( uno::RuntimeException); // XElementAccess virtual uno::Type SAL_CALL getElementType( ) throw( uno::RuntimeException); }; SvxUnoDashTable::SvxUnoDashTable( SdrModel* pModel ) throw() : SvxUnoNameItemTable( pModel, XATTR_LINEDASH, MID_LINEDASH ) { } SvxUnoDashTable::~SvxUnoDashTable() throw() { } OUString SAL_CALL SvxUnoDashTable::getImplementationName() throw( uno::RuntimeException ) { return OUString( RTL_CONSTASCII_USTRINGPARAM("SvxUnoDashTable") ); } uno::Sequence< OUString > SAL_CALL SvxUnoDashTable::getSupportedServiceNames( ) throw( uno::RuntimeException ) { uno::Sequence< OUString > aSNS( 1 ); aSNS.getArray()[0] = OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.DashTable" )); return aSNS; } NameOrIndex* SvxUnoDashTable::createItem() const throw() { XLineDashItem* pNewItem = new XLineDashItem(); pNewItem->SetWhich( XATTR_LINEDASH ); // set which id for pooling return pNewItem; } // XElementAccess uno::Type SAL_CALL SvxUnoDashTable::getElementType( ) throw( uno::RuntimeException ) { return ::getCppuType((const struct drawing::LineDash*)0); } /** * Create a gradienttable */ uno::Reference< uno::XInterface > SAL_CALL SvxUnoDashTable_createInstance( SdrModel* pModel ) { return *new SvxUnoDashTable(pModel); } <|endoftext|>
<commit_before>#include <cstddef> #include <utility> #include <new> #include <experimental/dynarray> namespace archie { namespace utils { namespace containers { template <typename Tp, std::size_t N> struct stack_allocator { using value_type = Tp; using pointer = Tp*; using reference = Tp&; using const_reference = Tp const&; using const_pointer = Tp const*; using size_type = std::size_t; using difference_type = std::ptrdiff_t; pointer allocate(size_type n) { auto s = taken_; taken_ += n; return &store.array[s]; } void deallocate(pointer, size_type) {} size_type max_size() const { return N - taken_; } private: union storage { char raw[N * sizeof(value_type)]; value_type array[N]; }; storage store; size_type taken_ = 0u; }; template <typename Tp, std::size_t N, typename Alloc = stack_allocator<Tp, N>> struct fixed_buffer { using allocator_type = Alloc; using value_type = typename allocator_type::value_type; using pointer = typename allocator_type::pointer; using reference = typename allocator_type::reference; using const_reference = typename allocator_type::const_reference; using const_pointer = typename allocator_type::const_pointer; using size_type = typename allocator_type::size_type; using iterator = pointer; using const_iterator = const_pointer; explicit fixed_buffer(size_type n) : impl_() { while (n--) emplace_back(); } template <typename Up> fixed_buffer(size_type n, Up const& ref) : impl_() { while (n--) emplace_back(ref); } fixed_buffer() : fixed_buffer(0u) {} ~fixed_buffer() { while (size()) { back().~value_type(); --impl_.size_; } } const_reference operator[](size_type n) const { return *(impl_.begin_ + n); } const_reference front() const { return operator[](0); } const_reference back() const { return operator[](size() - 1u); } const_iterator begin() const { return &front(); } const_iterator end() const { return begin() + size(); } reference operator[](size_type n) { return *(impl_.begin_ + n); } reference front() { return operator[](0); } reference back() { return operator[](size() - 1u); } iterator begin() { return &front(); } iterator end() { return begin() + size(); } size_type size() const { return impl_.size_; } template <typename... Us> void emplace_back(Us&&... us) { new (end()) value_type(std::forward<Us>(us)...); ++impl_.size_; } private: struct impl : allocator_type { using allocator_type::allocate; using allocator_type::deallocate; impl() : begin_(allocate(N)) {} ~impl() { deallocate(begin_, N); } pointer const begin_ = nullptr; size_type size_ = 0u; }; impl impl_; }; template <typename Tp, std::size_t N> struct ring_buffer { using buff_t = fixed_buffer<Tp, N>; using value_type = typename buff_t::value_type; using pointer = typename buff_t::pointer; using reference = typename buff_t::reference; using const_reference = typename buff_t::const_reference; using const_pointer = typename buff_t::const_pointer; using size_type = typename buff_t::size_type; size_type size() const { return 0; } private: buff_t buff_; }; } } } #include <archie/utils/test.h> #include <memory> namespace cont = archie::utils::containers; void canCreateStackAlloc() { auto alloc = cont::stack_allocator<int, 4>{}; EXPECT_EQ(4u, alloc.max_size()); } void canAllocateWithStackAlloc() { auto alloc = cont::stack_allocator<int, 4>{}; EXPECT_EQ(4u, alloc.max_size()); auto ptr1 = alloc.allocate(2); EXPECT_EQ(2u, alloc.max_size()); EXPECT_TRUE((void*)ptr1 >= (void*)&alloc); EXPECT_TRUE((void*)ptr1 < (void*)(&alloc + 1)); auto ptr2 = alloc.allocate(1); EXPECT_EQ(1u, alloc.max_size()); EXPECT_TRUE((void*)ptr2 >= (void*)&alloc); EXPECT_TRUE((void*)ptr2 < (void*)(&alloc + 1)); EXPECT_NE(ptr1, ptr2); } void canDefaultConstructFixedBuffer() { auto buff = cont::fixed_buffer<int, 5>{}; EXPECT_EQ(0u, buff.size()); } void canConstructFixedBufferWithNum() { using buff_t = cont::fixed_buffer<int, 5>; EXPECT_EQ(0u, buff_t{0}.size()); EXPECT_EQ(1u, buff_t{1}.size()); auto buff2 = buff_t{2, 1}; EXPECT_EQ(2u, buff2.size()); EXPECT_EQ(1u, buff2[0]); EXPECT_EQ(1u, buff2[1]); } void canCreateRingBuffer() { auto buff = cont::ring_buffer<int, 5>{}; EXPECT_EQ(0u, buff.size()); } int main() { canCreateStackAlloc(); canAllocateWithStackAlloc(); canDefaultConstructFixedBuffer(); canConstructFixedBufferWithNum(); canCreateRingBuffer(); return 0; } <commit_msg>dummy<commit_after>#include <cstddef> #include <utility> #include <new> #include <experimental/dynarray> namespace archie { namespace utils { namespace containers { template <typename Tp, std::size_t N> struct stack_allocator { using value_type = Tp; using pointer = Tp*; using reference = Tp&; using const_reference = Tp const&; using const_pointer = Tp const*; using size_type = std::size_t; using difference_type = std::ptrdiff_t; pointer allocate(size_type n) { auto s = taken_; taken_ += n; return &store.array[s]; } void deallocate(pointer, size_type) {} size_type max_size() const { return N - taken_; } private: union storage { char raw[N * sizeof(value_type)]; value_type array[N]; }; storage store; size_type taken_ = 0u; }; template <typename Tp, std::size_t N, typename Alloc = stack_allocator<Tp, N>> struct fixed_buffer { using allocator_type = Alloc; using value_type = typename allocator_type::value_type; using pointer = typename allocator_type::pointer; using reference = typename allocator_type::reference; using const_reference = typename allocator_type::const_reference; using const_pointer = typename allocator_type::const_pointer; using size_type = typename allocator_type::size_type; using iterator = pointer; using const_iterator = const_pointer; explicit fixed_buffer(size_type n) : impl_() { while (n--) emplace_back(); } template <typename Up> fixed_buffer(size_type n, Up const& ref) : impl_() { while (n--) emplace_back(ref); } fixed_buffer() : fixed_buffer(0u) {} ~fixed_buffer() { while (size()) { back().~value_type(); --impl_.size_; } } const_reference operator[](size_type n) const { return *(impl_.begin_ + n); } const_reference front() const { return operator[](0); } const_reference back() const { return operator[](size() - 1u); } const_iterator begin() const { return &front(); } const_iterator end() const { return begin() + size(); } reference operator[](size_type n) { return *(impl_.begin_ + n); } reference front() { return operator[](0); } reference back() { return operator[](size() - 1u); } iterator begin() { return &front(); } iterator end() { return begin() + size(); } size_type size() const { return impl_.size_; } template <typename... Us> void emplace_back(Us&&... us) { new (end()) value_type(std::forward<Us>(us)...); ++impl_.size_; } private: struct impl : allocator_type { using allocator_type::allocate; using allocator_type::deallocate; impl() : begin_(allocate(N)) {} ~impl() { deallocate(begin_, N); } pointer const begin_ = nullptr; size_type size_ = 0u; }; impl impl_; }; template <typename Tp, std::size_t N> struct ring_buffer { using buff_t = fixed_buffer<Tp, N>; using value_type = typename buff_t::value_type; using pointer = typename buff_t::pointer; using reference = typename buff_t::reference; using const_reference = typename buff_t::const_reference; using const_pointer = typename buff_t::const_pointer; using size_type = typename buff_t::size_type; size_type size() const { return 0; } private: buff_t buff_; }; } } } #include <archie/utils/test.h> #include <memory> namespace cont = archie::utils::containers; void canCreateStackAlloc() { auto alloc = cont::stack_allocator<int, 4>{}; EXPECT_EQ(4u, alloc.max_size()); } void canAllocateWithStackAlloc() { auto alloc = cont::stack_allocator<int, 4>{}; EXPECT_EQ(4u, alloc.max_size()); auto ptr1 = alloc.allocate(2); EXPECT_EQ(2u, alloc.max_size()); EXPECT_TRUE((void*)ptr1 >= (void*)&alloc); EXPECT_TRUE((void*)ptr1 < (void*)(&alloc + 1)); auto ptr2 = alloc.allocate(1); EXPECT_EQ(1u, alloc.max_size()); EXPECT_TRUE((void*)ptr2 >= (void*)&alloc); EXPECT_TRUE((void*)ptr2 < (void*)(&alloc + 1)); EXPECT_NE(ptr1, ptr2); } void canDefaultConstructFixedBuffer() { auto buff = cont::fixed_buffer<int, 5>{}; EXPECT_EQ(0u, buff.size()); } void canConstructFixedBufferWithNum() { using buff_t = cont::fixed_buffer<int, 5>; EXPECT_EQ(0u, buff_t{0}.size()); EXPECT_EQ(1u, buff_t{1}.size()); auto buff2 = buff_t{2, 1}; EXPECT_EQ(2u, buff2.size()); EXPECT_EQ(1u, buff2[0]); EXPECT_EQ(1u, buff2[1]); } void canCreateRingBuffer() { auto buff = cont::ring_buffer<int, 5>{}; EXPECT_EQ(0u, buff.size()); } int main() { canCreateStackAlloc(); canAllocateWithStackAlloc(); canDefaultConstructFixedBuffer(); canConstructFixedBufferWithNum(); canCreateRingBuffer(); return 0; } <|endoftext|>
<commit_before>#ifndef _SUBMODULAR_FLOW_HPP_ #define _SUBMODULAR_FLOW_HPP_ #include "sos-common.hpp" #include "boost/optional/optional.hpp" #include <list> #include <map> typedef int64_t REAL; class SubmodularFlow { public: typedef int NodeId; typedef int CliqueId; struct Clique; typedef std::shared_ptr<Clique> CliquePtr; typedef std::vector<CliquePtr> CliqueVec; struct arc { NodeId i, j; CliqueId c; // if this is a clique edge; -1 otherwise }; typedef arc Arc; SubmodularFlow(); // Add n new nodes to the base set V NodeId AddNode(int n = 1); // GetLabel returns 1, 0 or -1 if n is in S, not in S, or haven't // computed flow yet, respectively int GetLabel(NodeId n) const; // Add a constant to the energy function void AddConstantTerm(REAL c) { m_constant_term += c; } // AddUnaryTerm for node n, with cost E0 for not being in S and E1 // for being in S void AddUnaryTerm(NodeId n, REAL E0, REAL E1); void AddUnaryTerm(NodeId n, REAL coeff); // Add Clique pointed to by cp void AddClique(const CliquePtr& cp); // Add Clique defined by nodes and energy table given void AddClique(const std::vector<NodeId>& nodes, const std::vector<REAL>& energyTable); // Compute the max flow using PushRelabel void PushRelabel(); // After computing the max flow, extract the min cut void ComputeMinCut(); // Compute the total energy across all cliques of the current labeling REAL ComputeEnergy() const; REAL ComputeEnergy(const std::vector<int>& labels) const; /* Clique: abstract base class for user-defined clique functions * * Clique stores the list of nodes associated with a clique. * Actual functionality is provided by the user writing a derived * class with Clique as the base, and which implements the * ComputeEnergy and ExchangeCapacity functions */ class Clique { public: Clique(const std::vector<NodeId>& nodes) : m_nodes(nodes), m_alpha_Ci(nodes.size(), 0) { } ~Clique() = default; // Returns the energy of the given labeling for this clique function virtual REAL ComputeEnergy(const std::vector<int>& labels) const = 0; // Returns the exchange capacity between nodes u and v virtual REAL ExchangeCapacity(NodeId u, NodeId v) const = 0; // Normalizes energy so that it is always >= 0, and the all 1 and // all 0 labeling have energy 0. Subtracts a linear function from // the energy, so we may need to change c_si, c_it virtual void NormalizeEnergy(SubmodularFlow& sf) = 0; const std::vector<NodeId>& Nodes() const { return m_nodes; } size_t Size() const { return m_nodes.size(); } std::vector<REAL>& AlphaCi() { return m_alpha_Ci; } const std::vector<REAL>& AlphaCi() const { return m_alpha_Ci; } // Returns the energy of the given labeling, minus alphas for i in S REAL ComputeEnergyAlpha(const std::vector<int>& labels) const { REAL e = ComputeEnergy(labels); for (size_t idx = 0; idx < m_nodes.size(); ++idx) { if (labels[m_nodes[idx]] == 1) e -= m_alpha_Ci[idx]; } return e; } protected: std::vector<NodeId> m_nodes; // The list of nodes in the clique std::vector<REAL> m_alpha_Ci; // The reparameterization variables for this clique // Prohibit copying and moving clique functions, to prevent slicing // of derived class data Clique(Clique&&) = delete; Clique& operator=(Clique&&) = delete; Clique(const Clique&) = delete; Clique& operator=(const Clique&) = delete; }; protected: // Layers store vertices by distance. struct preflow_layer { std::list<NodeId> active_vertices; // std::list<NodeId> inactive_vertices; }; typedef preflow_layer Layer; typedef std::vector<Layer> LayerArray; typedef typename LayerArray::iterator layer_iterator; LayerArray layers; int max_active, min_active; typedef typename std::list<NodeId>::iterator list_iterator; std::map<NodeId, typename std::list<NodeId>::iterator> layer_list_ptr; // Data needed during push-relabel NodeId s,t; std::vector<int> dis; std::vector<REAL> excess; std::vector<int> current_arc_index; std::vector< std::vector<Arc> > m_arc_list; void add_to_active_list(NodeId u, Layer& layer); void remove_from_active_list(NodeId u); REAL ResCap(Arc arc); boost::optional<Arc> FindPushableEdge(NodeId i); void Push(Arc arc); void Relabel(NodeId i); typedef std::vector<CliqueId> NeighborList; REAL m_constant_term; NodeId m_num_nodes; std::vector<REAL> m_c_si; std::vector<REAL> m_c_it; std::vector<REAL> m_phi_si; std::vector<REAL> m_phi_it; std::vector<int> m_labels; CliqueId m_num_cliques; CliqueVec m_cliques; std::vector<NeighborList> m_neighbors; public: // Functions for reading out data, useful for testing NodeId GetS() const { return s; } NodeId GetT() const { return t; } const std::vector<int>& GetDis() const { return dis; } const std::vector<REAL>& GetExcess() const { return excess; } REAL GetConstantTerm() const { return m_constant_term; } NodeId GetNumNodes() const { return m_num_nodes; } const std::vector<REAL>& GetC_si() const { return m_c_si; } const std::vector<REAL>& GetC_it() const { return m_c_it; } const std::vector<REAL>& GetPhi_si() const { return m_phi_si; } const std::vector<REAL>& GetPhi_it() const { return m_phi_it; } const std::vector<int>& GetLabels() const { return m_labels; } std::vector<int>& GetLabels() { return m_labels; } CliqueId GetNumCliques() const { return m_num_cliques; } const CliqueVec& GetCliques() const { return m_cliques; } const std::vector<NeighborList>& GetNeighbors() const { return m_neighbors; } int GetMaxActive() const { return max_active; } int GetMinActive() const { return min_active; } // Functions for breaking push-relabel into pieces // Only use for testing! void PushRelabelInit(); void PushRelabelStep(); bool PushRelabelNotDone(); }; /* * EnergyTableClique: stores energy as a list of 2^k values for each subset */ class EnergyTableClique : public SubmodularFlow::Clique { public: typedef SubmodularFlow::NodeId NodeId; typedef uint32_t Assignment; EnergyTableClique(const std::vector<NodeId>& nodes, const std::vector<REAL>& energy) : SubmodularFlow::Clique(nodes), m_energy(energy) { ASSERT(nodes.size() <= 31); } virtual REAL ComputeEnergy(const std::vector<int>& labels) const; virtual REAL ExchangeCapacity(NodeId u, NodeId v) const; virtual void NormalizeEnergy(SubmodularFlow& sf); protected: std::vector<REAL> m_energy; }; #endif <commit_msg>Playing around with different types.<commit_after>#ifndef _SUBMODULAR_FLOW_HPP_ #define _SUBMODULAR_FLOW_HPP_ #include "sos-common.hpp" #include "boost/optional/optional.hpp" #include <list> #include <map> typedef int64_t REAL; class SubmodularFlow { public: typedef int NodeId; typedef int CliqueId; struct Clique; typedef std::shared_ptr<Clique> CliquePtr; typedef std::vector<CliquePtr> CliqueVec; struct arc { NodeId i, j; CliqueId c; // if this is a clique edge; -1 otherwise }; typedef arc Arc; SubmodularFlow(); // Add n new nodes to the base set V NodeId AddNode(int n = 1); // GetLabel returns 1, 0 or -1 if n is in S, not in S, or haven't // computed flow yet, respectively int GetLabel(NodeId n) const; // Add a constant to the energy function void AddConstantTerm(REAL c) { m_constant_term += c; } // AddUnaryTerm for node n, with cost E0 for not being in S and E1 // for being in S void AddUnaryTerm(NodeId n, REAL E0, REAL E1); void AddUnaryTerm(NodeId n, REAL coeff); // Add Clique pointed to by cp void AddClique(const CliquePtr& cp); // Add Clique defined by nodes and energy table given void AddClique(const std::vector<NodeId>& nodes, const std::vector<REAL>& energyTable); // Compute the max flow using PushRelabel void PushRelabel(); // After computing the max flow, extract the min cut void ComputeMinCut(); // Compute the total energy across all cliques of the current labeling REAL ComputeEnergy() const; REAL ComputeEnergy(const std::vector<int>& labels) const; /* Clique: abstract base class for user-defined clique functions * * Clique stores the list of nodes associated with a clique. * Actual functionality is provided by the user writing a derived * class with Clique as the base, and which implements the * ComputeEnergy and ExchangeCapacity functions */ class Clique { public: Clique(const std::vector<NodeId>& nodes) : m_nodes(nodes), m_alpha_Ci(nodes.size(), 0) { } ~Clique() = default; // Returns the energy of the given labeling for this clique function virtual REAL ComputeEnergy(const std::vector<int>& labels) const = 0; // Returns the exchange capacity between nodes u and v virtual REAL ExchangeCapacity(NodeId u, NodeId v) const = 0; // Normalizes energy so that it is always >= 0, and the all 1 and // all 0 labeling have energy 0. Subtracts a linear function from // the energy, so we may need to change c_si, c_it virtual void NormalizeEnergy(SubmodularFlow& sf) = 0; const std::vector<NodeId>& Nodes() const { return m_nodes; } size_t Size() const { return m_nodes.size(); } std::vector<REAL>& AlphaCi() { return m_alpha_Ci; } const std::vector<REAL>& AlphaCi() const { return m_alpha_Ci; } // Returns the energy of the given labeling, minus alphas for i in S REAL ComputeEnergyAlpha(const std::vector<int>& labels) const { REAL e = ComputeEnergy(labels); for (size_t idx = 0; idx < m_nodes.size(); ++idx) { if (labels[m_nodes[idx]] == 1) e -= m_alpha_Ci[idx]; } return e; } protected: std::vector<NodeId> m_nodes; // The list of nodes in the clique std::vector<REAL> m_alpha_Ci; // The reparameterization variables for this clique // Prohibit copying and moving clique functions, to prevent slicing // of derived class data Clique(Clique&&) = delete; Clique& operator=(Clique&&) = delete; Clique(const Clique&) = delete; Clique& operator=(const Clique&) = delete; }; protected: // Layers store vertices by distance. struct preflow_layer { std::list<NodeId> active_vertices; // std::list<NodeId> inactive_vertices; }; typedef preflow_layer Layer; typedef std::vector<Layer> LayerArray; typedef typename LayerArray::iterator layer_iterator; LayerArray layers; int max_active, min_active; typedef typename std::list<NodeId>::iterator list_iterator; std::map<NodeId, typename std::list<NodeId>::iterator> layer_list_ptr; //iterator_property_map<typename std::vector< list_iterator >::iterator, VertexIndexMap> layer_list_ptr; // Data needed during push-relabel NodeId s,t; std::vector<int> dis; std::vector<REAL> excess; std::vector<int> current_arc_index; std::vector< std::vector<Arc> > m_arc_list; void add_to_active_list(NodeId u, Layer& layer); void remove_from_active_list(NodeId u); REAL ResCap(Arc arc); boost::optional<Arc> FindPushableEdge(NodeId i); void Push(Arc arc); void Relabel(NodeId i); typedef std::vector<CliqueId> NeighborList; REAL m_constant_term; NodeId m_num_nodes; std::vector<REAL> m_c_si; std::vector<REAL> m_c_it; std::vector<REAL> m_phi_si; std::vector<REAL> m_phi_it; std::vector<int> m_labels; CliqueId m_num_cliques; CliqueVec m_cliques; std::vector<NeighborList> m_neighbors; public: // Functions for reading out data, useful for testing NodeId GetS() const { return s; } NodeId GetT() const { return t; } const std::vector<int>& GetDis() const { return dis; } const std::vector<REAL>& GetExcess() const { return excess; } REAL GetConstantTerm() const { return m_constant_term; } NodeId GetNumNodes() const { return m_num_nodes; } const std::vector<REAL>& GetC_si() const { return m_c_si; } const std::vector<REAL>& GetC_it() const { return m_c_it; } const std::vector<REAL>& GetPhi_si() const { return m_phi_si; } const std::vector<REAL>& GetPhi_it() const { return m_phi_it; } const std::vector<int>& GetLabels() const { return m_labels; } std::vector<int>& GetLabels() { return m_labels; } CliqueId GetNumCliques() const { return m_num_cliques; } const CliqueVec& GetCliques() const { return m_cliques; } const std::vector<NeighborList>& GetNeighbors() const { return m_neighbors; } int GetMaxActive() const { return max_active; } int GetMinActive() const { return min_active; } // Functions for breaking push-relabel into pieces // Only use for testing! void PushRelabelInit(); void PushRelabelStep(); bool PushRelabelNotDone(); }; /* * EnergyTableClique: stores energy as a list of 2^k values for each subset */ class EnergyTableClique : public SubmodularFlow::Clique { public: typedef SubmodularFlow::NodeId NodeId; typedef uint32_t Assignment; EnergyTableClique(const std::vector<NodeId>& nodes, const std::vector<REAL>& energy) : SubmodularFlow::Clique(nodes), m_energy(energy) { ASSERT(nodes.size() <= 31); } virtual REAL ComputeEnergy(const std::vector<int>& labels) const; virtual REAL ExchangeCapacity(NodeId u, NodeId v) const; virtual void NormalizeEnergy(SubmodularFlow& sf); protected: std::vector<REAL> m_energy; }; #endif <|endoftext|>
<commit_before>#include "z80mbc.h" #include <fstream> z80mbc0::z80mbc0(const std::vector<quint8> &rom) { this->rom = rom; ram.resize(0x2000); } quint8 z80mbc0::readROM(quint16 address) { return rom[address]; } quint8 z80mbc0::readRAM(quint16 address) { return ram[address]; } void z80mbc0::writeROM(quint16, quint8) {} void z80mbc0::writeRAM(quint16 address, quint8 value) { ram[address] = value; } /********************************/ z80mbc1::z80mbc1(const std::vector<quint8> &rom) { this->rom = rom; ram.resize(0x10000); rombank = 1; rambank = 0; extram_on = false; ram_mode = false; } quint8 z80mbc1::readROM(quint16 address) { if (address < 0x4000) return rom[address]; address &= 0x3FFF; int the_rombank = (ram_mode) ? rombank & 0x1F : rombank; return rom[the_rombank * 0x4000 | address]; } quint8 z80mbc1::readRAM(quint16 address) { if (!extram_on || !ram_mode) return 0; address &= 0x1FFF; return ram[rambank * 0x2000 | address]; } void z80mbc1::writeROM(quint16 address, quint8 value) { switch (address & 0xF000) { case 0x0000: case 0x1000: extram_on = (value == 0x0A); break; case 0x2000: case 0x3000: value &= 0x1F; if (value == 0) value = 1; rombank = (rombank & 0x60) | value; break; case 0x4000: case 0x5000: value &= 0x03; if (ram_mode) { rambank = value; } else { rombank = (value << 5) | (rombank & 0x1F); } break; case 0x6000: case 0x7000: ram_mode = value & 1; break; } } void z80mbc1::writeRAM(quint16 address, quint8 value) { if (!extram_on || !ram_mode) return; if (!ram_mode) rambank = 0; address &= 0x1FFF; ram[rambank * 0x2000 | address] = value; } /********************************/ z80mbc3::z80mbc3(const std::vector<quint8> &rom) { rtczero = time(NULL); this->rom = rom; ram.resize(0x10000); rtc.resize(5); rombank = 1; rambank = 0; extram_on = false; } quint8 z80mbc3::readROM(quint16 address) { if (address < 0x4000) return rom[address]; address &= 0x3FFF; return rom[rombank * 0x4000 | address]; } quint8 z80mbc3::readRAM(quint16 address) { if (!extram_on) return 0; if (rambank <= 3) { address &= 0x1FFF; return ram[rambank * 0x2000 | address]; } else { calc_rtcregs(); return rtc[rambank - 0x08]; return 0; } } void z80mbc3::writeROM(quint16 address, quint8 value) { switch (address & 0xF000) { case 0x0000: case 0x1000: extram_on = (value == 0x0A); break; case 0x2000: case 0x3000: value &= 0x7F; rombank = (value == 0) ? 1 : value; break; case 0x4000: case 0x5000: rambank = value; break; case 0x6000: case 0x7000: // TODO: Lock RTC... break; } } void z80mbc3::writeRAM(quint16 address, quint8 value) { if (!extram_on) return; if (rambank <= 3) { address &= 0x1FFF; ram[rambank * 0x2000 | address] = value; } else { rtc[rambank - 0x8] = value; calc_rtczero(); } } void z80mbc3::save(std::string filename) { std::ofstream fout(filename.c_str(), std::ios_base::out | std::ios_base::binary); fout.write(reinterpret_cast<const char *>(&rtczero), sizeof(rtczero)); for (unsigned i = 0; i < ram.size(); ++i) { fout.write((char*)&ram[i], 1); } fout.close(); } void z80mbc3::load(std::string filename) { std::ifstream fin(filename.c_str(), std::ios_base::in | std::ios_base::binary); if (!fin.is_open()) return; char byte; ram.clear(); fin.read(reinterpret_cast<char *>(&rtczero), sizeof(rtczero)); while (fin.read(&byte, 1)) { ram.push_back(byte); } fin.close(); } void z80mbc3::calc_rtczero() { time_t difftime = time(NULL); long long days; difftime -= rtc[0]; difftime -= rtc[1] * 60; difftime -= rtc[2] * 3600; days = rtc[4] & 0x1; days = days << 8 | rtc[3]; difftime -= days * 3600 * 24; rtczero = difftime; } void z80mbc3::calc_rtcregs() { time_t difftime = time(NULL) - rtczero; rtc[0] = difftime % 60; rtc[1] = (difftime / 60) % 60; rtc[2] = (difftime / 3600) % 24; long long days = (difftime / (3600*24)); rtc[3] = days & 0xFF; rtc[4] = (rtc[4] & 0xFE) | ((days >> 8) & 0x1); } void z80mbc3::calc_halttime() { } /********************************/ z80mbc5::z80mbc5(const std::vector<quint8> &rom) { this->rom = rom; ram.resize(0x20000); rombank = 1; rambank = 0; extram_on = false; } quint8 z80mbc5::readROM(quint16 address) { if (address < 0x4000) return rom[address]; address &= 0x3FFF; return rom[rombank * 0x4000 | address]; } quint8 z80mbc5::readRAM(quint16 address) { if (!extram_on) return 0; address &= 0x1FFF; return ram[rambank * 0x2000 | address]; } void z80mbc5::writeROM(quint16 address, quint8 value) { switch (address & 0xF000) { case 0x0000: case 0x1000: extram_on = (value == 0x0A); break; case 0x2000: rombank = (rombank & 0x100) | (value); break; case 0x3000: value &= 0x1; rombank = (rombank & 0xFF) | (((int)value) << 8); break; case 0x4000: case 0x5000: rambank = value & 0x0F; break; } } void z80mbc5::writeRAM(quint16 address, quint8 value) { if (!extram_on) return; address &= 0x1FFF; ram[rambank * 0x2000 | address] = value; } void z80mbc5::save(std::string filename) { std::ofstream fout(filename.c_str(), std::ios_base::out | std::ios_base::binary); for (unsigned i = 0; i < ram.size(); ++i) { fout.write((char*)&ram[i], 1); } fout.close(); } void z80mbc5::load(std::string filename) { std::ifstream fin(filename.c_str(), std::ios_base::in | std::ios_base::binary); if (!fin.is_open()) return; char byte; ram.clear(); while (fin.read(&byte, 1)) { ram.push_back(byte); } fin.close(); } <commit_msg>MBC3 additions<commit_after>#include "z80mbc.h" #include <fstream> z80mbc0::z80mbc0(const std::vector<quint8> &rom) { this->rom = rom; ram.resize(0x2000); } quint8 z80mbc0::readROM(quint16 address) { return rom[address]; } quint8 z80mbc0::readRAM(quint16 address) { return ram[address]; } void z80mbc0::writeROM(quint16, quint8) {} void z80mbc0::writeRAM(quint16 address, quint8 value) { ram[address] = value; } /********************************/ z80mbc1::z80mbc1(const std::vector<quint8> &rom) { this->rom = rom; ram.resize(0x10000); rombank = 1; rambank = 0; extram_on = false; ram_mode = false; } quint8 z80mbc1::readROM(quint16 address) { if (address < 0x4000) return rom[address]; address &= 0x3FFF; int the_rombank = (ram_mode) ? rombank & 0x1F : rombank; return rom[the_rombank * 0x4000 | address]; } quint8 z80mbc1::readRAM(quint16 address) { if (!extram_on || !ram_mode) return 0; address &= 0x1FFF; return ram[rambank * 0x2000 | address]; } void z80mbc1::writeROM(quint16 address, quint8 value) { switch (address & 0xF000) { case 0x0000: case 0x1000: extram_on = (value == 0x0A); break; case 0x2000: case 0x3000: value &= 0x1F; if (value == 0) value = 1; rombank = (rombank & 0x60) | value; break; case 0x4000: case 0x5000: value &= 0x03; if (ram_mode) { rambank = value; } else { rombank = (value << 5) | (rombank & 0x1F); } break; case 0x6000: case 0x7000: ram_mode = value & 1; break; } } void z80mbc1::writeRAM(quint16 address, quint8 value) { if (!extram_on || !ram_mode) return; if (!ram_mode) rambank = 0; address &= 0x1FFF; ram[rambank * 0x2000 | address] = value; } /********************************/ z80mbc3::z80mbc3(const std::vector<quint8> &rom) { this->rom = rom; int ramsize; switch (rom[0x0149]) { case 0x00: ramsize = 0; break; case 0x01: ramsize = 0x800; break; // 2 kB case 0x02: ramsize = 0x2000; break; // 8 kB case 0x03: ramsize = 0x8000; break; // 32 kB } ram.resize(ramsize); rtc.resize(5); rombank = 1; rambank = 0; extram_on = false; } quint8 z80mbc3::readROM(quint16 address) { if (address < 0x4000) return rom[address]; address &= 0x3FFF; return rom[rombank * 0x4000 | address]; } quint8 z80mbc3::readRAM(quint16 address) { if (!extram_on) return 0; if (rambank <= 3) { address &= 0x1FFF; return ram[rambank * 0x2000 | address]; } else { calc_rtcregs(); return rtc[rambank - 0x08]; return 0; } } void z80mbc3::writeROM(quint16 address, quint8 value) { switch (address & 0xF000) { case 0x0000: case 0x1000: extram_on = (value == 0x0A); break; case 0x2000: case 0x3000: value &= 0x7F; rombank = (value == 0) ? 1 : value; break; case 0x4000: case 0x5000: rambank = value; break; case 0x6000: case 0x7000: // TODO: Lock RTC... break; } } void z80mbc3::writeRAM(quint16 address, quint8 value) { if (!extram_on) return; if (rambank <= 3) { address &= 0x1FFF; ram[rambank * 0x2000 | address] = value; } else { rtc[rambank - 0x8] = value; calc_rtczero(); } } void z80mbc3::save(std::string filename) { std::ofstream fout(filename.c_str(), std::ios_base::out | std::ios_base::binary); char head[] = "GB_MBC"; fout.write(head, sizeof head); fout.write(reinterpret_cast<char *>(&rom[0x0147]), 1); for (int i = 0; i < 5; ++i) { fout.write(reinterpret_cast<char *>(&rtc[i]), 1); } quint64 rtc = rtczero; fout.write(reinterpret_cast<char *>(&rtc), 8); for (unsigned i = 0; i < ram.size(); ++i) { fout.write(reinterpret_cast<char *>(&ram[i]), 1); } fout.close(); } void z80mbc3::load(std::string filename) { std::ifstream fin(filename.c_str(), std::ios_base::in | std::ios_base::binary); if (!fin.is_open()) return; char head[7]; char ver; fin.read(head, 7); fin.read(&ver, 1); if (strcmp(head, "GB_MBC") != 0) { fin.close(); return; } char byte; rtc.clear(); for (int i = 0; i < 5; ++i) { fin.read(&byte, 1); rtc.push_back(byte); } quint64 rtc; fin.read(reinterpret_cast<char *>(&rtc), 8); rtczero = rtc; ram.clear(); while (fin.read(&byte, 1)) { ram.push_back(byte); } fin.close(); calc_rtcregs(); } void z80mbc3::calc_rtczero() { time_t difftime = time(NULL); long long days; difftime -= rtc[0]; difftime -= rtc[1] * 60; difftime -= rtc[2] * 3600; days = rtc[4] & 0x1; days = days << 8 | rtc[3]; difftime -= days * 3600 * 24; rtczero = difftime; } void z80mbc3::calc_rtcregs() { if (rtc[4] & 0x40) { return; } time_t difftime = time(NULL) - rtczero; rtc[0] = difftime % 60; rtc[1] = (difftime / 60) % 60; rtc[2] = (difftime / 3600) % 24; long long days = (difftime / (3600*24)); rtc[3] = days & 0xFF; rtc[4] = (rtc[4] & 0xFE) | ((days >> 8) & 0x1); if (days >= 512) { rtc[4] |= 0x80; calc_rtczero(); } } void z80mbc3::calc_halttime() { } /********************************/ z80mbc5::z80mbc5(const std::vector<quint8> &rom) { this->rom = rom; ram.resize(0x20000); rombank = 1; rambank = 0; extram_on = false; } quint8 z80mbc5::readROM(quint16 address) { if (address < 0x4000) return rom[address]; address &= 0x3FFF; return rom[rombank * 0x4000 | address]; } quint8 z80mbc5::readRAM(quint16 address) { if (!extram_on) return 0; address &= 0x1FFF; return ram[rambank * 0x2000 | address]; } void z80mbc5::writeROM(quint16 address, quint8 value) { switch (address & 0xF000) { case 0x0000: case 0x1000: extram_on = (value == 0x0A); break; case 0x2000: rombank = (rombank & 0x100) | (value); break; case 0x3000: value &= 0x1; rombank = (rombank & 0xFF) | (((int)value) << 8); break; case 0x4000: case 0x5000: rambank = value & 0x0F; break; } } void z80mbc5::writeRAM(quint16 address, quint8 value) { if (!extram_on) return; address &= 0x1FFF; ram[rambank * 0x2000 | address] = value; } void z80mbc5::save(std::string filename) { std::ofstream fout(filename.c_str(), std::ios_base::out | std::ios_base::binary); for (unsigned i = 0; i < ram.size(); ++i) { fout.write((char*)&ram[i], 1); } fout.close(); } void z80mbc5::load(std::string filename) { std::ifstream fin(filename.c_str(), std::ios_base::in | std::ios_base::binary); if (!fin.is_open()) return; char byte; ram.clear(); while (fin.read(&byte, 1)) { ram.push_back(byte); } fin.close(); } <|endoftext|>
<commit_before><commit_msg>Remove superfluous bug numbers<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: wrtrtf.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2004-09-20 15:19:04 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _WRTRTF_HXX #define _WRTRTF_HXX #ifndef _SHELLIO_HXX #include <shellio.hxx> #endif #ifndef _WRT_FN_HXX #include <wrt_fn.hxx> #endif #ifndef SW_MS_MSFILTER_HXX #include "../inc/msfilter.hxx" #endif // einige Forward Deklarationen class Color; class Font; class SvPtrarr; class RTFColorTbl; class SwFmt; class SwFmtColl; class SwFlyFrmFmt; class SwPosFlyFrms; class SwPageDesc; class SwTableNode; class SwTxtFmtColl; class SwNumRule; class SwNumRuleTbl; class SwNodeNum; class DateTime; class RTFEndPosLst; extern SwAttrFnTab aRTFAttrFnTab; extern SwNodeFnTab aRTFNodeFnTab; // the default text encoding for the export, if it doesn't fit unicode will // be used #define DEF_ENCODING RTL_TEXTENCODING_ASCII_US class RTF_WrtRedlineAuthor : public sw::util::WrtRedlineAuthor { public: virtual void Write(Writer &rWrt); }; // der RTF-Writer class SwRTFWriter : public Writer { friend class RTFEndPosLst; SvPtrarr* pFontRemoveLst; RTFColorTbl* pColTbl; SwPosFlyFrms* pFlyPos; // Pointer auf die aktuelle "FlyFrmTabelle" RTFEndPosLst* pCurEndPosLst; const SfxItemSet* pAttrSet; // akt. Format/Collection vom Node // fuer den Zugriff auf einige Attribute // z.B. Font-Size, LR-Space,.. SwNumRuleTbl* pNumRuleTbl; // list of all exported numrules RTF_WrtRedlineAuthor *pRedlAuthors; USHORT nAktFlyPos; // Index auf das naechste "FlyFrmFmt" void OutRTFColorTab(); void OutRTFFontTab(); void OutRTFStyleTab(); void OutRTFListTab(); bool OutRTFRevTab(); void MakeHeader(); void OutUnicodeSafeRecord(const sal_Char *pToken, const String &rContent); void OutDocInfoStat(); void OutInfoDateTime( const DateTime&, const sal_Char* ); void CheckEndNodeForSection( const SwNode& rNd ); void BuildNumRuleTbl(); public: // --- public Member -------------------------------------------------- USHORT nCurRedline; const SwFlyFrmFmt* pFlyFmt; // liegt der Node in einem FlyFrame, // ist das Format gesetzt, sonst 0 const SwPageDesc* pAktPageDesc; // aktuell gesetzter PageDesc. USHORT nBkmkTabPos; // akt. Position in der Bookmark-Tabelle USHORT nCurScript; // actual scripttype #if defined(MAC) || defined(UNX) static const sal_Char sNewLine; // nur \012 oder \015 #else static const sal_Char __FAR_DATA sNewLine[]; // \015\012 #endif BOOL bFirstLine : 1; // wird die 1. Zeile ausgegeben ? BOOL bOutFmtAttr : 1; // TRUE: beim Schreiben eines Formates // existierte mindestens ein Attribut BOOL bRTFFlySyntax : 1; // gebe nur original RTFSyntax aus // (nur fuer die fliegenden Rahmen) BOOL bOutPageDesc: 1; // gebe einen PageDescriptor aus BOOL bOutPageDescTbl: 1; // gebe die PageDescriptor-Tabelle aus BOOL bOutTable : 1; // gebe eine Tabelle aus BOOL bTxtAttr : 1; // werden TextAttribute ausgegeben ? BOOL bWriteHelpFmt : 1; // schreibe Win-RTF-HelpFileFmt BOOL bOutStyleTab : 1; // gebe die StyleSheet-Tabelle aus BOOL bOutPageAttr : 1; // PageDescAttribut ausgeben? BOOL bAutoAttrSet : 1; // TRUE: pAttrSet ist harte Attributierung // FALSE: pAttrSet ist vom Format/Collection BOOL bOutOutlineOnly : 1; // TRUE: nur Gliederungs-Absaetze schreiben BOOL bOutListNumTxt : 1; // TRUE: der ListNumText wird ausgegeben BOOL bOutLeftHeadFoot : 1; // gebe vom PageDesc. den linkten // Header/Footer aus BOOL bOutSection : 1; // TRUE: Section PageDesc ausgeben BOOL bIgnoreNextPgBreak : 1; // TRUE: naechsten PageDesc/Break ignorieren BOOL bAssociated : 1; // use associated tokens // --- public Methoden ------------------------------------------------ SwRTFWriter( const String& rFilterName ); virtual ~SwRTFWriter(); virtual ULONG WriteStream(); void Out_SwDoc( SwPaM* ); // schreibe den makierten Bereich // gebe die evt. an der akt. Position stehenden FlyFrame aus. void OutFlyFrm(); void OutRTFFlyFrms( const SwFlyFrmFmt& ); // gebe alle an der Position stehenden Bookmarks aus void OutBookmarks( xub_StrLen nCntntPos ); // gebe die PageDesc-Daten im normalen RTF-Format aus void OutRTFPageDescription( const SwPageDesc&, BOOL , BOOL ); void OutRTFBorders( SvxBoxItem aBox ); void OutRTFBorder( const SvxBorderLine* aLine, const USHORT nSpace ); BOOL OutBreaks( const SfxItemSet& rSet ); void OutRedline( xub_StrLen nCntntPos ); // gebe die PageDescriptoren aus USHORT GetId( const Color& ) const; USHORT GetId( const SvxFontItem& ) const; USHORT GetId( const Font& ) const; USHORT GetId( const SwTxtFmtColl& ) const; USHORT GetId( const SwCharFmt& ) const; USHORT GetId( const SwNumRuleItem& rItem ) const; void OutPageDesc(); BOOL OutListNum( const SwTxtNode& rNd ); USHORT GetNumRuleId( const SwNumRule& rRule ); // fuer RTFSaveData SwPaM* GetEndPaM() { return pOrigPam; } void SetEndPaM( SwPaM* pPam ) { pOrigPam = pPam; } const SfxPoolItem& GetItem( USHORT nWhich ) const; const SfxItemSet* GetAttrSet() const { return pAttrSet; } void SetAttrSet( const SfxItemSet* p ) { pAttrSet = p; } const RTFEndPosLst* GetEndPosLst() const { return pCurEndPosLst; } void SetAssociatedFlag( BOOL b ) { bAssociated = b; } BOOL IsAssociatedFlag() const { return bAssociated; } void SetCurrScriptType( USHORT n ) { nCurScript = n; } USHORT GetCurrScriptType() const { return nCurScript; } short TrueFrameDirection(const SwFrmFmt &rFlyFmt) const; short GetCurrentPageDirection() const; }; // Struktur speichert die aktuellen Daten des Writers zwischen, um // einen anderen Dokument-Teil auszugeben, wie z.B. Header/Footer // Mit den beiden USHORTs im CTOR wird ein neuer PaM erzeugt und auf // die Position im Dokument gesetzt. // Im Destructor werden alle Daten wieder restauriert und der angelegte // Pam wieder geloescht. struct RTFSaveData { SwRTFWriter& rWrt; SwPaM* pOldPam, *pOldEnd; const SwFlyFrmFmt* pOldFlyFmt; const SwPageDesc* pOldPageDesc; const SfxItemSet* pOldAttrSet; // akt. Attribute vom Node BOOL bOldWriteAll : 1; BOOL bOldOutTable : 1; BOOL bOldOutPageAttr : 1; BOOL bOldAutoAttrSet : 1; BOOL bOldOutSection : 1; RTFSaveData( SwRTFWriter&, ULONG nStt, ULONG nEnd ); ~RTFSaveData(); }; // einige Funktions-Deklarationen Writer& OutRTF_AsByteString( Writer& rWrt, const String& rStr ); Writer& OutRTF_SwFmt( Writer& rWrt, const SwFmt& ); Writer& OutRTF_SwTblNode(Writer& , const SwTableNode&); Writer& OutRTF_SwSectionNode( Writer& , SwSectionNode & ); // Augabe von RTF-Bitmaps (steht im File "wrtpict.cxx") //struct SvxRTFPictureType; //class Bitmap; //USHORT WriteRTFPict( const SwPictureType&, Bitmap&, SvStream& ); // Ausagbe von Footer-/Headers Writer& OutRTF_SwFmtHeader( Writer& , const SfxPoolItem& ); Writer& OutRTF_SwFmtFooter( Writer& , const SfxPoolItem& ); // Kommentar und zusaetzlichen String ausgeben SvStream& OutComment( Writer& rWrt, const sal_Char* pStr ); // zusaetzlich das bOutFmtAttr-Flag manipulieren SvStream& OutComment( Writer& rWrt, const sal_Char* pStr, BOOL bSetFlag ); bool ExportAsInline(const SwFlyFrmFmt& rFlyFrmFmt); #endif // _WRTRTF_HXX <commit_msg>INTEGRATION: CWS adarefilterteam29 (1.8.64); FILE MERGED 2004/10/12 12:53:15 mmaher 1.8.64.2: RESYNC: (1.8-1.9); FILE MERGED 2004/07/06 13:10:30 mmaher 1.8.64.1: #i20264# Applied patch from tono@openoffice.org for writing in local charsets<commit_after>/************************************************************************* * * $RCSfile: wrtrtf.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2004-10-28 13:05:56 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _WRTRTF_HXX #define _WRTRTF_HXX #ifndef _SHELLIO_HXX #include <shellio.hxx> #endif #ifndef _WRT_FN_HXX #include <wrt_fn.hxx> #endif #ifndef SW_MS_MSFILTER_HXX #include "../inc/msfilter.hxx" #endif // einige Forward Deklarationen class Color; class Font; class SvPtrarr; class RTFColorTbl; class SwFmt; class SwFmtColl; class SwFlyFrmFmt; class SwPosFlyFrms; class SwPageDesc; class SwTableNode; class SwTxtFmtColl; class SwNumRule; class SwNumRuleTbl; class SwNodeNum; class DateTime; class RTFEndPosLst; extern SwAttrFnTab aRTFAttrFnTab; extern SwNodeFnTab aRTFNodeFnTab; // the default text encoding for the export, if it doesn't fit unicode will // be used #define DEF_ENCODING RTL_TEXTENCODING_ASCII_US class RTF_WrtRedlineAuthor : public sw::util::WrtRedlineAuthor { public: virtual void Write(Writer &rWrt); }; // der RTF-Writer class SwRTFWriter : public Writer { friend class RTFEndPosLst; SvPtrarr* pFontRemoveLst; RTFColorTbl* pColTbl; SwPosFlyFrms* pFlyPos; // Pointer auf die aktuelle "FlyFrmTabelle" RTFEndPosLst* pCurEndPosLst; const SfxItemSet* pAttrSet; // akt. Format/Collection vom Node // fuer den Zugriff auf einige Attribute // z.B. Font-Size, LR-Space,.. SwNumRuleTbl* pNumRuleTbl; // list of all exported numrules RTF_WrtRedlineAuthor *pRedlAuthors; USHORT nAktFlyPos; // Index auf das naechste "FlyFrmFmt" void OutRTFColorTab(); void OutRTFFontTab(); const rtl::OUString XlateFmtName( const rtl::OUString &rName, SwGetPoolIdFromName eFlags ); void OutRTFStyleTab(); void OutRTFListTab(); bool OutRTFRevTab(); void MakeHeader(); void OutUnicodeSafeRecord(const sal_Char *pToken, const String &rContent); void OutDocInfoStat(); void OutInfoDateTime( const DateTime&, const sal_Char* ); void CheckEndNodeForSection( const SwNode& rNd ); void BuildNumRuleTbl(); public: // --- public Member -------------------------------------------------- USHORT nCurRedline; const SwFlyFrmFmt* pFlyFmt; // liegt der Node in einem FlyFrame, // ist das Format gesetzt, sonst 0 const SwPageDesc* pAktPageDesc; // aktuell gesetzter PageDesc. USHORT nBkmkTabPos; // akt. Position in der Bookmark-Tabelle USHORT nCurScript; // actual scripttype rtl_TextEncoding eCurrentCharSet; #if defined(MAC) || defined(UNX) static const sal_Char sNewLine; // nur \012 oder \015 #else static const sal_Char __FAR_DATA sNewLine[]; // \015\012 #endif BOOL bFirstLine : 1; // wird die 1. Zeile ausgegeben ? BOOL bOutFmtAttr : 1; // TRUE: beim Schreiben eines Formates // existierte mindestens ein Attribut BOOL bRTFFlySyntax : 1; // gebe nur original RTFSyntax aus // (nur fuer die fliegenden Rahmen) BOOL bOutPageDesc: 1; // gebe einen PageDescriptor aus BOOL bOutPageDescTbl: 1; // gebe die PageDescriptor-Tabelle aus BOOL bOutTable : 1; // gebe eine Tabelle aus BOOL bTxtAttr : 1; // werden TextAttribute ausgegeben ? BOOL bWriteHelpFmt : 1; // schreibe Win-RTF-HelpFileFmt BOOL bOutStyleTab : 1; // gebe die StyleSheet-Tabelle aus BOOL bOutPageAttr : 1; // PageDescAttribut ausgeben? BOOL bAutoAttrSet : 1; // TRUE: pAttrSet ist harte Attributierung // FALSE: pAttrSet ist vom Format/Collection BOOL bOutOutlineOnly : 1; // TRUE: nur Gliederungs-Absaetze schreiben BOOL bOutListNumTxt : 1; // TRUE: der ListNumText wird ausgegeben BOOL bOutLeftHeadFoot : 1; // gebe vom PageDesc. den linkten // Header/Footer aus BOOL bOutSection : 1; // TRUE: Section PageDesc ausgeben BOOL bIgnoreNextPgBreak : 1; // TRUE: naechsten PageDesc/Break ignorieren BOOL bAssociated : 1; // use associated tokens // --- public Methoden ------------------------------------------------ SwRTFWriter( const String& rFilterName ); virtual ~SwRTFWriter(); virtual ULONG WriteStream(); void Out_SwDoc( SwPaM* ); // schreibe den makierten Bereich // gebe die evt. an der akt. Position stehenden FlyFrame aus. void OutFlyFrm(); void OutRTFFlyFrms( const SwFlyFrmFmt& ); // gebe alle an der Position stehenden Bookmarks aus void OutBookmarks( xub_StrLen nCntntPos ); // gebe die PageDesc-Daten im normalen RTF-Format aus void OutRTFPageDescription( const SwPageDesc&, BOOL , BOOL ); void OutRTFBorders( SvxBoxItem aBox ); void OutRTFBorder( const SvxBorderLine* aLine, const USHORT nSpace ); BOOL OutBreaks( const SfxItemSet& rSet ); void OutRedline( xub_StrLen nCntntPos ); // gebe die PageDescriptoren aus USHORT GetId( const Color& ) const; USHORT GetId( const SvxFontItem& ) const; USHORT GetId( const Font& ) const; USHORT GetId( const SwTxtFmtColl& ) const; USHORT GetId( const SwCharFmt& ) const; USHORT GetId( const SwNumRuleItem& rItem ) const; void OutPageDesc(); BOOL OutListNum( const SwTxtNode& rNd ); USHORT GetNumRuleId( const SwNumRule& rRule ); // fuer RTFSaveData SwPaM* GetEndPaM() { return pOrigPam; } void SetEndPaM( SwPaM* pPam ) { pOrigPam = pPam; } const SfxPoolItem& GetItem( USHORT nWhich ) const; const SfxItemSet* GetAttrSet() const { return pAttrSet; } void SetAttrSet( const SfxItemSet* p ) { pAttrSet = p; } const RTFEndPosLst* GetEndPosLst() const { return pCurEndPosLst; } void SetAssociatedFlag( BOOL b ) { bAssociated = b; } BOOL IsAssociatedFlag() const { return bAssociated; } void SetCurrScriptType( USHORT n ) { nCurScript = n; } USHORT GetCurrScriptType() const { return nCurScript; } short TrueFrameDirection(const SwFrmFmt &rFlyFmt) const; short GetCurrentPageDirection() const; }; // Struktur speichert die aktuellen Daten des Writers zwischen, um // einen anderen Dokument-Teil auszugeben, wie z.B. Header/Footer // Mit den beiden USHORTs im CTOR wird ein neuer PaM erzeugt und auf // die Position im Dokument gesetzt. // Im Destructor werden alle Daten wieder restauriert und der angelegte // Pam wieder geloescht. struct RTFSaveData { SwRTFWriter& rWrt; SwPaM* pOldPam, *pOldEnd; const SwFlyFrmFmt* pOldFlyFmt; const SwPageDesc* pOldPageDesc; const SfxItemSet* pOldAttrSet; // akt. Attribute vom Node BOOL bOldWriteAll : 1; BOOL bOldOutTable : 1; BOOL bOldOutPageAttr : 1; BOOL bOldAutoAttrSet : 1; BOOL bOldOutSection : 1; RTFSaveData( SwRTFWriter&, ULONG nStt, ULONG nEnd ); ~RTFSaveData(); }; // einige Funktions-Deklarationen Writer& OutRTF_AsByteString( Writer& rWrt, const String& rStr ); Writer& OutRTF_SwFmt( Writer& rWrt, const SwFmt& ); Writer& OutRTF_SwTblNode(Writer& , const SwTableNode&); Writer& OutRTF_SwSectionNode( Writer& , SwSectionNode & ); // Augabe von RTF-Bitmaps (steht im File "wrtpict.cxx") //struct SvxRTFPictureType; //class Bitmap; //USHORT WriteRTFPict( const SwPictureType&, Bitmap&, SvStream& ); // Ausagbe von Footer-/Headers Writer& OutRTF_SwFmtHeader( Writer& , const SfxPoolItem& ); Writer& OutRTF_SwFmtFooter( Writer& , const SfxPoolItem& ); // Kommentar und zusaetzlichen String ausgeben SvStream& OutComment( Writer& rWrt, const sal_Char* pStr ); // zusaetzlich das bOutFmtAttr-Flag manipulieren SvStream& OutComment( Writer& rWrt, const sal_Char* pStr, BOOL bSetFlag ); bool ExportAsInline(const SwFlyFrmFmt& rFlyFrmFmt); #endif // _WRTRTF_HXX <|endoftext|>
<commit_before>#include <iostream> #include <stdio.h> #include <stdio.h> #include <ctype.h> #include <cstring> #include <vector> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> using namespace std; bool conntest(string x){ int i = x.size() - 1; if(x == "&&" || x == ";" || x == "||"){ //cout << "a" << endl; return true; } else if(x.at(i) == ';' || x.at(i) == '&' || x.at(i) == '|') { //cout << "b" << endl; return true; } else{ return false; } } bool endswith(string x){ int i = x.size() - 1; if(x.at(i) == ';' || x.at(i) == '&' || x.at(i) == '|') { //cout << "b" << endl; return true; } else{ return false; } } int findend(string x){ for(int i = 0; i < x.size(); i++){ if(x.at(i) == '&' || x.at(i) == ';' || x.at(i) == '|') { return i; } } return -1; } int main(){ string input; cout << "$ "; getline(cin, input); char str[input.size()+1]; strcpy(str, input.c_str()); char* pch; bool sucs; char conn; vector<string> cmd; int cnt = 0; pch = strtok(str, " "); while(cnt < 100){ /*if(isexit(pch)){ return 0; }*/ if(pch == NULL || conntest(pch)){ if(pch != NULL && endswith(pch)){ string tmp = pch; int loc = findend(pch); if(loc > 0){ tmp = tmp.substr(0, loc); cmd.push_back(tmp); } } int pid = fork(); if(pid == 0){ char* argc[cmd.size() + 1]; for(int i = 0 ; i < cmd.size(); i++ ){ argc[i] = new char[cmd.at(i).size()]; strcpy(argc[i], cmd.at(i).c_str()); } argc[cmd.size()] = NULL; if(-1 == execvp(argc[0], argc)){ perror("There was an error in execvp"); } } else{ wait(NULL); return 0; } } else{ cnt++; if(pch != " ") cmd.push_back(pch); pch = strtok(NULL, " "); } } return 0; } <commit_msg>removed duplicate hw0.cpp<commit_after><|endoftext|>
<commit_before>#include <iostream> using namespace std; //============implete a positive int Queue.========== class intQueue{ private: int num[10]; int front; int rear; public: void Queue(int i); int deQueue(); intQueue(); }; intQueue::intQueue(void){ front=0; rear=0; } void intQueue::Queue(int i){ if(front==rear+1 || rear-10==front){ // full. }else{ rear = (rear + 1) % 10; num[rear]=i; } } int intQueue::deQueue(){ if(front==rear){ return -1; } front = (front + 1) % 10; return num[front]; } //============implete a positive int Queue.========== //============implete client list.========== class ClientList{ private: int count; //default 0 int Arr[10]; // store from 1 int Ser[10]; // store from 1 int All[10]; // store from 1 public: void Input(int Arr , int Ser , int All); int GetArr(int index); int GetSer(int index); int GetAll(int index); ClientList(); }; ClientList::ClientList(void){ count=0; } void ClientList::Input(int ArrIn , int SerIn , int AllIn){ count++; Arr[count] = ArrIn; Ser[count] = SerIn; All[count] = AllIn; } int ClientList::GetArr(int index){ if (count<index) { return -1; } return Arr[index]; } int ClientList::GetSer(int index){ if (count<index) { return -1; } return Ser[index]; } int ClientList::GetAll(int index){ if (count<index) { return -1; } return All[index]; } //============implete client list.========== //==========MyString======== int main() { int clients; cout << "Welcome , how many clients? >>"; cin >> clients; cout << "OK , let's starting input every client with space separated , Ex.:1 2 3\n"; ClientList ClientList; for (int i = 1; i <= clients; i++) { cout << "Please input No." << i << " Client's Arr,Ser,All: >>"; int Arr,Ser,All; cin >> Arr >> Ser >> All; ClientList.Input(Arr,Ser,All); } cout << ClientList.GetArr(2); cout << ClientList.GetSer(2); cout << ClientList.GetAll(2); return 0; } <commit_msg>Implete Store Answer function<commit_after>#include <iostream> using namespace std; //============implete a positive int Queue.========== class intQueue{ private: int num[10]; int front; int rear; public: void Queue(int i); int deQueue(); intQueue(); }; intQueue::intQueue(void){ front=0; rear=0; } void intQueue::Queue(int i){ if(front==rear+1 || rear-10==front){ // full. }else{ rear = (rear + 1) % 10; num[rear]=i; } } int intQueue::deQueue(){ if(front==rear){ return -1; } front = (front + 1) % 10; return num[front]; } //============implete a positive int Queue.========== //============implete client list.========== class ClientList{ private: int count; //default 0 int Arr[10]; // store from 1 int Ser[10]; // store from 1 int All[10]; // store from 1 int Served[10]; // store from 1 , store 1 or 0 int DepTime[10]; // store from 1 public: void Input(int Arr , int Ser , int All); void StoreAnswer(int index , int ServedIn , int DepTimeIn); int GetArr(int index); int GetSer(int index); int GetAll(int index); ClientList(); }; ClientList::ClientList(void){ count=0; } void ClientList::Input(int ArrIn , int SerIn , int AllIn){ count++; Arr[count] = ArrIn; Ser[count] = SerIn; All[count] = AllIn; } void ClientList::StoreAnswer(int index , int ServedIn , int DepTimeIn){ Served[count] = ServedIn; DepTime[count] = DepTimeIn; } int ClientList::GetArr(int index){ if (count<index) { return -1; } return Arr[index]; } int ClientList::GetSer(int index){ if (count<index) { return -1; } return Ser[index]; } int ClientList::GetAll(int index){ if (count<index) { return -1; } return All[index]; } //============implete client list.========== //==========MyString======== int main() { int clients; cout << "Welcome , how many clients? >>"; cin >> clients; cout << "OK , let's starting input every client with space separated , Ex.:1 2 3\n"; ClientList ClientList; for (int i = 1; i <= clients; i++) { cout << "Please input No." << i << " Client's Arr,Ser,All: >>"; int Arr,Ser,All; cin >> Arr >> Ser >> All; ClientList.Input(Arr,Ser,All); } cout << ClientList.GetArr(2); cout << ClientList.GetSer(2); cout << ClientList.GetAll(2); ClientList.StoreAnswer(1,0,2); return 0; } <|endoftext|>
<commit_before>#include "types.h" #include "amd64.h" #include "mmu.h" #include "cpu.hh" #include "kernel.hh" #include "bits.hh" #include "spinlock.h" #include "kalloc.h" #include "queue.h" #include "condvar.h" #include "proc.hh" #include "vm.hh" #include <stddef.h> extern pml4e_t kpml4[]; static pme_t* descend(pme_t *dir, const void *va, u64 flags, int create, int level) { pme_t entry; pme_t *next; retry: dir = &dir[PX(level, va)]; entry = *dir; if (entry & PTE_P) { next = (pme_t*) p2v(PTE_ADDR(entry)); } else { if (!create) return NULL; next = (pme_t*) kalloc(); if (!next) return NULL; memset(next, 0, PGSIZE); if (!cmpswap(dir, entry, v2p(next) | PTE_P | PTE_W | flags)) { kfree((void*) next); goto retry; } } return next; } // Return the address of the PTE in page table pgdir // that corresponds to linear address va. If create!=0, // create any required page table pages. pme_t * walkpgdir(pml4e_t *pml4, const void *va, int create) { pme_t *pdp; pme_t *pd; pme_t *pt; pdp = descend(pml4, va, PTE_U, create, 3); if (pdp == NULL) return NULL; pd = descend(pdp, va, PTE_U, create, 2); if (pd == NULL) return NULL; pt = descend(pd, va, PTE_U, create, 1); if (pt == NULL) return NULL; return &pt[PX(0,va)]; } void updatepages(pme_t *pml4, void *begin, void *end, int perm) { char *a, *last; pme_t *pte; a = (char*) PGROUNDDOWN(begin); last = (char*) PGROUNDDOWN(end); for (;;) { pte = walkpgdir(pml4, a, 1); if(pte != 0) { if (perm == 0) *pte = 0; else *pte = PTE_ADDR(*pte) | perm | PTE_P; } if (a == last) break; a += PGSIZE; } } // Map from 0 to 128Gbytes starting at KBASE. void initpg(void) { extern char end[]; void *va = (void*)KBASE; paddr pa = 0; while (va < (void*)(KBASE+(128ull<<30))) { pme_t *pdp = descend(kpml4, va, 0, 1, 3); pme_t *pd = descend(pdp, va, 0, 1, 2); pme_t *sp = &pd[PX(1,va)]; u64 flags = PTE_W | PTE_P | PTE_PS; // Set NX for non-code pages if (va >= (void*) end) flags |= PTE_NX; *sp = pa | flags; va = (char*)va + PGSIZE*512; pa += PGSIZE*512; } } // Set up kernel part of a page table. pml4e_t* setupkvm(void) { pml4e_t *pml4; int k; if((pml4 = (pml4e_t*)kalloc()) == 0) return 0; k = PX(3, KBASE); memset(&pml4[0], 0, 8*k); memmove(&pml4[k], &kpml4[k], 8*(512-k)); return pml4; } int setupkshared(pml4e_t *pml4, char *kshared) { for (u64 off = 0; off < KSHAREDSIZE; off+=4096) { pme_t *pte = walkpgdir(pml4, (void*)(KSHARED+off), 1); if (pte == NULL) panic("setupkshared: oops"); *pte = v2p(kshared+off) | PTE_P | PTE_U | PTE_W; } return 0; } // Switch h/w page table register to the kernel-only page table, // for when no process is running. void switchkvm(void) { lcr3(v2p(kpml4)); // switch to the kernel page table } // Switch TSS and h/w page table to correspond to process p. void switchuvm(struct proc *p) { u64 base = (u64) &mycpu()->ts; pushcli(); mycpu()->gdt[TSSSEG>>3] = (struct segdesc) SEGDESC(base, (sizeof(mycpu()->ts)-1), SEG_P|SEG_TSS64A); mycpu()->gdt[(TSSSEG>>3)+1] = (struct segdesc) SEGDESCHI(base); mycpu()->ts.rsp[0] = (u64) myproc()->kstack + KSTACKSIZE; mycpu()->ts.iomba = (u16)offsetof(struct taskstate, iopb); ltr(TSSSEG); if(p->vmap == 0 || p->vmap->pml4 == 0) panic("switchuvm: no vmap/pml4"); lcr3(v2p(p->vmap->pml4)); // switch to new address space popcli(); } static void freepm(pme_t *pm, int level) { int i; if (level != 0) { for (i = 0; i < 512; i++) { if (pm[i] & PTE_P) freepm((pme_t*) p2v(PTE_ADDR(pm[i])), level - 1); } } kfree(pm); } // Free a page table and all the physical memory pages // in the user part. void freevm(pml4e_t *pml4) { int k; int i; if(pml4 == 0) panic("freevm: no pgdir"); // Don't free kernel portion of the pml4 k = PX(3, KBASE); for (i = 0; i < k; i++) { if (pml4[i] & PTE_P) { freepm((pme_t*) p2v(PTE_ADDR(pml4[i])), 2); } } kfree(pml4); } // Set up CPU's kernel segment descriptors. // Run once at boot time on each CPU. void inittls(void) { struct cpu *c; // Initialize cpu-local storage. c = &cpus[cpunum()]; writegs(KDSEG); writemsr(MSR_GS_BASE, (u64)&c->cpu); c->cpu = c; c->proc = NULL; c->kmem = &kmems[cpunum()]; } atomic<u64> tlbflush_req; void tlbflush() { u64 myreq = tlbflush_req++; pushcli(); int myid = mycpu()->id; lcr3(rcr3()); popcli(); for (int i = 0; i < ncpu; i++) if (i != myid) lapic_tlbflush(i); for (int i = 0; i < ncpu; i++) if (i != myid) while (cpus[i].tlbflush_done < myreq) /* spin */ ; } <commit_msg>deadlock: if the caller of tlbflush is holding a spinlock, another CPU may have interrupts disabled waiting for that spinlock too, and will never acknowledge our tlb flush..<commit_after>#include "types.h" #include "amd64.h" #include "mmu.h" #include "cpu.hh" #include "kernel.hh" #include "bits.hh" #include "spinlock.h" #include "kalloc.h" #include "queue.h" #include "condvar.h" #include "proc.hh" #include "vm.hh" #include <stddef.h> extern pml4e_t kpml4[]; static pme_t* descend(pme_t *dir, const void *va, u64 flags, int create, int level) { pme_t entry; pme_t *next; retry: dir = &dir[PX(level, va)]; entry = *dir; if (entry & PTE_P) { next = (pme_t*) p2v(PTE_ADDR(entry)); } else { if (!create) return NULL; next = (pme_t*) kalloc(); if (!next) return NULL; memset(next, 0, PGSIZE); if (!cmpswap(dir, entry, v2p(next) | PTE_P | PTE_W | flags)) { kfree((void*) next); goto retry; } } return next; } // Return the address of the PTE in page table pgdir // that corresponds to linear address va. If create!=0, // create any required page table pages. pme_t * walkpgdir(pml4e_t *pml4, const void *va, int create) { pme_t *pdp; pme_t *pd; pme_t *pt; pdp = descend(pml4, va, PTE_U, create, 3); if (pdp == NULL) return NULL; pd = descend(pdp, va, PTE_U, create, 2); if (pd == NULL) return NULL; pt = descend(pd, va, PTE_U, create, 1); if (pt == NULL) return NULL; return &pt[PX(0,va)]; } void updatepages(pme_t *pml4, void *begin, void *end, int perm) { char *a, *last; pme_t *pte; a = (char*) PGROUNDDOWN(begin); last = (char*) PGROUNDDOWN(end); for (;;) { pte = walkpgdir(pml4, a, 1); if(pte != 0) { if (perm == 0) *pte = 0; else *pte = PTE_ADDR(*pte) | perm | PTE_P; } if (a == last) break; a += PGSIZE; } } // Map from 0 to 128Gbytes starting at KBASE. void initpg(void) { extern char end[]; void *va = (void*)KBASE; paddr pa = 0; while (va < (void*)(KBASE+(128ull<<30))) { pme_t *pdp = descend(kpml4, va, 0, 1, 3); pme_t *pd = descend(pdp, va, 0, 1, 2); pme_t *sp = &pd[PX(1,va)]; u64 flags = PTE_W | PTE_P | PTE_PS; // Set NX for non-code pages if (va >= (void*) end) flags |= PTE_NX; *sp = pa | flags; va = (char*)va + PGSIZE*512; pa += PGSIZE*512; } } // Set up kernel part of a page table. pml4e_t* setupkvm(void) { pml4e_t *pml4; int k; if((pml4 = (pml4e_t*)kalloc()) == 0) return 0; k = PX(3, KBASE); memset(&pml4[0], 0, 8*k); memmove(&pml4[k], &kpml4[k], 8*(512-k)); return pml4; } int setupkshared(pml4e_t *pml4, char *kshared) { for (u64 off = 0; off < KSHAREDSIZE; off+=4096) { pme_t *pte = walkpgdir(pml4, (void*)(KSHARED+off), 1); if (pte == NULL) panic("setupkshared: oops"); *pte = v2p(kshared+off) | PTE_P | PTE_U | PTE_W; } return 0; } // Switch h/w page table register to the kernel-only page table, // for when no process is running. void switchkvm(void) { lcr3(v2p(kpml4)); // switch to the kernel page table } // Switch TSS and h/w page table to correspond to process p. void switchuvm(struct proc *p) { u64 base = (u64) &mycpu()->ts; pushcli(); mycpu()->gdt[TSSSEG>>3] = (struct segdesc) SEGDESC(base, (sizeof(mycpu()->ts)-1), SEG_P|SEG_TSS64A); mycpu()->gdt[(TSSSEG>>3)+1] = (struct segdesc) SEGDESCHI(base); mycpu()->ts.rsp[0] = (u64) myproc()->kstack + KSTACKSIZE; mycpu()->ts.iomba = (u16)offsetof(struct taskstate, iopb); ltr(TSSSEG); if(p->vmap == 0 || p->vmap->pml4 == 0) panic("switchuvm: no vmap/pml4"); lcr3(v2p(p->vmap->pml4)); // switch to new address space popcli(); } static void freepm(pme_t *pm, int level) { int i; if (level != 0) { for (i = 0; i < 512; i++) { if (pm[i] & PTE_P) freepm((pme_t*) p2v(PTE_ADDR(pm[i])), level - 1); } } kfree(pm); } // Free a page table and all the physical memory pages // in the user part. void freevm(pml4e_t *pml4) { int k; int i; if(pml4 == 0) panic("freevm: no pgdir"); // Don't free kernel portion of the pml4 k = PX(3, KBASE); for (i = 0; i < k; i++) { if (pml4[i] & PTE_P) { freepm((pme_t*) p2v(PTE_ADDR(pml4[i])), 2); } } kfree(pml4); } // Set up CPU's kernel segment descriptors. // Run once at boot time on each CPU. void inittls(void) { struct cpu *c; // Initialize cpu-local storage. c = &cpus[cpunum()]; writegs(KDSEG); writemsr(MSR_GS_BASE, (u64)&c->cpu); c->cpu = c; c->proc = NULL; c->kmem = &kmems[cpunum()]; } atomic<u64> tlbflush_req; void tlbflush() { u64 myreq = tlbflush_req++; pushcli(); // the caller may not hold any spinlock, because other CPUs might // be spinning waiting for that spinlock, with interrupts disabled, // so we will deadlock waiting for their TLB flush.. assert(mycpu()->ncli == 1); int myid = mycpu()->id; lcr3(rcr3()); popcli(); for (int i = 0; i < ncpu; i++) if (i != myid) lapic_tlbflush(i); for (int i = 0; i < ncpu; i++) if (i != myid) while (cpus[i].tlbflush_done < myreq) /* spin */ ; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: textsh2.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: oj $ $Date: 2002-08-21 12:23:40 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PRECOMPILED #include "ui_pch.hxx" #endif #pragma hdrstop #if STLPORT_VERSION>=321 #include <cstdarg> #endif #include <svtools/svmedit.hxx> #ifndef _SBASLTID_HRC //autogen #include <offmgr/sbasltid.hrc> #endif #ifndef _SFXENUMITEM_HXX //autogen #include <svtools/eitem.hxx> #endif #ifndef _SFX_WHITER_HXX //autogen #include <svtools/whiter.hxx> #endif #ifndef _SFXEVENT_HXX //autogen #include <sfx2/event.hxx> #endif #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #ifndef _SFXVIEWFRM_HXX //autogen #include <sfx2/viewfrm.hxx> #endif #ifndef _MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _SFXSTRITEM_HXX //autogen #include <svtools/stritem.hxx> #endif #ifndef _OFF_APP_HXX //autogen #include <offmgr/app.hxx> #endif #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #ifndef _SFXREQUEST_HXX #include <sfx2/request.hxx> #endif #ifndef _COM_SUN_STAR_SDB_COMMANDTYPE_HPP_ #include <com/sun/star/sdb/CommandType.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XDATASOURCE_HPP_ #include <com/sun/star/sdbc/XDataSource.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XTablesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XColumnsSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDB_XQUERIESSUPPLIER_HPP_ #include <com/sun/star/sdb/XQueriesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDB_XDATABASEACCESS_HPP_ #include <com/sun/star/sdb/XDatabaseAccess.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_ #include <com/sun/star/container/XChild.hpp> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _COM_SUN_STAR_SDBC_XROWSET_HPP_ #include <com/sun/star/sdbc/XRowSet.hpp> #endif #ifndef _SFXFRAME_HXX #include <sfx2/frame.hxx> #endif #ifndef _FLDMGR_HXX #include <fldmgr.hxx> #endif #ifndef _FLDBAS_HXX #include <fldbas.hxx> #endif #include "dbmgr.hxx" #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #ifndef _SVX_DATACCESSDESCRIPTOR_HXX_ #include <svx/dataaccessdescriptor.hxx> #endif #include <memory> #include "view.hxx" #include "wrtsh.hxx" #include "swtypes.hxx" #include "cmdid.h" #include "swevent.hxx" #include "shells.hrc" #include "textsh.hxx" #include "dbinsdlg.hxx" using namespace rtl; using namespace svx; using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::container; using namespace com::sun::star::lang; using namespace com::sun::star::sdb; using namespace com::sun::star::sdbc; using namespace com::sun::star::sdbcx; using namespace com::sun::star::beans; #define C2U(cChar) ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(cChar)) #define C2S(cChar) UniString::CreateFromAscii(cChar) #define DB_DD_DELIM 0x0b struct DBTextStruct_Impl { SwDBData aDBData; Sequence<Any> aSelection; Reference<XResultSet> xCursor; Reference<XConnection> xConnection; }; inline void AddSelList( List& rLst, long nRow ) { rLst.Insert( (void*)nRow , LIST_APPEND ); } void SwTextShell::ExecDB(SfxRequest &rReq) { const SfxItemSet *pArgs = rReq.GetArgs(); SwNewDBMgr* pNewDBMgr = GetShell().GetNewDBMgr(); USHORT nSlot = rReq.GetSlot(); OUString sSourceArg, sCommandArg; sal_Int32 nCommandTypeArg = 0; const SfxPoolItem* pSourceItem = 0; const SfxPoolItem* pCursorItem = 0; const SfxPoolItem* pConnectionItem = 0; const SfxPoolItem* pCommandItem = 0; const SfxPoolItem* pCommandTypeItem = 0; const SfxPoolItem* pSelectionItem = 0; // first get the selection of rows to be inserted pArgs->GetItemState(FN_DB_DATA_SELECTION_ANY, FALSE, &pSelectionItem); Sequence<Any> aSelection; if(pSelectionItem) ((SfxUsrAnyItem*)pSelectionItem)->GetValue() >>= aSelection; // get the data source name pArgs->GetItemState(FN_DB_DATA_SOURCE_ANY, FALSE, &pSourceItem); if(pSourceItem) ((const SfxUsrAnyItem*)pSourceItem)->GetValue() >>= sSourceArg; // get the command pArgs->GetItemState(FN_DB_DATA_COMMAND_ANY, FALSE, &pCommandItem); if(pCommandItem) ((const SfxUsrAnyItem*)pCommandItem)->GetValue() >>= sCommandArg; // get the command type pArgs->GetItemState(FN_DB_DATA_COMMAND_TYPE_ANY, FALSE, &pCommandTypeItem); if(pCommandTypeItem) ((const SfxUsrAnyItem*)pCommandTypeItem)->GetValue() >>= nCommandTypeArg; Reference<XConnection> xConnection; pArgs->GetItemState(FN_DB_CONNECTION_ANY, FALSE, &pConnectionItem); if ( pConnectionItem ) ((const SfxUsrAnyItem*)pConnectionItem)->GetValue() >>= xConnection; // may be we even get no connection if ( !xConnection.is() ) { Reference<XDataSource> xSource; xConnection = pNewDBMgr->GetConnection(sSourceArg, xSource); } if(!xConnection.is()) return ; // get the cursor, we use to travel, may be NULL Reference<XResultSet> xCursor; pArgs->GetItemState(FN_DB_DATA_CURSOR_ANY, FALSE, &pCursorItem); if ( pCursorItem ) ((const SfxUsrAnyItem*)pCursorItem)->GetValue() >>= xCursor; switch (nSlot) { case FN_QRY_INSERT: { if(pSourceItem && pCommandItem && pCommandTypeItem) { DBTextStruct_Impl* pNew = new DBTextStruct_Impl; pNew->aDBData.sDataSource = sSourceArg; pNew->aDBData.sCommand = sCommandArg; pNew->aDBData.nCommandType = nCommandTypeArg; pNew->aSelection = aSelection; //if the cursor is NULL, it must be created inside InsertDBTextHdl // because it called via a PostUserEvent pNew->xCursor = xCursor; pNew->xConnection = xConnection; Application::PostUserEvent( STATIC_LINK( this, SwBaseShell, InsertDBTextHdl ), pNew ); // the pNew will be removed in InsertDBTextHdl !! } } break; case FN_QRY_MERGE_FIELD: { // we don't get any cursor, so we must create our own BOOL bDisposeResultSet = FALSE; if ( !xCursor.is() ) { xCursor = SwNewDBMgr::createCursor(sSourceArg,sCommandArg,nCommandTypeArg,xConnection); bDisposeResultSet = xCursor.is(); } ODataAccessDescriptor aDescriptor; aDescriptor[daDataSource] <<= sSourceArg; aDescriptor[daCommand] <<= sCommandArg; aDescriptor[daCursor] <<= xCursor; aDescriptor[daSelection] <<= aSelection; aDescriptor[daCommandType] <<= nCommandTypeArg; pNewDBMgr->MergeNew(DBMGR_MERGE, *GetShellPtr(), aDescriptor); if ( bDisposeResultSet ) ::comphelper::disposeComponent(xCursor); } break; case FN_QRY_INSERT_FIELD: { const SfxPoolItem* pColumnItem = 0; const SfxPoolItem* pColumnNameItem = 0; pArgs->GetItemState(FN_DB_COLUMN_ANY, FALSE, &pColumnItem); pArgs->GetItemState(FN_DB_DATA_COLUMN_NAME_ANY, FALSE, &pColumnNameItem); OUString sColumnName; if(pColumnNameItem) ((SfxUsrAnyItem*)pColumnNameItem)->GetValue() >>= sColumnName; String sDBName = sSourceArg; sDBName += DB_DELIM; sDBName += (String)sCommandArg; sDBName += DB_DELIM; sDBName += String::CreateFromInt32(nCommandTypeArg); sDBName += DB_DELIM; sDBName += (String)sColumnName; SwFldMgr aFldMgr(GetShellPtr()); SwInsertFld_Data aData(TYP_DBFLD, 0, sDBName, aEmptyStr, 0, FALSE, TRUE); if(pConnectionItem) aData.aDBConnection = ((SfxUsrAnyItem*)pConnectionItem)->GetValue(); if(pColumnItem) aData.aDBColumn = ((SfxUsrAnyItem*)pColumnItem)->GetValue(); aFldMgr.InsertFld(aData); } break; default: ASSERT(!this, falscher Dispatcher); return; } } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ IMPL_STATIC_LINK( SwBaseShell, InsertDBTextHdl, DBTextStruct_Impl*, pDBStruct ) { if( pDBStruct ) { sal_Bool bDispose = sal_False; Reference< sdbc::XConnection> xConnection = pDBStruct->xConnection; Reference<XDataSource> xSource = SwNewDBMgr::getDataSourceAsParent(xConnection,pDBStruct->aDBData.sDataSource); if ( !xConnection.is() ) { xConnection = SwNewDBMgr::GetConnection(pDBStruct->aDBData.sDataSource, xSource); bDispose = sal_True; } Reference< XColumnsSupplier> xColSupp; if(xConnection.is()) xColSupp = SwNewDBMgr::GetColumnSupplier(xConnection, pDBStruct->aDBData.sCommand, pDBStruct->aDBData.nCommandType == CommandType::QUERY ? SW_DB_SELECT_QUERY : SW_DB_SELECT_TABLE); if( xColSupp.is() ) { SwDBData aDBData = pDBStruct->aDBData; ::std::auto_ptr<SwInsertDBColAutoPilot> pDlg( new SwInsertDBColAutoPilot( pThis->GetView(), xSource, xColSupp, aDBData ) ); if( RET_OK == pDlg->Execute() ) { Reference <XResultSet> xResSet = pDBStruct->xCursor; pDlg->DataToDoc( pDBStruct->aSelection, xSource, xConnection, xResSet); } } if ( bDispose ) ::comphelper::disposeComponent(xConnection); } delete pDBStruct; return 0; } <commit_msg>INTEGRATION: CWS os8 (1.14.142); FILE MERGED 2003/04/03 07:15:09 os 1.14.142.1: #108583# precompiled headers removed<commit_after>/************************************************************************* * * $RCSfile: textsh2.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: vg $ $Date: 2003-04-17 15:44:33 $ * * 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 #if STLPORT_VERSION>=321 #include <cstdarg> #endif #include <svtools/svmedit.hxx> #ifndef _SBASLTID_HRC //autogen #include <offmgr/sbasltid.hrc> #endif #ifndef _SFXENUMITEM_HXX //autogen #include <svtools/eitem.hxx> #endif #ifndef _SFX_WHITER_HXX //autogen #include <svtools/whiter.hxx> #endif #ifndef _SFXEVENT_HXX //autogen #include <sfx2/event.hxx> #endif #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #ifndef _SFXVIEWFRM_HXX //autogen #include <sfx2/viewfrm.hxx> #endif #ifndef _MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _SFXSTRITEM_HXX //autogen #include <svtools/stritem.hxx> #endif #ifndef _OFF_APP_HXX //autogen #include <offmgr/app.hxx> #endif #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #ifndef _SFXREQUEST_HXX #include <sfx2/request.hxx> #endif #ifndef _COM_SUN_STAR_SDB_COMMANDTYPE_HPP_ #include <com/sun/star/sdb/CommandType.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XDATASOURCE_HPP_ #include <com/sun/star/sdbc/XDataSource.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XTablesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XColumnsSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDB_XQUERIESSUPPLIER_HPP_ #include <com/sun/star/sdb/XQueriesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDB_XDATABASEACCESS_HPP_ #include <com/sun/star/sdb/XDatabaseAccess.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_ #include <com/sun/star/container/XChild.hpp> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _COM_SUN_STAR_SDBC_XROWSET_HPP_ #include <com/sun/star/sdbc/XRowSet.hpp> #endif #ifndef _SFXFRAME_HXX #include <sfx2/frame.hxx> #endif #ifndef _FLDMGR_HXX #include <fldmgr.hxx> #endif #ifndef _FLDBAS_HXX #include <fldbas.hxx> #endif #include "dbmgr.hxx" #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #ifndef _SVX_DATACCESSDESCRIPTOR_HXX_ #include <svx/dataaccessdescriptor.hxx> #endif #include <memory> #include "view.hxx" #include "wrtsh.hxx" #include "swtypes.hxx" #include "cmdid.h" #include "swevent.hxx" #include "shells.hrc" #include "textsh.hxx" #include "dbinsdlg.hxx" using namespace rtl; using namespace svx; using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::container; using namespace com::sun::star::lang; using namespace com::sun::star::sdb; using namespace com::sun::star::sdbc; using namespace com::sun::star::sdbcx; using namespace com::sun::star::beans; #define C2U(cChar) ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(cChar)) #define C2S(cChar) UniString::CreateFromAscii(cChar) #define DB_DD_DELIM 0x0b struct DBTextStruct_Impl { SwDBData aDBData; Sequence<Any> aSelection; Reference<XResultSet> xCursor; Reference<XConnection> xConnection; }; inline void AddSelList( List& rLst, long nRow ) { rLst.Insert( (void*)nRow , LIST_APPEND ); } void SwTextShell::ExecDB(SfxRequest &rReq) { const SfxItemSet *pArgs = rReq.GetArgs(); SwNewDBMgr* pNewDBMgr = GetShell().GetNewDBMgr(); USHORT nSlot = rReq.GetSlot(); OUString sSourceArg, sCommandArg; sal_Int32 nCommandTypeArg = 0; const SfxPoolItem* pSourceItem = 0; const SfxPoolItem* pCursorItem = 0; const SfxPoolItem* pConnectionItem = 0; const SfxPoolItem* pCommandItem = 0; const SfxPoolItem* pCommandTypeItem = 0; const SfxPoolItem* pSelectionItem = 0; // first get the selection of rows to be inserted pArgs->GetItemState(FN_DB_DATA_SELECTION_ANY, FALSE, &pSelectionItem); Sequence<Any> aSelection; if(pSelectionItem) ((SfxUsrAnyItem*)pSelectionItem)->GetValue() >>= aSelection; // get the data source name pArgs->GetItemState(FN_DB_DATA_SOURCE_ANY, FALSE, &pSourceItem); if(pSourceItem) ((const SfxUsrAnyItem*)pSourceItem)->GetValue() >>= sSourceArg; // get the command pArgs->GetItemState(FN_DB_DATA_COMMAND_ANY, FALSE, &pCommandItem); if(pCommandItem) ((const SfxUsrAnyItem*)pCommandItem)->GetValue() >>= sCommandArg; // get the command type pArgs->GetItemState(FN_DB_DATA_COMMAND_TYPE_ANY, FALSE, &pCommandTypeItem); if(pCommandTypeItem) ((const SfxUsrAnyItem*)pCommandTypeItem)->GetValue() >>= nCommandTypeArg; Reference<XConnection> xConnection; pArgs->GetItemState(FN_DB_CONNECTION_ANY, FALSE, &pConnectionItem); if ( pConnectionItem ) ((const SfxUsrAnyItem*)pConnectionItem)->GetValue() >>= xConnection; // may be we even get no connection if ( !xConnection.is() ) { Reference<XDataSource> xSource; xConnection = pNewDBMgr->GetConnection(sSourceArg, xSource); } if(!xConnection.is()) return ; // get the cursor, we use to travel, may be NULL Reference<XResultSet> xCursor; pArgs->GetItemState(FN_DB_DATA_CURSOR_ANY, FALSE, &pCursorItem); if ( pCursorItem ) ((const SfxUsrAnyItem*)pCursorItem)->GetValue() >>= xCursor; switch (nSlot) { case FN_QRY_INSERT: { if(pSourceItem && pCommandItem && pCommandTypeItem) { DBTextStruct_Impl* pNew = new DBTextStruct_Impl; pNew->aDBData.sDataSource = sSourceArg; pNew->aDBData.sCommand = sCommandArg; pNew->aDBData.nCommandType = nCommandTypeArg; pNew->aSelection = aSelection; //if the cursor is NULL, it must be created inside InsertDBTextHdl // because it called via a PostUserEvent pNew->xCursor = xCursor; pNew->xConnection = xConnection; Application::PostUserEvent( STATIC_LINK( this, SwBaseShell, InsertDBTextHdl ), pNew ); // the pNew will be removed in InsertDBTextHdl !! } } break; case FN_QRY_MERGE_FIELD: { // we don't get any cursor, so we must create our own BOOL bDisposeResultSet = FALSE; if ( !xCursor.is() ) { xCursor = SwNewDBMgr::createCursor(sSourceArg,sCommandArg,nCommandTypeArg,xConnection); bDisposeResultSet = xCursor.is(); } ODataAccessDescriptor aDescriptor; aDescriptor[daDataSource] <<= sSourceArg; aDescriptor[daCommand] <<= sCommandArg; aDescriptor[daCursor] <<= xCursor; aDescriptor[daSelection] <<= aSelection; aDescriptor[daCommandType] <<= nCommandTypeArg; pNewDBMgr->MergeNew(DBMGR_MERGE, *GetShellPtr(), aDescriptor); if ( bDisposeResultSet ) ::comphelper::disposeComponent(xCursor); } break; case FN_QRY_INSERT_FIELD: { const SfxPoolItem* pColumnItem = 0; const SfxPoolItem* pColumnNameItem = 0; pArgs->GetItemState(FN_DB_COLUMN_ANY, FALSE, &pColumnItem); pArgs->GetItemState(FN_DB_DATA_COLUMN_NAME_ANY, FALSE, &pColumnNameItem); OUString sColumnName; if(pColumnNameItem) ((SfxUsrAnyItem*)pColumnNameItem)->GetValue() >>= sColumnName; String sDBName = sSourceArg; sDBName += DB_DELIM; sDBName += (String)sCommandArg; sDBName += DB_DELIM; sDBName += String::CreateFromInt32(nCommandTypeArg); sDBName += DB_DELIM; sDBName += (String)sColumnName; SwFldMgr aFldMgr(GetShellPtr()); SwInsertFld_Data aData(TYP_DBFLD, 0, sDBName, aEmptyStr, 0, FALSE, TRUE); if(pConnectionItem) aData.aDBConnection = ((SfxUsrAnyItem*)pConnectionItem)->GetValue(); if(pColumnItem) aData.aDBColumn = ((SfxUsrAnyItem*)pColumnItem)->GetValue(); aFldMgr.InsertFld(aData); } break; default: ASSERT(!this, falscher Dispatcher); return; } } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ IMPL_STATIC_LINK( SwBaseShell, InsertDBTextHdl, DBTextStruct_Impl*, pDBStruct ) { if( pDBStruct ) { sal_Bool bDispose = sal_False; Reference< sdbc::XConnection> xConnection = pDBStruct->xConnection; Reference<XDataSource> xSource = SwNewDBMgr::getDataSourceAsParent(xConnection,pDBStruct->aDBData.sDataSource); if ( !xConnection.is() ) { xConnection = SwNewDBMgr::GetConnection(pDBStruct->aDBData.sDataSource, xSource); bDispose = sal_True; } Reference< XColumnsSupplier> xColSupp; if(xConnection.is()) xColSupp = SwNewDBMgr::GetColumnSupplier(xConnection, pDBStruct->aDBData.sCommand, pDBStruct->aDBData.nCommandType == CommandType::QUERY ? SW_DB_SELECT_QUERY : SW_DB_SELECT_TABLE); if( xColSupp.is() ) { SwDBData aDBData = pDBStruct->aDBData; ::std::auto_ptr<SwInsertDBColAutoPilot> pDlg( new SwInsertDBColAutoPilot( pThis->GetView(), xSource, xColSupp, aDBData ) ); if( RET_OK == pDlg->Execute() ) { Reference <XResultSet> xResSet = pDBStruct->xCursor; pDlg->DataToDoc( pDBStruct->aSelection, xSource, xConnection, xResSet); } } if ( bDispose ) ::comphelper::disposeComponent(xConnection); } delete pDBStruct; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: uivwimp.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: jp $ $Date: 2001-04-30 15:59:56 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PRECOMPILED #include "ui_pch.hxx" #endif #pragma hdrstop #include <cmdid.h> #include "globals.hrc" #ifndef _COM_SUN_STAR_SCANNER_XSCANNERMANAGER_HPP_ #include <com/sun/star/scanner/XScannerManager.hpp> #endif #ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDNOTIFIER_HPP_ #include <com/sun/star/datatransfer/clipboard/XClipboardNotifier.hpp> #endif #ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARD_HPP_ #include <com/sun/star/datatransfer/clipboard/XClipboard.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _SV_WRKWIN_HXX #include <vcl/wrkwin.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef _SFXVIEWFRM_HXX #include <sfx2/viewfrm.hxx> #endif #ifndef _SFX_BINDINGS_HXX #include <sfx2/bindings.hxx> #endif #ifndef _UIVWIMP_HXX #include <uivwimp.hxx> #endif #ifndef _SWWVIEW_HXX //autogen #include <wview.hxx> #endif #ifndef _UNOTXVW_HXX #include <unotxvw.hxx> #endif #ifndef _UNODISPATCH_HXX #include <unodispatch.hxx> #endif #ifndef _SWMODULE_HXX #include <swmodule.hxx> #endif #ifndef _SWDTFLVR_HXX #include <swdtflvr.hxx> #endif #include <view.hrc> using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::scanner; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::datatransfer::clipboard; /* -----------------02.06.98 15:31------------------- * * --------------------------------------------------*/ SwView_Impl::SwView_Impl(SwView* pShell) : pView(pShell), pxXTextView(new uno::Reference<view::XSelectionSupplier>), eShellMode(SEL_TEXT) { *pxXTextView = new SwXTextView(pView); xDisProvInterceptor = new SwXDispatchProviderInterceptor(*pView); } /*-----------------13.12.97 09:51------------------- --------------------------------------------------*/ SwView_Impl::~SwView_Impl() { view::XSelectionSupplier* pTextView = pxXTextView->get(); ((SwXTextView*)pTextView)->Invalidate(); delete pxXTextView; if( xScanEvtLstnr.is() ) pScanEvtLstnr->ViewDestroyed(); if( xClipEvtLstnr.is() ) { pClipEvtLstnr->AddRemoveListener( FALSE ); pClipEvtLstnr->ViewDestroyed(); } } /*-----------------13.12.97 09:54------------------- --------------------------------------------------*/ void SwView_Impl::SetShellMode(ShellModes eSet) { eShellMode = eSet; } /*-----------------13.12.97 09:59------------------- --------------------------------------------------*/ view::XSelectionSupplier* SwView_Impl::GetUNOObject() { return pxXTextView->get(); } /* -----------------02.06.98 15:29------------------- * * --------------------------------------------------*/ SwXTextView* SwView_Impl::GetUNOObject_Impl() { view::XSelectionSupplier* pTextView = pxXTextView->get(); return ((SwXTextView*)pTextView); } /* -----------------------------29.05.00 09:04-------------------------------- ---------------------------------------------------------------------------*/ void SwView_Impl::ExcuteScan(USHORT nSlot) { switch(nSlot) { case SID_TWAIN_SELECT: { BOOL bDone = FALSE; Reference< XScannerManager > xScanMgr = SW_MOD()->GetScannerManager(); if( xScanMgr.is() ) { //JP 26.06.00: the appwindow doen't exist // Application::GetAppWindow()->EnableInput( FALSE ); try { const Sequence< ScannerContext > aContexts( xScanMgr->getAvailableScanners() ); if( aContexts.getLength() ) { ScannerContext aContext( aContexts.getConstArray()[ 0 ] ); bDone = xScanMgr->configureScanner( aContext ); } } catch(...) { } //JP 26.06.00: the appwindow doen't exist // Application::GetAppWindow()->EnableInput( TRUE ); } if( !bDone ) InfoBox( 0, SW_RES(MSG_SCAN_NOSOURCE) ).Execute(); } break; case SID_TWAIN_TRANSFER: { BOOL bDone = FALSE; Reference< XScannerManager > xScanMgr = SW_MOD()->GetScannerManager(); if( xScanMgr.is() ) { SwScannerEventListener& rListener = GetScannerEventListener(); //JP 26.06.00: the appwindow doen't exist // Application::GetAppWindow()->EnableInput( FALSE ); try { const Sequence< scanner::ScannerContext >aContexts( xScanMgr->getAvailableScanners() ); if( aContexts.getLength() ) { Reference< XEventListener > xLstner = &rListener; xScanMgr->startScan( aContexts.getConstArray()[ 0 ], xLstner ); bDone = TRUE; } } catch(...) { } } if( !bDone ) { //JP 26.06.00: the appwindow doen't exist // Application::GetAppWindow()->EnableInput( TRUE ); InfoBox( 0, SW_RES(MSG_SCAN_NOSOURCE) ).Execute(); } else { SfxBindings& rBind = pView->GetViewFrame()->GetBindings(); rBind.Invalidate( SID_TWAIN_SELECT ); rBind.Invalidate( SID_TWAIN_TRANSFER ); } } break; } } /* -----------------------------29.05.00 08:26-------------------------------- ---------------------------------------------------------------------------*/ SwScannerEventListener& SwView_Impl::GetScannerEventListener() { if(!xScanEvtLstnr.is()) xScanEvtLstnr = pScanEvtLstnr = new SwScannerEventListener(*pView); return *pScanEvtLstnr; } void SwView_Impl::AddClipboardListener() { if(!xClipEvtLstnr.is()) { xClipEvtLstnr = pClipEvtLstnr = new SwClipboardChangeListener( *pView ); pClipEvtLstnr->AddRemoveListener( TRUE ); } } // ------------------------- SwScannerEventListener --------------------- SwScannerEventListener::~SwScannerEventListener() { } void SAL_CALL SwScannerEventListener::disposing( const EventObject& rEventObject ) { if( pView ) pView->ScannerEventHdl( rEventObject ); } // ------------------------- SwClipboardChangeListener --------------------- SwClipboardChangeListener::~SwClipboardChangeListener() { } void SAL_CALL SwClipboardChangeListener::disposing( const EventObject& rEventObject ) { } void SAL_CALL SwClipboardChangeListener::changedContents( const CLIP_NMSPC::ClipboardEvent& rEventObject ) { if( pView ) { { const ::vos::OGuard aGuard( Application::GetSolarMutex() ); TransferableDataHelper aDataHelper( rEventObject.Contents ); SwWrtShell& rSh = pView->GetWrtShell(); pView->nLastPasteDestination = SwTransferable::GetSotDestination( rSh ); pView->bPasteState = aDataHelper.GetTransferable().is() && SwTransferable::IsPaste( rSh, aDataHelper ); pView->bPasteSpecialState = aDataHelper.GetTransferable().is() && SwTransferable::IsPasteSpecial( rSh, aDataHelper ); } SfxBindings& rBind = pView->GetViewFrame()->GetBindings(); rBind.Invalidate( SID_PASTE ); rBind.Invalidate( FN_PASTESPECIAL ); } } void SwClipboardChangeListener::AddRemoveListener( BOOL bAdd ) { try { do { Reference< XMultiServiceFactory > xFact( ::comphelper::getProcessServiceFactory() ); if( !xFact.is() ) break; Reference< XClipboard > xClipboard( xFact->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.datatransfer.clipboard.SystemClipboard" )), UNO_QUERY ); if( !xClipboard.is() ) break; Reference< XClipboardNotifier > xClpbrdNtfr( xClipboard, UNO_QUERY ); if( xClpbrdNtfr.is() ) { Reference< XClipboardListener > xClipEvtLstnr( this ); if( bAdd ) xClpbrdNtfr->addClipboardListener( xClipEvtLstnr ); else xClpbrdNtfr->removeClipboardListener( xClipEvtLstnr ); } } while ( FALSE ); } catch( const ::com::sun::star::uno::Exception& ) { } } /*------------------------------------------------------------------------ $Log: not supported by cvs2svn $ Revision 1.2 2000/11/07 14:38:25 os Dispatch interface for database component Revision 1.1.1.1 2000/09/18 17:14:49 hr initial import Revision 1.14 2000/09/18 16:06:11 willem.vandorp OpenOffice header added. Revision 1.13 2000/09/07 15:59:32 os change: SFX_DISPATCHER/SFX_BINDINGS removed Revision 1.12 2000/06/26 10:44:13 jp must change: GetAppWindow->GetDefaultDevice Revision 1.11 2000/05/29 08:03:23 os new scanner interface Revision 1.10 2000/05/09 14:43:13 os BASIC interface partially removed Revision 1.9 2000/03/23 07:50:24 os UNO III Revision 1.8 1999/01/27 08:58:26 OS #56371# TF_ONE51 Rev 1.7 27 Jan 1999 09:58:26 OS #56371# TF_ONE51 Rev 1.6 30 Sep 1998 11:37:50 OS #52654# ueberfluessigen Aufruf entfernt Rev 1.5 02 Jun 1998 15:51:16 OS TF_STARONE raus; Ctor nicht mehr inline Rev 1.4 03 Apr 1998 14:38:28 OS UnoObject fuer die View reaktiviert Rev 1.3 04 Feb 1998 17:28:44 OS Starone raus Rev 1.2 29 Jan 1998 09:21:06 OS TF_STARONE Rev 1.1 19 Jan 1998 14:59:14 OS UNO-Aenderungen Rev 1.0 16 Dec 1997 11:58:48 OS Impl-Pointer fuer UNO ------------------------------------------------------------------------*/ <commit_msg>AddRemoveListener: get the XClipboard from the Window - this works also in the WebTop<commit_after>/************************************************************************* * * $RCSfile: uivwimp.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: jp $ $Date: 2001-07-04 18:18:43 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PRECOMPILED #include "ui_pch.hxx" #endif #pragma hdrstop #include <cmdid.h> #include "globals.hrc" #ifndef _COM_SUN_STAR_SCANNER_XSCANNERMANAGER_HPP_ #include <com/sun/star/scanner/XScannerManager.hpp> #endif #ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDNOTIFIER_HPP_ #include <com/sun/star/datatransfer/clipboard/XClipboardNotifier.hpp> #endif #ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARD_HPP_ #include <com/sun/star/datatransfer/clipboard/XClipboard.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _SV_WRKWIN_HXX #include <vcl/wrkwin.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef _SFXVIEWFRM_HXX #include <sfx2/viewfrm.hxx> #endif #ifndef _SFX_BINDINGS_HXX #include <sfx2/bindings.hxx> #endif #ifndef _UIVWIMP_HXX #include <uivwimp.hxx> #endif #ifndef _SWWVIEW_HXX //autogen #include <wview.hxx> #endif #ifndef _UNOTXVW_HXX #include <unotxvw.hxx> #endif #ifndef _UNODISPATCH_HXX #include <unodispatch.hxx> #endif #ifndef _SWMODULE_HXX #include <swmodule.hxx> #endif #ifndef _SWDTFLVR_HXX #include <swdtflvr.hxx> #endif #ifndef _EDTWIN_HXX #include <edtwin.hxx> #endif #include <view.hrc> using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::scanner; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::datatransfer::clipboard; /* -----------------02.06.98 15:31------------------- * * --------------------------------------------------*/ SwView_Impl::SwView_Impl(SwView* pShell) : pView(pShell), pxXTextView(new uno::Reference<view::XSelectionSupplier>), eShellMode(SEL_TEXT) { *pxXTextView = new SwXTextView(pView); xDisProvInterceptor = new SwXDispatchProviderInterceptor(*pView); } /*-----------------13.12.97 09:51------------------- --------------------------------------------------*/ SwView_Impl::~SwView_Impl() { view::XSelectionSupplier* pTextView = pxXTextView->get(); ((SwXTextView*)pTextView)->Invalidate(); delete pxXTextView; if( xScanEvtLstnr.is() ) pScanEvtLstnr->ViewDestroyed(); if( xClipEvtLstnr.is() ) { pClipEvtLstnr->AddRemoveListener( FALSE ); pClipEvtLstnr->ViewDestroyed(); } } /*-----------------13.12.97 09:54------------------- --------------------------------------------------*/ void SwView_Impl::SetShellMode(ShellModes eSet) { eShellMode = eSet; } /*-----------------13.12.97 09:59------------------- --------------------------------------------------*/ view::XSelectionSupplier* SwView_Impl::GetUNOObject() { return pxXTextView->get(); } /* -----------------02.06.98 15:29------------------- * * --------------------------------------------------*/ SwXTextView* SwView_Impl::GetUNOObject_Impl() { view::XSelectionSupplier* pTextView = pxXTextView->get(); return ((SwXTextView*)pTextView); } /* -----------------------------29.05.00 09:04-------------------------------- ---------------------------------------------------------------------------*/ void SwView_Impl::ExcuteScan(USHORT nSlot) { switch(nSlot) { case SID_TWAIN_SELECT: { BOOL bDone = FALSE; Reference< XScannerManager > xScanMgr = SW_MOD()->GetScannerManager(); if( xScanMgr.is() ) { //JP 26.06.00: the appwindow doen't exist // Application::GetAppWindow()->EnableInput( FALSE ); try { const Sequence< ScannerContext > aContexts( xScanMgr->getAvailableScanners() ); if( aContexts.getLength() ) { ScannerContext aContext( aContexts.getConstArray()[ 0 ] ); bDone = xScanMgr->configureScanner( aContext ); } } catch(...) { } //JP 26.06.00: the appwindow doen't exist // Application::GetAppWindow()->EnableInput( TRUE ); } if( !bDone ) InfoBox( 0, SW_RES(MSG_SCAN_NOSOURCE) ).Execute(); } break; case SID_TWAIN_TRANSFER: { BOOL bDone = FALSE; Reference< XScannerManager > xScanMgr = SW_MOD()->GetScannerManager(); if( xScanMgr.is() ) { SwScannerEventListener& rListener = GetScannerEventListener(); //JP 26.06.00: the appwindow doen't exist // Application::GetAppWindow()->EnableInput( FALSE ); try { const Sequence< scanner::ScannerContext >aContexts( xScanMgr->getAvailableScanners() ); if( aContexts.getLength() ) { Reference< XEventListener > xLstner = &rListener; xScanMgr->startScan( aContexts.getConstArray()[ 0 ], xLstner ); bDone = TRUE; } } catch(...) { } } if( !bDone ) { //JP 26.06.00: the appwindow doen't exist // Application::GetAppWindow()->EnableInput( TRUE ); InfoBox( 0, SW_RES(MSG_SCAN_NOSOURCE) ).Execute(); } else { SfxBindings& rBind = pView->GetViewFrame()->GetBindings(); rBind.Invalidate( SID_TWAIN_SELECT ); rBind.Invalidate( SID_TWAIN_TRANSFER ); } } break; } } /* -----------------------------29.05.00 08:26-------------------------------- ---------------------------------------------------------------------------*/ SwScannerEventListener& SwView_Impl::GetScannerEventListener() { if(!xScanEvtLstnr.is()) xScanEvtLstnr = pScanEvtLstnr = new SwScannerEventListener(*pView); return *pScanEvtLstnr; } void SwView_Impl::AddClipboardListener() { if(!xClipEvtLstnr.is()) { xClipEvtLstnr = pClipEvtLstnr = new SwClipboardChangeListener( *pView ); pClipEvtLstnr->AddRemoveListener( TRUE ); } } // ------------------------- SwScannerEventListener --------------------- SwScannerEventListener::~SwScannerEventListener() { } void SAL_CALL SwScannerEventListener::disposing( const EventObject& rEventObject ) { if( pView ) pView->ScannerEventHdl( rEventObject ); } // ------------------------- SwClipboardChangeListener --------------------- SwClipboardChangeListener::~SwClipboardChangeListener() { } void SAL_CALL SwClipboardChangeListener::disposing( const EventObject& rEventObject ) { } void SAL_CALL SwClipboardChangeListener::changedContents( const CLIP_NMSPC::ClipboardEvent& rEventObject ) { if( pView ) { { const ::vos::OGuard aGuard( Application::GetSolarMutex() ); TransferableDataHelper aDataHelper( rEventObject.Contents ); SwWrtShell& rSh = pView->GetWrtShell(); pView->nLastPasteDestination = SwTransferable::GetSotDestination( rSh ); pView->bPasteState = aDataHelper.GetTransferable().is() && SwTransferable::IsPaste( rSh, aDataHelper ); pView->bPasteSpecialState = aDataHelper.GetTransferable().is() && SwTransferable::IsPasteSpecial( rSh, aDataHelper ); } SfxBindings& rBind = pView->GetViewFrame()->GetBindings(); rBind.Invalidate( SID_PASTE ); rBind.Invalidate( FN_PASTESPECIAL ); } } void SwClipboardChangeListener::AddRemoveListener( BOOL bAdd ) { try { do { #ifdef _DONT_WORD_FOR_WEBTOP_ JP 4.7.2001: change for WebTop - get Clipboard from the Window. Reference< XMultiServiceFactory > xFact( ::comphelper::getProcessServiceFactory() ); if( !xFact.is() ) break; Reference< XClipboard > xClipboard( xFact->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.datatransfer.clipboard.SystemClipboard" )), UNO_QUERY ); #else Reference< XClipboard > xClipboard( pView->GetEditWin().GetClipboard() ); #endif if( !xClipboard.is() ) break; Reference< XClipboardNotifier > xClpbrdNtfr( xClipboard, UNO_QUERY ); if( xClpbrdNtfr.is() ) { Reference< XClipboardListener > xClipEvtLstnr( this ); if( bAdd ) xClpbrdNtfr->addClipboardListener( xClipEvtLstnr ); else xClpbrdNtfr->removeClipboardListener( xClipEvtLstnr ); } } while ( FALSE ); } catch( const ::com::sun::star::uno::Exception& ) { } } /*------------------------------------------------------------------------ $Log: not supported by cvs2svn $ Revision 1.3 2001/04/30 15:59:56 jp use Clipboard state listener instead of polling Revision 1.2 2000/11/07 14:38:25 os Dispatch interface for database component Revision 1.1.1.1 2000/09/18 17:14:49 hr initial import Revision 1.14 2000/09/18 16:06:11 willem.vandorp OpenOffice header added. Revision 1.13 2000/09/07 15:59:32 os change: SFX_DISPATCHER/SFX_BINDINGS removed Revision 1.12 2000/06/26 10:44:13 jp must change: GetAppWindow->GetDefaultDevice Revision 1.11 2000/05/29 08:03:23 os new scanner interface Revision 1.10 2000/05/09 14:43:13 os BASIC interface partially removed Revision 1.9 2000/03/23 07:50:24 os UNO III Revision 1.8 1999/01/27 08:58:26 OS #56371# TF_ONE51 Rev 1.7 27 Jan 1999 09:58:26 OS #56371# TF_ONE51 Rev 1.6 30 Sep 1998 11:37:50 OS #52654# ueberfluessigen Aufruf entfernt Rev 1.5 02 Jun 1998 15:51:16 OS TF_STARONE raus; Ctor nicht mehr inline Rev 1.4 03 Apr 1998 14:38:28 OS UnoObject fuer die View reaktiviert Rev 1.3 04 Feb 1998 17:28:44 OS Starone raus Rev 1.2 29 Jan 1998 09:21:06 OS TF_STARONE Rev 1.1 19 Jan 1998 14:59:14 OS UNO-Aenderungen Rev 1.0 16 Dec 1997 11:58:48 OS Impl-Pointer fuer UNO ------------------------------------------------------------------------*/ <|endoftext|>
<commit_before>#include <iostream> #include "GL/gl_core_3_3.h" #include "framework/platform.hh" #include "system/keycode.hh" #include "system/utility.hh" #include "controllerstack.hh" #include "gamecontroller.hh" #include "ticker.hh" using Framework::ReadingKeyboardState; using System::KeyCode; using System::Utility; class SleepService : public ISleepService { public: SleepService(System::Utility *utility) : m_utility(utility) { } virtual void Sleep(unsigned int milliseconds) { m_utility->Sleep(milliseconds); } private: System::Utility *m_utility; }; class SystemTimer : public ISystemTimer { public: SystemTimer(System::Utility *utility) : m_utility(utility) { } virtual unsigned int GetTicks() { return m_utility->GetTicks(); } private: System::Utility *m_utility; }; class OtherTestController : public GameController { public: virtual void OnStackAdd() { std::cout << "OtherTestController added to stack" << std::endl; } virtual void OnStackRemove() { std::cout << "OtherTestController removed from stack" << std::endl; } virtual void OnStackFocus() { std::cout << "OtherTestController stack focus" << std::endl; } virtual void OnStackBlur() { std::cout << "OtherTestController stack blur" << std::endl; } }; class TestController : public GameController { public: TestController() : m_otherController(NULL) { } ~TestController() { if (m_otherController != NULL) { GetControllerStack()->Pop(); delete m_otherController; m_otherController = NULL; } } virtual void OnStackAdd() { std::cout << "TestController added to stack" << std::endl; } virtual void OnStackRemove() { std::cout << "TestController removed from stack" << std::endl; } virtual void OnStackFocus() { std::cout << "TestController stack focus" << std::endl; } virtual void OnStackBlur() { std::cout << "TestController stack blur" << std::endl; } virtual void OnTick() { ReadingKeyboardState *keyboardState = GetKeyboardState(); std::cout << "TestController: "; if (keyboardState != NULL) { std::cout << keyboardState->GetKeyState(KeyCode::KeyTab); } else { std::cout << "No state"; } std::cout << std::endl; if (m_otherController == NULL) { m_otherController = new OtherTestController(); GetControllerStack()->Push(m_otherController); } else { GetControllerStack()->Pop(); delete m_otherController; m_otherController = NULL; } } private: OtherTestController *m_otherController; }; static Framework::ApplicationState applicationState = { .windowName = "Fire Frame Demo" }; GetApplicationState_FunctionSignature(GetApplicationState) { return &applicationState; } GraphicsThreadEntry_FunctionSignature(GraphicsThreadEntry) { std::cout << "GraphicsThreadEntry: " << std::endl; windowController->CreateContext(); const GLubyte *renderer = glGetString(GL_RENDERER); const GLubyte *vendor = glGetString(GL_VENDOR); const GLubyte *version = glGetString(GL_VERSION); const GLubyte *glslVersion = glGetString(GL_SHADING_LANGUAGE_VERSION); std::cout << "- renderer: " << renderer << std::endl; std::cout << "- vendor: " << vendor << std::endl; std::cout << "- version: " << version << std::endl; std::cout << "- GLSL version: " << version << std::endl; //GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); //GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); unsigned int framerateTicks = 1000 / 60; SystemTimer systemTimer(applicationContext->GetSystemUtility()); SleepService sleepService(applicationContext->GetSystemUtility()); Ticker ticker = Ticker(&systemTimer, &sleepService); ticker.Start(); while (!applicationContext->IsClosing()) { ticker.Wait(framerateTicks); } } LogicThreadEntry_FunctionSignature(LogicThreadEntry) { SystemTimer systemTimer(applicationContext->GetSystemUtility()); SleepService sleepService(applicationContext->GetSystemUtility()); Ticker ticker = Ticker(&systemTimer, &sleepService); unsigned int ticks = systemTimer.GetTicks(); unsigned int newTicks; ControllerStack controllerStack(windowController); GameController *controller = new TestController(); controllerStack.Push(controller); ticker.Start(); while (!applicationContext->IsClosing()) { controller = (GameController *)controllerStack.Top(); controller->OnTick(); newTicks = systemTimer.GetTicks(); ticker.Wait(500); std::cout << "Logic Thread (" << ticks << " -> " << newTicks << ")" << std::endl; ticks = newTicks; } controllerStack.Clear(); }<commit_msg>Fix whitespace<commit_after>#include <iostream> #include "GL/gl_core_3_3.h" #include "framework/platform.hh" #include "system/keycode.hh" #include "system/utility.hh" #include "controllerstack.hh" #include "gamecontroller.hh" #include "ticker.hh" using Framework::ReadingKeyboardState; using System::KeyCode; using System::Utility; class SleepService : public ISleepService { public: SleepService(System::Utility *utility) : m_utility(utility) { } virtual void Sleep(unsigned int milliseconds) { m_utility->Sleep(milliseconds); } private: System::Utility *m_utility; }; class SystemTimer : public ISystemTimer { public: SystemTimer(System::Utility *utility) : m_utility(utility) { } virtual unsigned int GetTicks() { return m_utility->GetTicks(); } private: System::Utility *m_utility; }; class OtherTestController : public GameController { public: virtual void OnStackAdd() { std::cout << "OtherTestController added to stack" << std::endl; } virtual void OnStackRemove() { std::cout << "OtherTestController removed from stack" << std::endl; } virtual void OnStackFocus() { std::cout << "OtherTestController stack focus" << std::endl; } virtual void OnStackBlur() { std::cout << "OtherTestController stack blur" << std::endl; } }; class TestController : public GameController { public: TestController() : m_otherController(NULL) { } ~TestController() { if (m_otherController != NULL) { GetControllerStack()->Pop(); delete m_otherController; m_otherController = NULL; } } virtual void OnStackAdd() { std::cout << "TestController added to stack" << std::endl; } virtual void OnStackRemove() { std::cout << "TestController removed from stack" << std::endl; } virtual void OnStackFocus() { std::cout << "TestController stack focus" << std::endl; } virtual void OnStackBlur() { std::cout << "TestController stack blur" << std::endl; } virtual void OnTick() { ReadingKeyboardState *keyboardState = GetKeyboardState(); std::cout << "TestController: "; if (keyboardState != NULL) { std::cout << keyboardState->GetKeyState(KeyCode::KeyTab); } else { std::cout << "No state"; } std::cout << std::endl; if (m_otherController == NULL) { m_otherController = new OtherTestController(); GetControllerStack()->Push(m_otherController); } else { GetControllerStack()->Pop(); delete m_otherController; m_otherController = NULL; } } private: OtherTestController *m_otherController; }; static Framework::ApplicationState applicationState = { .windowName = "Fire Frame Demo" }; GetApplicationState_FunctionSignature(GetApplicationState) { return &applicationState; } GraphicsThreadEntry_FunctionSignature(GraphicsThreadEntry) { std::cout << "GraphicsThreadEntry: " << std::endl; /* windowController->CreateContext(); const GLubyte *renderer = glGetString(GL_RENDERER); const GLubyte *vendor = glGetString(GL_VENDOR); const GLubyte *version = glGetString(GL_VERSION); const GLubyte *glslVersion = glGetString(GL_SHADING_LANGUAGE_VERSION); std::cout << "- renderer: " << renderer << std::endl; std::cout << "- vendor: " << vendor << std::endl; std::cout << "- version: " << version << std::endl; std::cout << "- GLSL version: " << version << std::endl; //GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); //GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); unsigned int framerateTicks = 1000 / 60; SystemTimer systemTimer(applicationContext->GetSystemUtility()); SleepService sleepService(applicationContext->GetSystemUtility()); Ticker ticker = Ticker(&systemTimer, &sleepService); ticker.Start(); while (!applicationContext->IsClosing()) { ticker.Wait(framerateTicks); } */ } LogicThreadEntry_FunctionSignature(LogicThreadEntry) { /* SystemTimer systemTimer(applicationContext->GetSystemUtility()); SleepService sleepService(applicationContext->GetSystemUtility()); Ticker ticker = Ticker(&systemTimer, &sleepService); unsigned int ticks = systemTimer.GetTicks(); unsigned int newTicks; ControllerStack controllerStack(windowController); GameController *controller = new TestController(); controllerStack.Push(controller); ticker.Start(); while (!applicationContext->IsClosing()) { controller = (GameController *)controllerStack.Top(); controller->OnTick(); newTicks = systemTimer.GetTicks(); ticker.Wait(500); std::cout << "Logic Thread (" << ticks << " -> " << newTicks << ")" << std::endl; ticks = newTicks; } controllerStack.Clear(); */ } <|endoftext|>
<commit_before>/********************************************************************* ** Author: Zach Colbert ** Date: 1 November 2017 ** Description: *********************************************************************/ // Pre-processing includes pre-requisite libraries for the functions below #include <string> // Make sure to include the header file where we declare the player and team classes! #include "Player.hpp" #include "Team.hpp" /********************************************************************* ** Description: The constructor for the Team class takes five objects of the Player type as arguments, and sets them as positions on the team. Those positions are, in this order: ** Point Guard ** Shooting Guard ** Small Forward ** Power Forward ** Center This class does not have a default constructor because there is no "I" in "Team." ** Example: Team::Team myTeam(pointGuard, shootingGuard, smallForward, powerForward, center); *********************************************************************/ Team::Team(Player point_Guard, Player shooting_Guard, Player small_Forward, Player power_Forward, Player center_In) { // Set each of the positions using mutator functions setPointGuard(point_Guard); setShootingGuard(shooting_Guard); setSmallForward(small_Forward); setPowerForward(power_Forward); setCenter(center_In); } // Mutator for pointGuard void setPointGuard(Player pIn) { pointGuard = pIn; } // Accessor for pointGuard Player getPointGuard() { return pointGuard; } // Mutator for shootingGuard void setShootingGuard(Player pIn) { shootingGuard = pIn; } // Accessor for shootingGuard Player getShootingGuard() { return shootingGuard; } // Mutator for smallForward void setSmallForward(Player pIn) { smallForward = pIn; } // Accessor for smallForward Player getSmallForward() { return smallForward; } // Mutator for powerForward void setPowerForward(Player pIn) { powerForward = pIn; } // Accessor for powerForward Player getPowerForward() { return powerForward; } // Mutator for center void setCenter(Player pIn) { center = pIn; } // Accessor for center Player getCenter() { return center; } /********************************************************************* ** Description: The totalPoints function of the Team class gets the points attribute from each Player object in the team, sums them, and returns the total value of points of all players on the team. ** Example: myTeam.totalPoints(); ** Example Output: 12; *********************************************************************/ int totalPoints() { return pointGuard.getPoints() + shootingGuard.getPoints() + smallForward.getPoints() + powerForward.getPoints() + center.getPoints(); }<commit_msg>Functions needed class:: prefix<commit_after>/********************************************************************* ** Author: Zach Colbert ** Date: 1 November 2017 ** Description: *********************************************************************/ // Pre-processing includes pre-requisite libraries for the functions below #include <string> // Make sure to include the header file where we declare the player and team classes! #include "Player.hpp" #include "Team.hpp" /********************************************************************* ** Description: The constructor for the Team class takes five objects of the Player type as arguments, and sets them as positions on the team. Those positions are, in this order: ** Point Guard ** Shooting Guard ** Small Forward ** Power Forward ** Center This class does not have a default constructor because there is no "I" in "Team." ** Example: Team::Team myTeam(pointGuard, shootingGuard, smallForward, powerForward, center); *********************************************************************/ Team::Team(Player point_Guard, Player shooting_Guard, Player small_Forward, Player power_Forward, Player center_In) { // Set each of the positions using mutator functions setPointGuard(point_Guard); setShootingGuard(shooting_Guard); setSmallForward(small_Forward); setPowerForward(power_Forward); setCenter(center_In); } // Mutator for pointGuard void Team::setPointGuard(Player pIn) { pointGuard = pIn; } // Accessor for pointGuard Player Team::getPointGuard() { return pointGuard; } // Mutator for shootingGuard void Team::setShootingGuard(Player pIn) { shootingGuard = pIn; } // Accessor for shootingGuard Player Team::getShootingGuard() { return shootingGuard; } // Mutator for smallForward void Team::setSmallForward(Player pIn) { smallForward = pIn; } // Accessor for smallForward Player Team::getSmallForward() { return smallForward; } // Mutator for powerForward void Team::setPowerForward(Player pIn) { powerForward = pIn; } // Accessor for powerForward Player Team::getPowerForward() { return powerForward; } // Mutator for center void Team::setCenter(Player pIn) { center = pIn; } // Accessor for center Player Team::getCenter() { return center; } /********************************************************************* ** Description: The totalPoints function of the Team class gets the points attribute from each Player object in the team, sums them, and returns the total value of points of all players on the team. ** Example: myTeam.totalPoints(); ** Example Output: 12; *********************************************************************/ int Team::totalPoints() { return pointGuard.getPoints() + shootingGuard.getPoints() + smallForward.getPoints() + powerForward.getPoints() + center.getPoints(); }<|endoftext|>
<commit_before>#include "RansacLineDetector.h" RansacLineDetector::RansacLineDetector() { // initialize some stuff here DEBUG_REQUEST_REGISTER("Vision:RansacLineDetector:draw_edgels_field", "", false); DEBUG_REQUEST_REGISTER("Vision:RansacLineDetector:draw_lines_field", "", false); DEBUG_REQUEST_REGISTER("Vision:RansacLineDetector:fit_and_draw_circle_field", "", false); getDebugParameterList().add(&params); } RansacLineDetector::~RansacLineDetector() { getDebugParameterList().remove(&params); } void RansacLineDetector::execute() { getLinePercept().reset(); DEBUG_REQUEST("Vision:RansacLineDetector:draw_edgels_field", FIELD_DRAWING_CONTEXT; for(const Edgel& e: getLineGraphPercept().edgels) { PEN("FF0000",2); if(e.point.x > 0 || e.point.y > 0) { CIRCLE(e.point.x, e.point.y, 25); } PEN("000000",0.1); LINE(e.point.x, e.point.y, e.point.x + e.direction.x*100.0, e.point.y + e.direction.y*100.0); } ); // copy the edgels // todo: can this be optimized? //outliers.assign(getLineGraphPercept().edgels.begin(), getLineGraphPercept().edgels.end()); outliers.resize(getLineGraphPercept().edgels.size()); for(size_t i = 0; i < getLineGraphPercept().edgels.size(); ++i) { outliers[i] = i; } bool foundLines = false; for(int i = 0; i < params.maxLines; ++i) { Math::LineSegment result; if(ransac(result) > 0) { foundLines = true; LinePercept::FieldLineSegment fieldLine; fieldLine.lineOnField = result; getLinePercept().lines.push_back(fieldLine); } else { break; } } DEBUG_REQUEST("Vision:RansacLineDetector:draw_lines_field", FIELD_DRAWING_CONTEXT; if (foundLines) { for(const LinePercept::FieldLineSegment& line: getLinePercept().lines) { PEN("999999", 50); LINE( line.lineOnField.begin().x, line.lineOnField.begin().y, line.lineOnField.end().x, line.lineOnField.end().y); } } ); DEBUG_REQUEST("Vision:RansacLineDetector:fit_and_draw_circle_field", FIELD_DRAWING_CONTEXT; // fit ellipse Ellipse circResult; int bestInlierCirc = ransacEllipse(circResult); if (bestInlierCirc > 0) { double c[2]; circResult.getCenter(c); double a[2]; circResult.axesLength(a); PEN("009900", 50); CIRCLE(c[0], c[1], 30); OVAL_ROTATED(c[0], c[1], a[0], a[1], circResult.rotationAngle()); PEN("0000AA", 20); for(int i=0; i<circResult.x_toFit.size(); i++) { CIRCLE(circResult.x_toFit[i], circResult.y_toFit[i], 20); } } ); } int RansacLineDetector::ransac(Math::LineSegment& result) { if(outliers.size() <= 2) { return 0; } Math::Line bestModel; int bestInlier = 0; double bestInlierError = 0; for(int i = 0; i < params.iterations; ++i) { //pick two random points int i0 = Math::random((int)outliers.size()); int i1 = Math::random((int)outliers.size()); if(i0 == i1) { continue; } const Edgel& a = getLineGraphPercept().edgels[outliers[i0]]; const Edgel& b = getLineGraphPercept().edgels[outliers[i1]]; //double x = a.sim(b); if(a.sim(b) < params.directionSimilarity) { continue; } // check the orientation // TODO Math::Line model(a.point, b.point-a.point); double inlierError = 0; int inlier = 0; for(size_t i: outliers) { const Edgel& e = getLineGraphPercept().edgels[i]; double d = model.minDistance(e.point); // inlier if(d < params.outlierThreshold && sim(model, e) > params.directionSimilarity) { ++inlier; inlierError += d; } } if(inlier >= params.inlierMin && (inlier > bestInlier || (inlier == bestInlier && inlierError < bestInlierError))) { bestModel = model; bestInlier = inlier; bestInlierError = inlierError; } } if(bestInlier > 2) { // update the outliers // todo: make it faster std::vector<size_t> newOutliers; newOutliers.reserve(outliers.size() - bestInlier + 1); double minT = 0; double maxT = 0; for(size_t i: outliers) { const Edgel& e = getLineGraphPercept().edgels[i]; double d = bestModel.minDistance(e.point); if(d < params.outlierThreshold && sim(bestModel, e) > params.directionSimilarity) { double t = bestModel.project(e.point); minT = std::min(t, minT); maxT = std::max(t, maxT); } else { newOutliers.push_back(i); } } outliers = newOutliers; // return results result = Math::LineSegment(bestModel.point(minT), bestModel.point(maxT)); } return bestInlier; } int RansacLineDetector::ransacEllipse(Ellipse& result) { if(outliers.size() <= 5) { return 0; } Ellipse bestModel; int bestInlier = 0; double bestInlierError = 0; for(int i = 0; i < params.circle_iterations; ++i) { // create model Ellipse ellipse; std::vector<double> x, y; x.reserve(5); y.reserve(5); for(int t=0; t<5; t++) { size_t r = swap_random(outliers, (int) outliers.size()-(t+1)); const Edgel& e = getLineGraphPercept().edgels[r]; x.push_back(e.point.x); y.push_back(e.point.y); } ellipse.fitPoints(x,y); // check model double inlierError = 0; int inlier = 0; for(size_t i: outliers) { const Edgel& e = getLineGraphPercept().edgels[i]; double d = ellipse.error_to(e.point.x, e.point.y); if(d <= params.circle_outlierThreshold) { ++inlier; inlierError += d; continue; } } if(inlier >= params.circle_inlierMin && (inlier > bestInlier || (inlier == bestInlier && inlierError < bestInlierError))) { bestModel = ellipse; bestInlier = inlier; bestInlierError = inlierError; } } if (bestInlier > 5) { // update the outliers // todo: make it faster std::vector<size_t> newOutliers; newOutliers.reserve(outliers.size() - bestInlier + 1); std::vector<double> inliers_x, inliers_y; inliers_x.reserve(bestInlier); inliers_y.reserve(bestInlier); for(size_t i: outliers) { const Edgel& e = getLineGraphPercept().edgels[i]; double d = bestModel.error_to(e.point.x, e.point.y); if(d > params.circle_outlierThreshold) { newOutliers.push_back(i); } else { inliers_x.push_back(e.point.x); inliers_y.push_back(e.point.y); } } outliers = newOutliers; // return results bestModel.fitPoints(inliers_x, inliers_y); result = bestModel; } return bestInlier; } <commit_msg>fixed index<commit_after>#include "RansacLineDetector.h" RansacLineDetector::RansacLineDetector() { // initialize some stuff here DEBUG_REQUEST_REGISTER("Vision:RansacLineDetector:draw_edgels_field", "", false); DEBUG_REQUEST_REGISTER("Vision:RansacLineDetector:draw_lines_field", "", false); DEBUG_REQUEST_REGISTER("Vision:RansacLineDetector:fit_and_draw_circle_field", "", false); getDebugParameterList().add(&params); } RansacLineDetector::~RansacLineDetector() { getDebugParameterList().remove(&params); } void RansacLineDetector::execute() { getLinePercept().reset(); DEBUG_REQUEST("Vision:RansacLineDetector:draw_edgels_field", FIELD_DRAWING_CONTEXT; for(const Edgel& e: getLineGraphPercept().edgels) { PEN("FF0000",2); if(e.point.x > 0 || e.point.y > 0) { CIRCLE(e.point.x, e.point.y, 25); } PEN("000000",0.1); LINE(e.point.x, e.point.y, e.point.x + e.direction.x*100.0, e.point.y + e.direction.y*100.0); } ); // copy the edgels // todo: can this be optimized? //outliers.assign(getLineGraphPercept().edgels.begin(), getLineGraphPercept().edgels.end()); outliers.resize(getLineGraphPercept().edgels.size()); for(size_t i = 0; i < getLineGraphPercept().edgels.size(); ++i) { outliers[i] = i; } bool foundLines = false; for(int i = 0; i < params.maxLines; ++i) { Math::LineSegment result; if(ransac(result) > 0) { foundLines = true; LinePercept::FieldLineSegment fieldLine; fieldLine.lineOnField = result; getLinePercept().lines.push_back(fieldLine); } else { break; } } DEBUG_REQUEST("Vision:RansacLineDetector:draw_lines_field", FIELD_DRAWING_CONTEXT; if (foundLines) { for(const LinePercept::FieldLineSegment& line: getLinePercept().lines) { PEN("999999", 50); LINE( line.lineOnField.begin().x, line.lineOnField.begin().y, line.lineOnField.end().x, line.lineOnField.end().y); } } ); DEBUG_REQUEST("Vision:RansacLineDetector:fit_and_draw_circle_field", FIELD_DRAWING_CONTEXT; // fit ellipse Ellipse circResult; int bestInlierCirc = ransacEllipse(circResult); if (bestInlierCirc > 0) { double c[2]; circResult.getCenter(c); double a[2]; circResult.axesLength(a); PEN("009900", 50); CIRCLE(c[0], c[1], 30); OVAL_ROTATED(c[0], c[1], a[0], a[1], circResult.rotationAngle()); PEN("0000AA", 20); for(size_t i=0; i<circResult.x_toFit.size(); i++) { CIRCLE(circResult.x_toFit[i], circResult.y_toFit[i], 20); } } ); } int RansacLineDetector::ransac(Math::LineSegment& result) { if(outliers.size() <= 2) { return 0; } Math::Line bestModel; int bestInlier = 0; double bestInlierError = 0; for(int i = 0; i < params.iterations; ++i) { //pick two random points int i0 = Math::random((int)outliers.size()); int i1 = Math::random((int)outliers.size()); if(i0 == i1) { continue; } const Edgel& a = getLineGraphPercept().edgels[outliers[i0]]; const Edgel& b = getLineGraphPercept().edgels[outliers[i1]]; //double x = a.sim(b); if(a.sim(b) < params.directionSimilarity) { continue; } // check the orientation // TODO Math::Line model(a.point, b.point-a.point); double inlierError = 0; int inlier = 0; for(size_t i: outliers) { const Edgel& e = getLineGraphPercept().edgels[i]; double d = model.minDistance(e.point); // inlier if(d < params.outlierThreshold && sim(model, e) > params.directionSimilarity) { ++inlier; inlierError += d; } } if(inlier >= params.inlierMin && (inlier > bestInlier || (inlier == bestInlier && inlierError < bestInlierError))) { bestModel = model; bestInlier = inlier; bestInlierError = inlierError; } } if(bestInlier > 2) { // update the outliers // todo: make it faster std::vector<size_t> newOutliers; newOutliers.reserve(outliers.size() - bestInlier + 1); double minT = 0; double maxT = 0; for(size_t i: outliers) { const Edgel& e = getLineGraphPercept().edgels[i]; double d = bestModel.minDistance(e.point); if(d < params.outlierThreshold && sim(bestModel, e) > params.directionSimilarity) { double t = bestModel.project(e.point); minT = std::min(t, minT); maxT = std::max(t, maxT); } else { newOutliers.push_back(i); } } outliers = newOutliers; // return results result = Math::LineSegment(bestModel.point(minT), bestModel.point(maxT)); } return bestInlier; } int RansacLineDetector::ransacEllipse(Ellipse& result) { if(outliers.size() <= 5) { return 0; } Ellipse bestModel; int bestInlier = 0; double bestInlierError = 0; for(int i = 0; i < params.circle_iterations; ++i) { // create model Ellipse ellipse; std::vector<double> x, y; x.reserve(5); y.reserve(5); for(int t=0; t<5; t++) { size_t r = swap_random(outliers, (int) outliers.size()-(t+1)); const Edgel& e = getLineGraphPercept().edgels[r]; x.push_back(e.point.x); y.push_back(e.point.y); } ellipse.fitPoints(x,y); // check model double inlierError = 0; int inlier = 0; for(size_t i: outliers) { const Edgel& e = getLineGraphPercept().edgels[i]; double d = ellipse.error_to(e.point.x, e.point.y); if(d <= params.circle_outlierThreshold) { ++inlier; inlierError += d; continue; } } if(inlier >= params.circle_inlierMin && (inlier > bestInlier || (inlier == bestInlier && inlierError < bestInlierError))) { bestModel = ellipse; bestInlier = inlier; bestInlierError = inlierError; } } if (bestInlier > 5) { // update the outliers // todo: make it faster std::vector<size_t> newOutliers; newOutliers.reserve(outliers.size() - bestInlier + 1); std::vector<double> inliers_x, inliers_y; inliers_x.reserve(bestInlier); inliers_y.reserve(bestInlier); for(size_t i: outliers) { const Edgel& e = getLineGraphPercept().edgels[i]; double d = bestModel.error_to(e.point.x, e.point.y); if(d > params.circle_outlierThreshold) { newOutliers.push_back(i); } else { inliers_x.push_back(e.point.x); inliers_y.push_back(e.point.y); } } outliers = newOutliers; // return results bestModel.fitPoints(inliers_x, inliers_y); result = bestModel; } return bestInlier; } <|endoftext|>
<commit_before>#include "chainerx/routines/statistics.h" #include "chainerx/array.h" #include "chainerx/axes.h" #include "chainerx/backprop_mode.h" #include "chainerx/backward.h" #include "chainerx/backward_builder.h" #include "chainerx/backward_context.h" #include "chainerx/dtype.h" #include "chainerx/macro.h" #include "chainerx/routines/creation.h" #include "chainerx/routines/type_util.h" namespace chainerx { Dtype PromoteInt2Float(Dtype dtype){ return GetKind(dtype) == DtypeKind::kFloat? dtype :internal::GetDefaultDtype(DtypeKind::kFloat); } Array Mean(const Array& a, const OptionalAxes& axis, bool keepdims) { Axes sorted_axis = internal::GetSortedAxesOrAll(axis, a.ndim()); Dtype out_dtype = PromoteInt2Float(a.dtype()); Array out = internal::EmptyReduced(a.shape(), out_dtype, sorted_axis, keepdims, a.device()); Scalar n = internal::CountItemsAlongAxes(a.shape(), sorted_axis); { NoBackpropModeScope scope{}; a.device().Sum(a, sorted_axis, out); a.device().DivideAS(out, n, out); } BackwardBuilder bb{"mean", a, out}; if (BackwardBuilder::Target bt = bb.CreateTarget(0)) { bt.Define([n, sorted_axis, in_shape = a.shape(), keepdims](BackwardContext& bctx) { const Array& gout = *bctx.output_grad(); CHAINERX_ASSERT(std::is_sorted(sorted_axis.begin(), sorted_axis.end())); if (!(in_shape.ndim() == 0 || sorted_axis.empty() || keepdims)) { Shape out_shape_broadcastable = gout.shape(); for (auto axis : sorted_axis) { out_shape_broadcastable.insert(out_shape_broadcastable.begin() + axis, 1); } bctx.input_grad() = gout.Reshape(out_shape_broadcastable).BroadcastTo(in_shape) / n; } else { bctx.input_grad() = gout.BroadcastTo(in_shape) / n; } }); } bb.Finalize(); return out; } Array Var(const Array& a, const OptionalAxes& axis, bool keepdims) { // TODO(hvy): Consider allowing device implementations. Axes sorted_axis = internal::GetSortedAxesOrAll(axis, a.ndim()); Dtype mean_out = PromoteInt2Float(a.dtype()); // TODO(kshitij12345): remove once subtract allows mixed types. Array diff = a.AsType(mean_out, true) - Mean(a, sorted_axis, true); return Mean(diff * diff, sorted_axis, keepdims); } } // namespace chainerx <commit_msg>fix styling clang-format<commit_after>#include "chainerx/routines/statistics.h" #include "chainerx/array.h" #include "chainerx/axes.h" #include "chainerx/backprop_mode.h" #include "chainerx/backward.h" #include "chainerx/backward_builder.h" #include "chainerx/backward_context.h" #include "chainerx/dtype.h" #include "chainerx/macro.h" #include "chainerx/routines/creation.h" #include "chainerx/routines/type_util.h" namespace chainerx { Dtype PromoteInt2Float(Dtype dtype) { return GetKind(dtype) == DtypeKind::kFloat ? dtype : internal::GetDefaultDtype(DtypeKind::kFloat); } Array Mean(const Array& a, const OptionalAxes& axis, bool keepdims) { Axes sorted_axis = internal::GetSortedAxesOrAll(axis, a.ndim()); Dtype out_dtype = PromoteInt2Float(a.dtype()); Array out = internal::EmptyReduced(a.shape(), out_dtype, sorted_axis, keepdims, a.device()); Scalar n = internal::CountItemsAlongAxes(a.shape(), sorted_axis); { NoBackpropModeScope scope{}; a.device().Sum(a, sorted_axis, out); a.device().DivideAS(out, n, out); } BackwardBuilder bb{"mean", a, out}; if (BackwardBuilder::Target bt = bb.CreateTarget(0)) { bt.Define([n, sorted_axis, in_shape = a.shape(), keepdims](BackwardContext& bctx) { const Array& gout = *bctx.output_grad(); CHAINERX_ASSERT(std::is_sorted(sorted_axis.begin(), sorted_axis.end())); if (!(in_shape.ndim() == 0 || sorted_axis.empty() || keepdims)) { Shape out_shape_broadcastable = gout.shape(); for (auto axis : sorted_axis) { out_shape_broadcastable.insert(out_shape_broadcastable.begin() + axis, 1); } bctx.input_grad() = gout.Reshape(out_shape_broadcastable).BroadcastTo(in_shape) / n; } else { bctx.input_grad() = gout.BroadcastTo(in_shape) / n; } }); } bb.Finalize(); return out; } Array Var(const Array& a, const OptionalAxes& axis, bool keepdims) { // TODO(hvy): Consider allowing device implementations. Axes sorted_axis = internal::GetSortedAxesOrAll(axis, a.ndim()); Dtype mean_out = PromoteInt2Float(a.dtype()); // TODO(kshitij12345): remove once subtract allows mixed types. Array diff = a.AsType(mean_out, true) - Mean(a, sorted_axis, true); return Mean(diff * diff, sorted_axis, keepdims); } } // namespace chainerx <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // Name: stcdlg.cpp // Purpose: Implementation of class wxExSTCEntryDialog // Author: Anton van Wezenbeek // Created: 2009-11-18 // RCS-ID: $Id$ // Copyright: (c) 2009 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/extension/stcdlg.h> #include <wx/extension/stc.h> #if wxUSE_GUI BEGIN_EVENT_TABLE(wxExSTCEntryDialog, wxExDialog) EVT_MENU(wxID_FIND, wxExSTCEntryDialog::OnCommand) END_EVENT_TABLE() wxExSTCEntryDialog::wxExSTCEntryDialog(wxWindow* parent, const wxString& caption, const wxString& text, const wxString& prompt, long button_style, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name) : wxExDialog(parent, caption, button_style, id, pos, size, style, name) { if (!prompt.empty()) { AddUserSizer(CreateTextSizer(prompt), wxSizerFlags().Center()); } m_STC = new wxExSTC( this, text, wxExSTC::STC_MENU_SIMPLE | wxExSTC::STC_MENU_FIND, wxID_ANY, pos, size); // Override defaults from config. m_STC->SetEdgeMode(wxSTC_EDGE_NONE); m_STC->ResetMargins(); m_STC->SetViewEOL(false); m_STC->SetViewWhiteSpace(wxSTC_WS_INVISIBLE); if ((button_style & wxCANCEL) == 0 && (button_style & wxNO) == 0) { // You did not specify one of these buttons, // so you cannot cancel the operation. // Therefore make the component readonly. m_STC->SetReadOnly(true); } AddUserSizer(m_STC); LayoutSizers(); } const wxString wxExSTCEntryDialog::GetLexer() const { return m_STC->GetFileName().GetLexer().GetScintillaLexer(); } const wxString wxExSTCEntryDialog::GetText() const { return m_STC->GetText(); } wxCharBuffer wxExSTCEntryDialog::GetTextRaw() const { return m_STC->GetTextRaw(); } void wxExSTCEntryDialog::OnCommand(wxCommandEvent& command) { switch (command.GetId()) { case wxID_FIND: wxPostEvent(wxTheApp->GetTopWindow(), command); break; default: wxFAIL; } } void wxExSTCEntryDialog::SetLexer(const wxString& lexer) { m_STC->SetLexer(lexer); } void wxExSTCEntryDialog::SetText(const wxString& text, bool reset_lexer) { const bool readonly = m_STC->GetReadOnly(); if (readonly) { m_STC->SetReadOnly(false); } m_STC->SetText(text); if (readonly) { m_STC->SetReadOnly(true); } if (reset_lexer) { if (!GetLexer().empty()) { SetLexer(wxEmptyString); } } } #endif // wxUSE_GUI <commit_msg>added replace as well<commit_after>//////////////////////////////////////////////////////////////////////////////// // Name: stcdlg.cpp // Purpose: Implementation of class wxExSTCEntryDialog // Author: Anton van Wezenbeek // Created: 2009-11-18 // RCS-ID: $Id$ // Copyright: (c) 2009 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/extension/stcdlg.h> #include <wx/extension/stc.h> #if wxUSE_GUI BEGIN_EVENT_TABLE(wxExSTCEntryDialog, wxExDialog) EVT_MENU(wxID_FIND, wxExSTCEntryDialog::OnCommand) EVT_MENU(wxID_REPLACE, wxExSTCEntryDialog::OnCommand) END_EVENT_TABLE() wxExSTCEntryDialog::wxExSTCEntryDialog(wxWindow* parent, const wxString& caption, const wxString& text, const wxString& prompt, long button_style, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name) : wxExDialog(parent, caption, button_style, id, pos, size, style, name) { if (!prompt.empty()) { AddUserSizer(CreateTextSizer(prompt), wxSizerFlags().Center()); } m_STC = new wxExSTC( this, text, wxExSTC::STC_MENU_SIMPLE | wxExSTC::STC_MENU_FIND | wxExSTC::STC_MENU_REPLACE, wxID_ANY, pos, size); // Override defaults from config. m_STC->SetEdgeMode(wxSTC_EDGE_NONE); m_STC->ResetMargins(); m_STC->SetViewEOL(false); m_STC->SetViewWhiteSpace(wxSTC_WS_INVISIBLE); if ((button_style & wxCANCEL) == 0 && (button_style & wxNO) == 0) { // You did not specify one of these buttons, // so you cannot cancel the operation. // Therefore make the component readonly. m_STC->SetReadOnly(true); } AddUserSizer(m_STC); LayoutSizers(); } const wxString wxExSTCEntryDialog::GetLexer() const { return m_STC->GetFileName().GetLexer().GetScintillaLexer(); } const wxString wxExSTCEntryDialog::GetText() const { return m_STC->GetText(); } wxCharBuffer wxExSTCEntryDialog::GetTextRaw() const { return m_STC->GetTextRaw(); } void wxExSTCEntryDialog::OnCommand(wxCommandEvent& command) { switch (command.GetId()) { case wxID_FIND: case wxID_REPLACE: wxPostEvent(wxTheApp->GetTopWindow(), command); break; default: wxFAIL; } } void wxExSTCEntryDialog::SetLexer(const wxString& lexer) { m_STC->SetLexer(lexer); } void wxExSTCEntryDialog::SetText(const wxString& text, bool reset_lexer) { const bool readonly = m_STC->GetReadOnly(); if (readonly) { m_STC->SetReadOnly(false); } m_STC->SetText(text); if (readonly) { m_STC->SetReadOnly(true); } if (reset_lexer) { if (!GetLexer().empty()) { SetLexer(wxEmptyString); } } } #endif // wxUSE_GUI <|endoftext|>
<commit_before>//@author A0094446X #include "stdafx.h" #include "CppUnitTest.h" #include "You-GUI\main_window.h" #include "You-GUI\system_tray_manager.h" #include "You-QueryEngine\api.h" #include "You-GUI\task_panel_manager.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; using Task = You::Controller::Task; using TaskList = You::Controller::TaskList; using Date = boost::gregorian::date; namespace You { namespace GUI { namespace UnitTests { QApplication *app; // Simulate running the main() function // Sets up the logging facility and the Qt event loop TEST_MODULE_INITIALIZE(ModuleInitialize) { int argc = 1; char *argv[] = { "You.exe" }; app = new QApplication(argc, argv); } // Cleans up what we set up TEST_MODULE_CLEANUP(ModuleCleanup) { app->quit(); delete app; } TEST_CLASS(MainWindowTests) { public: TEST_METHOD(isMainWindowVisible) { MainWindow w; Assert::IsTrue(w.isVisible()); } TEST_METHOD(isCentralWidgetVisible) { MainWindow w; Assert::IsTrue(w.ui.centralWidget->isVisible()); } TEST_METHOD(isTaskPanelVisible) { MainWindow w; Assert::IsTrue(w.ui.taskTreePanel->isVisible()); } TEST_METHOD(isCommandEnterButtonVisible) { MainWindow w; Assert::IsTrue(w.ui.commandEnterButton->isVisible()); } TEST_METHOD(isCommandInputBoxVisible) { MainWindow w; Assert::IsTrue(w.ui.commandInputBox->isVisible()); } TEST_METHOD(isStatusBarVisible) { MainWindow w; Assert::IsTrue(w.ui.statusBar->isVisible()); } TEST_METHOD(isStatusIconVisible) { MainWindow w; Assert::IsTrue(w.ui.statusIcon->isVisible()); } TEST_METHOD(isStatusMessageVisible) { MainWindow w; Assert::IsTrue(w.ui.statusMessage->isVisible()); } TEST_METHOD(isMainToolBarHidden) { MainWindow w; Assert::IsFalse(w.ui.mainToolBar->isVisible()); } TEST_METHOD(isMenuBarHidden) { MainWindow w; Assert::IsFalse(w.ui.menuBar->isVisible()); } TEST_METHOD(addSingleTaskCount) { MainWindow w; w.clearTasks(); w.ui.commandInputBox->setText(QString("/add test by Nov 20")); w.commandEnterPressed(); Assert::IsTrue(w.ui.taskTreePanel->topLevelItemCount() == 1); } TEST_METHOD(addSingleTaskContent) { MainWindow w; w.clearTasks(); w.ui.commandInputBox->setText(QString("/add test by Nov 20")); w.commandEnterPressed(); QTreeWidgetItem item = *w.ui.taskTreePanel->topLevelItem(0); int column1 = QString::compare(item.text(1), QString("0")); int column2 = QString::compare(item.text(2), QString("test")); int column3 = QString::compare( item.text(3), QString("2020-Nov-01 00:00:00")); int column4 = QString::compare(item.text(4), QString("Normal")); Assert::IsTrue((column1 == 0) && (column2 == 0) && (column3 == 0) && (column4 == 0)); } TEST_METHOD(testDueToday1) { MainWindow w; Task::Time dl = boost::posix_time::second_clock::local_time(); Assert::IsTrue(MainWindow::TaskPanelManager::isDueAfter(dl, 0)); } TEST_METHOD(testDueToday2) { MainWindow w; Task::Time dl = boost::posix_time::second_clock::local_time(); dl += boost::posix_time::hours(24) + boost::posix_time::minutes(1); Assert::IsFalse(MainWindow::TaskPanelManager::isDueAfter(dl, 0)); } TEST_METHOD(testDueToday3) { MainWindow w; Task::Time dl = boost::posix_time::second_clock::local_time(); dl -= (boost::posix_time::hours(24) + boost::posix_time::minutes(1)); Assert::IsFalse(MainWindow::TaskPanelManager::isDueAfter(dl, 0)); } TEST_METHOD(deleteSingleTaskCount) { MainWindow w; w.clearTasks(); w.ui.commandInputBox->setText(QString("/add test by Nov 20")); w.commandEnterPressed(); w.ui.commandInputBox->setText(QString("/add test2 by Nov 20")); w.commandEnterPressed(); w.ui.commandInputBox->setText(QString("/delete 1")); w.commandEnterPressed(); Assert::IsTrue(w.ui.taskTreePanel->topLevelItemCount() == 1); } TEST_METHOD(deleteSingleTaskFind) { MainWindow w; w.clearTasks(); w.ui.commandInputBox->setText(QString("/add test by Nov 20")); w.commandEnterPressed(); w.ui.commandInputBox->setText(QString("/add test2 by Nov 20")); w.commandEnterPressed(); w.ui.commandInputBox->setText(QString("/delete 1")); w.commandEnterPressed(); Assert::IsTrue(w.ui.taskTreePanel->findItems( QString("1"), Qt::MatchExactly, 1).size() == 0); } }; } // namespace UnitTests } // namespace GUI } // namespace You <commit_msg>Added a few more date tests.<commit_after>//@author A0094446X #include "stdafx.h" #include "CppUnitTest.h" #include "You-GUI\main_window.h" #include "You-GUI\system_tray_manager.h" #include "You-QueryEngine\api.h" #include "You-GUI\task_panel_manager.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; using Task = You::Controller::Task; using TaskList = You::Controller::TaskList; using Date = boost::gregorian::date; namespace You { namespace GUI { namespace UnitTests { QApplication *app; // Simulate running the main() function // Sets up the logging facility and the Qt event loop TEST_MODULE_INITIALIZE(ModuleInitialize) { int argc = 1; char *argv[] = { "You.exe" }; app = new QApplication(argc, argv); } // Cleans up what we set up TEST_MODULE_CLEANUP(ModuleCleanup) { app->quit(); delete app; } TEST_CLASS(MainWindowTests) { public: TEST_METHOD_INITIALIZE(init) { Sleep(20); } TEST_METHOD(isMainWindowVisible) { MainWindow w; Assert::IsTrue(w.isVisible()); } TEST_METHOD(isCentralWidgetVisible) { MainWindow w; Assert::IsTrue(w.ui.centralWidget->isVisible()); } TEST_METHOD(isTaskPanelVisible) { MainWindow w; Assert::IsTrue(w.ui.taskTreePanel->isVisible()); } TEST_METHOD(isCommandEnterButtonVisible) { MainWindow w; Assert::IsTrue(w.ui.commandEnterButton->isVisible()); } TEST_METHOD(isCommandInputBoxVisible) { MainWindow w; Assert::IsTrue(w.ui.commandInputBox->isVisible()); } TEST_METHOD(isStatusBarVisible) { MainWindow w; Assert::IsTrue(w.ui.statusBar->isVisible()); } TEST_METHOD(isStatusIconVisible) { MainWindow w; Assert::IsTrue(w.ui.statusIcon->isVisible()); } TEST_METHOD(isStatusMessageVisible) { MainWindow w; Assert::IsTrue(w.ui.statusMessage->isVisible()); } TEST_METHOD(isMainToolBarHidden) { MainWindow w; Assert::IsFalse(w.ui.mainToolBar->isVisible()); } TEST_METHOD(isMenuBarHidden) { MainWindow w; Assert::IsFalse(w.ui.menuBar->isVisible()); } TEST_METHOD(addSingleTaskCount) { MainWindow w; w.clearTasks(); w.ui.commandInputBox->setText(QString("/add test by Nov 20")); w.commandEnterPressed(); Assert::IsTrue(w.ui.taskTreePanel->topLevelItemCount() == 1); } TEST_METHOD(addSingleTaskContent) { MainWindow w; w.clearTasks(); w.ui.commandInputBox->setText(QString("/add test by Nov 20")); w.commandEnterPressed(); QTreeWidgetItem item = *w.ui.taskTreePanel->topLevelItem(0); int column1 = QString::compare(item.text(1), QString("0")); int column2 = QString::compare(item.text(2), QString("test")); int column3 = QString::compare( item.text(3), QString("2020-Nov-01 00:00:00")); int column4 = QString::compare(item.text(4), QString("Normal")); Assert::IsTrue((column1 == 0) && (column2 == 0) && (column3 == 0) && (column4 == 0)); } TEST_METHOD(testDueToday1) { MainWindow w; Task::Time dl = boost::posix_time::second_clock::local_time(); Assert::IsTrue(MainWindow::TaskPanelManager::isDueAfter(dl, 0)); } TEST_METHOD(testDueToday2) { MainWindow w; Task::Time dl = boost::posix_time::second_clock::local_time(); dl += boost::posix_time::hours(24) + boost::posix_time::minutes(1); Assert::IsFalse(MainWindow::TaskPanelManager::isDueAfter(dl, 0)); } TEST_METHOD(testDueToday3) { MainWindow w; Task::Time dl = boost::posix_time::second_clock::local_time(); dl -= (boost::posix_time::hours(24) + boost::posix_time::minutes(1)); Assert::IsFalse(MainWindow::TaskPanelManager::isDueAfter(dl, 0)); } TEST_METHOD(testPastDue1) { MainWindow w; Task::Time dl = boost::posix_time::second_clock::local_time(); dl -= boost::posix_time::minutes(1); Assert::IsTrue(MainWindow::TaskPanelManager::isPastDue(dl)); } TEST_METHOD(testPastDue2) { MainWindow w; Task::Time dl = boost::posix_time::second_clock::local_time(); dl -= (boost::posix_time::hours(24) + boost::posix_time::minutes(1)); Assert::IsTrue(MainWindow::TaskPanelManager::isPastDue(dl)); } TEST_METHOD(deleteSingleTaskCount) { MainWindow w; w.clearTasks(); w.ui.commandInputBox->setText(QString("/add test by Nov 20")); w.commandEnterPressed(); w.ui.commandInputBox->setText(QString("/add test2 by Nov 20")); w.commandEnterPressed(); w.ui.commandInputBox->setText(QString("/delete 1")); w.commandEnterPressed(); Assert::IsTrue(w.ui.taskTreePanel->topLevelItemCount() == 1); } TEST_METHOD(deleteSingleTaskFind) { MainWindow w; w.clearTasks(); w.ui.commandInputBox->setText(QString("/add test by Nov 20")); w.commandEnterPressed(); w.ui.commandInputBox->setText(QString("/add test2 by Nov 20")); w.commandEnterPressed(); w.ui.commandInputBox->setText(QString("/delete 1")); w.commandEnterPressed(); Assert::IsTrue(w.ui.taskTreePanel->findItems( QString("1"), Qt::MatchExactly, 1).size() == 0); } }; } // namespace UnitTests } // namespace GUI } // namespace You <|endoftext|>
<commit_before>/** * Behaviours - UML-like graphic programming language * Copyright (C) 2013 Coralbits SL & AISoy Robotics. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <Python.h> #include <ab/action.h> #include <ab/factory.h> #include <ab/manager.h> #include <ab/log.h> #include <ab/object_basic.h> namespace AB{ namespace Python3{ static PyObject *object2pyobject(AB::Object &obj); static Object to_object(PyObject *obj); extern Manager *ab_module_manager; static PyObject *manager_error; typedef struct{ PyObject_HEAD Node *node; } NodeObject; static PyObject *node_getattr(PyObject *self, char *attr){ NodeObject *oself=(NodeObject*)self; try{ auto v=oself->node->attr(attr); return object2pyobject(v); } catch(const AB::attribute_not_found &a){ return NULL; } } static int node_setattr(PyObject *self, char *attr, PyObject *value){ NodeObject *oself=(NodeObject*)self; try{ oself->node->setAttr(attr, to_object(value)); return 0; } catch(const AB::attribute_not_found &a){ return -1; } } static PyObject *node_dir(PyObject *self){ NodeObject *oself=(NodeObject*)self; try{ auto attrlist=oself->node->attrList(); auto I=attrlist.begin(), endI=attrlist.end(); PyObject *ret=PyList_New(attrlist.size()); Py_INCREF(ret); int i; for(i=0;I!=endI;++i,++I){ PyObject *name=PyUnicode_FromString((*I).c_str()); Py_INCREF(name); PyList_SetItem(ret, i, name); } return ret; } catch(const AB::attribute_not_found &a){ return NULL; } } static PyTypeObject NodeObjectType = { PyVarObject_HEAD_INIT(NULL,0) "ab.node", /*tp_name*/ sizeof(NodeObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ 0, /*tp_dealloc*/ 0, /*tp_print*/ node_getattr, /*tp_getattr*/ node_setattr, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "Node objects", /* tp_doc */ }; static PyObject *object2pyobject(AB::Object &obj){ auto t=obj->type(); if (t==AB::Integer::type) return PyLong_FromLong(object2int(obj)); if (t==AB::Float::type) return PyFloat_FromDouble(object2float(obj)); if (t==AB::String::type) return PyUnicode_FromString(object2string(obj).c_str()); try{ NodeObject *no=PyObject_New(NodeObject, &NodeObjectType); no->node=object2node(obj); return (PyObject*)(no); } catch(const AB::object_not_convertible &exc){ } DEBUG("Create node %s failed", obj->type()); return NULL; } static Object to_object(PyObject *obj){ if (PyBool_Check(obj)) return AB::to_object( obj == Py_True ); if (PyFloat_Check(obj)) return AB::to_object( PyFloat_AsDouble(obj) ); if (PyLong_Check(obj)) return AB::to_object( (int)PyLong_AsLong(obj) ); if (PyUnicode_Check(obj)) return AB::to_object( PyUnicode_AsUTF8(obj) ); throw(AB::object_not_convertible( obj->ob_type->tp_name, "Object")); } /// Define a new class for the manager. static PyObject *ab_manager_resolve(PyObject *self, PyObject *args){ const char *name; if (!PyArg_ParseTuple(args, "s", &name)){ return NULL; } try{ AB::Object n( ab_module_manager->resolve(name) ); return object2pyobject(n); } catch(const AB::attribute_not_found &e){ PyErr_SetString(manager_error, (std::string("Could not resolve symbol ")+name).c_str()); return NULL; } } static PyObject *ab_manager_list_nodes(PyObject *self){ auto nodelist=ab_module_manager->getNodes(); auto typelist=AB::Factory::list(); PyObject *ret=PyList_New(nodelist.size() + typelist.size()); Py_INCREF(ret); { auto I=nodelist.begin(), endI=nodelist.end(); int i; for(i=0;I!=endI;++i,++I){ PyObject *name=PyUnicode_FromString((*I)->name().c_str()); Py_INCREF(name); PyList_SetItem(ret, i, name); } } int b=nodelist.size(); { auto I=typelist.begin(), endI=typelist.end(); int i; for(i=0;I!=endI;++i,++I){ PyObject *name=PyUnicode_FromString((*I).c_str()); Py_INCREF(name); PyList_SetItem(ret, b + i, name); } } return ret; } static PyMethodDef ab_methods[] = { {"resolve", ab_manager_resolve, METH_VARARGS, NULL}, {"list_nodes", (PyCFunction)ab_manager_list_nodes, METH_NOARGS, NULL}, {NULL, NULL, 0, NULL} }; static struct PyModuleDef ab_module = { PyModuleDef_HEAD_INIT, "ab", "Behaviours interface module", -1, ab_methods }; static struct PyMethodDef node_methods[] = { { "__dir__", (PyCFunction)node_dir, METH_NOARGS, NULL}, {NULL, NULL, 0, NULL} }; PyObject *PyInit_ab(void){ auto m = PyModule_Create(&ab_module); if (!m) return NULL; manager_error = PyErr_NewException("ab.exception", NULL, NULL); Py_INCREF(manager_error); PyModule_AddObject(m, "exception", manager_error); NodeObjectType.tp_new = PyType_GenericNew; NodeObjectType.tp_methods = node_methods; if (PyType_Ready(&NodeObjectType) < 0) return NULL; //Py_INCREF(&NodeObjectType); //PyModule_AddObject(m, "Node", (PyObject*)&NodeObjectType); return m; } } } <commit_msg>Fixed support for python3.2, do not use PyUnicode_AsUTF8 (just emulate it).<commit_after>/** * Behaviours - UML-like graphic programming language * Copyright (C) 2013 Coralbits SL & AISoy Robotics. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <Python.h> #include <wchar.h> #include <ab/action.h> #include <ab/factory.h> #include <ab/manager.h> #include <ab/log.h> #include <ab/object_basic.h> namespace AB{ namespace Python3{ static PyObject *object2pyobject(AB::Object &obj); static Object to_object(PyObject *obj); extern Manager *ab_module_manager; static PyObject *manager_error; typedef struct{ PyObject_HEAD Node *node; } NodeObject; static PyObject *node_getattr(PyObject *self, char *attr){ NodeObject *oself=(NodeObject*)self; try{ auto v=oself->node->attr(attr); return object2pyobject(v); } catch(const AB::attribute_not_found &a){ return NULL; } } static int node_setattr(PyObject *self, char *attr, PyObject *value){ NodeObject *oself=(NodeObject*)self; try{ oself->node->setAttr(attr, to_object(value)); return 0; } catch(const AB::attribute_not_found &a){ return -1; } } static PyObject *node_dir(PyObject *self){ NodeObject *oself=(NodeObject*)self; try{ auto attrlist=oself->node->attrList(); auto I=attrlist.begin(), endI=attrlist.end(); PyObject *ret=PyList_New(attrlist.size()); Py_INCREF(ret); int i; for(i=0;I!=endI;++i,++I){ PyObject *name=PyUnicode_FromString((*I).c_str()); Py_INCREF(name); PyList_SetItem(ret, i, name); } return ret; } catch(const AB::attribute_not_found &a){ return NULL; } } static PyTypeObject NodeObjectType = { PyVarObject_HEAD_INIT(NULL,0) "ab.node", /*tp_name*/ sizeof(NodeObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ 0, /*tp_dealloc*/ 0, /*tp_print*/ node_getattr, /*tp_getattr*/ node_setattr, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "Node objects", /* tp_doc */ }; static PyObject *object2pyobject(AB::Object &obj){ auto t=obj->type(); if (t==AB::Integer::type) return PyLong_FromLong(object2int(obj)); if (t==AB::Float::type) return PyFloat_FromDouble(object2float(obj)); if (t==AB::String::type) return PyUnicode_FromString(object2string(obj).c_str()); try{ NodeObject *no=PyObject_New(NodeObject, &NodeObjectType); no->node=object2node(obj); return (PyObject*)(no); } catch(const AB::object_not_convertible &exc){ } DEBUG("Create node %s failed", obj->type()); return NULL; } static Object to_object(PyObject *obj){ if (PyBool_Check(obj)) return AB::to_object( obj == Py_True ); if (PyFloat_Check(obj)) return AB::to_object( PyFloat_AsDouble(obj) ); if (PyLong_Check(obj)) return AB::to_object( (int)PyLong_AsLong(obj) ); if (PyUnicode_Check(obj)){ Py_ssize_t size; wchar_t *str=PyUnicode_AsWideCharString(obj, &size); char str8[wcslen(str) + 1]; wcstombs( str8, str, wcslen(str) ); PyMem_Free(str); return AB::to_object( std::string(str8) ); } throw(AB::object_not_convertible( obj->ob_type->tp_name, "Object")); } /// Define a new class for the manager. static PyObject *ab_manager_resolve(PyObject *self, PyObject *args){ const char *name; if (!PyArg_ParseTuple(args, "s", &name)){ return NULL; } try{ AB::Object n( ab_module_manager->resolve(name) ); return object2pyobject(n); } catch(const AB::attribute_not_found &e){ PyErr_SetString(manager_error, (std::string("Could not resolve symbol ")+name).c_str()); return NULL; } } static PyObject *ab_manager_list_nodes(PyObject *self){ auto nodelist=ab_module_manager->getNodes(); auto typelist=AB::Factory::list(); PyObject *ret=PyList_New(nodelist.size() + typelist.size()); Py_INCREF(ret); { auto I=nodelist.begin(), endI=nodelist.end(); int i; for(i=0;I!=endI;++i,++I){ PyObject *name=PyUnicode_FromString((*I)->name().c_str()); Py_INCREF(name); PyList_SetItem(ret, i, name); } } int b=nodelist.size(); { auto I=typelist.begin(), endI=typelist.end(); int i; for(i=0;I!=endI;++i,++I){ PyObject *name=PyUnicode_FromString((*I).c_str()); Py_INCREF(name); PyList_SetItem(ret, b + i, name); } } return ret; } static PyMethodDef ab_methods[] = { {"resolve", ab_manager_resolve, METH_VARARGS, NULL}, {"list_nodes", (PyCFunction)ab_manager_list_nodes, METH_NOARGS, NULL}, {NULL, NULL, 0, NULL} }; static struct PyModuleDef ab_module = { PyModuleDef_HEAD_INIT, "ab", "Behaviours interface module", -1, ab_methods }; static struct PyMethodDef node_methods[] = { { "__dir__", (PyCFunction)node_dir, METH_NOARGS, NULL}, {NULL, NULL, 0, NULL} }; PyObject *PyInit_ab(void){ auto m = PyModule_Create(&ab_module); if (!m) return NULL; manager_error = PyErr_NewException("ab.exception", NULL, NULL); Py_INCREF(manager_error); PyModule_AddObject(m, "exception", manager_error); NodeObjectType.tp_new = PyType_GenericNew; NodeObjectType.tp_methods = node_methods; if (PyType_Ready(&NodeObjectType) < 0) return NULL; //Py_INCREF(&NodeObjectType); //PyModule_AddObject(m, "Node", (PyObject*)&NodeObjectType); return m; } } } <|endoftext|>
<commit_before>// // Copyright © 2017 Lennart Oymanns. All rights reserved. // #include <iostream> #include <map> #include "Error.h" #include "Factor.hpp" #include "Function.hpp" #include "Lexer.hpp" #include "Number.hpp" #include "Parser.hpp" #include "Power.hpp" #include "Summand.hpp" #include "UnaryMinus.hpp" #include "Variable.hpp" using namespace Equation; const Token Parser::NoToken(Token::Type_t::End, "NoToken", 0); NodePtr Parser::Parse(const std::string &expr) { Lexer lexer(expr); tokens = lexer.TokenList(); index = 0; auto nodes = parseSummand(); auto token = readNextToken(); if (token.Type != Token::Type_t::End) { if (token.Type == Token::Type_t::Operator && token.Value == ")") { throw InputEquationError(token.pos - 1, "unmatched ')'"); } if (token.Type == Token::Type_t::Operator && token.Value == "^") { throw InputEquationError(token.pos - 1, "multiple '^' not supported"); } throw InputEquationError(token.pos - 1, "expected end of expression"); } return nodes; } NodePtr Parser::parseSummand() { auto first = parseFactor(); auto summand = std::make_shared<Summand>(first); bool valid = false; auto token = readNextToken(); while (token.Type == Token::Type_t::Operator && (token.Value == "+" || token.Value == "-")) { auto next = parseFactor(); if (token.Value == "+") { summand->AddOp1(next); } else { auto m = std::make_shared<UnaryMinus>(next); summand->AddOp1(m); } valid = true; token = readNextToken(); } unreadToken(); if (valid) { return summand; } return first; } NodePtr Parser::parseFactor() { auto first = parsePower(); auto factor = std::make_shared<Factor>(first); bool valid = false; auto token = readNextToken(); while (token.Type == Token::Type_t::Operator && (token.Value == "*" || token.Value == "/")) { auto next = parsePower(); if (token.Value == "*") { factor->AddOp1(next); } else { auto d = std::make_shared<Power>(next, std::make_shared<Number>(-1l)); factor->AddOp1(d); // factor->AddOp2(next); } valid = true; token = readNextToken(); } unreadToken(); if (valid) { return factor; } return first; } NodePtr Parser::parsePower() { auto base = parseNumber(); auto token = readNextToken(); if (token.Type == Token::Type_t::Operator && token.Value == "^") { auto exponent = parseNumber(); auto power = std::make_shared<Power>(base, exponent); return power; } unreadToken(); return base; } NodePtr Parser::parseNumber() { const Token &token = readNextToken(); if (token.Type == Token::Type_t::Operator && token.Value == "(") { auto v = parseSummand(); auto t = readNextToken(); if (t.Type != Token::Type_t::Operator || token.Value == ")") { throw InputEquationError(t.pos, "missing ')'"); } return v; } if (token.Type == Token::Type_t::Operator && token.Value == "-") { return std::make_shared<UnaryMinus>(parsePower()); } if (token.Type == Token::Type_t::String) { const Token &next = readNextToken(); unreadToken(); if (next.Type == Token::Type_t::Operator && next.Value == "(") { // function unreadToken(); // unread function name return parseFunction(); } return std::make_shared<Variable>(token.Value); } if (token.Type == Token::Type_t::Number) { return std::make_shared<Number>(Number(token.Value)); } if (token.Type == Token::Type_t::End) { throw InputEquationError(token.pos, "unexpected end of expression"); } throw InputEquationError(token.pos, "unknown token type"); return 0; } NodePtr Parser::parseFunction() { auto name = readNextToken(); if (name.Type != Token::Type_t::String) { throw InputEquationError(name.pos, "not a valid function name"); } auto open = readNextToken(); if (open.Type != Token::Type_t::Operator || open.Value != "(") { throw InputEquationError(open.pos, "missing '(' after function"); } auto first = parseSummand(); auto fun = std::make_shared<Function>(name.Value); fun->AddArg(first); auto token = readNextToken(); while (token.Type == Token::Type_t::Comma && token.Value == ",") { auto next = parseSummand(); fun->AddArg(next); token = readNextToken(); } if (token.Type != Token::Type_t::Operator || token.Value != ")") { throw InputEquationError(token.pos, "missing ')'"); } return fun; } const Token &Parser::readNextToken() { if (index >= tokens.size()) { return Parser::NoToken; } index += 1; return tokens[index - 1]; } void Parser::unreadToken() { if (index == 0) { return; } index -= 1; } <commit_msg>handle exceptions in parsing of numbers<commit_after>// // Copyright © 2017 Lennart Oymanns. All rights reserved. // #include <iostream> #include <map> #include "Error.h" #include "Factor.hpp" #include "Function.hpp" #include "Lexer.hpp" #include "Number.hpp" #include "Parser.hpp" #include "Power.hpp" #include "Summand.hpp" #include "UnaryMinus.hpp" #include "Variable.hpp" using namespace Equation; const Token Parser::NoToken(Token::Type_t::End, "NoToken", 0); NodePtr Parser::Parse(const std::string &expr) { Lexer lexer(expr); tokens = lexer.TokenList(); index = 0; auto nodes = parseSummand(); auto token = readNextToken(); if (token.Type != Token::Type_t::End) { if (token.Type == Token::Type_t::Operator && token.Value == ")") { throw InputEquationError(token.pos - 1, "unmatched ')'"); } if (token.Type == Token::Type_t::Operator && token.Value == "^") { throw InputEquationError(token.pos - 1, "multiple '^' not supported"); } throw InputEquationError(token.pos - 1, "expected end of expression"); } return nodes; } NodePtr Parser::parseSummand() { auto first = parseFactor(); auto summand = std::make_shared<Summand>(first); bool valid = false; auto token = readNextToken(); while (token.Type == Token::Type_t::Operator && (token.Value == "+" || token.Value == "-")) { auto next = parseFactor(); if (token.Value == "+") { summand->AddOp1(next); } else { auto m = std::make_shared<UnaryMinus>(next); summand->AddOp1(m); } valid = true; token = readNextToken(); } unreadToken(); if (valid) { return summand; } return first; } NodePtr Parser::parseFactor() { auto first = parsePower(); auto factor = std::make_shared<Factor>(first); bool valid = false; auto token = readNextToken(); while (token.Type == Token::Type_t::Operator && (token.Value == "*" || token.Value == "/")) { auto next = parsePower(); if (token.Value == "*") { factor->AddOp1(next); } else { auto d = std::make_shared<Power>(next, std::make_shared<Number>(-1l)); factor->AddOp1(d); // factor->AddOp2(next); } valid = true; token = readNextToken(); } unreadToken(); if (valid) { return factor; } return first; } NodePtr Parser::parsePower() { auto base = parseNumber(); auto token = readNextToken(); if (token.Type == Token::Type_t::Operator && token.Value == "^") { auto exponent = parseNumber(); auto power = std::make_shared<Power>(base, exponent); return power; } unreadToken(); return base; } NodePtr Parser::parseNumber() { const Token &token = readNextToken(); if (token.Type == Token::Type_t::Operator && token.Value == "(") { auto v = parseSummand(); auto t = readNextToken(); if (t.Type != Token::Type_t::Operator || token.Value == ")") { throw InputEquationError(t.pos, "missing ')'"); } return v; } if (token.Type == Token::Type_t::Operator && token.Value == "-") { return std::make_shared<UnaryMinus>(parsePower()); } if (token.Type == Token::Type_t::String) { const Token &next = readNextToken(); unreadToken(); if (next.Type == Token::Type_t::Operator && next.Value == "(") { // function unreadToken(); // unread function name return parseFunction(); } return std::make_shared<Variable>(token.Value); } if (token.Type == Token::Type_t::Number) { try { return std::make_shared<Number>(Number(token.Value)); } catch (const std::exception &e) { throw InputEquationError(token.pos, e.what()); } } if (token.Type == Token::Type_t::End) { throw InputEquationError(token.pos, "unexpected end of expression"); } throw InputEquationError(token.pos, "unknown token type"); return 0; } NodePtr Parser::parseFunction() { auto name = readNextToken(); if (name.Type != Token::Type_t::String) { throw InputEquationError(name.pos, "not a valid function name"); } auto open = readNextToken(); if (open.Type != Token::Type_t::Operator || open.Value != "(") { throw InputEquationError(open.pos, "missing '(' after function"); } auto first = parseSummand(); auto fun = std::make_shared<Function>(name.Value); fun->AddArg(first); auto token = readNextToken(); while (token.Type == Token::Type_t::Comma && token.Value == ",") { auto next = parseSummand(); fun->AddArg(next); token = readNextToken(); } if (token.Type != Token::Type_t::Operator || token.Value != ")") { throw InputEquationError(token.pos, "missing ')'"); } return fun; } const Token &Parser::readNextToken() { if (index >= tokens.size()) { return Parser::NoToken; } index += 1; return tokens[index - 1]; } void Parser::unreadToken() { if (index == 0) { return; } index -= 1; } <|endoftext|>
<commit_before>// torBlock.cpp : Defines the entry point for the DLL application. // #include "bzfsAPI.h" #include <string> #include <algorithm> #include <sstream> #include <stdarg.h> #include <vector> #include <stdio.h> #include <assert.h> #include <map> #include <vector> inline std::string tolower(const std::string& s) { std::string trans = s; for (std::string::iterator i=trans.begin(), end=trans.end(); i!=end; ++i) *i = ::tolower(*i); return trans; } std::string format(const char* fmt, ...) { va_list args; va_start(args, fmt); char temp[2048]; vsprintf(temp,fmt, args); std::string result = temp; va_end(args); return result; } std::vector<std::string> tokenize(const std::string& in, const std::string &delims, const int maxTokens, const bool useQuotes){ std::vector<std::string> tokens; int numTokens = 0; bool inQuote = false; std::ostringstream currentToken; std::string::size_type pos = in.find_first_not_of(delims); int currentChar = (pos == std::string::npos) ? -1 : in[pos]; bool enoughTokens = (maxTokens && (numTokens >= (maxTokens-1))); while (pos != std::string::npos && !enoughTokens) { // get next token bool tokenDone = false; bool foundSlash = false; currentChar = (pos < in.size()) ? in[pos] : -1; while ((currentChar != -1) && !tokenDone){ tokenDone = false; if (delims.find(currentChar) != std::string::npos && !inQuote) { // currentChar is a delim pos ++; break; // breaks out of while loop } if (!useQuotes){ currentToken << char(currentChar); } else { switch (currentChar){ case '\\' : // found a backslash if (foundSlash){ currentToken << char(currentChar); foundSlash = false; } else { foundSlash = true; } break; case '\"' : // found a quote if (foundSlash){ // found \" currentToken << char(currentChar); foundSlash = false; } else { // found unescaped " if (inQuote){ // exiting a quote // finish off current token tokenDone = true; inQuote = false; //slurp off one additional delimeter if possible if (pos+1 < in.size() && delims.find(in[pos+1]) != std::string::npos) { pos++; } } else { // entering a quote // finish off current token tokenDone = true; inQuote = true; } } break; default: if (foundSlash){ // don't care about slashes except for above cases currentToken << '\\'; foundSlash = false; } currentToken << char(currentChar); break; } } pos++; currentChar = (pos < in.size()) ? in[pos] : -1; } // end of getting a Token if (currentToken.str().size() > 0){ // if the token is something add to list tokens.push_back(currentToken.str()); currentToken.str(""); numTokens ++; } enoughTokens = (maxTokens && (numTokens >= (maxTokens-1))); if (enoughTokens){ break; } else{ pos = in.find_first_not_of(delims,pos); } } // end of getting all tokens -- either EOL or max tokens reached if (enoughTokens && pos != std::string::npos) { std::string lastToken = in.substr(pos); if (lastToken.size() > 0) tokens.push_back(lastToken); } return tokens; } BZ_GET_PLUGIN_VERSION std::string torMasterList("http://belegost.mit.edu/tor/status/authority"); double lastUpdateTime = -99999.0; double updateInterval = 3600.0; std::vector<std::string> exitNodes; class Handler : public bz_EventHandler { public: virtual void process ( bz_EventData *eventData ); }; Handler handler; class MyURLHandler: public bz_BaseURLHandler { public: std::string page; virtual void done ( const char* URL, void * data, unsigned int size, bool complete ) { char *str = (char*)malloc(size+1); memcpy(str,data,size); str[size] = 0; page += str; free(str); if (!complete) return; std::vector<std::string> tokes = tokenize(page,std::string("\n"),0,false); bool gotKey = false; for (unsigned int i = 0; i < tokes.size(); i++ ) { if (!gotKey) { if ( tokes[i] == "-----END RSA PUBLIC KEY-----") { gotKey = true; exitNodes.clear(); // only clear when we have a list } } else { if ( tokes[i].size() ) { std::vector<std::string> chunks = tokenize(tokes[i],std::string(" "),0,false); if ( chunks.size() > 1 ) { if ( chunks[0] == "r" && chunks.size() > 7 ) exitNodes.push_back(chunks[6]); } } } } } }; class mySlashCommand : public bz_CustomSlashCommandHandler { public: virtual bool handle ( int playerID, bz_ApiString command, bz_ApiString message, bz_APIStringList *params ) { bz_sendTextMessage(BZ_SERVER,playerID,"torBlock List"); for ( unsigned int i = 0; i < exitNodes.size(); i++ ) bz_sendTextMessage(BZ_SERVER,playerID,exitNodes[i].c_str()); return true; } }; mySlashCommand mySlash; MyURLHandler myURL; void updateTorList ( void ) { if ( bz_getCurrentTime() - lastUpdateTime >= updateInterval) { lastUpdateTime = bz_getCurrentTime(); myURL.page.clear(); bz_addURLJob(torMasterList.c_str(),&myURL); } } bool isTorAddress ( const char* addy ) { for ( unsigned int i = 0; i < exitNodes.size(); i++ ) { if (exitNodes[i] == addy) return true; } return false; } BZF_PLUGIN_CALL int bz_Load ( const char* /*commandLine*/ ) { bz_debugMessage(4,"torBlock plugin loaded"); bz_registerEvent(bz_eAllowPlayer,&handler); bz_registerEvent(bz_eTickEvent,&handler); bz_registerCustomSlashCommand("torlist",&mySlash); lastUpdateTime = -updateInterval * 2; return 0; } BZF_PLUGIN_CALL int bz_Unload ( void ) { bz_removeCustomSlashCommand("torlist"); bz_removeEvent(bz_eTickEvent,&handler); bz_removeEvent(bz_eAllowPlayer,&handler); bz_debugMessage(4,"torBlock plugin unloaded"); return 0; } void Handler::process ( bz_EventData *eventData ) { if (!eventData) return; switch (eventData->eventType) { case bz_eAllowPlayer: { bz_AllowPlayerEventData_V1 *data = (bz_AllowPlayerEventData_V1*)eventData; if (isTorAddress(data->ipAddress.c_str())) { data->allow = false; data->reason = "Proxy Network Ban"; } } break; case bz_eTickEvent: updateTorList(); break; default: break; } } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>Update the torBlock URL.<commit_after>// torBlock.cpp : Defines the entry point for the DLL application. // #include "bzfsAPI.h" #include <string> #include <algorithm> #include <sstream> #include <stdarg.h> #include <vector> #include <stdio.h> #include <assert.h> #include <map> #include <vector> inline std::string tolower(const std::string& s) { std::string trans = s; for (std::string::iterator i=trans.begin(), end=trans.end(); i!=end; ++i) *i = ::tolower(*i); return trans; } std::string format(const char* fmt, ...) { va_list args; va_start(args, fmt); char temp[2048]; vsprintf(temp,fmt, args); std::string result = temp; va_end(args); return result; } std::vector<std::string> tokenize(const std::string& in, const std::string &delims, const int maxTokens, const bool useQuotes){ std::vector<std::string> tokens; int numTokens = 0; bool inQuote = false; std::ostringstream currentToken; std::string::size_type pos = in.find_first_not_of(delims); int currentChar = (pos == std::string::npos) ? -1 : in[pos]; bool enoughTokens = (maxTokens && (numTokens >= (maxTokens-1))); while (pos != std::string::npos && !enoughTokens) { // get next token bool tokenDone = false; bool foundSlash = false; currentChar = (pos < in.size()) ? in[pos] : -1; while ((currentChar != -1) && !tokenDone){ tokenDone = false; if (delims.find(currentChar) != std::string::npos && !inQuote) { // currentChar is a delim pos ++; break; // breaks out of while loop } if (!useQuotes){ currentToken << char(currentChar); } else { switch (currentChar){ case '\\' : // found a backslash if (foundSlash){ currentToken << char(currentChar); foundSlash = false; } else { foundSlash = true; } break; case '\"' : // found a quote if (foundSlash){ // found \" currentToken << char(currentChar); foundSlash = false; } else { // found unescaped " if (inQuote){ // exiting a quote // finish off current token tokenDone = true; inQuote = false; //slurp off one additional delimeter if possible if (pos+1 < in.size() && delims.find(in[pos+1]) != std::string::npos) { pos++; } } else { // entering a quote // finish off current token tokenDone = true; inQuote = true; } } break; default: if (foundSlash){ // don't care about slashes except for above cases currentToken << '\\'; foundSlash = false; } currentToken << char(currentChar); break; } } pos++; currentChar = (pos < in.size()) ? in[pos] : -1; } // end of getting a Token if (currentToken.str().size() > 0){ // if the token is something add to list tokens.push_back(currentToken.str()); currentToken.str(""); numTokens ++; } enoughTokens = (maxTokens && (numTokens >= (maxTokens-1))); if (enoughTokens){ break; } else{ pos = in.find_first_not_of(delims,pos); } } // end of getting all tokens -- either EOL or max tokens reached if (enoughTokens && pos != std::string::npos) { std::string lastToken = in.substr(pos); if (lastToken.size() > 0) tokens.push_back(lastToken); } return tokens; } BZ_GET_PLUGIN_VERSION std::string torMasterList("http://moria.seul.org:9032/tor/status/authority"); double lastUpdateTime = -99999.0; double updateInterval = 3600.0; std::vector<std::string> exitNodes; class Handler : public bz_EventHandler { public: virtual void process ( bz_EventData *eventData ); }; Handler handler; class MyURLHandler: public bz_BaseURLHandler { public: std::string page; virtual void done ( const char* URL, void * data, unsigned int size, bool complete ) { char *str = (char*)malloc(size+1); memcpy(str,data,size); str[size] = 0; page += str; free(str); if (!complete) return; std::vector<std::string> tokes = tokenize(page,std::string("\n"),0,false); bool gotKey = false; for (unsigned int i = 0; i < tokes.size(); i++ ) { if (!gotKey) { if ( tokes[i] == "-----END RSA PUBLIC KEY-----") { gotKey = true; exitNodes.clear(); // only clear when we have a list } } else { if ( tokes[i].size() ) { std::vector<std::string> chunks = tokenize(tokes[i],std::string(" "),0,false); if ( chunks.size() > 1 ) { if ( chunks[0] == "r" && chunks.size() > 7 ) exitNodes.push_back(chunks[6]); } } } } } }; class mySlashCommand : public bz_CustomSlashCommandHandler { public: virtual bool handle ( int playerID, bz_ApiString command, bz_ApiString message, bz_APIStringList *params ) { bz_sendTextMessage(BZ_SERVER,playerID,"torBlock List"); for ( unsigned int i = 0; i < exitNodes.size(); i++ ) bz_sendTextMessage(BZ_SERVER,playerID,exitNodes[i].c_str()); return true; } }; mySlashCommand mySlash; MyURLHandler myURL; void updateTorList ( void ) { if ( bz_getCurrentTime() - lastUpdateTime >= updateInterval) { lastUpdateTime = bz_getCurrentTime(); myURL.page.clear(); bz_addURLJob(torMasterList.c_str(),&myURL); } } bool isTorAddress ( const char* addy ) { for ( unsigned int i = 0; i < exitNodes.size(); i++ ) { if (exitNodes[i] == addy) return true; } return false; } BZF_PLUGIN_CALL int bz_Load ( const char* /*commandLine*/ ) { bz_debugMessage(4,"torBlock plugin loaded"); bz_registerEvent(bz_eAllowPlayer,&handler); bz_registerEvent(bz_eTickEvent,&handler); bz_registerCustomSlashCommand("torlist",&mySlash); lastUpdateTime = -updateInterval * 2; return 0; } BZF_PLUGIN_CALL int bz_Unload ( void ) { bz_removeCustomSlashCommand("torlist"); bz_removeEvent(bz_eTickEvent,&handler); bz_removeEvent(bz_eAllowPlayer,&handler); bz_debugMessage(4,"torBlock plugin unloaded"); return 0; } void Handler::process ( bz_EventData *eventData ) { if (!eventData) return; switch (eventData->eventType) { case bz_eAllowPlayer: { bz_AllowPlayerEventData_V1 *data = (bz_AllowPlayerEventData_V1*)eventData; if (isTorAddress(data->ipAddress.c_str())) { data->allow = false; data->reason = "Proxy Network Ban"; bz_debugMessage(0, "Proxy Network Ban: Rejected"); } } break; case bz_eTickEvent: updateTorList(); break; default: break; } } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>// // Parser is used to invoke the clang libraries to perform actual parsing of // the input received in the Console. // // Part of ccons, the interactive console for the C programming language. // // Copyright (c) 2009 Alexei Svitkine. This file is distributed under the // terms of MIT Open Source License. See file LICENSE for details. // #include "Parser.h" #include <iostream> #include <stack> #include <algorithm> #include <llvm/Config/config.h> #include <clang/AST/AST.h> #include <clang/AST/ASTConsumer.h> #include <clang/Basic/TargetInfo.h> #include <clang/Basic/TargetOptions.h> #include <clang/Frontend/FrontendOptions.h> #include <clang/Frontend/HeaderSearchOptions.h> #include <clang/Frontend/PreprocessorOptions.h> #include <clang/Frontend/Utils.h> #include <clang/Lex/HeaderSearch.h> #include <clang/Lex/LexDiagnostic.h> #include <clang/Lex/Preprocessor.h> #include <clang/Sema/ParseAST.h> #include <clang/Sema/SemaDiagnostic.h> #include <clang/Basic/TargetInfo.h> #include <clang/Basic/Diagnostic.h> #include "Diagnostics.h" #include "SrcGen.h" using std::string; namespace ccons { // // ParseOperation // ParseOperation::ParseOperation(const clang::LangOptions& options, clang::Diagnostic *diag, clang::PPCallbacks *callbacks) : _sm(new clang::SourceManager(*diag)), _fm(new clang::FileManager), _hs(new clang::HeaderSearch(*_fm)) { llvm::Triple triple(LLVM_HOSTTRIPLE); clang::TargetOptions targetOptions; targetOptions.ABI = ""; targetOptions.CPU = ""; targetOptions.Features.clear(); targetOptions.Triple = LLVM_HOSTTRIPLE; _target.reset(clang::TargetInfo::CreateTargetInfo(*diag, targetOptions)); clang::HeaderSearchOptions hsOptions; ApplyHeaderSearchOptions(*_hs, hsOptions, options, triple); _pp.reset(new clang::Preprocessor(*diag, options, *_target, *_sm, *_hs)); _pp->addPPCallbacks(callbacks); clang::PreprocessorOptions ppOptions; clang::FrontendOptions frontendOptions; InitializePreprocessor(*_pp, ppOptions, hsOptions, frontendOptions); _ast.reset(new clang::ASTContext(options, *_sm, *_target, _pp->getIdentifierTable(), _pp->getSelectorTable(), _pp->getBuiltinInfo())); } clang::ASTContext * ParseOperation::getASTContext() const { return _ast.get(); } clang::Preprocessor * ParseOperation::getPreprocessor() const { return _pp.get(); } clang::SourceManager * ParseOperation::getSourceManager() const { return _sm.get(); } clang::TargetInfo * ParseOperation::getTargetInfo() const { return _target.get(); } // // Parser // Parser::Parser(const clang::LangOptions& options) : _options(options) { } Parser::~Parser() { releaseAccumulatedParseOperations(); } void Parser::releaseAccumulatedParseOperations() { for (std::vector<ParseOperation*>::iterator I = _ops.begin(), E = _ops.end(); I != E; ++I) { delete *I; } _ops.clear(); } ParseOperation * Parser::getLastParseOperation() const { return _ops.empty() ? NULL : _ops.back(); } Parser::InputType Parser::analyzeInput(const string& contextSource, const string& buffer, int& indentLevel, std::vector<clang::FunctionDecl*> *fds) { if (buffer.length() > 1 && buffer[buffer.length() - 2] == '\\') { indentLevel = 1; return Incomplete; } ProxyDiagnosticClient pdc(NULL); clang::Diagnostic diag(&pdc); llvm::OwningPtr<ParseOperation> parseOp(new ParseOperation(_options, &diag)); llvm::MemoryBuffer *memBuf = createMemoryBuffer(buffer, "", parseOp->getSourceManager()); clang::Token LastTok; bool TokWasDo = false; int stackSize = analyzeTokens(*parseOp->getPreprocessor(), memBuf, LastTok, indentLevel, TokWasDo); if (stackSize < 0) return TopLevel; // TokWasDo is used for do { ... } while (...); loops if (LastTok.is(clang::tok::semi) || (LastTok.is(clang::tok::r_brace) && !TokWasDo)) { if (stackSize > 0) return Incomplete; ProxyDiagnosticClient pdc(NULL); // do not output diagnostics clang::Diagnostic diag(&pdc); // Setting this ensures "foo();" is not a valid top-level declaration. diag.setDiagnosticMapping(clang::diag::ext_missing_type_specifier, clang::diag::MAP_ERROR); diag.setSuppressSystemWarnings(true); string src = contextSource + buffer; struct : public clang::ASTConsumer { bool hadIncludedDecls; unsigned pos; unsigned maxPos; clang::SourceManager *sm; std::vector<clang::FunctionDecl*> fds; void HandleTopLevelDecl(clang::DeclGroupRef D) { for (clang::DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) { if (clang::FunctionDecl *FD = dyn_cast<clang::FunctionDecl>(*I)) { clang::SourceLocation Loc = FD->getTypeSpecStartLoc(); if (!Loc.isValid()) continue; if (sm->isFromMainFile(Loc)) { unsigned offset = sm->getFileOffset(sm->getInstantiationLoc(Loc)); if (offset >= pos) { fds.push_back(FD); } } else { while (!sm->isFromMainFile(Loc)) { const clang::SrcMgr::SLocEntry& Entry = sm->getSLocEntry(sm->getFileID(sm->getSpellingLoc(Loc))); if (!Entry.isFile()) break; Loc = Entry.getFile().getIncludeLoc(); } unsigned offset = sm->getFileOffset(Loc); if (offset >= pos) { hadIncludedDecls = true; } } } } } } consumer; ParseOperation *parseOp = createParseOperation(&diag); consumer.hadIncludedDecls = false; consumer.pos = contextSource.length(); consumer.maxPos = consumer.pos + buffer.length(); consumer.sm = parseOp->getSourceManager(); parse(src, parseOp, &consumer); if (pdc.hadError(clang::diag::err_unterminated_block_comment)) return Incomplete; if (!pdc.hadErrors() && (!consumer.fds.empty() || consumer.hadIncludedDecls)) { if (!consumer.fds.empty()) fds->swap(consumer.fds); return TopLevel; } return Stmt; } return Incomplete; } int Parser::analyzeTokens(clang::Preprocessor& PP, const llvm::MemoryBuffer *MemBuf, clang::Token& LastTok, int& IndentLevel, bool& TokWasDo) { int result; std::stack<std::pair<clang::Token, clang::Token> > S; // Tok, PrevTok IndentLevel = 0; PP.EnterMainSourceFile(); clang::Token Tok; PP.Lex(Tok); while (Tok.isNot(clang::tok::eof)) { if (Tok.is(clang::tok::l_square)) { S.push(std::make_pair(Tok, LastTok)); // [ } else if (Tok.is(clang::tok::l_paren)) { S.push(std::make_pair(Tok, LastTok)); // ( } else if (Tok.is(clang::tok::l_brace)) { S.push(std::make_pair(Tok, LastTok)); // { IndentLevel++; } else if (Tok.is(clang::tok::r_square)) { if (S.empty() || S.top().first.isNot(clang::tok::l_square)) { std::cout << "Unmatched [\n"; return -1; } TokWasDo = false; S.pop(); } else if (Tok.is(clang::tok::r_paren)) { if (S.empty() || S.top().first.isNot(clang::tok::l_paren)) { std::cout << "Unmatched (\n"; return -1; } TokWasDo = false; S.pop(); } else if (Tok.is(clang::tok::r_brace)) { if (S.empty() || S.top().first.isNot(clang::tok::l_brace)) { std::cout << "Unmatched {\n"; return -1; } TokWasDo = S.top().second.is(clang::tok::kw_do); S.pop(); IndentLevel--; } LastTok = Tok; PP.Lex(Tok); } result = S.size(); // TODO: We need to properly account for indent-level for blocks that do not // have braces... such as: // // if (X) // Y; // // TODO: Do-while without braces doesn't work, e.g.: // // do // foo(); // while (bar()); // // Both of the above could be solved by some kind of rewriter-pass that would // insert implicit braces (or simply a more involved analysis). // Also try to match preprocessor conditionals... if (result == 0) { clang::Lexer Lexer(PP.getSourceManager().getMainFileID(), MemBuf, PP.getSourceManager(), PP.getLangOptions()); Lexer.LexFromRawLexer(Tok); while (Tok.isNot(clang::tok::eof)) { if (Tok.is(clang::tok::hash)) { Lexer.LexFromRawLexer(Tok); if (clang::IdentifierInfo *II = PP.LookUpIdentifierInfo(Tok)) { switch (II->getPPKeywordID()) { case clang::tok::pp_if: case clang::tok::pp_ifdef: case clang::tok::pp_ifndef: result++; break; case clang::tok::pp_endif: if (result == 0) return -1; // Nesting error. result--; break; default: break; } } } Lexer.LexFromRawLexer(Tok); } } return result; } ParseOperation * Parser::createParseOperation(clang::Diagnostic *diag, clang::PPCallbacks *callbacks) { return new ParseOperation(_options, diag, callbacks); } void Parser::parse(const string& src, ParseOperation *parseOp, clang::ASTConsumer *consumer) { _ops.push_back(parseOp); createMemoryBuffer(src, "", parseOp->getSourceManager()); clang::ParseAST(*parseOp->getPreprocessor(), consumer, *parseOp->getASTContext()); } void Parser::parse(const string& src, clang::Diagnostic *diag, clang::ASTConsumer *consumer) { parse(src, createParseOperation(diag), consumer); } llvm::MemoryBuffer * Parser::createMemoryBuffer(const string& src, const char *name, clang::SourceManager *sm) { llvm::MemoryBuffer *mb = llvm::MemoryBuffer::getMemBufferCopy(src, name); assert(mb && "Error creating MemoryBuffer!"); sm->createMainFileIDForMemBuffer(mb); assert(!sm->getMainFileID().isInvalid() && "Error creating MainFileID!"); return mb; } } // namespace ccons <commit_msg>fix build<commit_after>// // Parser is used to invoke the clang libraries to perform actual parsing of // the input received in the Console. // // Part of ccons, the interactive console for the C programming language. // // Copyright (c) 2009 Alexei Svitkine. This file is distributed under the // terms of MIT Open Source License. See file LICENSE for details. // #include "Parser.h" #include <iostream> #include <stack> #include <algorithm> #include <llvm/Config/config.h> #include <clang/AST/AST.h> #include <clang/AST/ASTConsumer.h> #include <clang/Basic/TargetInfo.h> #include <clang/Basic/TargetOptions.h> #include <clang/Frontend/FrontendOptions.h> #include <clang/Frontend/HeaderSearchOptions.h> #include <clang/Frontend/PreprocessorOptions.h> #include <clang/Frontend/Utils.h> #include <clang/Lex/HeaderSearch.h> #include <clang/Lex/LexDiagnostic.h> #include <clang/Lex/Preprocessor.h> #include <clang/Sema/ParseAST.h> #include <clang/Sema/SemaDiagnostic.h> #include <clang/Basic/TargetInfo.h> #include <clang/Basic/Diagnostic.h> #include "Diagnostics.h" #include "SrcGen.h" using std::string; namespace ccons { // // ParseOperation // ParseOperation::ParseOperation(const clang::LangOptions& options, clang::Diagnostic *diag, clang::PPCallbacks *callbacks) : _sm(new clang::SourceManager(*diag)), _fm(new clang::FileManager), _hs(new clang::HeaderSearch(*_fm)) { llvm::Triple triple(LLVM_HOSTTRIPLE); clang::TargetOptions targetOptions; targetOptions.ABI = ""; targetOptions.CPU = ""; targetOptions.Features.clear(); targetOptions.Triple = LLVM_HOSTTRIPLE; _target.reset(clang::TargetInfo::CreateTargetInfo(*diag, targetOptions)); clang::HeaderSearchOptions hsOptions; ApplyHeaderSearchOptions(*_hs, hsOptions, options, triple); _pp.reset(new clang::Preprocessor(*diag, options, *_target, *_sm, *_hs)); _pp->addPPCallbacks(callbacks); clang::PreprocessorOptions ppOptions; clang::FrontendOptions frontendOptions; InitializePreprocessor(*_pp, ppOptions, hsOptions, frontendOptions); _ast.reset(new clang::ASTContext(options, *_sm, *_target, _pp->getIdentifierTable(), _pp->getSelectorTable(), _pp->getBuiltinInfo(), 0)); } clang::ASTContext * ParseOperation::getASTContext() const { return _ast.get(); } clang::Preprocessor * ParseOperation::getPreprocessor() const { return _pp.get(); } clang::SourceManager * ParseOperation::getSourceManager() const { return _sm.get(); } clang::TargetInfo * ParseOperation::getTargetInfo() const { return _target.get(); } // // Parser // Parser::Parser(const clang::LangOptions& options) : _options(options) { } Parser::~Parser() { releaseAccumulatedParseOperations(); } void Parser::releaseAccumulatedParseOperations() { for (std::vector<ParseOperation*>::iterator I = _ops.begin(), E = _ops.end(); I != E; ++I) { delete *I; } _ops.clear(); } ParseOperation * Parser::getLastParseOperation() const { return _ops.empty() ? NULL : _ops.back(); } Parser::InputType Parser::analyzeInput(const string& contextSource, const string& buffer, int& indentLevel, std::vector<clang::FunctionDecl*> *fds) { if (buffer.length() > 1 && buffer[buffer.length() - 2] == '\\') { indentLevel = 1; return Incomplete; } ProxyDiagnosticClient pdc(NULL); clang::Diagnostic diag(&pdc); llvm::OwningPtr<ParseOperation> parseOp(new ParseOperation(_options, &diag)); llvm::MemoryBuffer *memBuf = createMemoryBuffer(buffer, "", parseOp->getSourceManager()); clang::Token LastTok; bool TokWasDo = false; int stackSize = analyzeTokens(*parseOp->getPreprocessor(), memBuf, LastTok, indentLevel, TokWasDo); if (stackSize < 0) return TopLevel; // TokWasDo is used for do { ... } while (...); loops if (LastTok.is(clang::tok::semi) || (LastTok.is(clang::tok::r_brace) && !TokWasDo)) { if (stackSize > 0) return Incomplete; ProxyDiagnosticClient pdc(NULL); // do not output diagnostics clang::Diagnostic diag(&pdc); // Setting this ensures "foo();" is not a valid top-level declaration. diag.setDiagnosticMapping(clang::diag::ext_missing_type_specifier, clang::diag::MAP_ERROR); diag.setSuppressSystemWarnings(true); string src = contextSource + buffer; struct : public clang::ASTConsumer { bool hadIncludedDecls; unsigned pos; unsigned maxPos; clang::SourceManager *sm; std::vector<clang::FunctionDecl*> fds; void HandleTopLevelDecl(clang::DeclGroupRef D) { for (clang::DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) { if (clang::FunctionDecl *FD = dyn_cast<clang::FunctionDecl>(*I)) { clang::SourceLocation Loc = FD->getTypeSpecStartLoc(); if (!Loc.isValid()) continue; if (sm->isFromMainFile(Loc)) { unsigned offset = sm->getFileOffset(sm->getInstantiationLoc(Loc)); if (offset >= pos) { fds.push_back(FD); } } else { while (!sm->isFromMainFile(Loc)) { const clang::SrcMgr::SLocEntry& Entry = sm->getSLocEntry(sm->getFileID(sm->getSpellingLoc(Loc))); if (!Entry.isFile()) break; Loc = Entry.getFile().getIncludeLoc(); } unsigned offset = sm->getFileOffset(Loc); if (offset >= pos) { hadIncludedDecls = true; } } } } } } consumer; ParseOperation *parseOp = createParseOperation(&diag); consumer.hadIncludedDecls = false; consumer.pos = contextSource.length(); consumer.maxPos = consumer.pos + buffer.length(); consumer.sm = parseOp->getSourceManager(); parse(src, parseOp, &consumer); if (pdc.hadError(clang::diag::err_unterminated_block_comment)) return Incomplete; if (!pdc.hadErrors() && (!consumer.fds.empty() || consumer.hadIncludedDecls)) { if (!consumer.fds.empty()) fds->swap(consumer.fds); return TopLevel; } return Stmt; } return Incomplete; } int Parser::analyzeTokens(clang::Preprocessor& PP, const llvm::MemoryBuffer *MemBuf, clang::Token& LastTok, int& IndentLevel, bool& TokWasDo) { int result; std::stack<std::pair<clang::Token, clang::Token> > S; // Tok, PrevTok IndentLevel = 0; PP.EnterMainSourceFile(); clang::Token Tok; PP.Lex(Tok); while (Tok.isNot(clang::tok::eof)) { if (Tok.is(clang::tok::l_square)) { S.push(std::make_pair(Tok, LastTok)); // [ } else if (Tok.is(clang::tok::l_paren)) { S.push(std::make_pair(Tok, LastTok)); // ( } else if (Tok.is(clang::tok::l_brace)) { S.push(std::make_pair(Tok, LastTok)); // { IndentLevel++; } else if (Tok.is(clang::tok::r_square)) { if (S.empty() || S.top().first.isNot(clang::tok::l_square)) { std::cout << "Unmatched [\n"; return -1; } TokWasDo = false; S.pop(); } else if (Tok.is(clang::tok::r_paren)) { if (S.empty() || S.top().first.isNot(clang::tok::l_paren)) { std::cout << "Unmatched (\n"; return -1; } TokWasDo = false; S.pop(); } else if (Tok.is(clang::tok::r_brace)) { if (S.empty() || S.top().first.isNot(clang::tok::l_brace)) { std::cout << "Unmatched {\n"; return -1; } TokWasDo = S.top().second.is(clang::tok::kw_do); S.pop(); IndentLevel--; } LastTok = Tok; PP.Lex(Tok); } result = S.size(); // TODO: We need to properly account for indent-level for blocks that do not // have braces... such as: // // if (X) // Y; // // TODO: Do-while without braces doesn't work, e.g.: // // do // foo(); // while (bar()); // // Both of the above could be solved by some kind of rewriter-pass that would // insert implicit braces (or simply a more involved analysis). // Also try to match preprocessor conditionals... if (result == 0) { clang::Lexer Lexer(PP.getSourceManager().getMainFileID(), MemBuf, PP.getSourceManager(), PP.getLangOptions()); Lexer.LexFromRawLexer(Tok); while (Tok.isNot(clang::tok::eof)) { if (Tok.is(clang::tok::hash)) { Lexer.LexFromRawLexer(Tok); if (clang::IdentifierInfo *II = PP.LookUpIdentifierInfo(Tok)) { switch (II->getPPKeywordID()) { case clang::tok::pp_if: case clang::tok::pp_ifdef: case clang::tok::pp_ifndef: result++; break; case clang::tok::pp_endif: if (result == 0) return -1; // Nesting error. result--; break; default: break; } } } Lexer.LexFromRawLexer(Tok); } } return result; } ParseOperation * Parser::createParseOperation(clang::Diagnostic *diag, clang::PPCallbacks *callbacks) { return new ParseOperation(_options, diag, callbacks); } void Parser::parse(const string& src, ParseOperation *parseOp, clang::ASTConsumer *consumer) { _ops.push_back(parseOp); createMemoryBuffer(src, "", parseOp->getSourceManager()); clang::ParseAST(*parseOp->getPreprocessor(), consumer, *parseOp->getASTContext()); } void Parser::parse(const string& src, clang::Diagnostic *diag, clang::ASTConsumer *consumer) { parse(src, createParseOperation(diag), consumer); } llvm::MemoryBuffer * Parser::createMemoryBuffer(const string& src, const char *name, clang::SourceManager *sm) { llvm::MemoryBuffer *mb = llvm::MemoryBuffer::getMemBufferCopy(src, name); assert(mb && "Error creating MemoryBuffer!"); sm->createMainFileIDForMemBuffer(mb); assert(!sm->getMainFileID().isInvalid() && "Error creating MainFileID!"); return mb; } } // namespace ccons <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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. * ************************************************************************/ #error dieser Header entfaellt nun! #ifndef _SVDPOMV_HXX #define _SVDPOMV_HXX #include <svx/svdmrkv.hxx> //////////////////////////////////////////////////////////////////////////////////////////////////// // // @@@@@ @@@@ @@ @@ @@ @@ @@ @@@@ @@@@@ @@ @@ @@ @@ @@ @@@@@ @@ @@ // @@ @@ @@ @@ @@ @@ @@ @@@ @@@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @ @@ // @@@@@ @@ @@ @@ @@@@ @@@@@@@ @@@@@@ @@@@@ @@@@ @@@@@ @@ @@@@ @@@@@@@ // @@ @@ @@ @@ @@ @@ @ @@ @@ @@ @@ @@ @@ @@ @@@ @@ @@ @@@ @@@ // @@ @@@@ @@@@@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @ @@ @@@@@ @@ @@ // //////////////////////////////////////////////////////////////////////////////////////////////////// class SdrPolyMarkView: public SdrMarkView { private: #ifndef _SVDRAW_HXX void ImpClearVars(); #endif public: SdrPolyMarkView(SdrModel* pModel1, OutputDevice* pOut = 0L); ~SdrPolyMarkView(); }; //////////////////////////////////////////////////////////////////////////////////////////////////// #endif //_SVDPOMV_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>removed unused header<commit_after><|endoftext|>
<commit_before>/*************************************************************************** copyright : (C) 2004-2005 by Allan Sandfeld Jensen email : kde@carewolf.org ***************************************************************************/ /*************************************************************************** * 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., 51 Franklin Street, Fifth Floor, Boston, MA * * 02110-1301 USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include <tbytevector.h> #include <tstring.h> #include <tdebug.h> #include <tpropertymap.h> #include <tagutils.h> #include <xiphcomment.h> #include "oggflacfile.h" using namespace TagLib; using TagLib::FLAC::Properties; class Ogg::FLAC::File::FilePrivate { public: FilePrivate() : comment(0), properties(0), streamStart(0), streamLength(0), scanned(false), hasXiphComment(false), commentPacket(0) {} ~FilePrivate() { delete comment; delete properties; } Ogg::XiphComment *comment; Properties *properties; ByteVector streamInfoData; ByteVector xiphCommentData; long streamStart; long streamLength; bool scanned; bool hasXiphComment; int commentPacket; }; //////////////////////////////////////////////////////////////////////////////// // static members //////////////////////////////////////////////////////////////////////////////// bool Ogg::FLAC::File::isSupported(IOStream *stream) { // An Ogg FLAC file has IDs "OggS" and "fLaC" somewhere. const ByteVector buffer = Utils::readHeader(stream, bufferSize(), false); return (buffer.find("OggS") >= 0 && buffer.find("fLaC") >= 0); } //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// Ogg::FLAC::File::File(FileName file, bool readProperties, Properties::ReadStyle propertiesStyle) : Ogg::File(file), d(new FilePrivate()) { if(isOpen()) read(readProperties, propertiesStyle); } Ogg::FLAC::File::File(IOStream *stream, bool readProperties, Properties::ReadStyle propertiesStyle) : Ogg::File(stream), d(new FilePrivate()) { if(isOpen()) read(readProperties, propertiesStyle); } Ogg::FLAC::File::~File() { delete d; } Ogg::XiphComment *Ogg::FLAC::File::tag() const { return d->comment; } PropertyMap Ogg::FLAC::File::properties() const { return d->comment->properties(); } PropertyMap Ogg::FLAC::File::setProperties(const PropertyMap &properties) { return d->comment->setProperties(properties); } Properties *Ogg::FLAC::File::audioProperties() const { return d->properties; } bool Ogg::FLAC::File::save() { d->xiphCommentData = d->comment->render(false); // Create FLAC metadata-block: // Put the size in the first 32 bit (I assume no more than 24 bit are used) ByteVector v = ByteVector::fromUInt(d->xiphCommentData.size()); // Set the type of the metadata-block to be a Xiph / Vorbis comment v[0] = 4; // Append the comment-data after the 32 bit header v.append(d->xiphCommentData); // Save the packet at the old spot // FIXME: Use padding if size is increasing setPacket(d->commentPacket, v); return Ogg::File::save(); } bool Ogg::FLAC::File::hasXiphComment() const { return d->hasXiphComment; } //////////////////////////////////////////////////////////////////////////////// // private members //////////////////////////////////////////////////////////////////////////////// void Ogg::FLAC::File::read(bool readProperties, Properties::ReadStyle propertiesStyle) { // Sanity: Check if we really have an Ogg/FLAC file /* ByteVector oggHeader = packet(0); if (oggHeader.mid(28,4) != "fLaC") { debug("Ogg::FLAC::File::read() -- Not an Ogg/FLAC file"); setValid(false); return; }*/ // Look for FLAC metadata, including vorbis comments scan(); if (!d->scanned) { setValid(false); return; } if(d->hasXiphComment) d->comment = new Ogg::XiphComment(xiphCommentData()); else d->comment = new Ogg::XiphComment(); if(readProperties) d->properties = new Properties(streamInfoData(), streamLength(), propertiesStyle); } ByteVector Ogg::FLAC::File::streamInfoData() { scan(); return d->streamInfoData; } ByteVector Ogg::FLAC::File::xiphCommentData() { scan(); return d->xiphCommentData; } long Ogg::FLAC::File::streamLength() { scan(); return d->streamLength; } void Ogg::FLAC::File::scan() { // Scan the metadata pages if(d->scanned) return; if(!isValid()) return; int ipacket = 0; long overhead = 0; ByteVector metadataHeader = packet(ipacket); if(metadataHeader.isEmpty()) return; if(!metadataHeader.startsWith("fLaC")) { // FLAC 1.1.2+ if(metadataHeader.mid(1, 4) != "FLAC") return; if(metadataHeader[5] != 1) return; // not version 1 metadataHeader = metadataHeader.mid(13); } else { // FLAC 1.1.0 & 1.1.1 metadataHeader = packet(++ipacket); } ByteVector header = metadataHeader.mid(0, 4); if(header.size() != 4) { debug("Ogg::FLAC::File::scan() -- Invalid Ogg/FLAC metadata header"); return; } // Header format (from spec): // <1> Last-metadata-block flag // <7> BLOCK_TYPE // 0 : STREAMINFO // 1 : PADDING // .. // 4 : VORBIS_COMMENT // .. // <24> Length of metadata to follow char blockType = header[0] & 0x7f; bool lastBlock = (header[0] & 0x80) != 0; unsigned int length = header.toUInt(1, 3, true); overhead += length; // Sanity: First block should be the stream_info metadata if(blockType != 0) { debug("Ogg::FLAC::File::scan() -- Invalid Ogg/FLAC stream"); return; } d->streamInfoData = metadataHeader.mid(4, length); // Search through the remaining metadata while(!lastBlock) { metadataHeader = packet(++ipacket); header = metadataHeader.mid(0, 4); if(header.size() != 4) { debug("Ogg::FLAC::File::scan() -- Invalid Ogg/FLAC metadata header"); return; } blockType = header[0] & 0x7f; lastBlock = (header[0] & 0x80) != 0; length = header.toUInt(1, 3, true); overhead += length; if(blockType == 1) { // debug("Ogg::FLAC::File::scan() -- Padding found"); } else if(blockType == 4) { // debug("Ogg::FLAC::File::scan() -- Vorbis-comments found"); d->xiphCommentData = metadataHeader.mid(4, length); d->hasXiphComment = true; d->commentPacket = ipacket; } else if(blockType > 5) { debug("Ogg::FLAC::File::scan() -- Unknown metadata block"); } } // End of metadata, now comes the datastream d->streamStart = overhead; d->streamLength = File::length() - d->streamStart; d->scanned = true; } <commit_msg>Fixed OOB read when loading invalid ogg flac file. (#868) (#869)<commit_after>/*************************************************************************** copyright : (C) 2004-2005 by Allan Sandfeld Jensen email : kde@carewolf.org ***************************************************************************/ /*************************************************************************** * 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., 51 Franklin Street, Fifth Floor, Boston, MA * * 02110-1301 USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include <tbytevector.h> #include <tstring.h> #include <tdebug.h> #include <tpropertymap.h> #include <tagutils.h> #include <xiphcomment.h> #include "oggflacfile.h" using namespace TagLib; using TagLib::FLAC::Properties; class Ogg::FLAC::File::FilePrivate { public: FilePrivate() : comment(0), properties(0), streamStart(0), streamLength(0), scanned(false), hasXiphComment(false), commentPacket(0) {} ~FilePrivate() { delete comment; delete properties; } Ogg::XiphComment *comment; Properties *properties; ByteVector streamInfoData; ByteVector xiphCommentData; long streamStart; long streamLength; bool scanned; bool hasXiphComment; int commentPacket; }; //////////////////////////////////////////////////////////////////////////////// // static members //////////////////////////////////////////////////////////////////////////////// bool Ogg::FLAC::File::isSupported(IOStream *stream) { // An Ogg FLAC file has IDs "OggS" and "fLaC" somewhere. const ByteVector buffer = Utils::readHeader(stream, bufferSize(), false); return (buffer.find("OggS") >= 0 && buffer.find("fLaC") >= 0); } //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// Ogg::FLAC::File::File(FileName file, bool readProperties, Properties::ReadStyle propertiesStyle) : Ogg::File(file), d(new FilePrivate()) { if(isOpen()) read(readProperties, propertiesStyle); } Ogg::FLAC::File::File(IOStream *stream, bool readProperties, Properties::ReadStyle propertiesStyle) : Ogg::File(stream), d(new FilePrivate()) { if(isOpen()) read(readProperties, propertiesStyle); } Ogg::FLAC::File::~File() { delete d; } Ogg::XiphComment *Ogg::FLAC::File::tag() const { return d->comment; } PropertyMap Ogg::FLAC::File::properties() const { return d->comment->properties(); } PropertyMap Ogg::FLAC::File::setProperties(const PropertyMap &properties) { return d->comment->setProperties(properties); } Properties *Ogg::FLAC::File::audioProperties() const { return d->properties; } bool Ogg::FLAC::File::save() { d->xiphCommentData = d->comment->render(false); // Create FLAC metadata-block: // Put the size in the first 32 bit (I assume no more than 24 bit are used) ByteVector v = ByteVector::fromUInt(d->xiphCommentData.size()); // Set the type of the metadata-block to be a Xiph / Vorbis comment v[0] = 4; // Append the comment-data after the 32 bit header v.append(d->xiphCommentData); // Save the packet at the old spot // FIXME: Use padding if size is increasing setPacket(d->commentPacket, v); return Ogg::File::save(); } bool Ogg::FLAC::File::hasXiphComment() const { return d->hasXiphComment; } //////////////////////////////////////////////////////////////////////////////// // private members //////////////////////////////////////////////////////////////////////////////// void Ogg::FLAC::File::read(bool readProperties, Properties::ReadStyle propertiesStyle) { // Sanity: Check if we really have an Ogg/FLAC file /* ByteVector oggHeader = packet(0); if (oggHeader.mid(28,4) != "fLaC") { debug("Ogg::FLAC::File::read() -- Not an Ogg/FLAC file"); setValid(false); return; }*/ // Look for FLAC metadata, including vorbis comments scan(); if (!d->scanned) { setValid(false); return; } if(d->hasXiphComment) d->comment = new Ogg::XiphComment(xiphCommentData()); else d->comment = new Ogg::XiphComment(); if(readProperties) d->properties = new Properties(streamInfoData(), streamLength(), propertiesStyle); } ByteVector Ogg::FLAC::File::streamInfoData() { scan(); return d->streamInfoData; } ByteVector Ogg::FLAC::File::xiphCommentData() { scan(); return d->xiphCommentData; } long Ogg::FLAC::File::streamLength() { scan(); return d->streamLength; } void Ogg::FLAC::File::scan() { // Scan the metadata pages if(d->scanned) return; if(!isValid()) return; int ipacket = 0; long overhead = 0; ByteVector metadataHeader = packet(ipacket); if(metadataHeader.isEmpty()) return; if(!metadataHeader.startsWith("fLaC")) { // FLAC 1.1.2+ // See https://xiph.org/flac/ogg_mapping.html for the header specification. if(metadataHeader.size() < 13) return; if(metadataHeader[0] != 0x7f) return; if(metadataHeader.mid(1, 4) != "FLAC") return; if(metadataHeader[5] != 1 && metadataHeader[6] != 0) return; // not version 1.0 if(metadataHeader.mid(9, 4) != "fLaC") return; metadataHeader = metadataHeader.mid(13); } else { // FLAC 1.1.0 & 1.1.1 metadataHeader = packet(++ipacket); } ByteVector header = metadataHeader.mid(0, 4); if(header.size() != 4) { debug("Ogg::FLAC::File::scan() -- Invalid Ogg/FLAC metadata header"); return; } // Header format (from spec): // <1> Last-metadata-block flag // <7> BLOCK_TYPE // 0 : STREAMINFO // 1 : PADDING // .. // 4 : VORBIS_COMMENT // .. // <24> Length of metadata to follow char blockType = header[0] & 0x7f; bool lastBlock = (header[0] & 0x80) != 0; unsigned int length = header.toUInt(1, 3, true); overhead += length; // Sanity: First block should be the stream_info metadata if(blockType != 0) { debug("Ogg::FLAC::File::scan() -- Invalid Ogg/FLAC stream"); return; } d->streamInfoData = metadataHeader.mid(4, length); // Search through the remaining metadata while(!lastBlock) { metadataHeader = packet(++ipacket); header = metadataHeader.mid(0, 4); if(header.size() != 4) { debug("Ogg::FLAC::File::scan() -- Invalid Ogg/FLAC metadata header"); return; } blockType = header[0] & 0x7f; lastBlock = (header[0] & 0x80) != 0; length = header.toUInt(1, 3, true); overhead += length; if(blockType == 1) { // debug("Ogg::FLAC::File::scan() -- Padding found"); } else if(blockType == 4) { // debug("Ogg::FLAC::File::scan() -- Vorbis-comments found"); d->xiphCommentData = metadataHeader.mid(4, length); d->hasXiphComment = true; d->commentPacket = ipacket; } else if(blockType > 5) { debug("Ogg::FLAC::File::scan() -- Unknown metadata block"); } } // End of metadata, now comes the datastream d->streamStart = overhead; d->streamLength = File::length() - d->streamStart; d->scanned = true; } <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/register.h" #include "kernel/celltypes.h" #include "kernel/rtlil.h" #include "kernel/log.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN bool check_label(bool &active, std::string run_from, std::string run_to, std::string label) { if (label == run_from) active = true; if (label == run_to) active = false; return active; } struct SynthXilinxPass : public Pass { SynthXilinxPass() : Pass("synth_xilinx", "synthesis for Xilinx FPGAs") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" synth_xilinx [options]\n"); log("\n"); log("This command runs synthesis for Xilinx FPGAs. This command does not operate on\n"); log("partly selected designs. At the moment this command creates netlists that are\n"); log("compatible with 7-Series Xilinx devices.\n"); log("\n"); log(" -top <module>\n"); log(" use the specified module as top module\n"); log("\n"); log(" -edif <file>\n"); log(" write the design to the specified edif file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -blif <file>\n"); log(" write the design to the specified BLIF file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -vpr\n"); log(" generate an output netlist (and BLIF file) suitable for VPR\n"); log(" (this feature is experimental and incomplete)\n"); log("\n"); log(" -nobram\n"); log(" disable infering of block rams\n"); log("\n"); log(" -nodram\n"); log(" disable infering of distributed rams\n"); log("\n"); log(" -run <from_label>:<to_label>\n"); log(" only run the commands between the labels (see below). an empty\n"); log(" from label is synonymous to 'begin', and empty to label is\n"); log(" synonymous to the end of the command list.\n"); log("\n"); log(" -flatten\n"); log(" flatten design before synthesis\n"); log("\n"); log(" -retime\n"); log(" run 'abc' with -dff option\n"); log("\n"); log(" -abc9\n"); log(" use abc9 instead of abc\n"); log("\n"); log("\n"); log("The following commands are executed by this synthesis command:\n"); log("\n"); log(" begin:\n"); log(" read_verilog -lib +/xilinx/cells_sim.v\n"); log(" read_verilog -lib +/xilinx/cells_xtra.v\n"); log(" read_verilog -lib +/xilinx/brams_bb.v\n"); log(" hierarchy -check -top <top>\n"); log("\n"); log(" flatten: (only if -flatten)\n"); log(" proc\n"); log(" flatten\n"); log("\n"); log(" coarse:\n"); log(" synth -run coarse\n"); log("\n"); log(" bram: (only executed when '-nobram' is not given)\n"); log(" memory_bram -rules +/xilinx/brams.txt\n"); log(" techmap -map +/xilinx/brams_map.v\n"); log("\n"); log(" dram: (only executed when '-nodram' is not given)\n"); log(" memory_bram -rules +/xilinx/drams.txt\n"); log(" techmap -map +/xilinx/drams_map.v\n"); log("\n"); log(" fine:\n"); log(" opt -fast -full\n"); log(" memory_map\n"); log(" dffsr2dff\n"); log(" dff2dffe\n"); log(" opt -full\n"); log(" techmap -map +/techmap.v -map +/xilinx/arith_map.v -map +/xilinx/ff_map.v\n"); log(" opt -fast\n"); log("\n"); log(" map_luts:\n"); log(" abc -luts 2:2,3,6:5,10,20 [-dff] (without '-vpr' only!)\n"); log(" abc -lut 5 [-dff] (with '-vpr' only!)\n"); log(" clean\n"); log("\n"); log(" map_cells:\n"); log(" techmap -map +/xilinx/cells_map.v\n"); log(" dffinit -ff FDRE Q INIT -ff FDCE Q INIT -ff FDPE Q INIT -ff FDSE Q INIT \\\n"); log(" -ff FDRE_1 Q INIT -ff FDCE_1 Q INIT -ff FDPE_1 Q INIT -ff FDSE_1 Q INIT\n"); log(" clean\n"); log("\n"); log(" check:\n"); log(" hierarchy -check\n"); log(" stat\n"); log(" check -noinit\n"); log("\n"); log(" edif: (only if -edif)\n"); log(" write_edif <file-name>\n"); log("\n"); log(" blif: (only if -blif)\n"); log(" write_blif <file-name>\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { std::string top_opt = "-auto-top"; std::string edif_file; std::string blif_file; std::string run_from, run_to; std::string abc = "abc"; bool flatten = false; bool retime = false; bool vpr = false; bool nobram = false; bool nodram = false; size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-top" && argidx+1 < args.size()) { top_opt = "-top " + args[++argidx]; continue; } if (args[argidx] == "-edif" && argidx+1 < args.size()) { edif_file = args[++argidx]; continue; } if (args[argidx] == "-blif" && argidx+1 < args.size()) { blif_file = args[++argidx]; continue; } if (args[argidx] == "-run" && argidx+1 < args.size()) { size_t pos = args[argidx+1].find(':'); if (pos == std::string::npos) break; run_from = args[++argidx].substr(0, pos); run_to = args[argidx].substr(pos+1); continue; } if (args[argidx] == "-flatten") { flatten = true; continue; } if (args[argidx] == "-retime") { retime = true; continue; } if (args[argidx] == "-vpr") { vpr = true; continue; } if (args[argidx] == "-nobram") { nobram = true; continue; } if (args[argidx] == "-nodram") { nodram = true; continue; } if (args[argidx] == "-abc9") { abc = "abc9"; continue; } break; } extra_args(args, argidx, design); if (!design->full_selection()) log_cmd_error("This command only operates on fully selected designs!\n"); bool active = run_from.empty(); log_header(design, "Executing SYNTH_XILINX pass.\n"); log_push(); if (check_label(active, run_from, run_to, "begin")) { if (vpr) { Pass::call(design, "read_verilog -lib -D_EXPLICIT_CARRY +/xilinx/cells_sim.v"); } else { Pass::call(design, "read_verilog -lib +/xilinx/cells_sim.v"); } Pass::call(design, "read_verilog -lib +/xilinx/cells_xtra.v"); if (!nobram) { Pass::call(design, "read_verilog -lib +/xilinx/brams_bb.v"); } Pass::call(design, stringf("hierarchy -check %s", top_opt.c_str())); } if (flatten && check_label(active, run_from, run_to, "flatten")) { Pass::call(design, "proc"); Pass::call(design, "flatten"); } if (check_label(active, run_from, run_to, "coarse")) { Pass::call(design, "synth -run coarse"); } if (check_label(active, run_from, run_to, "bram")) { if (!nobram) { Pass::call(design, "memory_bram -rules +/xilinx/brams.txt"); Pass::call(design, "techmap -map +/xilinx/brams_map.v"); } } if (check_label(active, run_from, run_to, "dram")) { if (!nodram) { Pass::call(design, "memory_bram -rules +/xilinx/drams.txt"); Pass::call(design, "techmap -map +/xilinx/drams_map.v"); } } if (check_label(active, run_from, run_to, "fine")) { Pass::call(design, "opt -fast -full"); Pass::call(design, "memory_map"); Pass::call(design, "dffsr2dff"); Pass::call(design, "dff2dffe"); Pass::call(design, "opt -full"); if (vpr) { Pass::call(design, "techmap -map +/techmap.v -map +/xilinx/arith_map.v -map +/xilinx/ff_map.v -D _EXPLICIT_CARRY"); } else { Pass::call(design, "techmap -map +/techmap.v -map +/xilinx/arith_map.v -map +/xilinx/ff_map.v"); } Pass::call(design, "hierarchy -check"); Pass::call(design, "opt -fast"); } if (check_label(active, run_from, run_to, "map_luts")) { if (abc == "abc9") Pass::call(design, abc + " -luts 2:2,3,6:5,10,20 -box +/xilinx/cells.box" + string(retime ? " -dff" : "")); else Pass::call(design, abc + " -luts 2:2,3,6:5,10,20" + string(retime ? " -dff" : "")); Pass::call(design, "clean"); Pass::call(design, "techmap -map +/xilinx/lut_map.v"); } if (check_label(active, run_from, run_to, "map_cells")) { Pass::call(design, "techmap -map +/xilinx/cells_map.v"); Pass::call(design, "dffinit -ff FDRE Q INIT -ff FDCE Q INIT -ff FDPE Q INIT -ff FDSE Q INIT " "-ff FDRE_1 Q INIT -ff FDCE_1 Q INIT -ff FDPE_1 Q INIT -ff FDSE_1 Q INIT"); Pass::call(design, "clean"); } if (check_label(active, run_from, run_to, "check")) { Pass::call(design, "hierarchy -check"); Pass::call(design, "stat"); Pass::call(design, "check -noinit"); } if (check_label(active, run_from, run_to, "edif")) { if (!edif_file.empty()) Pass::call(design, stringf("write_edif -pvector bra %s", edif_file.c_str())); } if (check_label(active, run_from, run_to, "blif")) { if (!blif_file.empty()) Pass::call(design, stringf("write_blif %s", edif_file.c_str())); } log_pop(); } } SynthXilinxPass; PRIVATE_NAMESPACE_END <commit_msg>synth_xilinx to call abc with -lut +/xilinx/cells.lut<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/register.h" #include "kernel/celltypes.h" #include "kernel/rtlil.h" #include "kernel/log.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN bool check_label(bool &active, std::string run_from, std::string run_to, std::string label) { if (label == run_from) active = true; if (label == run_to) active = false; return active; } struct SynthXilinxPass : public Pass { SynthXilinxPass() : Pass("synth_xilinx", "synthesis for Xilinx FPGAs") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" synth_xilinx [options]\n"); log("\n"); log("This command runs synthesis for Xilinx FPGAs. This command does not operate on\n"); log("partly selected designs. At the moment this command creates netlists that are\n"); log("compatible with 7-Series Xilinx devices.\n"); log("\n"); log(" -top <module>\n"); log(" use the specified module as top module\n"); log("\n"); log(" -edif <file>\n"); log(" write the design to the specified edif file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -blif <file>\n"); log(" write the design to the specified BLIF file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -vpr\n"); log(" generate an output netlist (and BLIF file) suitable for VPR\n"); log(" (this feature is experimental and incomplete)\n"); log("\n"); log(" -nobram\n"); log(" disable infering of block rams\n"); log("\n"); log(" -nodram\n"); log(" disable infering of distributed rams\n"); log("\n"); log(" -run <from_label>:<to_label>\n"); log(" only run the commands between the labels (see below). an empty\n"); log(" from label is synonymous to 'begin', and empty to label is\n"); log(" synonymous to the end of the command list.\n"); log("\n"); log(" -flatten\n"); log(" flatten design before synthesis\n"); log("\n"); log(" -retime\n"); log(" run 'abc' with -dff option\n"); log("\n"); log(" -abc9\n"); log(" use abc9 instead of abc\n"); log("\n"); log("\n"); log("The following commands are executed by this synthesis command:\n"); log("\n"); log(" begin:\n"); log(" read_verilog -lib +/xilinx/cells_sim.v\n"); log(" read_verilog -lib +/xilinx/cells_xtra.v\n"); log(" read_verilog -lib +/xilinx/brams_bb.v\n"); log(" hierarchy -check -top <top>\n"); log("\n"); log(" flatten: (only if -flatten)\n"); log(" proc\n"); log(" flatten\n"); log("\n"); log(" coarse:\n"); log(" synth -run coarse\n"); log("\n"); log(" bram: (only executed when '-nobram' is not given)\n"); log(" memory_bram -rules +/xilinx/brams.txt\n"); log(" techmap -map +/xilinx/brams_map.v\n"); log("\n"); log(" dram: (only executed when '-nodram' is not given)\n"); log(" memory_bram -rules +/xilinx/drams.txt\n"); log(" techmap -map +/xilinx/drams_map.v\n"); log("\n"); log(" fine:\n"); log(" opt -fast -full\n"); log(" memory_map\n"); log(" dffsr2dff\n"); log(" dff2dffe\n"); log(" opt -full\n"); log(" techmap -map +/techmap.v -map +/xilinx/arith_map.v -map +/xilinx/ff_map.v\n"); log(" opt -fast\n"); log("\n"); log(" map_luts:\n"); log(" abc -luts 2:2,3,6:5,10,20 [-dff] (without '-vpr' only!)\n"); log(" abc -lut 5 [-dff] (with '-vpr' only!)\n"); log(" clean\n"); log("\n"); log(" map_cells:\n"); log(" techmap -map +/xilinx/cells_map.v\n"); log(" dffinit -ff FDRE Q INIT -ff FDCE Q INIT -ff FDPE Q INIT -ff FDSE Q INIT \\\n"); log(" -ff FDRE_1 Q INIT -ff FDCE_1 Q INIT -ff FDPE_1 Q INIT -ff FDSE_1 Q INIT\n"); log(" clean\n"); log("\n"); log(" check:\n"); log(" hierarchy -check\n"); log(" stat\n"); log(" check -noinit\n"); log("\n"); log(" edif: (only if -edif)\n"); log(" write_edif <file-name>\n"); log("\n"); log(" blif: (only if -blif)\n"); log(" write_blif <file-name>\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { std::string top_opt = "-auto-top"; std::string edif_file; std::string blif_file; std::string run_from, run_to; std::string abc = "abc"; bool flatten = false; bool retime = false; bool vpr = false; bool nobram = false; bool nodram = false; size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-top" && argidx+1 < args.size()) { top_opt = "-top " + args[++argidx]; continue; } if (args[argidx] == "-edif" && argidx+1 < args.size()) { edif_file = args[++argidx]; continue; } if (args[argidx] == "-blif" && argidx+1 < args.size()) { blif_file = args[++argidx]; continue; } if (args[argidx] == "-run" && argidx+1 < args.size()) { size_t pos = args[argidx+1].find(':'); if (pos == std::string::npos) break; run_from = args[++argidx].substr(0, pos); run_to = args[argidx].substr(pos+1); continue; } if (args[argidx] == "-flatten") { flatten = true; continue; } if (args[argidx] == "-retime") { retime = true; continue; } if (args[argidx] == "-vpr") { vpr = true; continue; } if (args[argidx] == "-nobram") { nobram = true; continue; } if (args[argidx] == "-nodram") { nodram = true; continue; } if (args[argidx] == "-abc9") { abc = "abc9"; continue; } break; } extra_args(args, argidx, design); if (!design->full_selection()) log_cmd_error("This command only operates on fully selected designs!\n"); bool active = run_from.empty(); log_header(design, "Executing SYNTH_XILINX pass.\n"); log_push(); if (check_label(active, run_from, run_to, "begin")) { if (vpr) { Pass::call(design, "read_verilog -lib -D_EXPLICIT_CARRY +/xilinx/cells_sim.v"); } else { Pass::call(design, "read_verilog -lib +/xilinx/cells_sim.v"); } Pass::call(design, "read_verilog -lib +/xilinx/cells_xtra.v"); if (!nobram) { Pass::call(design, "read_verilog -lib +/xilinx/brams_bb.v"); } Pass::call(design, stringf("hierarchy -check %s", top_opt.c_str())); } if (flatten && check_label(active, run_from, run_to, "flatten")) { Pass::call(design, "proc"); Pass::call(design, "flatten"); } if (check_label(active, run_from, run_to, "coarse")) { Pass::call(design, "synth -run coarse"); } if (check_label(active, run_from, run_to, "bram")) { if (!nobram) { Pass::call(design, "memory_bram -rules +/xilinx/brams.txt"); Pass::call(design, "techmap -map +/xilinx/brams_map.v"); } } if (check_label(active, run_from, run_to, "dram")) { if (!nodram) { Pass::call(design, "memory_bram -rules +/xilinx/drams.txt"); Pass::call(design, "techmap -map +/xilinx/drams_map.v"); } } if (check_label(active, run_from, run_to, "fine")) { Pass::call(design, "opt -fast -full"); Pass::call(design, "memory_map"); Pass::call(design, "dffsr2dff"); Pass::call(design, "dff2dffe"); Pass::call(design, "opt -full"); if (vpr) { Pass::call(design, "techmap -map +/techmap.v -map +/xilinx/arith_map.v -map +/xilinx/ff_map.v -D _EXPLICIT_CARRY"); } else { Pass::call(design, "techmap -map +/techmap.v -map +/xilinx/arith_map.v -map +/xilinx/ff_map.v"); } Pass::call(design, "hierarchy -check"); Pass::call(design, "opt -fast"); } if (check_label(active, run_from, run_to, "map_luts")) { if (abc == "abc9") Pass::call(design, abc + " -lut +/xilinx/cells.lut -box +/xilinx/cells.box" + string(retime ? " -dff" : "")); else Pass::call(design, abc + " -lut +/xilinx/cells.lut" + string(retime ? " -dff" : "")); Pass::call(design, "clean"); Pass::call(design, "techmap -map +/xilinx/lut_map.v"); } if (check_label(active, run_from, run_to, "map_cells")) { Pass::call(design, "techmap -map +/xilinx/cells_map.v"); Pass::call(design, "dffinit -ff FDRE Q INIT -ff FDCE Q INIT -ff FDPE Q INIT -ff FDSE Q INIT " "-ff FDRE_1 Q INIT -ff FDCE_1 Q INIT -ff FDPE_1 Q INIT -ff FDSE_1 Q INIT"); Pass::call(design, "clean"); } if (check_label(active, run_from, run_to, "check")) { Pass::call(design, "hierarchy -check"); Pass::call(design, "stat"); Pass::call(design, "check -noinit"); } if (check_label(active, run_from, run_to, "edif")) { if (!edif_file.empty()) Pass::call(design, stringf("write_edif -pvector bra %s", edif_file.c_str())); } if (check_label(active, run_from, run_to, "blif")) { if (!blif_file.empty()) Pass::call(design, stringf("write_blif %s", edif_file.c_str())); } log_pop(); } } SynthXilinxPass; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>#include "instanciate.h" #include <iostream> using namespace Yuni; namespace Nany { namespace Pass { namespace Instanciate { enum class AssignStrategy { rawregister, ref, deepcopy, }; bool ProgramBuilder::instanciateAssignment(AtomStackFrame& frame, LVID lhs, LVID rhs, bool canDisposeLHS, bool checktype, bool forceDeepcopy) { // lhs and rhs can not be null, but they can be identical, to force a clone // when required for example if (unlikely(lhs == 0 or rhs == 0 or lhs == rhs)) return (ICE() << "invalid lvid for variable assignment"); // current atom id auto atomid = frame.atomid; // LHS cdef auto& cdeflhs = cdeftable.classdefFollowClassMember(CLID{atomid, lhs}); // RHS cdef auto& cdefrhs = cdeftable.classdefFollowClassMember(CLID{atomid, rhs}); if (checktype) { auto similarity = cdeftable.isSimilarTo(nullptr, cdeflhs, cdefrhs, false); if (unlikely(Match::strictEqual != similarity)) { auto err = (error() << "cannot convert '"); cdefrhs.print(err.data().message, cdeftable, false); err << "' to '"; cdeflhs.print(err.data().message, cdeftable, false); err << "' in initialization"; return false; } } // type propagation if (not canDisposeLHS) cdeftable.substitute(lhs).import(cdefrhs); if (unlikely(not canGenerateCode())) return true; // can lhs be acquires ? bool lhsCanBeAcquired = canBeAcquired(cdeflhs); // deep copy by default auto strategy = AssignStrategy::deepcopy; if (lhsCanBeAcquired) { if (not forceDeepcopy) { // NOTE: the qualifiers from `cdeflhs` are not valid and correspond to nothing auto& originalcdef = cdeftable.classdef(CLID{atomid, lhs}); out.emitComment(originalcdef.print(cdeftable) << originalcdef.clid); if (originalcdef.qualifiers.ref) { strategy = AssignStrategy::ref; } else { assert(rhs < frame.lvids.size()); auto& lvidinfo = frame.lvids[rhs]; if (lvidinfo.origin.memalloc or lvidinfo.origin.returnedValue) strategy = AssignStrategy::ref; } } } else strategy = AssignStrategy::rawregister; auto& lhsLvidinfo = frame.lvids[lhs]; if (lhsCanBeAcquired) lhsLvidinfo.autorelease = true; auto& origin = lhsLvidinfo.origin.varMember; bool isMemberVariable = (origin.atomid != 0); if (debugmode) { String comment; switch (strategy) { case AssignStrategy::rawregister: comment << "raw copy "; break; case AssignStrategy::ref: comment << "assign ref "; break; case AssignStrategy::deepcopy: comment << "deep copy "; break; } comment << "%" << lhs << " = %" << rhs << " aka '"; cdeflhs.print(comment, cdeftable, false); comment << '\''; out.emitComment(comment); } switch (strategy) { case AssignStrategy::rawregister: { if (lhs != rhs) { out.emitStore(lhs, rhs); if (isMemberVariable) out.emitFieldset(lhs, origin.self, origin.field); } break; } case AssignStrategy::ref: { if (lhs != rhs) { // acquire first the right value to make sure that all data are alive // example: a = a out.emitRef(rhs); // release the old left value if (canDisposeLHS) { tryUnrefObject(lhs); if (isMemberVariable) tryUnrefObject(lhs); } // copy the pointer out.emitStore(lhs, rhs); if (isMemberVariable) { out.emitRef(lhs); // re-acquire for the object out.emitFieldset(lhs, origin.self, origin.field); } } break; } case AssignStrategy::deepcopy: { auto* rhsAtom = cdeftable.findClassdefAtom(cdefrhs); if (unlikely(nullptr == rhsAtom)) return (ICE() << "invalid atom for left-side assignment"); // 'clone' operator if (0 == rhsAtom->classinfo.clone.atomid) { if (unlikely(not instanciateAtomClassClone(*rhsAtom, lhs, rhs))) return false; } // acquire first the right value to make sure that all data are alive // example: a = a out.emitRef(rhs); // release the old left value if (canDisposeLHS) { tryUnrefObject(lhs); if (isMemberVariable) tryUnrefObject(lhs); } // note: do not keep a reference on 'out.at...', since the internal buffer might be reized assert(lastOpcodeStacksizeOffset != (uint32_t) -1); auto& operands = out.at<IR::ISA::Op::stacksize>(lastOpcodeStacksizeOffset); uint32_t lvid = operands.add; uint32_t retcall = operands.add + 1; operands.add += 2; frame.resizeRegisterCount(lvid + 2, cdeftable); uint32_t rsizof = out.emitStackalloc(lvid, nyt_u64); out.emitSizeof(rsizof, rhsAtom->atomid); // re-allocate some memory out.emitMemalloc(lhs, rsizof); out.emitRef(lhs); assert(lhs < frame.lvids.size()); frame.lvids[lhs].origin.memalloc = true; out.emitStackalloc(retcall, nyt_void); // call operator 'clone' out.emitPush(lhs); // self out.emitPush(rhs); // rhs, the object to copy out.emitCall(retcall, rhsAtom->classinfo.clone.atomid, rhsAtom->classinfo.clone.instanceid); // release rhs - copy is done tryUnrefObject(rhs); if (isMemberVariable) { out.emitRef(lhs); out.emitFieldset(lhs, origin.self, origin.field); } break; } } return true; } bool ProgramBuilder::instanciateAssignment(const IR::ISA::Operand<IR::ISA::Op::call>& operands) { if (unlikely(lastPushedIndexedParameters.size() != 1)) { ICE() << "assignment: invalid number of pushed parameters"; return false; } if (unlikely(not lastPushedNamedParameters.empty())) { ICE() << "assignment: named parameters are not accepted"; return false; } // the current frame auto& frame = atomStack.back(); // -- LHS // note: double indirection, since assignment is like method call // %y = %x."=" // %z = resolve %y."^()" assert(operands.ptr2func < frame.lvids.size()); LVID lhs = frame.lvids[operands.ptr2func].referer; if (likely(0 != lhs)) { assert(lhs < frame.lvids.size()); lhs = frame.lvids[lhs].referer; } // -- RHS LVID rhs = lastPushedIndexedParameters[0].lvid; lastPushedIndexedParameters.clear(); return instanciateAssignment(frame, lhs, rhs); } } // namespace Instanciate } // namespace Pass } // namespace Nany <commit_msg>opcode assign: code cleanup (test no longer required)<commit_after>#include "instanciate.h" #include <iostream> using namespace Yuni; namespace Nany { namespace Pass { namespace Instanciate { enum class AssignStrategy { rawregister, ref, deepcopy, }; bool ProgramBuilder::instanciateAssignment(AtomStackFrame& frame, LVID lhs, LVID rhs, bool canDisposeLHS, bool checktype, bool forceDeepcopy) { // lhs and rhs can not be null, but they can be identical, to force a clone // when required for example if (unlikely(lhs == 0 or rhs == 0 or lhs == rhs)) return (ICE() << "invalid lvid for variable assignment"); // current atom id auto atomid = frame.atomid; // LHS cdef auto& cdeflhs = cdeftable.classdefFollowClassMember(CLID{atomid, lhs}); // RHS cdef auto& cdefrhs = cdeftable.classdefFollowClassMember(CLID{atomid, rhs}); if (checktype) { auto similarity = cdeftable.isSimilarTo(nullptr, cdeflhs, cdefrhs, false); if (unlikely(Match::strictEqual != similarity)) { auto err = (error() << "cannot convert '"); cdefrhs.print(err.data().message, cdeftable, false); err << "' to '"; cdeflhs.print(err.data().message, cdeftable, false); err << "' in initialization"; return false; } } // type propagation if (not canDisposeLHS) cdeftable.substitute(lhs).import(cdefrhs); if (unlikely(not canGenerateCode())) return true; // can lhs be acquires ? bool lhsCanBeAcquired = canBeAcquired(cdeflhs); // deep copy by default auto strategy = AssignStrategy::deepcopy; if (lhsCanBeAcquired) { if (not forceDeepcopy) { // NOTE: the qualifiers from `cdeflhs` are not valid and correspond to nothing auto& originalcdef = cdeftable.classdef(CLID{atomid, lhs}); out.emitComment(originalcdef.print(cdeftable) << originalcdef.clid); if (originalcdef.qualifiers.ref) { strategy = AssignStrategy::ref; } else { assert(rhs < frame.lvids.size()); auto& lvidinfo = frame.lvids[rhs]; if (lvidinfo.origin.memalloc or lvidinfo.origin.returnedValue) strategy = AssignStrategy::ref; } } } else strategy = AssignStrategy::rawregister; auto& lhsLvidinfo = frame.lvids[lhs]; if (lhsCanBeAcquired) lhsLvidinfo.autorelease = true; auto& origin = lhsLvidinfo.origin.varMember; bool isMemberVariable = (origin.atomid != 0); if (debugmode) { String comment; switch (strategy) { case AssignStrategy::rawregister: comment << "raw copy "; break; case AssignStrategy::ref: comment << "assign ref "; break; case AssignStrategy::deepcopy: comment << "deep copy "; break; } comment << "%" << lhs << " = %" << rhs << " aka '"; cdeflhs.print(comment, cdeftable, false); comment << '\''; out.emitComment(comment); } switch (strategy) { case AssignStrategy::rawregister: { out.emitStore(lhs, rhs); if (isMemberVariable) out.emitFieldset(lhs, origin.self, origin.field); break; } case AssignStrategy::ref: { // acquire first the right value to make sure that all data are alive // example: a = a out.emitRef(rhs); // release the old left value if (canDisposeLHS) { tryUnrefObject(lhs); if (isMemberVariable) tryUnrefObject(lhs); } // copy the pointer out.emitStore(lhs, rhs); if (isMemberVariable) { out.emitRef(lhs); // re-acquire for the object out.emitFieldset(lhs, origin.self, origin.field); } break; } case AssignStrategy::deepcopy: { auto* rhsAtom = cdeftable.findClassdefAtom(cdefrhs); if (unlikely(nullptr == rhsAtom)) return (ICE() << "invalid atom for left-side assignment"); // 'clone' operator if (0 == rhsAtom->classinfo.clone.atomid) { if (unlikely(not instanciateAtomClassClone(*rhsAtom, lhs, rhs))) return false; } // acquire first the right value to make sure that all data are alive // example: a = a out.emitRef(rhs); // release the old left value if (canDisposeLHS) { tryUnrefObject(lhs); if (isMemberVariable) tryUnrefObject(lhs); } // note: do not keep a reference on 'out.at...', since the internal buffer might be reized assert(lastOpcodeStacksizeOffset != (uint32_t) -1); auto& operands = out.at<IR::ISA::Op::stacksize>(lastOpcodeStacksizeOffset); uint32_t lvid = operands.add; uint32_t retcall = operands.add + 1; operands.add += 2; frame.resizeRegisterCount(lvid + 2, cdeftable); uint32_t rsizof = out.emitStackalloc(lvid, nyt_u64); out.emitSizeof(rsizof, rhsAtom->atomid); // re-allocate some memory out.emitMemalloc(lhs, rsizof); out.emitRef(lhs); assert(lhs < frame.lvids.size()); frame.lvids[lhs].origin.memalloc = true; out.emitStackalloc(retcall, nyt_void); // call operator 'clone' out.emitPush(lhs); // self out.emitPush(rhs); // rhs, the object to copy out.emitCall(retcall, rhsAtom->classinfo.clone.atomid, rhsAtom->classinfo.clone.instanceid); // release rhs - copy is done tryUnrefObject(rhs); if (isMemberVariable) { out.emitRef(lhs); out.emitFieldset(lhs, origin.self, origin.field); } break; } } return true; } bool ProgramBuilder::instanciateAssignment(const IR::ISA::Operand<IR::ISA::Op::call>& operands) { if (unlikely(lastPushedIndexedParameters.size() != 1)) { ICE() << "assignment: invalid number of pushed parameters"; return false; } if (unlikely(not lastPushedNamedParameters.empty())) { ICE() << "assignment: named parameters are not accepted"; return false; } // the current frame auto& frame = atomStack.back(); // -- LHS // note: double indirection, since assignment is like method call // %y = %x."=" // %z = resolve %y."^()" assert(operands.ptr2func < frame.lvids.size()); LVID lhs = frame.lvids[operands.ptr2func].referer; if (likely(0 != lhs)) { assert(lhs < frame.lvids.size()); lhs = frame.lvids[lhs].referer; } // -- RHS LVID rhs = lastPushedIndexedParameters[0].lvid; lastPushedIndexedParameters.clear(); return instanciateAssignment(frame, lhs, rhs); } } // namespace Instanciate } // namespace Pass } // namespace Nany <|endoftext|>
<commit_before>#include "arch/x86-64/page_manip.h" #include "interface/types.h" #include "interface/physical_mem.h" // Ensures that a page table exists before writing to it: void mem_create_pagetable( vmem_t vaddr ) { // check if the PML4T entry is there if( !(MEM_PML4T_ADDR[ MEM_PML4_INDEX(vaddr) ] & 1) ) { // not present, make a new PDPT pmem_t pdpt = physical_memory::allocate(1); MEM_PML4T_ADDR[ MEM_PML4_INDEX(vaddr) ] = (pdpt | 0x101); } // now it is; check if the PDPT entry is there if( !(MEM_PDPT_ADDR(vaddr)[ MEM_PDPT_INDEX(vaddr) ] & 1) ) { pmem_t pd = physical_memory::allocate(1); MEM_PDPT_ADDR(vaddr)[ MEM_PDPT_INDEX(vaddr) ] = (pd | 0x101); } // check for PD entry: if( !(MEM_PDIR_ADDR(vaddr)[ MEM_PDIR_INDEX(vaddr) ] & 1) ) { pmem_t pt = physical_memory::allocate(1); MEM_PDIR_ADDR(vaddr)[ MEM_PDIR_INDEX(vaddr) ] = (pt | 0x101); } } // As above, but only checks for existence; doesn't create tables bool mem_check_pagetable( vmem_t vaddr ) { if( !(MEM_PML4T_ADDR[ MEM_PML4_INDEX(vaddr) ] & 1) ) { return false; } if( !(MEM_PDPT_ADDR(vaddr)[ MEM_PDPT_INDEX(vaddr) ] & 1) ) { return false; } if( !(MEM_PDIR_ADDR(vaddr)[ MEM_PDIR_INDEX(vaddr) ] & 1) ) { return false; } return true; } page_entry mem_get_mmu_entry( vmem_t vaddr ) { if( !mem_check_pagetable(vaddr) ) { return page_entry(0); } return page_entry(MEM_PTBL_ADDR(vaddr)[ MEM_PTBL_INDEX(vaddr) ]); } pmem_t mem_get_physical_address( vmem_t vaddr ) { if( !mem_check_pagetable(vaddr) ) { return 0; } return MEM_PTBL_ADDR(vaddr)[ MEM_PTBL_INDEX(vaddr) ] & ~(0xFFF); } pmem_t mem_get_flags( vmem_t vaddr ) { if( !mem_check_pagetable(vaddr) ) { return 0; } return MEM_PTBL_ADDR(vaddr)[ MEM_PTBL_INDEX(vaddr) ] & 0xFFF; } void mem_set_mmu_entry( vmem_t vaddr, page_entry entry ) { mem_check_pagetable(vaddr); MEM_PTBL_ADDR(vaddr)[ MEM_PTBL_INDEX(vaddr) ] = static_cast<uint64_t>(entry); } void mem_set_physical_address( vmem_t vaddr, pmem_t paddr ) { mem_check_pagetable(vaddr); uint16_t flags = (MEM_PTBL_ADDR(vaddr)[ MEM_PTBL_INDEX(vaddr) ]) & 0xFFF; MEM_PTBL_ADDR(vaddr)[ MEM_PTBL_INDEX(vaddr) ] = (paddr & ~(0xFFF)) | flags; } void mem_set_flags( vmem_t vaddr, uint16_t flags ) { mem_check_pagetable(vaddr); pmem_t paddr = MEM_PTBL_ADDR(vaddr)[ MEM_PTBL_INDEX(vaddr) ] & ~(0xFFF); MEM_PTBL_ADDR(vaddr)[ MEM_PTBL_INDEX(vaddr) ] = paddr | (flags & 0xFFF); } <commit_msg>fix indentation in os/arch/x86-64/page_manip.cpp<commit_after>#include "arch/x86-64/page_manip.h" #include "interface/types.h" #include "interface/physical_mem.h" // Ensures that a page table exists before writing to it: void mem_create_pagetable( vmem_t vaddr ) { // check if the PML4T entry is there if( !(MEM_PML4T_ADDR[ MEM_PML4_INDEX(vaddr) ] & 1) ) { // not present, make a new PDPT pmem_t pdpt = physical_memory::allocate(1); MEM_PML4T_ADDR[ MEM_PML4_INDEX(vaddr) ] = (pdpt | 0x101); } // now it is; check if the PDPT entry is there if( !(MEM_PDPT_ADDR(vaddr)[ MEM_PDPT_INDEX(vaddr) ] & 1) ) { pmem_t pd = physical_memory::allocate(1); MEM_PDPT_ADDR(vaddr)[ MEM_PDPT_INDEX(vaddr) ] = (pd | 0x101); } // check for PD entry: if( !(MEM_PDIR_ADDR(vaddr)[ MEM_PDIR_INDEX(vaddr) ] & 1) ) { pmem_t pt = physical_memory::allocate(1); MEM_PDIR_ADDR(vaddr)[ MEM_PDIR_INDEX(vaddr) ] = (pt | 0x101); } } // As above, but only checks for existence; doesn't create tables bool mem_check_pagetable( vmem_t vaddr ) { if( !(MEM_PML4T_ADDR[ MEM_PML4_INDEX(vaddr) ] & 1) ) { return false; } if( !(MEM_PDPT_ADDR(vaddr)[ MEM_PDPT_INDEX(vaddr) ] & 1) ) { return false; } if( !(MEM_PDIR_ADDR(vaddr)[ MEM_PDIR_INDEX(vaddr) ] & 1) ) { return false; } return true; } page_entry mem_get_mmu_entry( vmem_t vaddr ) { if( !mem_check_pagetable(vaddr) ) { return page_entry(0); } return page_entry(MEM_PTBL_ADDR(vaddr)[ MEM_PTBL_INDEX(vaddr) ]); } pmem_t mem_get_physical_address( vmem_t vaddr ) { if( !mem_check_pagetable(vaddr) ) { return 0; } return MEM_PTBL_ADDR(vaddr)[ MEM_PTBL_INDEX(vaddr) ] & ~(0xFFF); } pmem_t mem_get_flags( vmem_t vaddr ) { if( !mem_check_pagetable(vaddr) ) { return 0; } return MEM_PTBL_ADDR(vaddr)[ MEM_PTBL_INDEX(vaddr) ] & 0xFFF; } void mem_set_mmu_entry( vmem_t vaddr, page_entry entry ) { mem_check_pagetable(vaddr); MEM_PTBL_ADDR(vaddr)[ MEM_PTBL_INDEX(vaddr) ] = static_cast<uint64_t>(entry); } void mem_set_physical_address( vmem_t vaddr, pmem_t paddr ) { mem_check_pagetable(vaddr); uint16_t flags = (MEM_PTBL_ADDR(vaddr)[ MEM_PTBL_INDEX(vaddr) ]) & 0xFFF; MEM_PTBL_ADDR(vaddr)[ MEM_PTBL_INDEX(vaddr) ] = (paddr & ~(0xFFF)) | flags; } void mem_set_flags( vmem_t vaddr, uint16_t flags ) { mem_check_pagetable(vaddr); pmem_t paddr = MEM_PTBL_ADDR(vaddr)[ MEM_PTBL_INDEX(vaddr) ] & ~(0xFFF); MEM_PTBL_ADDR(vaddr)[ MEM_PTBL_INDEX(vaddr) ] = paddr | (flags & 0xFFF); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: SchSlotIds.hxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: bm $ $Date: 2003-10-06 09:58:27 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SCH_SLOTIDS_HXX #define SCH_SLOTIDS_HXX // header for SID_OBJ1_START #ifndef _SFXSIDS_HRC #include <sfx2/sfxsids.hrc> #endif // SID_OBJ1_START == 30000 + 512 #define SID_COPYFORMAT SID_OBJ1_START #define SID_PASTEFORMAT (SID_OBJ1_START + 1) #define SID_DIAGRAM_DATA (SID_OBJ1_START + 2) #define SID_INSERT_TITLE (SID_OBJ1_START + 3) #define SID_INSERT_CHART_LEGEND (SID_OBJ1_START + 4) #define SID_INSERT_DESCRIPTION (SID_OBJ1_START + 5) #define SID_INSERT_AXIS (SID_OBJ1_START + 6) #define SID_DATA_ROW_POINT (SID_OBJ1_START + 7) #define SID_CHART_TITLE (SID_OBJ1_START + 8) #define SID_LEGEND (SID_OBJ1_START + 9) #define SID_DIAGRAM_AXIS (SID_OBJ1_START + 10) #define SID_DIAGRAM_GRID (SID_OBJ1_START + 11) #define SID_DIAGRAM_WALL (SID_OBJ1_START + 12) #define SID_DIAGRAM_FLOOR (SID_OBJ1_START + 13) #define SID_DIAGRAM_AREA (SID_OBJ1_START + 14) #define SID_3D_VIEW (SID_OBJ1_START + 15) #define SID_DIAGRAM_TYPE (SID_OBJ1_START + 16) #define SID_TOGGLE_TITLE (SID_OBJ1_START + 17) #define SID_TOGGLE_LEGEND (SID_OBJ1_START + 18) #define SID_TOGGLE_AXIS_TITLE (SID_OBJ1_START + 19) #define SID_TOGGLE_AXIS_DESCR (SID_OBJ1_START + 20) // 30532 #define SID_TOGGLE_GRID_HORZ (SID_OBJ1_START + 21) #define SID_TOGGLE_GRID_VERT (SID_OBJ1_START + 22) #define SID_DATA_IN_ROWS (SID_OBJ1_START + 23) #define SID_DATA_IN_COLUMNS (SID_OBJ1_START + 24) #define SID_TOOL_SELECT (SID_OBJ1_START + 25) #define SID_CONTEXT_TYPE (SID_OBJ1_START + 26) #define SID_NEW_ARRANGEMENT (SID_OBJ1_START + 27) // 30539 #define SID_INSERT_GRIDS (SID_OBJ1_START + 28) #define SID_MAINTITLE (SID_OBJ1_START + 29) #define SID_SUBTITLE (SID_OBJ1_START + 30) #define SID_XAXIS_TITLE (SID_OBJ1_START + 31) #define SID_YAXIS_TITLE (SID_OBJ1_START + 32) #define SID_ZAXIS_TITLE (SID_OBJ1_START + 33) #ifdef SID_UPDATE #undef SID_UPDATE #endif #define SID_UPDATE (SID_OBJ1_START + 34) // DataCollection #define SID_DATA (SID_OBJ1_START + 35) #define SID_ADD_COLUMN (SID_OBJ1_START + 36) #define SID_ADD_ROW (SID_OBJ1_START + 37) #define SID_DIAGRAM_AXIS_X (SID_OBJ1_START + 40) #define SID_DIAGRAM_AXIS_Y (SID_OBJ1_START + 41) #define SID_DIAGRAM_AXIS_Z (SID_OBJ1_START + 42) #define SID_DIAGRAM_AXIS_ALL (SID_OBJ1_START + 43) #define SID_INSERT_STATISTICS (SID_OBJ1_START + 44) #define SID_DIAGRAM_TITLE_MAIN (SID_OBJ1_START + 45) #define SID_DIAGRAM_TITLE_SUB (SID_OBJ1_START + 46) #define SID_DIAGRAM_TITLE_X (SID_OBJ1_START + 47) #define SID_DIAGRAM_TITLE_Y (SID_OBJ1_START + 48) #define SID_DIAGRAM_TITLE_Z (SID_OBJ1_START + 49) #define SID_DIAGRAM_TITLE_ALL (SID_OBJ1_START + 50) #define SID_DIAGRAM_GRID_Y_MAIN (SID_OBJ1_START + 51) #define SID_DIAGRAM_GRID_X_MAIN (SID_OBJ1_START + 52) #define SID_DIAGRAM_GRID_Z_MAIN (SID_OBJ1_START + 53) #define SID_DIAGRAM_GRID_ALL (SID_OBJ1_START + 54) #define SID_HAS_X_DESCR (SID_OBJ1_START + 55) #define SID_HAS_Y_DESCR (SID_OBJ1_START + 56) #define SID_HAS_Z_DESCR (SID_OBJ1_START + 57) #define SID_DIAGRAM_OBJECTS (SID_OBJ1_START + 60) #define SID_HAS_X_TITLE (SID_OBJ1_START + 61) #define SID_HAS_Y_TITLE (SID_OBJ1_START + 62) #define SID_HAS_Z_TITLE (SID_OBJ1_START + 63) #define SID_HAS_MAIN_TITLE (SID_OBJ1_START + 64) #define SID_HAS_SUB_TITLE (SID_OBJ1_START + 65) #define SID_DIAGRAM_GRID_Y_HELP (SID_OBJ1_START + 66) #define SID_DIAGRAM_GRID_X_HELP (SID_OBJ1_START + 67) #define SID_DIAGRAM_GRID_Z_HELP (SID_OBJ1_START + 68) #define SID_DIAGRAM_DATA_WIN (SID_OBJ1_START + 70) #define SID_DIAGRAM_ERROR (SID_OBJ1_START + 71) #define SID_DIAGRAM_AVERAGEVALUE (SID_OBJ1_START + 72) #define SID_DIAGRAM_REGRESSION (SID_OBJ1_START + 73) #define SID_SCALE_TEXT (SID_OBJ1_START + 74) #define SID_TEXTBREAK (SID_OBJ1_START + 75) #define SID_DIAGRAM_DATADESCRIPTION (SID_OBJ1_START + 76) #define SID_DIAGRAM_POSLEGEND (SID_OBJ1_START + 77) #define SID_DIAGRAM_DEFAULTCOLORS (SID_OBJ1_START + 78) #define SID_DIAGRAM_BARWIDTH (SID_OBJ1_START + 79) #define SID_DIAGRAM_NUMLINES (SID_OBJ1_START + 80) #define SID_ROW_POSITION (SID_OBJ1_START + 81) #define SID_ROW_MOREFRONT (SID_OBJ1_START + 82) #define SID_ROW_MOREBACK (SID_OBJ1_START + 83) // Title-Object #define SID_TITLE_TEXT (SID_OBJ1_START + 100) #define SID_DIAGRAM_STOCK_LINE (SID_OBJ1_START + 101) #define SID_DIAGRAM_STOCK_LOSS (SID_OBJ1_START + 102) #define SID_DIAGRAM_STOCK_PLUS (SID_OBJ1_START + 103) #define SID_DIAGRAM_AXIS_A (SID_OBJ1_START + 104) #define SID_DIAGRAM_AXIS_B (SID_OBJ1_START + 105) #define SID_DIAGRAM_AXIS_C (SID_OBJ1_START + 106) // Reserved till (SID_OBJ1_START + 110) #endif // SCH_SLOTIDS_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.110); FILE MERGED 2005/09/05 18:42:35 rt 1.1.1.1.110.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SchSlotIds.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 00:25:24 $ * * 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 SCH_SLOTIDS_HXX #define SCH_SLOTIDS_HXX // header for SID_OBJ1_START #ifndef _SFXSIDS_HRC #include <sfx2/sfxsids.hrc> #endif // SID_OBJ1_START == 30000 + 512 #define SID_COPYFORMAT SID_OBJ1_START #define SID_PASTEFORMAT (SID_OBJ1_START + 1) #define SID_DIAGRAM_DATA (SID_OBJ1_START + 2) #define SID_INSERT_TITLE (SID_OBJ1_START + 3) #define SID_INSERT_CHART_LEGEND (SID_OBJ1_START + 4) #define SID_INSERT_DESCRIPTION (SID_OBJ1_START + 5) #define SID_INSERT_AXIS (SID_OBJ1_START + 6) #define SID_DATA_ROW_POINT (SID_OBJ1_START + 7) #define SID_CHART_TITLE (SID_OBJ1_START + 8) #define SID_LEGEND (SID_OBJ1_START + 9) #define SID_DIAGRAM_AXIS (SID_OBJ1_START + 10) #define SID_DIAGRAM_GRID (SID_OBJ1_START + 11) #define SID_DIAGRAM_WALL (SID_OBJ1_START + 12) #define SID_DIAGRAM_FLOOR (SID_OBJ1_START + 13) #define SID_DIAGRAM_AREA (SID_OBJ1_START + 14) #define SID_3D_VIEW (SID_OBJ1_START + 15) #define SID_DIAGRAM_TYPE (SID_OBJ1_START + 16) #define SID_TOGGLE_TITLE (SID_OBJ1_START + 17) #define SID_TOGGLE_LEGEND (SID_OBJ1_START + 18) #define SID_TOGGLE_AXIS_TITLE (SID_OBJ1_START + 19) #define SID_TOGGLE_AXIS_DESCR (SID_OBJ1_START + 20) // 30532 #define SID_TOGGLE_GRID_HORZ (SID_OBJ1_START + 21) #define SID_TOGGLE_GRID_VERT (SID_OBJ1_START + 22) #define SID_DATA_IN_ROWS (SID_OBJ1_START + 23) #define SID_DATA_IN_COLUMNS (SID_OBJ1_START + 24) #define SID_TOOL_SELECT (SID_OBJ1_START + 25) #define SID_CONTEXT_TYPE (SID_OBJ1_START + 26) #define SID_NEW_ARRANGEMENT (SID_OBJ1_START + 27) // 30539 #define SID_INSERT_GRIDS (SID_OBJ1_START + 28) #define SID_MAINTITLE (SID_OBJ1_START + 29) #define SID_SUBTITLE (SID_OBJ1_START + 30) #define SID_XAXIS_TITLE (SID_OBJ1_START + 31) #define SID_YAXIS_TITLE (SID_OBJ1_START + 32) #define SID_ZAXIS_TITLE (SID_OBJ1_START + 33) #ifdef SID_UPDATE #undef SID_UPDATE #endif #define SID_UPDATE (SID_OBJ1_START + 34) // DataCollection #define SID_DATA (SID_OBJ1_START + 35) #define SID_ADD_COLUMN (SID_OBJ1_START + 36) #define SID_ADD_ROW (SID_OBJ1_START + 37) #define SID_DIAGRAM_AXIS_X (SID_OBJ1_START + 40) #define SID_DIAGRAM_AXIS_Y (SID_OBJ1_START + 41) #define SID_DIAGRAM_AXIS_Z (SID_OBJ1_START + 42) #define SID_DIAGRAM_AXIS_ALL (SID_OBJ1_START + 43) #define SID_INSERT_STATISTICS (SID_OBJ1_START + 44) #define SID_DIAGRAM_TITLE_MAIN (SID_OBJ1_START + 45) #define SID_DIAGRAM_TITLE_SUB (SID_OBJ1_START + 46) #define SID_DIAGRAM_TITLE_X (SID_OBJ1_START + 47) #define SID_DIAGRAM_TITLE_Y (SID_OBJ1_START + 48) #define SID_DIAGRAM_TITLE_Z (SID_OBJ1_START + 49) #define SID_DIAGRAM_TITLE_ALL (SID_OBJ1_START + 50) #define SID_DIAGRAM_GRID_Y_MAIN (SID_OBJ1_START + 51) #define SID_DIAGRAM_GRID_X_MAIN (SID_OBJ1_START + 52) #define SID_DIAGRAM_GRID_Z_MAIN (SID_OBJ1_START + 53) #define SID_DIAGRAM_GRID_ALL (SID_OBJ1_START + 54) #define SID_HAS_X_DESCR (SID_OBJ1_START + 55) #define SID_HAS_Y_DESCR (SID_OBJ1_START + 56) #define SID_HAS_Z_DESCR (SID_OBJ1_START + 57) #define SID_DIAGRAM_OBJECTS (SID_OBJ1_START + 60) #define SID_HAS_X_TITLE (SID_OBJ1_START + 61) #define SID_HAS_Y_TITLE (SID_OBJ1_START + 62) #define SID_HAS_Z_TITLE (SID_OBJ1_START + 63) #define SID_HAS_MAIN_TITLE (SID_OBJ1_START + 64) #define SID_HAS_SUB_TITLE (SID_OBJ1_START + 65) #define SID_DIAGRAM_GRID_Y_HELP (SID_OBJ1_START + 66) #define SID_DIAGRAM_GRID_X_HELP (SID_OBJ1_START + 67) #define SID_DIAGRAM_GRID_Z_HELP (SID_OBJ1_START + 68) #define SID_DIAGRAM_DATA_WIN (SID_OBJ1_START + 70) #define SID_DIAGRAM_ERROR (SID_OBJ1_START + 71) #define SID_DIAGRAM_AVERAGEVALUE (SID_OBJ1_START + 72) #define SID_DIAGRAM_REGRESSION (SID_OBJ1_START + 73) #define SID_SCALE_TEXT (SID_OBJ1_START + 74) #define SID_TEXTBREAK (SID_OBJ1_START + 75) #define SID_DIAGRAM_DATADESCRIPTION (SID_OBJ1_START + 76) #define SID_DIAGRAM_POSLEGEND (SID_OBJ1_START + 77) #define SID_DIAGRAM_DEFAULTCOLORS (SID_OBJ1_START + 78) #define SID_DIAGRAM_BARWIDTH (SID_OBJ1_START + 79) #define SID_DIAGRAM_NUMLINES (SID_OBJ1_START + 80) #define SID_ROW_POSITION (SID_OBJ1_START + 81) #define SID_ROW_MOREFRONT (SID_OBJ1_START + 82) #define SID_ROW_MOREBACK (SID_OBJ1_START + 83) // Title-Object #define SID_TITLE_TEXT (SID_OBJ1_START + 100) #define SID_DIAGRAM_STOCK_LINE (SID_OBJ1_START + 101) #define SID_DIAGRAM_STOCK_LOSS (SID_OBJ1_START + 102) #define SID_DIAGRAM_STOCK_PLUS (SID_OBJ1_START + 103) #define SID_DIAGRAM_AXIS_A (SID_OBJ1_START + 104) #define SID_DIAGRAM_AXIS_B (SID_OBJ1_START + 105) #define SID_DIAGRAM_AXIS_C (SID_OBJ1_START + 106) // Reserved till (SID_OBJ1_START + 110) #endif // SCH_SLOTIDS_HXX <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "UndoGuard.hxx" #include "ChartModelClone.hxx" #include "UndoActions.hxx" #include <com/sun/star/container/XChild.hpp> #include <tools/diagnose_ex.h> using namespace ::com::sun::star; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Sequence; using ::rtl::OUString; namespace chart { //----------------------------------------------------------------------------- UndoGuard::UndoGuard( const OUString& i_undoString, const uno::Reference< document::XUndoManager > & i_undoManager, const ModelFacet i_facet ) :m_xChartModel( i_undoManager->getParent(), uno::UNO_QUERY_THROW ) ,m_xUndoManager( i_undoManager ) ,m_pDocumentSnapshot() ,m_aUndoString( i_undoString ) ,m_bActionPosted( false ) { m_pDocumentSnapshot.reset( new ChartModelClone( m_xChartModel, i_facet ) ); } //----------------------------------------------------------------------------- UndoGuard::~UndoGuard() { if ( !!m_pDocumentSnapshot ) discardSnapshot(); } //----------------------------------------------------------------------------- void UndoGuard::commit() { if ( !m_bActionPosted && !!m_pDocumentSnapshot && m_xUndoManager.is() ) { const Reference< document::XUndoAction > xAction( new impl::UndoElement( m_aUndoString, m_xChartModel, m_pDocumentSnapshot ) ); m_pDocumentSnapshot.reset(); // don't dispose, it's data went over to the UndoElement m_xUndoManager->addUndoAction( xAction ); } m_bActionPosted = true; } //----------------------------------------------------------------------------- void UndoGuard::rollback() { ENSURE_OR_RETURN_VOID( !!m_pDocumentSnapshot, "no snapshot!" ); m_pDocumentSnapshot->applyToModel( m_xChartModel ); discardSnapshot(); } //----------------------------------------------------------------------------- void UndoGuard::discardSnapshot() { ENSURE_OR_RETURN_VOID( !!m_pDocumentSnapshot, "no snapshot!" ); m_pDocumentSnapshot->dispose(); m_pDocumentSnapshot.reset(); } //----------------------------------------------------------------------------- UndoLiveUpdateGuard::UndoLiveUpdateGuard( const OUString& i_undoString, const uno::Reference< document::XUndoManager >& i_undoManager ) :UndoGuard( i_undoString, i_undoManager, E_MODEL ) { } UndoLiveUpdateGuard::~UndoLiveUpdateGuard() { if ( !isActionPosted() ) rollback(); } //----------------------------------------------------------------------------- UndoLiveUpdateGuardWithData::UndoLiveUpdateGuardWithData( const OUString& i_undoString, const uno::Reference< document::XUndoManager >& i_undoManager ) :UndoGuard( i_undoString, i_undoManager, E_MODEL_WITH_DATA ) { } UndoLiveUpdateGuardWithData::~UndoLiveUpdateGuardWithData() { if ( !isActionPosted() ) rollback(); } //----------------------------------------------------------------------------- UndoGuardWithSelection::UndoGuardWithSelection( const OUString& i_undoString, const uno::Reference< document::XUndoManager >& i_undoManager ) :UndoGuard( i_undoString, i_undoManager, E_MODEL_WITH_SELECTION ) { } UndoGuardWithSelection::~UndoGuardWithSelection() { if ( !isActionPosted() ) rollback(); } } // namespace chart <commit_msg>undoapi: some exception safety<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "UndoGuard.hxx" #include "ChartModelClone.hxx" #include "UndoActions.hxx" #include <com/sun/star/container/XChild.hpp> #include <tools/diagnose_ex.h> using namespace ::com::sun::star; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Sequence; using ::rtl::OUString; namespace chart { //----------------------------------------------------------------------------- UndoGuard::UndoGuard( const OUString& i_undoString, const uno::Reference< document::XUndoManager > & i_undoManager, const ModelFacet i_facet ) :m_xChartModel( i_undoManager->getParent(), uno::UNO_QUERY_THROW ) ,m_xUndoManager( i_undoManager ) ,m_pDocumentSnapshot() ,m_aUndoString( i_undoString ) ,m_bActionPosted( false ) { m_pDocumentSnapshot.reset( new ChartModelClone( m_xChartModel, i_facet ) ); } //----------------------------------------------------------------------------- UndoGuard::~UndoGuard() { if ( !!m_pDocumentSnapshot ) discardSnapshot(); } //----------------------------------------------------------------------------- void UndoGuard::commit() { if ( !m_bActionPosted && !!m_pDocumentSnapshot ) { try { const Reference< document::XUndoAction > xAction( new impl::UndoElement( m_aUndoString, m_xChartModel, m_pDocumentSnapshot ) ); m_pDocumentSnapshot.reset(); // don't dispose, it's data went over to the UndoElement m_xUndoManager->addUndoAction( xAction ); } catch( const uno::Exception& ) { DBG_UNHANDLED_EXCEPTION(); } } m_bActionPosted = true; } //----------------------------------------------------------------------------- void UndoGuard::rollback() { ENSURE_OR_RETURN_VOID( !!m_pDocumentSnapshot, "no snapshot!" ); m_pDocumentSnapshot->applyToModel( m_xChartModel ); discardSnapshot(); } //----------------------------------------------------------------------------- void UndoGuard::discardSnapshot() { ENSURE_OR_RETURN_VOID( !!m_pDocumentSnapshot, "no snapshot!" ); m_pDocumentSnapshot->dispose(); m_pDocumentSnapshot.reset(); } //----------------------------------------------------------------------------- UndoLiveUpdateGuard::UndoLiveUpdateGuard( const OUString& i_undoString, const uno::Reference< document::XUndoManager >& i_undoManager ) :UndoGuard( i_undoString, i_undoManager, E_MODEL ) { } UndoLiveUpdateGuard::~UndoLiveUpdateGuard() { if ( !isActionPosted() ) rollback(); } //----------------------------------------------------------------------------- UndoLiveUpdateGuardWithData::UndoLiveUpdateGuardWithData( const OUString& i_undoString, const uno::Reference< document::XUndoManager >& i_undoManager ) :UndoGuard( i_undoString, i_undoManager, E_MODEL_WITH_DATA ) { } UndoLiveUpdateGuardWithData::~UndoLiveUpdateGuardWithData() { if ( !isActionPosted() ) rollback(); } //----------------------------------------------------------------------------- UndoGuardWithSelection::UndoGuardWithSelection( const OUString& i_undoString, const uno::Reference< document::XUndoManager >& i_undoManager ) :UndoGuard( i_undoString, i_undoManager, E_MODEL_WITH_SELECTION ) { } UndoGuardWithSelection::~UndoGuardWithSelection() { if ( !isActionPosted() ) rollback(); } } // namespace chart <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include <basegfx/numeric/ftools.hxx> #include "VPolarAngleAxis.hxx" #include "VPolarGrid.hxx" #include "ShapeFactory.hxx" #include "macros.hxx" #include "NumberFormatterWrapper.hxx" #include "PolarLabelPositionHelper.hxx" #include <tools/color.hxx> #include <memory> //............................................................................. namespace chart { //............................................................................. using namespace ::com::sun::star; using namespace ::com::sun::star::chart2; using namespace ::rtl::math; VPolarAngleAxis::VPolarAngleAxis( const AxisProperties& rAxisProperties , const uno::Reference< util::XNumberFormatsSupplier >& xNumberFormatsSupplier , sal_Int32 nDimensionCount ) : VPolarAxis( rAxisProperties, xNumberFormatsSupplier, 0/*nDimensionIndex*/, nDimensionCount ) { } VPolarAngleAxis::~VPolarAngleAxis() { delete m_pPosHelper; m_pPosHelper = NULL; } bool VPolarAngleAxis::createTextShapes_ForAngleAxis( const uno::Reference< drawing::XShapes >& xTarget , EquidistantTickIter& rTickIter , AxisLabelProperties& rAxisLabelProperties , double fLogicRadius , double fLogicZ ) { sal_Int32 nDimensionCount = 2; ShapeFactory aShapeFactory(m_xShapeFactory); FixedNumberFormatter aFixedNumberFormatter( m_xNumberFormatsSupplier, rAxisLabelProperties.nNumberFormatKey ); //------------------------------------------------ //prepare text properties for multipropertyset-interface of shape tNameSequence aPropNames; tAnySequence aPropValues; uno::Reference< beans::XPropertySet > xProps( m_aAxisProperties.m_xAxisModel, uno::UNO_QUERY ); PropertyMapper::getTextLabelMultiPropertyLists( xProps, aPropNames, aPropValues, false ); LabelPositionHelper::doDynamicFontResize( aPropValues, aPropNames, xProps , rAxisLabelProperties.m_aFontReferenceSize ); uno::Any* pColorAny = PropertyMapper::getValuePointer(aPropValues,aPropNames,C2U("CharColor")); sal_Int32 nColor = Color( COL_AUTO ).GetColor(); if(pColorAny) *pColorAny >>= nColor; const uno::Sequence< rtl::OUString >* pLabels = m_bUseTextLabels? &m_aTextLabels : 0; //------------------------------------------------ //TickInfo* pLastVisibleNeighbourTickInfo = NULL; sal_Int32 nTick = 0; for( TickInfo* pTickInfo = rTickIter.firstInfo() ; pTickInfo ; pTickInfo = rTickIter.nextInfo(), nTick++ ) { //don't create labels which does not fit into the rhythm if( nTick%rAxisLabelProperties.nRhythm != 0) continue; //don't create labels for invisible ticks if( !pTickInfo->bPaintIt ) continue; //if NO OVERLAP -> don't create labels where the //anchor position is the same as for the last label //@todo if(!pTickInfo->xTextShape.is()) { //create single label bool bHasExtraColor=false; sal_Int32 nExtraColor=0; rtl::OUString aLabel; if(pLabels) { sal_Int32 nIndex = static_cast< sal_Int32 >(pTickInfo->getUnscaledTickValue()) - 1; //first category (index 0) matches with real number 1.0 if( nIndex>=0 && nIndex<pLabels->getLength() ) aLabel = (*pLabels)[nIndex]; } else aLabel = aFixedNumberFormatter.getFormattedString( pTickInfo->getUnscaledTickValue(), nExtraColor, bHasExtraColor ); if(pColorAny) *pColorAny = uno::makeAny(bHasExtraColor?nExtraColor:nColor); double fLogicAngle = pTickInfo->getUnscaledTickValue(); LabelAlignment eLabelAlignment(LABEL_ALIGN_CENTER); PolarLabelPositionHelper aPolarLabelPositionHelper(m_pPosHelper,nDimensionCount,xTarget,&aShapeFactory); sal_Int32 nScreenValueOffsetInRadiusDirection = m_aAxisLabelProperties.m_aMaximumSpaceForLabels.Height/15; awt::Point aAnchorScreenPosition2D( aPolarLabelPositionHelper.getLabelScreenPositionAndAlignmentForLogicValues( eLabelAlignment, fLogicAngle, fLogicRadius, fLogicZ, nScreenValueOffsetInRadiusDirection )); LabelPositionHelper::changeTextAdjustment( aPropValues, aPropNames, eLabelAlignment ); // #i78696# use mathematically correct rotation now const double fRotationAnglePi(rAxisLabelProperties.fRotationAngleDegree * (F_PI / -180.0)); uno::Any aATransformation = ShapeFactory::makeTransformation( aAnchorScreenPosition2D, fRotationAnglePi ); rtl::OUString aStackedLabel = ShapeFactory::getStackedString( aLabel, rAxisLabelProperties.bStackCharacters ); pTickInfo->xTextShape = aShapeFactory.createText( xTarget, aStackedLabel, aPropNames, aPropValues, aATransformation ); } //if NO OVERLAP -> remove overlapping shapes //@todo } return true; } void VPolarAngleAxis::createMaximumLabels() { if( !prepareShapeCreation() ) return; createLabels(); } void VPolarAngleAxis::updatePositions() { //todo: really only update the positions if( !prepareShapeCreation() ) return; createLabels(); } void VPolarAngleAxis::createLabels() { if( !prepareShapeCreation() ) return; double fLogicRadius = m_pPosHelper->getOuterLogicRadius(); double fLogicZ = 1.0;//as defined if( m_aAxisProperties.m_bDisplayLabels ) { //----------------------------------------- //get the transformed screen values for all tickmarks in aAllTickInfos std::auto_ptr< TickFactory > apTickFactory( this->createTickFactory() ); //create tick mark text shapes //@todo: iterate through all tick depth wich should be labeled EquidistantTickIter aTickIter( m_aAllTickInfos, m_aIncrement, 0, 0 ); this->updateUnscaledValuesAtTicks( aTickIter ); removeTextShapesFromTicks(); AxisLabelProperties aAxisLabelProperties( m_aAxisLabelProperties ); aAxisLabelProperties.bOverlapAllowed = true; double fLogicZ = -0.5;//as defined while( !createTextShapes_ForAngleAxis( m_xTextTarget, aTickIter , aAxisLabelProperties , fLogicRadius, fLogicZ ) ) { }; //no staggering for polar angle axis } } void VPolarAngleAxis::createShapes() { if( !prepareShapeCreation() ) return; double fLogicRadius = m_pPosHelper->getOuterLogicRadius(); double fLogicZ = 1.0;//as defined //----------------------------------------- //create axis main lines drawing::PointSequenceSequence aPoints(1); VPolarGrid::createLinePointSequence_ForAngleAxis( aPoints, m_aAllTickInfos, m_aIncrement, m_aScale, m_pPosHelper, fLogicRadius, fLogicZ ); uno::Reference< drawing::XShape > xShape = m_pShapeFactory->createLine2D( m_xGroupShape_Shapes, aPoints, &m_aAxisProperties.m_aLineProperties ); //because of this name this line will be used for marking the axis m_pShapeFactory->setShapeName( xShape, C2U("MarkHandles") ); //----------------------------------------- //create labels createLabels(); } //............................................................................. } //namespace chart //............................................................................. /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>mis-merge: a declaration was moved due to cppcheck, and also changed value<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include <basegfx/numeric/ftools.hxx> #include "VPolarAngleAxis.hxx" #include "VPolarGrid.hxx" #include "ShapeFactory.hxx" #include "macros.hxx" #include "NumberFormatterWrapper.hxx" #include "PolarLabelPositionHelper.hxx" #include <tools/color.hxx> #include <memory> //............................................................................. namespace chart { //............................................................................. using namespace ::com::sun::star; using namespace ::com::sun::star::chart2; using namespace ::rtl::math; VPolarAngleAxis::VPolarAngleAxis( const AxisProperties& rAxisProperties , const uno::Reference< util::XNumberFormatsSupplier >& xNumberFormatsSupplier , sal_Int32 nDimensionCount ) : VPolarAxis( rAxisProperties, xNumberFormatsSupplier, 0/*nDimensionIndex*/, nDimensionCount ) { } VPolarAngleAxis::~VPolarAngleAxis() { delete m_pPosHelper; m_pPosHelper = NULL; } bool VPolarAngleAxis::createTextShapes_ForAngleAxis( const uno::Reference< drawing::XShapes >& xTarget , EquidistantTickIter& rTickIter , AxisLabelProperties& rAxisLabelProperties , double fLogicRadius , double fLogicZ ) { sal_Int32 nDimensionCount = 2; ShapeFactory aShapeFactory(m_xShapeFactory); FixedNumberFormatter aFixedNumberFormatter( m_xNumberFormatsSupplier, rAxisLabelProperties.nNumberFormatKey ); //------------------------------------------------ //prepare text properties for multipropertyset-interface of shape tNameSequence aPropNames; tAnySequence aPropValues; uno::Reference< beans::XPropertySet > xProps( m_aAxisProperties.m_xAxisModel, uno::UNO_QUERY ); PropertyMapper::getTextLabelMultiPropertyLists( xProps, aPropNames, aPropValues, false ); LabelPositionHelper::doDynamicFontResize( aPropValues, aPropNames, xProps , rAxisLabelProperties.m_aFontReferenceSize ); uno::Any* pColorAny = PropertyMapper::getValuePointer(aPropValues,aPropNames,C2U("CharColor")); sal_Int32 nColor = Color( COL_AUTO ).GetColor(); if(pColorAny) *pColorAny >>= nColor; const uno::Sequence< rtl::OUString >* pLabels = m_bUseTextLabels? &m_aTextLabels : 0; //------------------------------------------------ //TickInfo* pLastVisibleNeighbourTickInfo = NULL; sal_Int32 nTick = 0; for( TickInfo* pTickInfo = rTickIter.firstInfo() ; pTickInfo ; pTickInfo = rTickIter.nextInfo(), nTick++ ) { //don't create labels which does not fit into the rhythm if( nTick%rAxisLabelProperties.nRhythm != 0) continue; //don't create labels for invisible ticks if( !pTickInfo->bPaintIt ) continue; //if NO OVERLAP -> don't create labels where the //anchor position is the same as for the last label //@todo if(!pTickInfo->xTextShape.is()) { //create single label bool bHasExtraColor=false; sal_Int32 nExtraColor=0; rtl::OUString aLabel; if(pLabels) { sal_Int32 nIndex = static_cast< sal_Int32 >(pTickInfo->getUnscaledTickValue()) - 1; //first category (index 0) matches with real number 1.0 if( nIndex>=0 && nIndex<pLabels->getLength() ) aLabel = (*pLabels)[nIndex]; } else aLabel = aFixedNumberFormatter.getFormattedString( pTickInfo->getUnscaledTickValue(), nExtraColor, bHasExtraColor ); if(pColorAny) *pColorAny = uno::makeAny(bHasExtraColor?nExtraColor:nColor); double fLogicAngle = pTickInfo->getUnscaledTickValue(); LabelAlignment eLabelAlignment(LABEL_ALIGN_CENTER); PolarLabelPositionHelper aPolarLabelPositionHelper(m_pPosHelper,nDimensionCount,xTarget,&aShapeFactory); sal_Int32 nScreenValueOffsetInRadiusDirection = m_aAxisLabelProperties.m_aMaximumSpaceForLabels.Height/15; awt::Point aAnchorScreenPosition2D( aPolarLabelPositionHelper.getLabelScreenPositionAndAlignmentForLogicValues( eLabelAlignment, fLogicAngle, fLogicRadius, fLogicZ, nScreenValueOffsetInRadiusDirection )); LabelPositionHelper::changeTextAdjustment( aPropValues, aPropNames, eLabelAlignment ); // #i78696# use mathematically correct rotation now const double fRotationAnglePi(rAxisLabelProperties.fRotationAngleDegree * (F_PI / -180.0)); uno::Any aATransformation = ShapeFactory::makeTransformation( aAnchorScreenPosition2D, fRotationAnglePi ); rtl::OUString aStackedLabel = ShapeFactory::getStackedString( aLabel, rAxisLabelProperties.bStackCharacters ); pTickInfo->xTextShape = aShapeFactory.createText( xTarget, aStackedLabel, aPropNames, aPropValues, aATransformation ); } //if NO OVERLAP -> remove overlapping shapes //@todo } return true; } void VPolarAngleAxis::createMaximumLabels() { if( !prepareShapeCreation() ) return; createLabels(); } void VPolarAngleAxis::updatePositions() { //todo: really only update the positions if( !prepareShapeCreation() ) return; createLabels(); } void VPolarAngleAxis::createLabels() { if( !prepareShapeCreation() ) return; double fLogicRadius = m_pPosHelper->getOuterLogicRadius(); if( m_aAxisProperties.m_bDisplayLabels ) { //----------------------------------------- //get the transformed screen values for all tickmarks in aAllTickInfos std::auto_ptr< TickFactory > apTickFactory( this->createTickFactory() ); //create tick mark text shapes //@todo: iterate through all tick depth wich should be labeled EquidistantTickIter aTickIter( m_aAllTickInfos, m_aIncrement, 0, 0 ); this->updateUnscaledValuesAtTicks( aTickIter ); removeTextShapesFromTicks(); AxisLabelProperties aAxisLabelProperties( m_aAxisLabelProperties ); aAxisLabelProperties.bOverlapAllowed = true; double fLogicZ = 1.0;//as defined while( !createTextShapes_ForAngleAxis( m_xTextTarget, aTickIter , aAxisLabelProperties , fLogicRadius, fLogicZ ) ) { }; //no staggering for polar angle axis } } void VPolarAngleAxis::createShapes() { if( !prepareShapeCreation() ) return; double fLogicRadius = m_pPosHelper->getOuterLogicRadius(); double fLogicZ = 1.0;//as defined //----------------------------------------- //create axis main lines drawing::PointSequenceSequence aPoints(1); VPolarGrid::createLinePointSequence_ForAngleAxis( aPoints, m_aAllTickInfos, m_aIncrement, m_aScale, m_pPosHelper, fLogicRadius, fLogicZ ); uno::Reference< drawing::XShape > xShape = m_pShapeFactory->createLine2D( m_xGroupShape_Shapes, aPoints, &m_aAxisProperties.m_aLineProperties ); //because of this name this line will be used for marking the axis m_pShapeFactory->setShapeName( xShape, C2U("MarkHandles") ); //----------------------------------------- //create labels createLabels(); } //............................................................................. } //namespace chart //............................................................................. /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>//This tutorial illustrates how to create an histogram with polygonal //bins (TH2Poly), fill it and draw it. The initial data are stored //in TMultiGraphs. They represent the european countries. //The histogram filling is done according to a Mercator projection, //therefore the bin contains should be proportional to the real surface //of the countries. // //The initial data have been downloaded from: http://www.maproom.psu.edu/dcw/ //This database was developed in 1991/1992 and national boundaries reflect //political reality as of that time. // //Author: Olivier Couet void th2polyEurope() { Int_t i,j; Double_t lon1 = -25; Double_t lon2 = 35; Double_t lat1 = 34; Double_t lat2 = 72; Double_t R = (lat2-lat1)/(lon2-lon1); Int_t W = 800; Int_t H = (Int_t)(R*800); gStyle->SetTitleX(0.2); gStyle->SetStatY(0.89); gStyle->SetStatW(0.15); // Canvas used to draw TH2Poly (the map) TCanvas *ce = new TCanvas("ce", "ce",0,0,W,H); ce->ToggleEventStatus(); ce->SetGridx(); ce->SetGridy(); // Real surfaces taken from Wikipedia. const Int_t nx = 36; char *countries[nx] = { "france", "spain", "sweden", "germany", "finland", "norway", "poland", "italy", "yugoslavia", "united_kingdom", "romania", "belarus", "greece", "czechoslovakia", "bulgaria", "iceland", "hungary", "portugal", "austria", "ireland", "lithuania", "latvia", "estonia", "denmark", "netherlands", "switzerland", "moldova", "belgium", "albania", "cyprus", "luxembourg", "andorra", "malta", "liechtenstein", "san_marino", "monaco" }; Float_t surfaces[nx] = { 547030, 505580, 449964, 357021, 338145, 324220, 312685, 301230, 255438, 244820, 237500, 207600, 131940, 127711, 110910, 103000, 93030, 89242, 83870, 70280, 65200, 64589, 45226, 43094, 41526, 41290, 33843, 30528, 28748, 9250, 2586, 468, 316, 160, 61, 2}; TH1F *h = new TH1F("h","Countries' surfaces (in km^{2})",3,0,3); for (i=0; i<nx; i++) h->Fill(countries[i], surfaces[i]); h->LabelsDeflate(); TFile *f; f = TFile::Open("http://root.cern.ch/files/europe.root"); TH2Poly *p = new TH2Poly( "Europe", "Europe (bins' contains are normalize to the surfaces in km^{2})", lon1,lon2,lat1,lat2); p->GetXaxis()->SetNdivisions(520); TMultiGraph *mg; TKey *key; TIter nextkey(gDirectory->GetListOfKeys()); while (key = (TKey*)nextkey()) { obj = key->ReadObj(); if (obj->InheritsFrom("TMultiGraph")) { mg = (TMultiGraph*)obj; p->AddBin(mg); } } TRandom r; Double_t longitude, latitude; Double_t x, y, dr = TMath::Pi()/180, rd = 180/TMath::Pi(); gBenchmark->Start("Partitioning"); p->ChangePartition(100, 100); gBenchmark->Show("Partitioning"); // Fill TH2Poly according to a Mercator projection. gBenchmark->Start("Filling"); for (i=0; i<500000; i++) { longitude = r.Uniform(dr*lon1,dr*lon2); latitude = r.Uniform(-dr*90,dr*90); x = rd*longitude; y = 39*TMath::Log(TMath::Tan((TMath::Pi()/4)+(latitude/2))); p->Fill(x,y); } gBenchmark->Show("Filling"); Int_t nbins = p->GetNumberOfBins(); Double_t maximum = p->GetMaximum(); printf("Nbins = %d Minimum = %g Maximum = %g Integral = %f \n", nbins, p->GetMinimum(), maximum, p->Integral()); // h2 contains the surfaces computed from TH2Poly. TH1F *h2 = h->Clone(); h2->Reset(); for (j=0; j<nx; j++) { for (i=0; i<nbins; i++) { if (strstr(countries[j],p->GetBinName(i+1))) { h2->Fill(countries[j],p->GetBinContent(i+1)); h2->SetBinError(j, p->GetBinError(i+1)); } } } // Normalize the TH2Poly bin contents to the real surfaces. Double_t scale = surfaces[0]/maximum; for (i=0; i<nbins; i++) p->SetBinContent(i+1, scale*p->GetBinContent(i+1)); gStyle->SetOptStat(1111); gStyle->SetPalette(1); p->Draw("COL"); TCanvas *c1 = new TCanvas("c1", "c1",W+10,0,W-20,H); c1->SetRightMargin(0.047); Double_t scale = h->GetMaximum()/h2->GetMaximum(); h->SetStats(0); h->Draw("L"); h->SetLineColor(kRed-3); h->SetLineWidth(2); h->GetXaxis()->SetLabelFont(42); h->GetXaxis()->SetLabelSize(0.03); h->GetYaxis()->SetLabelFont(42); h2->Scale(scale); Double_t scale2=TMath::Sqrt(scale); for (i=0; i<nx; i++) h2->SetBinError(i+1, scale2*h2->GetBinError(i+1)); h2->Draw("E SAME"); h2->SetMarkerStyle(20); h2->SetMarkerSize(0.8); TLegend *leg = new TLegend(0.5,0.67,0.92,0.8,NULL,"NDC"); leg->SetTextFont(42); leg->SetTextSize(0.025); leg->AddEntry(h,"Real countries' surfaces from Wikipedia (in km^{2})","l"); leg->AddEntry(h2,"Countries' surfaces from TH2Poly (with errors)","lp"); leg->Draw(); } <commit_msg>Better efficiency when filling. Restrict the source to the Europe area<commit_after>//This tutorial illustrates how to create an histogram with polygonal //bins (TH2Poly), fill it and draw it. The initial data are stored //in TMultiGraphs. They represent the european countries. //The histogram filling is done according to a Mercator projection, //therefore the bin contains should be proportional to the real surface //of the countries. // //The initial data have been downloaded from: http://www.maproom.psu.edu/dcw/ //This database was developed in 1991/1992 and national boundaries reflect //political reality as of that time. // //Author: Olivier Couet void th2polyEurope() { Int_t i,j; Double_t lon1 = -25; Double_t lon2 = 35; Double_t lat1 = 34; Double_t lat2 = 72; Double_t R = (lat2-lat1)/(lon2-lon1); Int_t W = 800; Int_t H = (Int_t)(R*800); gStyle->SetTitleX(0.2); gStyle->SetStatY(0.89); gStyle->SetStatW(0.15); // Canvas used to draw TH2Poly (the map) TCanvas *ce = new TCanvas("ce", "ce",0,0,W,H); ce->ToggleEventStatus(); ce->SetGridx(); ce->SetGridy(); // Real surfaces taken from Wikipedia. const Int_t nx = 36; char *countries[nx] = { "france", "spain", "sweden", "germany", "finland", "norway", "poland", "italy", "yugoslavia", "united_kingdom", "romania", "belarus", "greece", "czechoslovakia", "bulgaria", "iceland", "hungary", "portugal", "austria", "ireland", "lithuania", "latvia", "estonia", "denmark", "netherlands", "switzerland", "moldova", "belgium", "albania", "cyprus", "luxembourg", "andorra", "malta", "liechtenstein", "san_marino", "monaco" }; Float_t surfaces[nx] = { 547030, 505580, 449964, 357021, 338145, 324220, 312685, 301230, 255438, 244820, 237500, 207600, 131940, 127711, 110910, 103000, 93030, 89242, 83870, 70280, 65200, 64589, 45226, 43094, 41526, 41290, 33843, 30528, 28748, 9250, 2586, 468, 316, 160, 61, 2}; TH1F *h = new TH1F("h","Countries' surfaces (in km^{2})",3,0,3); for (i=0; i<nx; i++) h->Fill(countries[i], surfaces[i]); h->LabelsDeflate(); TFile *f; f = TFile::Open("http://root.cern.ch/files/europe.root"); TH2Poly *p = new TH2Poly( "Europe", "Europe (bins' contains are normalize to the surfaces in km^{2})", lon1,lon2,lat1,lat2); p->GetXaxis()->SetNdivisions(520); TMultiGraph *mg; TKey *key; TIter nextkey(gDirectory->GetListOfKeys()); while (key = (TKey*)nextkey()) { obj = key->ReadObj(); if (obj->InheritsFrom("TMultiGraph")) { mg = (TMultiGraph*)obj; p->AddBin(mg); } } TRandom r; Double_t longitude, latitude; Double_t x, y, dr = TMath::Pi()/180, rd = 180/TMath::Pi(); gBenchmark->Start("Partitioning"); p->ChangePartition(100, 100); gBenchmark->Show("Partitioning"); latitude = r.Uniform(-dr*90,dr*90); // Fill TH2Poly according to a Mercator projection. gBenchmark->Start("Filling"); for (i=0; i<1000000; i++) { longitude = r.Uniform(dr*lon1,dr*lon2); //latitude = r.Uniform(-dr*90,dr*90); latitude = r.Uniform(dr*lat1,dr*lat2); x = rd*longitude; y = 39*TMath::Log(TMath::Tan((TMath::Pi()/4)+(latitude/2))); p->Fill(x,y); } gBenchmark->Show("Filling"); Int_t nbins = p->GetNumberOfBins(); Double_t maximum = p->GetMaximum(); printf("Nbins = %d Minimum = %g Maximum = %g Integral = %f \n", nbins, p->GetMinimum(), maximum, p->Integral()); // h2 contains the surfaces computed from TH2Poly. TH1F *h2 = h->Clone(); h2->Reset(); for (j=0; j<nx; j++) { for (i=0; i<nbins; i++) { if (strstr(countries[j],p->GetBinName(i+1))) { h2->Fill(countries[j],p->GetBinContent(i+1)); h2->SetBinError(j, p->GetBinError(i+1)); } } } // Normalize the TH2Poly bin contents to the real surfaces. Double_t scale = surfaces[0]/maximum; for (i=0; i<nbins; i++) p->SetBinContent(i+1, scale*p->GetBinContent(i+1)); gStyle->SetOptStat(1111); gStyle->SetPalette(1); p->Draw("COL"); TCanvas *c1 = new TCanvas("c1", "c1",W+10,0,W-20,H); c1->SetRightMargin(0.047); Double_t scale = h->GetMaximum()/h2->GetMaximum(); h->SetStats(0); h->Draw("L"); h->SetLineColor(kRed-3); h->SetLineWidth(2); h->GetXaxis()->SetLabelFont(42); h->GetXaxis()->SetLabelSize(0.03); h->GetYaxis()->SetLabelFont(42); h2->Scale(scale); Double_t scale2=TMath::Sqrt(scale); for (i=0; i<nx; i++) h2->SetBinError(i+1, scale2*h2->GetBinError(i+1)); h2->Draw("E SAME"); h2->SetMarkerStyle(20); h2->SetMarkerSize(0.8); TLegend *leg = new TLegend(0.5,0.67,0.92,0.8,NULL,"NDC"); leg->SetTextFont(42); leg->SetTextSize(0.025); leg->AddEntry(h,"Real countries' surfaces from Wikipedia (in km^{2})","l"); leg->AddEntry(h2,"Countries' surfaces from TH2Poly (with errors)","lp"); leg->Draw(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLFootnoteSeparatorExport.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-09 14:34:15 $ * * 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 _XMLOFF_XMLFOOTNOTESEPARATOREXPORT_HXX #define _XMLOFF_XMLFOOTNOTESEPARATOREXPORT_HXX #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif class SvXMLExport; class XMLPropertySetMapper; struct XMLPropertyState; template<class X> class UniReference; #include <vector> /** * export footnote separator element in page styles */ class XMLFootnoteSeparatorExport { SvXMLExport& rExport; public: XMLFootnoteSeparatorExport(SvXMLExport& rExp); ~XMLFootnoteSeparatorExport(); void exportXML( const ::std::vector<XMLPropertyState> * pProperties, sal_uInt32 nIdx, /// used only for debugging const UniReference<XMLPropertySetMapper> & rMapper); }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.2.450); FILE MERGED 2008/04/01 16:09:54 thb 1.2.450.2: #i85898# Stripping all external header guards 2008/03/31 16:28:21 rt 1.2.450.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: XMLFootnoteSeparatorExport.hxx,v $ * $Revision: 1.3 $ * * 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 _XMLOFF_XMLFOOTNOTESEPARATOREXPORT_HXX #define _XMLOFF_XMLFOOTNOTESEPARATOREXPORT_HXX #include <sal/types.h> class SvXMLExport; class XMLPropertySetMapper; struct XMLPropertyState; template<class X> class UniReference; #include <vector> /** * export footnote separator element in page styles */ class XMLFootnoteSeparatorExport { SvXMLExport& rExport; public: XMLFootnoteSeparatorExport(SvXMLExport& rExp); ~XMLFootnoteSeparatorExport(); void exportXML( const ::std::vector<XMLPropertyState> * pProperties, sal_uInt32 nIdx, /// used only for debugging const UniReference<XMLPropertySetMapper> & rMapper); }; #endif <|endoftext|>
<commit_before>//===- yaml2macho - Convert YAML to a Mach object file --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief The Mach component of yaml2obj. /// //===----------------------------------------------------------------------===// #include "yaml2obj.h" #include "llvm/ObjectYAML/MachOYAML.h" #include "llvm/Support/Error.h" #include "llvm/Support/MachO.h" #include "llvm/Support/YAMLTraits.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; namespace { class MachOWriter { public: MachOWriter(MachOYAML::Object &Obj) : Obj(Obj) { is64Bit = Obj.Header.magic == MachO::MH_MAGIC_64 || Obj.Header.magic == MachO::MH_CIGAM_64; bzero(&Header64, sizeof(MachO::mach_header_64)); } Error writeMachO(raw_ostream &OS); private: Error writeHeader(raw_ostream &OS); MachOYAML::Object Obj; bool is64Bit; union { MachO::mach_header_64 Header64; MachO::mach_header Header; }; }; Error MachOWriter::writeMachO(raw_ostream &OS) { if (auto Err = writeHeader(OS)) return Err; return Error::success(); } Error MachOWriter::writeHeader(raw_ostream &OS) { Header.magic = Obj.Header.magic; Header.cputype = Obj.Header.cputype; Header.cpusubtype = Obj.Header.cpusubtype; Header.filetype = Obj.Header.filetype; Header.ncmds = Obj.Header.ncmds; Header.sizeofcmds = Obj.Header.sizeofcmds; Header.flags = Obj.Header.flags; if (is64Bit) OS.write((const char *)&Header64, sizeof(MachO::mach_header_64)); else OS.write((const char *)&Header, sizeof(MachO::mach_header)); return Error::success(); } } // end anonymous namespace int yaml2macho(yaml::Input &YIn, raw_ostream &Out) { MachOYAML::Object Doc; YIn >> Doc; if (YIn.error()) { errs() << "yaml2obj: Failed to parse YAML file!\n"; return 1; } MachOWriter Writer(Doc); if (auto Err = Writer.writeMachO(Out)) { errs() << toString(std::move(Err)); return 1; } return 0; } <commit_msg>[yaml2macho] Use memset instead of bzero<commit_after>//===- yaml2macho - Convert YAML to a Mach object file --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief The Mach component of yaml2obj. /// //===----------------------------------------------------------------------===// #include "yaml2obj.h" #include "llvm/ObjectYAML/MachOYAML.h" #include "llvm/Support/Error.h" #include "llvm/Support/MachO.h" #include "llvm/Support/YAMLTraits.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; namespace { class MachOWriter { public: MachOWriter(MachOYAML::Object &Obj) : Obj(Obj) { is64Bit = Obj.Header.magic == MachO::MH_MAGIC_64 || Obj.Header.magic == MachO::MH_CIGAM_64; memset(reinterpret_cast<void *>(&Header64), 0, sizeof(MachO::mach_header_64)); } Error writeMachO(raw_ostream &OS); private: Error writeHeader(raw_ostream &OS); MachOYAML::Object Obj; bool is64Bit; union { MachO::mach_header_64 Header64; MachO::mach_header Header; }; }; Error MachOWriter::writeMachO(raw_ostream &OS) { if (auto Err = writeHeader(OS)) return Err; return Error::success(); } Error MachOWriter::writeHeader(raw_ostream &OS) { Header.magic = Obj.Header.magic; Header.cputype = Obj.Header.cputype; Header.cpusubtype = Obj.Header.cpusubtype; Header.filetype = Obj.Header.filetype; Header.ncmds = Obj.Header.ncmds; Header.sizeofcmds = Obj.Header.sizeofcmds; Header.flags = Obj.Header.flags; if (is64Bit) OS.write((const char *)&Header64, sizeof(MachO::mach_header_64)); else OS.write((const char *)&Header, sizeof(MachO::mach_header)); return Error::success(); } } // end anonymous namespace int yaml2macho(yaml::Input &YIn, raw_ostream &Out) { MachOYAML::Object Doc; YIn >> Doc; if (YIn.error()) { errs() << "yaml2obj: Failed to parse YAML file!\n"; return 1; } MachOWriter Writer(Doc); if (auto Err = Writer.writeMachO(Out)) { errs() << toString(std::move(Err)); return 1; } return 0; } <|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 "chrome/browser/jsmessage_box_handler_win.h" #include "base/string_util.h" #include "chrome/browser/app_modal_dialog_queue.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/web_contents.h" #include "chrome/common/gfx/text_elider.h" #include "chrome/common/l10n_util.h" #include "chrome/common/message_box_flags.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #include "chrome/views/controls/message_box_view.h" #include "chrome/views/window/window.h" #include "grit/generated_resources.h" void RunJavascriptMessageBox(WebContents* web_contents, const GURL& frame_url, int dialog_flags, const std::wstring& message_text, const std::wstring& default_prompt_text, bool display_suppress_checkbox, IPC::Message* reply_msg) { JavascriptMessageBoxHandler* handler = new JavascriptMessageBoxHandler(web_contents, frame_url, dialog_flags, message_text, default_prompt_text, display_suppress_checkbox, reply_msg); AppModalDialogQueue::AddDialog(handler); } JavascriptMessageBoxHandler::JavascriptMessageBoxHandler( WebContents* web_contents, const GURL& frame_url, int dialog_flags, const std::wstring& message_text, const std::wstring& default_prompt_text, bool display_suppress_checkbox, IPC::Message* reply_msg) : web_contents_(web_contents), frame_url_(frame_url), reply_msg_(reply_msg), dialog_flags_(dialog_flags), dialog_(NULL), message_box_view_(new MessageBoxView( dialog_flags | MessageBox::kAutoDetectAlignment, message_text, default_prompt_text)) { DCHECK(message_box_view_); DCHECK(reply_msg_); if (display_suppress_checkbox) { message_box_view_->SetCheckBoxLabel( l10n_util::GetString(IDS_JAVASCRIPT_MESSAGEBOX_SUPPRESS_OPTION)); } // Make sure we get navigation notifications so we know when our parent // contents will disappear or navigate to a different page. registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED, NotificationService::AllSources()); } JavascriptMessageBoxHandler::~JavascriptMessageBoxHandler() { } ////////////////////////////////////////////////////////////////////////////// // JavascriptMessageBoxHandler, views::DialogDelegate implementation: int JavascriptMessageBoxHandler::GetDialogButtons() const { int dialog_buttons = 0; if (dialog_flags_ & MessageBox::kFlagHasOKButton) dialog_buttons = DIALOGBUTTON_OK; if (dialog_flags_ & MessageBox::kFlagHasCancelButton) dialog_buttons |= DIALOGBUTTON_CANCEL; return dialog_buttons; } std::wstring JavascriptMessageBoxHandler::GetWindowTitle() const { if (!frame_url_.has_host()) return l10n_util::GetString(IDS_JAVASCRIPT_MESSAGEBOX_DEFAULT_TITLE); // We really only want the scheme, hostname, and port. GURL::Replacements replacements; replacements.ClearUsername(); replacements.ClearPassword(); replacements.ClearPath(); replacements.ClearQuery(); replacements.ClearRef(); GURL clean_url = frame_url_.ReplaceComponents(replacements); // TODO(brettw) it should be easier than this to do the correct language // handling without getting the accept language from the profile. std::wstring base_address = gfx::ElideUrl(clean_url, ChromeFont(), 0, web_contents_->profile()->GetPrefs()->GetString(prefs::kAcceptLanguages)); // Force URL to have LTR directionality. if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) l10n_util::WrapStringWithLTRFormatting(&base_address); return l10n_util::GetStringF(IDS_JAVASCRIPT_MESSAGEBOX_TITLE, base_address); } void JavascriptMessageBoxHandler::WindowClosing() { dialog_ = NULL; if (message_box_view_->IsCheckBoxSelected() && web_contents_) web_contents_->set_suppress_javascript_messages(true); } void JavascriptMessageBoxHandler::DeleteDelegate() { delete this; } bool JavascriptMessageBoxHandler::Cancel() { // We need to do this before WM_DESTROY (WindowClosing()) as any parent frame // will receive it's activation messages before this dialog receives // WM_DESTROY. The parent frame would then try to activate any modal dialogs // that were still open in the ModalDialogQueue, which would send activation // back to this one. The framework should be improved to handle this, so this // is a temporary workaround. AppModalDialogQueue::ShowNextDialog(); if (web_contents_) { web_contents_->OnJavaScriptMessageBoxClosed(reply_msg_, false, EmptyWString()); } return true; } bool JavascriptMessageBoxHandler::Accept() { AppModalDialogQueue::ShowNextDialog(); if (web_contents_) { web_contents_->OnJavaScriptMessageBoxClosed( reply_msg_, true, message_box_view_->GetInputText()); } return true; } ////////////////////////////////////////////////////////////////////////////// // JavascriptMessageBoxHandler, views::AppModalDialogDelegate // implementation: void JavascriptMessageBoxHandler::ShowModalDialog() { // If the WebContents that created this dialog navigated away before this // dialog became visible, simply show the next dialog if any. if (!web_contents_) { AppModalDialogQueue::ShowNextDialog(); delete this; return; } web_contents_->Activate(); HWND root_hwnd = GetAncestor(web_contents_->GetNativeView(), GA_ROOT); dialog_ = views::Window::CreateChromeWindow(root_hwnd, gfx::Rect(), this); dialog_->Show(); } void JavascriptMessageBoxHandler::ActivateModalDialog() { // Ensure that the dialog is visible and at the top of the z-order. These // conditions may not be true if the dialog was opened on a different virtual // desktop to the one the browser window is on. dialog_->Show(); dialog_->Activate(); } /////////////////////////////////////////////////////////////////////////////// // JavascriptMessageBoxHandler, views::WindowDelegate implementation: views::View* JavascriptMessageBoxHandler::GetContentsView() { return message_box_view_; } views::View* JavascriptMessageBoxHandler::GetInitiallyFocusedView() { if (message_box_view_->text_box()) return message_box_view_->text_box(); return views::AppModalDialogDelegate::GetInitiallyFocusedView(); } /////////////////////////////////////////////////////////////////////////////// // JavascriptMessageBoxHandler, private: void JavascriptMessageBoxHandler::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { bool web_contents_gone = false; if (!web_contents_) return; if (type == NotificationType::NAV_ENTRY_COMMITTED && Source<NavigationController>(source).ptr() == web_contents_->controller()) web_contents_gone = true; if (type == NotificationType::TAB_CONTENTS_DESTROYED && Source<TabContents>(source).ptr() == static_cast<TabContents*>(web_contents_)) web_contents_gone = true; if (web_contents_gone) { web_contents_ = NULL; // If the dialog is visible close it. if (dialog_) dialog_->Close(); } } <commit_msg>NULL check web_contents_ to prevent a crash. In the notification observer, web_contents_ can be set to NULL so check for a NULL web_contents_ in GetWindowTitle. All the other methods check web_contents_ before using it too.<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 "chrome/browser/jsmessage_box_handler_win.h" #include "base/string_util.h" #include "chrome/browser/app_modal_dialog_queue.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/web_contents.h" #include "chrome/common/gfx/text_elider.h" #include "chrome/common/l10n_util.h" #include "chrome/common/message_box_flags.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #include "chrome/views/controls/message_box_view.h" #include "chrome/views/window/window.h" #include "grit/generated_resources.h" void RunJavascriptMessageBox(WebContents* web_contents, const GURL& frame_url, int dialog_flags, const std::wstring& message_text, const std::wstring& default_prompt_text, bool display_suppress_checkbox, IPC::Message* reply_msg) { JavascriptMessageBoxHandler* handler = new JavascriptMessageBoxHandler(web_contents, frame_url, dialog_flags, message_text, default_prompt_text, display_suppress_checkbox, reply_msg); AppModalDialogQueue::AddDialog(handler); } JavascriptMessageBoxHandler::JavascriptMessageBoxHandler( WebContents* web_contents, const GURL& frame_url, int dialog_flags, const std::wstring& message_text, const std::wstring& default_prompt_text, bool display_suppress_checkbox, IPC::Message* reply_msg) : web_contents_(web_contents), frame_url_(frame_url), reply_msg_(reply_msg), dialog_flags_(dialog_flags), dialog_(NULL), message_box_view_(new MessageBoxView( dialog_flags | MessageBox::kAutoDetectAlignment, message_text, default_prompt_text)) { DCHECK(message_box_view_); DCHECK(reply_msg_); if (display_suppress_checkbox) { message_box_view_->SetCheckBoxLabel( l10n_util::GetString(IDS_JAVASCRIPT_MESSAGEBOX_SUPPRESS_OPTION)); } // Make sure we get navigation notifications so we know when our parent // contents will disappear or navigate to a different page. registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED, NotificationService::AllSources()); } JavascriptMessageBoxHandler::~JavascriptMessageBoxHandler() { } ////////////////////////////////////////////////////////////////////////////// // JavascriptMessageBoxHandler, views::DialogDelegate implementation: int JavascriptMessageBoxHandler::GetDialogButtons() const { int dialog_buttons = 0; if (dialog_flags_ & MessageBox::kFlagHasOKButton) dialog_buttons = DIALOGBUTTON_OK; if (dialog_flags_ & MessageBox::kFlagHasCancelButton) dialog_buttons |= DIALOGBUTTON_CANCEL; return dialog_buttons; } std::wstring JavascriptMessageBoxHandler::GetWindowTitle() const { if (!frame_url_.has_host() || !web_contents_) return l10n_util::GetString(IDS_JAVASCRIPT_MESSAGEBOX_DEFAULT_TITLE); // We really only want the scheme, hostname, and port. GURL::Replacements replacements; replacements.ClearUsername(); replacements.ClearPassword(); replacements.ClearPath(); replacements.ClearQuery(); replacements.ClearRef(); GURL clean_url = frame_url_.ReplaceComponents(replacements); // TODO(brettw) it should be easier than this to do the correct language // handling without getting the accept language from the profile. std::wstring base_address = gfx::ElideUrl(clean_url, ChromeFont(), 0, web_contents_->profile()->GetPrefs()->GetString(prefs::kAcceptLanguages)); // Force URL to have LTR directionality. if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) l10n_util::WrapStringWithLTRFormatting(&base_address); return l10n_util::GetStringF(IDS_JAVASCRIPT_MESSAGEBOX_TITLE, base_address); } void JavascriptMessageBoxHandler::WindowClosing() { dialog_ = NULL; if (message_box_view_->IsCheckBoxSelected() && web_contents_) web_contents_->set_suppress_javascript_messages(true); } void JavascriptMessageBoxHandler::DeleteDelegate() { delete this; } bool JavascriptMessageBoxHandler::Cancel() { // We need to do this before WM_DESTROY (WindowClosing()) as any parent frame // will receive it's activation messages before this dialog receives // WM_DESTROY. The parent frame would then try to activate any modal dialogs // that were still open in the ModalDialogQueue, which would send activation // back to this one. The framework should be improved to handle this, so this // is a temporary workaround. AppModalDialogQueue::ShowNextDialog(); if (web_contents_) { web_contents_->OnJavaScriptMessageBoxClosed(reply_msg_, false, EmptyWString()); } return true; } bool JavascriptMessageBoxHandler::Accept() { AppModalDialogQueue::ShowNextDialog(); if (web_contents_) { web_contents_->OnJavaScriptMessageBoxClosed( reply_msg_, true, message_box_view_->GetInputText()); } return true; } ////////////////////////////////////////////////////////////////////////////// // JavascriptMessageBoxHandler, views::AppModalDialogDelegate // implementation: void JavascriptMessageBoxHandler::ShowModalDialog() { // If the WebContents that created this dialog navigated away before this // dialog became visible, simply show the next dialog if any. if (!web_contents_) { AppModalDialogQueue::ShowNextDialog(); delete this; return; } web_contents_->Activate(); HWND root_hwnd = GetAncestor(web_contents_->GetNativeView(), GA_ROOT); dialog_ = views::Window::CreateChromeWindow(root_hwnd, gfx::Rect(), this); dialog_->Show(); } void JavascriptMessageBoxHandler::ActivateModalDialog() { // Ensure that the dialog is visible and at the top of the z-order. These // conditions may not be true if the dialog was opened on a different virtual // desktop to the one the browser window is on. dialog_->Show(); dialog_->Activate(); } /////////////////////////////////////////////////////////////////////////////// // JavascriptMessageBoxHandler, views::WindowDelegate implementation: views::View* JavascriptMessageBoxHandler::GetContentsView() { return message_box_view_; } views::View* JavascriptMessageBoxHandler::GetInitiallyFocusedView() { if (message_box_view_->text_box()) return message_box_view_->text_box(); return views::AppModalDialogDelegate::GetInitiallyFocusedView(); } /////////////////////////////////////////////////////////////////////////////// // JavascriptMessageBoxHandler, private: void JavascriptMessageBoxHandler::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (!web_contents_) return; bool web_contents_gone = false; if (type == NotificationType::NAV_ENTRY_COMMITTED && Source<NavigationController>(source).ptr() == web_contents_->controller()) web_contents_gone = true; if (type == NotificationType::TAB_CONTENTS_DESTROYED && Source<TabContents>(source).ptr() == static_cast<TabContents*>(web_contents_)) web_contents_gone = true; if (web_contents_gone) { web_contents_ = NULL; // If the dialog is visible close it. if (dialog_) dialog_->Close(); } } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/print_dialog_gtk.h" #include <gtk/gtkprintjob.h> #include <gtk/gtkprintunixdialog.h> #include <gtk/gtkpagesetupunixdialog.h> #include "base/file_util.h" #include "base/logging.h" #include "base/message_loop.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/tab_contents/infobar_delegate.h" #include "chrome/browser/tab_contents/tab_contents.h" namespace { // This is a temporary infobar designed to help gauge how many users are trying // to print to printers that don't support PDF. class PdfUnsupportedInfoBarDelegate : public LinkInfoBarDelegate { public: PdfUnsupportedInfoBarDelegate(Browser* browser) : LinkInfoBarDelegate(NULL), browser_(browser) { } ~PdfUnsupportedInfoBarDelegate() {} virtual std::wstring GetMessageTextWithOffset(size_t* link_offset) const { std::wstring message(L"Oops! Your printer does not support PDF. Please " L"report this to us ."); *link_offset = message.length() - 1; return message; } virtual std::wstring GetLinkText() const { return std::wstring(L"here"); } virtual Type GetInfoBarType() { return ERROR_TYPE; } virtual bool LinkClicked(WindowOpenDisposition disposition) { browser_->OpenURL( GURL("http://code.google.com/p/chromium/issues/detail?id=22027"), GURL(), NEW_FOREGROUND_TAB, PageTransition::TYPED); return true; } private: Browser* browser_; }; } // namespace // static void PrintDialogGtk::CreatePrintDialogForPdf(const FilePath& path, MessageLoop* loop) { loop->PostTask(FROM_HERE, NewRunnableFunction(&PrintDialogGtk::CreateDialogImpl, path)); } // static void PrintDialogGtk::CreateDialogImpl(const FilePath& path) { new PrintDialogGtk(path); } PrintDialogGtk::PrintDialogGtk(const FilePath& path_to_pdf) : path_to_pdf_(path_to_pdf), browser_(BrowserList::GetLastActive()) { GtkWindow* parent = browser_->window()->GetNativeHandle(); // TODO(estade): We need a window title here. dialog_ = gtk_print_unix_dialog_new(NULL, parent); g_signal_connect(dialog_, "response", G_CALLBACK(OnResponseThunk), this); gtk_widget_show_all(dialog_); } PrintDialogGtk::~PrintDialogGtk() { } void PrintDialogGtk::OnResponse(gint response_id) { gtk_widget_hide(dialog_); switch (response_id) { case GTK_RESPONSE_OK: { GtkPrinter* printer = gtk_print_unix_dialog_get_selected_printer( GTK_PRINT_UNIX_DIALOG(dialog_)); if (!gtk_printer_accepts_pdf(printer)) { browser_->GetSelectedTabContents()->AddInfoBar( new PdfUnsupportedInfoBarDelegate(browser_)); break; } GtkPrintSettings* settings = gtk_print_unix_dialog_get_settings( GTK_PRINT_UNIX_DIALOG(dialog_)); GtkPageSetup* setup = gtk_print_unix_dialog_get_page_setup( GTK_PRINT_UNIX_DIALOG(dialog_)); GtkPrintJob* job = gtk_print_job_new(path_to_pdf_.value().c_str(), printer, settings, setup); gtk_print_job_set_source_file(job, path_to_pdf_.value().c_str(), NULL); gtk_print_job_send(job, OnJobCompletedThunk, this, NULL); g_object_unref(settings); // Success; return early. return; } case GTK_RESPONSE_CANCEL: { break; } case GTK_RESPONSE_APPLY: default: { NOTREACHED(); } } // Delete this dialog. OnJobCompleted(NULL, NULL); } void PrintDialogGtk::OnJobCompleted(GtkPrintJob* job, GError* error) { gtk_widget_destroy(dialog_); if (error) LOG(ERROR) << "Printing failed: " << error->message; if (job) g_object_unref(job); file_util::Delete(path_to_pdf_, false); delete this; } <commit_msg>GTK: don't dcheck when user dismisses print dialog.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/print_dialog_gtk.h" #include <gtk/gtkprintjob.h> #include <gtk/gtkprintunixdialog.h> #include <gtk/gtkpagesetupunixdialog.h> #include "base/file_util.h" #include "base/logging.h" #include "base/message_loop.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/tab_contents/infobar_delegate.h" #include "chrome/browser/tab_contents/tab_contents.h" namespace { // This is a temporary infobar designed to help gauge how many users are trying // to print to printers that don't support PDF. class PdfUnsupportedInfoBarDelegate : public LinkInfoBarDelegate { public: PdfUnsupportedInfoBarDelegate(Browser* browser) : LinkInfoBarDelegate(NULL), browser_(browser) { } ~PdfUnsupportedInfoBarDelegate() {} virtual std::wstring GetMessageTextWithOffset(size_t* link_offset) const { std::wstring message(L"Oops! Your printer does not support PDF. Please " L"report this to us ."); *link_offset = message.length() - 1; return message; } virtual std::wstring GetLinkText() const { return std::wstring(L"here"); } virtual Type GetInfoBarType() { return ERROR_TYPE; } virtual bool LinkClicked(WindowOpenDisposition disposition) { browser_->OpenURL( GURL("http://code.google.com/p/chromium/issues/detail?id=22027"), GURL(), NEW_FOREGROUND_TAB, PageTransition::TYPED); return true; } private: Browser* browser_; }; } // namespace // static void PrintDialogGtk::CreatePrintDialogForPdf(const FilePath& path, MessageLoop* loop) { loop->PostTask(FROM_HERE, NewRunnableFunction(&PrintDialogGtk::CreateDialogImpl, path)); } // static void PrintDialogGtk::CreateDialogImpl(const FilePath& path) { new PrintDialogGtk(path); } PrintDialogGtk::PrintDialogGtk(const FilePath& path_to_pdf) : path_to_pdf_(path_to_pdf), browser_(BrowserList::GetLastActive()) { GtkWindow* parent = browser_->window()->GetNativeHandle(); // TODO(estade): We need a window title here. dialog_ = gtk_print_unix_dialog_new(NULL, parent); g_signal_connect(dialog_, "response", G_CALLBACK(OnResponseThunk), this); gtk_widget_show_all(dialog_); } PrintDialogGtk::~PrintDialogGtk() { } void PrintDialogGtk::OnResponse(gint response_id) { gtk_widget_hide(dialog_); switch (response_id) { case GTK_RESPONSE_OK: { GtkPrinter* printer = gtk_print_unix_dialog_get_selected_printer( GTK_PRINT_UNIX_DIALOG(dialog_)); if (!gtk_printer_accepts_pdf(printer)) { browser_->GetSelectedTabContents()->AddInfoBar( new PdfUnsupportedInfoBarDelegate(browser_)); break; } GtkPrintSettings* settings = gtk_print_unix_dialog_get_settings( GTK_PRINT_UNIX_DIALOG(dialog_)); GtkPageSetup* setup = gtk_print_unix_dialog_get_page_setup( GTK_PRINT_UNIX_DIALOG(dialog_)); GtkPrintJob* job = gtk_print_job_new(path_to_pdf_.value().c_str(), printer, settings, setup); gtk_print_job_set_source_file(job, path_to_pdf_.value().c_str(), NULL); gtk_print_job_send(job, OnJobCompletedThunk, this, NULL); g_object_unref(settings); // Success; return early. return; } case GTK_RESPONSE_DELETE_EVENT: // Fall through. case GTK_RESPONSE_CANCEL: { break; } case GTK_RESPONSE_APPLY: default: { NOTREACHED(); } } // Delete this dialog. OnJobCompleted(NULL, NULL); } void PrintDialogGtk::OnJobCompleted(GtkPrintJob* job, GError* error) { gtk_widget_destroy(dialog_); if (error) LOG(ERROR) << "Printing failed: " << error->message; if (job) g_object_unref(job); file_util::Delete(path_to_pdf_, false); delete this; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/safe_browsing/zip_analyzer.h" #include "base/logging.h" #include "base/macros.h" #include "chrome/common/safe_browsing/binary_feature_extractor.h" #include "chrome/common/safe_browsing/csd.pb.h" #include "chrome/common/safe_browsing/download_protection_util.h" #include "chrome/common/safe_browsing/zip_analyzer_results.h" #include "crypto/secure_hash.h" #include "crypto/sha2.h" #include "third_party/zlib/google/zip_reader.h" namespace safe_browsing { namespace zip_analyzer { namespace { // A writer delegate that computes a SHA-256 hash digest over the data while // writing it to a file. class HashingFileWriter : public zip::FileWriterDelegate { public: explicit HashingFileWriter(base::File* file); // zip::FileWriterDelegate methods: bool WriteBytes(const char* data, int num_bytes) override; void ComputeDigest(uint8_t* digest, size_t digest_length); private: scoped_ptr<crypto::SecureHash> sha256_; DISALLOW_COPY_AND_ASSIGN(HashingFileWriter); }; HashingFileWriter::HashingFileWriter(base::File* file) : zip::FileWriterDelegate(file), sha256_(crypto::SecureHash::Create(crypto::SecureHash::SHA256)) { } bool HashingFileWriter::WriteBytes(const char* data, int num_bytes) { if (!zip::FileWriterDelegate::WriteBytes(data, num_bytes)) return false; sha256_->Update(data, num_bytes); return true; } void HashingFileWriter::ComputeDigest(uint8_t* digest, size_t digest_length) { sha256_->Finish(digest, digest_length); } void AnalyzeContainedFile( const scoped_refptr<BinaryFeatureExtractor>& binary_feature_extractor, const base::FilePath& file_path, zip::ZipReader* reader, base::File* temp_file, ClientDownloadRequest_ArchivedBinary* archived_binary) { archived_binary->set_file_basename(file_path.BaseName().AsUTF8Unsafe()); archived_binary->set_download_type( download_protection_util::GetDownloadType(file_path)); archived_binary->set_length(reader->current_entry_info()->original_size()); HashingFileWriter writer(temp_file); if (reader->ExtractCurrentEntry(&writer)) { uint8_t digest[crypto::kSHA256Length]; writer.ComputeDigest(&digest[0], arraysize(digest)); archived_binary->mutable_digests()->set_sha256(&digest[0], arraysize(digest)); if (!binary_feature_extractor->ExtractImageHeadersFromFile( temp_file->Duplicate(), BinaryFeatureExtractor::kDefaultOptions, archived_binary->mutable_image_headers())) { archived_binary->clear_image_headers(); } } } } // namespace void AnalyzeZipFile(base::File zip_file, base::File temp_file, Results* results) { scoped_refptr<BinaryFeatureExtractor> binary_feature_extractor( new BinaryFeatureExtractor()); zip::ZipReader reader; if (!reader.OpenFromPlatformFile(zip_file.GetPlatformFile())) { DVLOG(1) << "Failed to open zip file"; return; } bool advanced = true; for (; reader.HasMore(); advanced = reader.AdvanceToNextEntry()) { if (!advanced) { DVLOG(1) << "Could not advance to next entry, aborting zip scan."; return; } if (!reader.OpenCurrentEntryInZip()) { DVLOG(1) << "Failed to open current entry in zip file"; continue; } const base::FilePath& file = reader.current_entry_info()->file_path(); if (download_protection_util::IsBinaryFile(file)) { // Don't consider an archived archive to be executable, but record // a histogram. if (download_protection_util::IsArchiveFile(file)) { results->has_archive = true; } else { DVLOG(2) << "Downloaded a zipped executable: " << file.value(); results->has_executable = true; AnalyzeContainedFile(binary_feature_extractor, file, &reader, &temp_file, results->archived_binary.Add()); } } else { DVLOG(3) << "Ignoring non-binary file: " << file.value(); } } results->success = true; } } // namespace zip_analyzer } // namespace safe_browsing <commit_msg>Validate that zip entry filenames are UTF8.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/safe_browsing/zip_analyzer.h" #include "base/i18n/streaming_utf8_validator.h" #include "base/logging.h" #include "base/macros.h" #include "chrome/common/safe_browsing/binary_feature_extractor.h" #include "chrome/common/safe_browsing/csd.pb.h" #include "chrome/common/safe_browsing/download_protection_util.h" #include "chrome/common/safe_browsing/zip_analyzer_results.h" #include "crypto/secure_hash.h" #include "crypto/sha2.h" #include "third_party/zlib/google/zip_reader.h" namespace safe_browsing { namespace zip_analyzer { namespace { // A writer delegate that computes a SHA-256 hash digest over the data while // writing it to a file. class HashingFileWriter : public zip::FileWriterDelegate { public: explicit HashingFileWriter(base::File* file); // zip::FileWriterDelegate methods: bool WriteBytes(const char* data, int num_bytes) override; void ComputeDigest(uint8_t* digest, size_t digest_length); private: scoped_ptr<crypto::SecureHash> sha256_; DISALLOW_COPY_AND_ASSIGN(HashingFileWriter); }; HashingFileWriter::HashingFileWriter(base::File* file) : zip::FileWriterDelegate(file), sha256_(crypto::SecureHash::Create(crypto::SecureHash::SHA256)) { } bool HashingFileWriter::WriteBytes(const char* data, int num_bytes) { if (!zip::FileWriterDelegate::WriteBytes(data, num_bytes)) return false; sha256_->Update(data, num_bytes); return true; } void HashingFileWriter::ComputeDigest(uint8_t* digest, size_t digest_length) { sha256_->Finish(digest, digest_length); } void AnalyzeContainedFile( const scoped_refptr<BinaryFeatureExtractor>& binary_feature_extractor, const base::FilePath& file_path, zip::ZipReader* reader, base::File* temp_file, ClientDownloadRequest_ArchivedBinary* archived_binary) { std::string file_basename(file_path.BaseName().AsUTF8Unsafe()); if (base::StreamingUtf8Validator::Validate(file_basename)) archived_binary->set_file_basename(file_basename); archived_binary->set_download_type( download_protection_util::GetDownloadType(file_path)); archived_binary->set_length(reader->current_entry_info()->original_size()); HashingFileWriter writer(temp_file); if (reader->ExtractCurrentEntry(&writer)) { uint8_t digest[crypto::kSHA256Length]; writer.ComputeDigest(&digest[0], arraysize(digest)); archived_binary->mutable_digests()->set_sha256(&digest[0], arraysize(digest)); if (!binary_feature_extractor->ExtractImageHeadersFromFile( temp_file->Duplicate(), BinaryFeatureExtractor::kDefaultOptions, archived_binary->mutable_image_headers())) { archived_binary->clear_image_headers(); } } } } // namespace void AnalyzeZipFile(base::File zip_file, base::File temp_file, Results* results) { scoped_refptr<BinaryFeatureExtractor> binary_feature_extractor( new BinaryFeatureExtractor()); zip::ZipReader reader; if (!reader.OpenFromPlatformFile(zip_file.GetPlatformFile())) { DVLOG(1) << "Failed to open zip file"; return; } bool advanced = true; for (; reader.HasMore(); advanced = reader.AdvanceToNextEntry()) { if (!advanced) { DVLOG(1) << "Could not advance to next entry, aborting zip scan."; return; } if (!reader.OpenCurrentEntryInZip()) { DVLOG(1) << "Failed to open current entry in zip file"; continue; } const base::FilePath& file = reader.current_entry_info()->file_path(); if (download_protection_util::IsBinaryFile(file)) { // Don't consider an archived archive to be executable, but record // a histogram. if (download_protection_util::IsArchiveFile(file)) { results->has_archive = true; } else { DVLOG(2) << "Downloaded a zipped executable: " << file.value(); results->has_executable = true; AnalyzeContainedFile(binary_feature_extractor, file, &reader, &temp_file, results->archived_binary.Add()); } } else { DVLOG(3) << "Ignoring non-binary file: " << file.value(); } } results->success = true; } } // namespace zip_analyzer } // namespace safe_browsing <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> //------------------------------------------------------------------------------ #include "cling/Interpreter/ValuePrinter.h" #include "cling/Interpreter/CValuePrinter.h" #include "cling/Interpreter/ValuePrinterInfo.h" #include "cling/Interpreter/Value.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/Expr.h" #include "clang/AST/Type.h" #include "llvm/Support/raw_ostream.h" #include <string> // Implements the CValuePrinter interface. extern "C" void cling_PrintValue(void* /*clang::Expr**/ E, void* /*clang::ASTContext**/ C, const void* value) { clang::Expr* Exp = (clang::Expr*)E; clang::ASTContext* Context = (clang::ASTContext*)C; cling::ValuePrinterInfo VPI(Exp, Context); cling::printValue(llvm::outs(), value, value, VPI); cling::flushOStream(llvm::outs()); } static void StreamChar(llvm::raw_ostream& o, const char v) { o << '"' << v << "\"\n"; } static void StreamCharPtr(llvm::raw_ostream& o, const char* const v) { o << '"'; const char* p = v; for (;*p && p - v < 128; ++p) { o << *p; } if (*p) o << "\"...\n"; else o << "\"\n"; } static void StreamRef(llvm::raw_ostream& o, const void* v) { o <<"&" << v << "\n"; } static void StreamPtr(llvm::raw_ostream& o, const void* v) { o << *(intptr_t*)v << "\n"; } static void StreamObj(llvm::raw_ostream& o, const void* v, const cling::ValuePrinterInfo& VPI) { const clang::Type* Ty = VPI.getExpr()->getType().getTypePtr(); if (clang::CXXRecordDecl* CXXRD = Ty->getAsCXXRecordDecl()) if (CXXRD->getQualifiedNameAsString().compare("cling::Value") == 0) { cling::Value* V = (cling::Value*)v; if (V->isValid()) { o << "boxes ["; const clang::ASTContext& C = *VPI.getASTContext(); o << "(" << V->type.getAsString(C.getPrintingPolicy()) << ") "; clang::QualType valType = V->type.getDesugaredType(C); if (valType->isPointerType()) o << V->value.PointerVal; else if (valType->isFloatingType()) o << V->value.DoubleVal; else if (valType->isIntegerType()) o << V->value.IntVal.getSExtValue(); else if (valType->isBooleanType()) o << V->value.IntVal.getBoolValue(); o << "]\n"; return; } else o << "<<<invalid>>> "; } // TODO: Print the object members. o << "@" << v << "\n"; } static void StreamValue(llvm::raw_ostream& o, const void* const p, const cling::ValuePrinterInfo& VPI) { clang::QualType Ty = VPI.getExpr()->getType(); const clang::ASTContext& C = *VPI.getASTContext(); Ty = Ty.getDesugaredType(C); if (const clang::BuiltinType *BT = llvm::dyn_cast<clang::BuiltinType>(Ty.getCanonicalType())) { switch (BT->getKind()) { case clang::BuiltinType::Bool: if (*(bool*)p) o << "true\n"; else o << "false\n"; break; case clang::BuiltinType::Char_U: case clang::BuiltinType::UChar: case clang::BuiltinType::Char_S: case clang::BuiltinType::SChar: StreamChar(o, *(char*)p); break; case clang::BuiltinType::Short: o << *(short*)p << "\n"; break; case clang::BuiltinType::UShort: o << *(unsigned short*)p << "\n"; break; case clang::BuiltinType::Int: o << *(int*)p << "\n"; break; case clang::BuiltinType::UInt: o << *(unsigned int*)p << "\n"; break; case clang::BuiltinType::Long: o << *(long*)p << "\n"; break; case clang::BuiltinType::ULong: o << *(unsigned long*)p << "\n"; break; case clang::BuiltinType::LongLong: o << *(long long*)p << "\n"; break; case clang::BuiltinType::ULongLong: o << *(unsigned long long*)p << "\n"; break; case clang::BuiltinType::Float: o << *(float*)p << "\n"; break; case clang::BuiltinType::Double: o << *(double*)p << "\n"; break; default: StreamObj(o, p, VPI); } } else if (Ty.getAsString().compare("std::string") == 0) { StreamObj(o, p, VPI); o <<"c_str: "; StreamCharPtr(o, ((const char*) (*(const std::string*)p).c_str())); } else if (Ty->isEnumeralType()) { StreamObj(o, p, VPI); int value = *(int*)p; clang::EnumDecl* ED = Ty->getAs<clang::EnumType>()->getDecl(); bool IsFirst = true; llvm::APSInt ValAsAPSInt = C.MakeIntValue(value, C.IntTy); for (clang::EnumDecl::enumerator_iterator I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E; ++I) { if (I->getInitVal() == ValAsAPSInt) { if (!IsFirst) { o << " ? "; } o << "(" << I->getQualifiedNameAsString() << ")"; IsFirst = false; } } o << " : (int) " << value << "\n"; } else if (Ty->isReferenceType()) StreamRef(o, p); else if (Ty->isPointerType()) { clang::QualType PointeeTy = Ty->getPointeeType(); if (PointeeTy->isCharType()) StreamCharPtr(o, (const char*)p); else StreamPtr(o, p); } else StreamObj(o, p, VPI); } namespace cling { void printValueDefault(llvm::raw_ostream& o, const void* const p, const ValuePrinterInfo& VPI) { const clang::Expr* E = VPI.getExpr(); o << "("; o << E->getType().getAsString(); if (E->isRValue()) // show the user that the var cannot be changed o << " const"; o << ") "; StreamValue(o, p, VPI); } void flushOStream(llvm::raw_ostream& o) { o.flush(); } } // end namespace cling <commit_msg>Follow update in clang: we get in the value printer the already desugared type instead of sugared one. This is a hack, which will be improved when I get my hands on the value printer.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> //------------------------------------------------------------------------------ #include "cling/Interpreter/ValuePrinter.h" #include "cling/Interpreter/CValuePrinter.h" #include "cling/Interpreter/ValuePrinterInfo.h" #include "cling/Interpreter/Value.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/Expr.h" #include "clang/AST/Type.h" #include "llvm/Support/raw_ostream.h" #include <string> // Implements the CValuePrinter interface. extern "C" void cling_PrintValue(void* /*clang::Expr**/ E, void* /*clang::ASTContext**/ C, const void* value) { clang::Expr* Exp = (clang::Expr*)E; clang::ASTContext* Context = (clang::ASTContext*)C; cling::ValuePrinterInfo VPI(Exp, Context); cling::printValue(llvm::outs(), value, value, VPI); cling::flushOStream(llvm::outs()); } static void StreamChar(llvm::raw_ostream& o, const char v) { o << '"' << v << "\"\n"; } static void StreamCharPtr(llvm::raw_ostream& o, const char* const v) { o << '"'; const char* p = v; for (;*p && p - v < 128; ++p) { o << *p; } if (*p) o << "\"...\n"; else o << "\"\n"; } static void StreamRef(llvm::raw_ostream& o, const void* v) { o <<"&" << v << "\n"; } static void StreamPtr(llvm::raw_ostream& o, const void* v) { o << *(intptr_t*)v << "\n"; } static void StreamObj(llvm::raw_ostream& o, const void* v, const cling::ValuePrinterInfo& VPI) { const clang::Type* Ty = VPI.getExpr()->getType().getTypePtr(); if (clang::CXXRecordDecl* CXXRD = Ty->getAsCXXRecordDecl()) if (CXXRD->getQualifiedNameAsString().compare("cling::Value") == 0) { cling::Value* V = (cling::Value*)v; if (V->isValid()) { o << "boxes ["; const clang::ASTContext& C = *VPI.getASTContext(); o << "(" << V->type.getAsString(C.getPrintingPolicy()) << ") "; clang::QualType valType = V->type.getDesugaredType(C); if (valType->isPointerType()) o << V->value.PointerVal; else if (valType->isFloatingType()) o << V->value.DoubleVal; else if (valType->isIntegerType()) o << V->value.IntVal.getSExtValue(); else if (valType->isBooleanType()) o << V->value.IntVal.getBoolValue(); o << "]\n"; return; } else o << "<<<invalid>>> "; } // TODO: Print the object members. o << "@" << v << "\n"; } static void StreamValue(llvm::raw_ostream& o, const void* const p, const cling::ValuePrinterInfo& VPI) { clang::QualType Ty = VPI.getExpr()->getType(); const clang::ASTContext& C = *VPI.getASTContext(); Ty = Ty.getDesugaredType(C); if (const clang::BuiltinType *BT = llvm::dyn_cast<clang::BuiltinType>(Ty.getCanonicalType())) { switch (BT->getKind()) { case clang::BuiltinType::Bool: if (*(bool*)p) o << "true\n"; else o << "false\n"; break; case clang::BuiltinType::Char_U: case clang::BuiltinType::UChar: case clang::BuiltinType::Char_S: case clang::BuiltinType::SChar: StreamChar(o, *(char*)p); break; case clang::BuiltinType::Short: o << *(short*)p << "\n"; break; case clang::BuiltinType::UShort: o << *(unsigned short*)p << "\n"; break; case clang::BuiltinType::Int: o << *(int*)p << "\n"; break; case clang::BuiltinType::UInt: o << *(unsigned int*)p << "\n"; break; case clang::BuiltinType::Long: o << *(long*)p << "\n"; break; case clang::BuiltinType::ULong: o << *(unsigned long*)p << "\n"; break; case clang::BuiltinType::LongLong: o << *(long long*)p << "\n"; break; case clang::BuiltinType::ULongLong: o << *(unsigned long long*)p << "\n"; break; case clang::BuiltinType::Float: o << *(float*)p << "\n"; break; case clang::BuiltinType::Double: o << *(double*)p << "\n"; break; default: StreamObj(o, p, VPI); } } else if (Ty.getAsString().compare("class std::basic_string<char>") == 0) { StreamObj(o, p, VPI); o <<"c_str: "; StreamCharPtr(o, ((const char*) (*(const std::string*)p).c_str())); } else if (Ty->isEnumeralType()) { StreamObj(o, p, VPI); int value = *(int*)p; clang::EnumDecl* ED = Ty->getAs<clang::EnumType>()->getDecl(); bool IsFirst = true; llvm::APSInt ValAsAPSInt = C.MakeIntValue(value, C.IntTy); for (clang::EnumDecl::enumerator_iterator I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E; ++I) { if (I->getInitVal() == ValAsAPSInt) { if (!IsFirst) { o << " ? "; } o << "(" << I->getQualifiedNameAsString() << ")"; IsFirst = false; } } o << " : (int) " << value << "\n"; } else if (Ty->isReferenceType()) StreamRef(o, p); else if (Ty->isPointerType()) { clang::QualType PointeeTy = Ty->getPointeeType(); if (PointeeTy->isCharType()) StreamCharPtr(o, (const char*)p); else StreamPtr(o, p); } else StreamObj(o, p, VPI); } namespace cling { void printValueDefault(llvm::raw_ostream& o, const void* const p, const ValuePrinterInfo& VPI) { const clang::Expr* E = VPI.getExpr(); o << "("; o << E->getType().getAsString(); if (E->isRValue()) // show the user that the var cannot be changed o << " const"; o << ") "; StreamValue(o, p, VPI); } void flushOStream(llvm::raw_ostream& o) { o.flush(); } } // end namespace cling <|endoftext|>
<commit_before>#include "nanocv.h" #include <boost/program_options.hpp> #include <set> using namespace ncv; static void test_grad_params( const string_t& header, const string_t& loss_id, const model_t& model, accumulator_t& acc_params) { random_t<size_t> rand(8, 16); const size_t n_tests = 64; const size_t n_samples = rand(); const rloss_t rloss = loss_manager_t::instance().get(loss_id); const loss_t& loss = *rloss; const size_t psize = model.psize(); const size_t isize = model.isize(); const size_t osize = model.osize(); vector_t params(psize); vectors_t targets(n_samples, vector_t(osize)); tensors_t inputs(n_samples, tensor_t(model.idims(), model.irows(), model.icols())); // optimization problem (wrt parameters & inputs): size auto fn_params_size = [&] () { return psize; }; // optimization problem (wrt parameters & inputs): function value auto fn_params_fval = [&] (const vector_t& x) { acc_params.reset(x); acc_params.update(inputs, targets, loss); return acc_params.value(); }; // optimization problem (wrt parameters & inputs): function value & gradient auto fn_params_grad = [&] (const vector_t& x, vector_t& gx) { acc_params.reset(x); acc_params.update(inputs, targets, loss); gx = acc_params.vgrad(); return acc_params.value(); }; // construct optimization problem: analytic gradient and finite difference approximation const opt_problem_t problem_analytic_params(fn_params_size, fn_params_fval, fn_params_grad); const opt_problem_t problem_aproxdif_params(fn_params_size, fn_params_fval); for (size_t t = 0; t < n_tests; t ++) { random_t<scalar_t> prgen(-1.0, +1.0); random_t<scalar_t> irgen(-0.1, +0.1); random_t<size_t> trgen(0, osize - 1); prgen(params.data(), params.data() + psize); for (vector_t& target : targets) { target = ncv::class_target(trgen(), osize); } for (tensor_t& input : inputs) { irgen(input.data(), input.data() + isize); } vector_t analytic_params_grad, aproxdif_params_grad; problem_analytic_params(params, analytic_params_grad); problem_aproxdif_params(params, aproxdif_params_grad); const scalar_t dg_params = (analytic_params_grad - aproxdif_params_grad).lpNorm<Eigen::Infinity>(); const bool ok = dg_params < 1e-4;//math::almost_equal(dg_params, scalar_t(0)); log_info() << header << " [" << (t + 1) << "/" << n_tests << "]: samples = " << n_samples << ", dg_params = " << dg_params << " (" << (ok ? "OK" : "ERROR") << ")."; } } static void test_grad_inputs(const string_t& header, const string_t& loss_id, const model_t& model) { rmodel_t rmodel_inputs = model.clone(); random_t<size_t> rand(8, 16); const size_t n_tests = 64; const size_t n_samples = rand(); const rloss_t rloss = loss_manager_t::instance().get(loss_id); const loss_t& loss = *rloss; const size_t psize = model.psize(); const size_t isize = model.isize(); const size_t osize = model.osize(); vector_t params(psize); vector_t target(osize); tensor_t input(model.idims(), model.irows(), model.icols()); // optimization problem (wrt parameters & inputs): size auto fn_inputs_size = [&] () { return isize; }; // optimization problem (wrt parameters & inputs): function value auto fn_inputs_fval = [&] (const vector_t& x) { rmodel_inputs->load_params(params); const vector_t output = rmodel_inputs->output(x).vector(); return loss.value(target, output); }; // optimization problem (wrt parameters & inputs): function value & gradient auto fn_inputs_grad = [&] (const vector_t& x, vector_t& gx) { rmodel_inputs->load_params(params); const vector_t output = rmodel_inputs->output(x).vector(); gx = rmodel_inputs->ginput(loss.vgrad(target, output)).vector(); return loss.value(target, output); }; // construct optimization problem: analytic gradient and finite difference approximation const opt_problem_t problem_analytic_inputs(fn_inputs_size, fn_inputs_fval, fn_inputs_grad); const opt_problem_t problem_aproxdif_inputs(fn_inputs_size, fn_inputs_fval); for (size_t t = 0; t < n_tests; t ++) { random_t<scalar_t> prgen(-1.0, +1.0); random_t<scalar_t> irgen(-0.1, +0.1); random_t<size_t> trgen(0, osize - 1); prgen(params.data(), params.data() + psize); target = ncv::class_target(trgen(), osize); irgen(input.data(), input.data() + isize); vector_t analytic_inputs_grad, aproxdif_inputs_grad; problem_analytic_inputs(input.vector(), analytic_inputs_grad); problem_aproxdif_inputs(input.vector(), aproxdif_inputs_grad); const scalar_t dg_inputs = (analytic_inputs_grad - aproxdif_inputs_grad).lpNorm<Eigen::Infinity>(); const bool ok = dg_inputs < 1e-5;//math::almost_equal(dg_inputs, scalar_t(0)); log_info() << header << " [" << (t + 1) << "/" << n_tests << "]: samples = " << n_samples << ", dg_inputs = " << dg_inputs << " (" << (ok ? "OK" : "ERROR") << ")."; } } static void test_grad(const string_t& header, const string_t& loss_id, const model_t& model) { // check all criteria const strings_t criteria = criterion_manager_t::instance().ids(); for (const string_t& criterion : criteria) { random_t<size_t> rand(2, 16); const size_t n_threads = 1 + (rand() % 2); accumulator_t acc_params(model, n_threads, criterion, criterion_t::type::vgrad, 1.0); test_grad_params(header + "[criterion = " + criterion + "]", loss_id, model, acc_params); } // check gradients wrt the input test_grad_inputs(header, loss_id, model); } int main(int argc, char *argv[]) { ncv::init(); const strings_t conv_layer_ids { "", "conv" }; const strings_t conv_masks { "25", "50", "100" }; const strings_t pool_layer_ids { "", "pool-max", "pool-min", "pool-avg" }; const strings_t full_layer_ids { "", "linear" }; const strings_t actv_layer_ids { "", "act-unit", "act-tanh", "act-snorm", "act-splus" }; const strings_t loss_ids = loss_manager_t::instance().ids(); const color_mode cmd_color = color_mode::luma; const size_t cmd_irows = 10; const size_t cmd_icols = 10; const size_t cmd_outputs = 4; const size_t cmd_max_layers = 2; // evaluate the analytical gradient vs. the finite difference approximation for various: // * convolution layers // * convolution connection types // * pooling layers // * fully connected layers // * activation layers std::set<string_t> descs; for (size_t n_layers = 0; n_layers <= cmd_max_layers; n_layers ++) { for (const string_t& actv_layer_id : actv_layer_ids) { for (const string_t& pool_layer_id : pool_layer_ids) { for (const string_t& conv_layer_id : conv_layer_ids) { for (const string_t& conv_mask : conv_masks) { for (const string_t& full_layer_id : full_layer_ids) { string_t desc; // convolution part for (size_t l = 0; l < n_layers && !conv_layer_id.empty(); l ++) { random_t<size_t> rgen(2, 3); string_t params; params += "dims=" + text::to_string(rgen()); params += (rgen() % 2 == 0) ? ",rows=3,cols=3," : ",rows=4,cols=4,"; params += "mask=" + conv_mask; desc += conv_layer_id + ":" + params + ";"; desc += pool_layer_id + ";"; desc += actv_layer_id + ";"; } // fully-connected part for (size_t l = 0; l < n_layers && !full_layer_id.empty(); l ++) { random_t<size_t> rgen(1, 8); string_t params; params += "dims=" + text::to_string(rgen()); desc += full_layer_id + ":" + params + ";"; desc += actv_layer_id + ";"; } desc += "linear:dims=" + text::to_string(cmd_outputs) + ";"; descs.insert(desc); } } } } } } for (const string_t& desc : descs) { // create network const rmodel_t model = model_manager_t::instance().get("forward-network", desc); assert(model); model->resize(cmd_irows, cmd_icols, cmd_outputs, cmd_color, true); // test network for (const string_t& loss_id : loss_ids) { test_grad("[loss = " + loss_id + "]", loss_id, *model); } } // OK log_info() << done; return EXIT_SUCCESS; } <commit_msg>revert threshold<commit_after>#include "nanocv.h" #include <boost/program_options.hpp> #include <set> using namespace ncv; static void test_grad_params( const string_t& header, const string_t& loss_id, const model_t& model, accumulator_t& acc_params) { random_t<size_t> rand(8, 16); const size_t n_tests = 64; const size_t n_samples = rand(); const rloss_t rloss = loss_manager_t::instance().get(loss_id); const loss_t& loss = *rloss; const size_t psize = model.psize(); const size_t isize = model.isize(); const size_t osize = model.osize(); vector_t params(psize); vectors_t targets(n_samples, vector_t(osize)); tensors_t inputs(n_samples, tensor_t(model.idims(), model.irows(), model.icols())); // optimization problem (wrt parameters & inputs): size auto fn_params_size = [&] () { return psize; }; // optimization problem (wrt parameters & inputs): function value auto fn_params_fval = [&] (const vector_t& x) { acc_params.reset(x); acc_params.update(inputs, targets, loss); return acc_params.value(); }; // optimization problem (wrt parameters & inputs): function value & gradient auto fn_params_grad = [&] (const vector_t& x, vector_t& gx) { acc_params.reset(x); acc_params.update(inputs, targets, loss); gx = acc_params.vgrad(); return acc_params.value(); }; // construct optimization problem: analytic gradient and finite difference approximation const opt_problem_t problem_analytic_params(fn_params_size, fn_params_fval, fn_params_grad); const opt_problem_t problem_aproxdif_params(fn_params_size, fn_params_fval); for (size_t t = 0; t < n_tests; t ++) { random_t<scalar_t> prgen(-1.0, +1.0); random_t<scalar_t> irgen(-0.1, +0.1); random_t<size_t> trgen(0, osize - 1); prgen(params.data(), params.data() + psize); for (vector_t& target : targets) { target = ncv::class_target(trgen(), osize); } for (tensor_t& input : inputs) { irgen(input.data(), input.data() + isize); } vector_t analytic_params_grad, aproxdif_params_grad; problem_analytic_params(params, analytic_params_grad); problem_aproxdif_params(params, aproxdif_params_grad); const scalar_t dg_params = (analytic_params_grad - aproxdif_params_grad).lpNorm<Eigen::Infinity>(); const bool ok = dg_params < 1e-5;//math::almost_equal(dg_params, scalar_t(0)); log_info() << header << " [" << (t + 1) << "/" << n_tests << "]: samples = " << n_samples << ", dg_params = " << dg_params << " (" << (ok ? "OK" : "ERROR") << ")."; } } static void test_grad_inputs(const string_t& header, const string_t& loss_id, const model_t& model) { rmodel_t rmodel_inputs = model.clone(); random_t<size_t> rand(8, 16); const size_t n_tests = 64; const size_t n_samples = rand(); const rloss_t rloss = loss_manager_t::instance().get(loss_id); const loss_t& loss = *rloss; const size_t psize = model.psize(); const size_t isize = model.isize(); const size_t osize = model.osize(); vector_t params(psize); vector_t target(osize); tensor_t input(model.idims(), model.irows(), model.icols()); // optimization problem (wrt parameters & inputs): size auto fn_inputs_size = [&] () { return isize; }; // optimization problem (wrt parameters & inputs): function value auto fn_inputs_fval = [&] (const vector_t& x) { rmodel_inputs->load_params(params); const vector_t output = rmodel_inputs->output(x).vector(); return loss.value(target, output); }; // optimization problem (wrt parameters & inputs): function value & gradient auto fn_inputs_grad = [&] (const vector_t& x, vector_t& gx) { rmodel_inputs->load_params(params); const vector_t output = rmodel_inputs->output(x).vector(); gx = rmodel_inputs->ginput(loss.vgrad(target, output)).vector(); return loss.value(target, output); }; // construct optimization problem: analytic gradient and finite difference approximation const opt_problem_t problem_analytic_inputs(fn_inputs_size, fn_inputs_fval, fn_inputs_grad); const opt_problem_t problem_aproxdif_inputs(fn_inputs_size, fn_inputs_fval); for (size_t t = 0; t < n_tests; t ++) { random_t<scalar_t> prgen(-1.0, +1.0); random_t<scalar_t> irgen(-0.1, +0.1); random_t<size_t> trgen(0, osize - 1); prgen(params.data(), params.data() + psize); target = ncv::class_target(trgen(), osize); irgen(input.data(), input.data() + isize); vector_t analytic_inputs_grad, aproxdif_inputs_grad; problem_analytic_inputs(input.vector(), analytic_inputs_grad); problem_aproxdif_inputs(input.vector(), aproxdif_inputs_grad); const scalar_t dg_inputs = (analytic_inputs_grad - aproxdif_inputs_grad).lpNorm<Eigen::Infinity>(); const bool ok = dg_inputs < 1e-5;//math::almost_equal(dg_inputs, scalar_t(0)); log_info() << header << " [" << (t + 1) << "/" << n_tests << "]: samples = " << n_samples << ", dg_inputs = " << dg_inputs << " (" << (ok ? "OK" : "ERROR") << ")."; } } static void test_grad(const string_t& header, const string_t& loss_id, const model_t& model) { // check all criteria const strings_t criteria = criterion_manager_t::instance().ids(); for (const string_t& criterion : criteria) { random_t<size_t> rand(2, 16); const size_t n_threads = 1 + (rand() % 2); accumulator_t acc_params(model, n_threads, criterion, criterion_t::type::vgrad, 1.0); test_grad_params(header + "[criterion = " + criterion + "]", loss_id, model, acc_params); } // check gradients wrt the input test_grad_inputs(header, loss_id, model); } int main(int argc, char *argv[]) { ncv::init(); const strings_t conv_layer_ids { "", "conv" }; const strings_t conv_masks { "25", "50", "100" }; const strings_t pool_layer_ids { "", "pool-max", "pool-min", "pool-avg" }; const strings_t full_layer_ids { "", "linear" }; const strings_t actv_layer_ids { "", "act-unit", "act-tanh", "act-snorm", "act-splus" }; const strings_t loss_ids = loss_manager_t::instance().ids(); const color_mode cmd_color = color_mode::luma; const size_t cmd_irows = 10; const size_t cmd_icols = 10; const size_t cmd_outputs = 4; const size_t cmd_max_layers = 2; // evaluate the analytical gradient vs. the finite difference approximation for various: // * convolution layers // * convolution connection types // * pooling layers // * fully connected layers // * activation layers std::set<string_t> descs; for (size_t n_layers = 0; n_layers <= cmd_max_layers; n_layers ++) { for (const string_t& actv_layer_id : actv_layer_ids) { for (const string_t& pool_layer_id : pool_layer_ids) { for (const string_t& conv_layer_id : conv_layer_ids) { for (const string_t& conv_mask : conv_masks) { for (const string_t& full_layer_id : full_layer_ids) { string_t desc; // convolution part for (size_t l = 0; l < n_layers && !conv_layer_id.empty(); l ++) { random_t<size_t> rgen(2, 3); string_t params; params += "dims=" + text::to_string(rgen()); params += (rgen() % 2 == 0) ? ",rows=3,cols=3," : ",rows=4,cols=4,"; params += "mask=" + conv_mask; desc += conv_layer_id + ":" + params + ";"; desc += pool_layer_id + ";"; desc += actv_layer_id + ";"; } // fully-connected part for (size_t l = 0; l < n_layers && !full_layer_id.empty(); l ++) { random_t<size_t> rgen(1, 8); string_t params; params += "dims=" + text::to_string(rgen()); desc += full_layer_id + ":" + params + ";"; desc += actv_layer_id + ";"; } desc += "linear:dims=" + text::to_string(cmd_outputs) + ";"; descs.insert(desc); } } } } } } for (const string_t& desc : descs) { // create network const rmodel_t model = model_manager_t::instance().get("forward-network", desc); assert(model); model->resize(cmd_irows, cmd_icols, cmd_outputs, cmd_color, true); // test network for (const string_t& loss_id : loss_ids) { test_grad("[loss = " + loss_id + "]", loss_id, *model); } } // OK log_info() << done; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Test doesn't build on windows, because OpenGL on windows is a nightmare. #ifdef _WIN32 #include <stdio.h> int main() { printf("Skipping test on Windows\n"); return 0; } #else #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <cstring> #include "../src/runtime/mini_opengl.h" #include "Halide.h" extern "C" void glGenTextures(GLsizei, GLuint *); extern "C" void glTexParameteri(GLenum, GLenum, GLint); extern "C" void glBindTexture(GLenum, GLuint); extern "C" void glTexImage2D(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *); extern "C" GLuint glCreateProgram(); extern "C" void glAttachShader(GLuint, GLuint); extern "C" void glLinkProgram(GLuint); extern "C" void glGetProgramiv(GLuint, GLenum, GLint *); extern "C" void glGetProgramInfoLog(GLuint, GLsizei, GLsizei *, GLchar *); extern "C" GLuint glCreateShader(GLenum); extern "C" void glShaderSource(GLuint, GLsizei, const GLchar **, const GLint *); extern "C" void glCompileShader(GLuint); extern "C" void glGetShaderiv(GLuint, GLenum, GLint *); extern "C" void glGetShaderInfoLog(GLuint, GLsizei, GLsizei *, GLchar *); extern "C" void glEnable(GLenum); extern "C" void glDisable(GLenum); extern "C" void glGetIntegerv(GLenum, GLint *); extern "C" void glGetBooleanv(GLenum, GLboolean *); extern "C" GLenum glGetError(); extern "C" void glActiveTexture(GLenum); extern "C" void glEnableVertexAttribArray(GLuint); extern "C" void glDisableVertexAttribArray(GLuint); extern "C" void glUseProgram(GLuint); extern "C" void glGenBuffers(GLsizei, GLuint *); extern "C" void glViewport(GLint, GLint, GLsizei, GLsizei); extern "C" void glGenFramebuffers(GLsizei, GLuint *); extern "C" void glBindBuffer(GLenum, GLuint); extern "C" void glBindFramebuffer(GLenum, GLuint); extern "C" void glGenVertexArrays(GLsizei, GLuint *); extern "C" void glBindVertexArray(GLuint); extern "C" void glGetVertexAttribiv(GLuint, GLenum, GLint *); extern "C" const GLubyte* glGetString(GLenum name); // Generates an arbitrary program. class Program { public: static GLuint handle() { const char *vertexShader = " \ attribute vec4 Position; \ attribute vec2 TexCoordIn; \ varying vec2 TexCoordOut; \ void main(void) { \ gl_Position = Position; \ TexCoordOut = TexCoordIn; \ }"; const char *fragmentShader = " \ varying vec2 TexCoordOut; \ uniform sampler2D Texture; \ void main(void) { \ gl_FragColor = texture2D(Texture, TexCoordOut); \ }"; GLuint handle = glCreateProgram(); glAttachShader(handle, compileShader("vertex", vertexShader, GL_VERTEX_SHADER)); glAttachShader(handle, compileShader("fragment", fragmentShader, GL_FRAGMENT_SHADER)); glLinkProgram(handle); GLint linkSuccess; glGetProgramiv(handle, GL_LINK_STATUS, &linkSuccess); if (linkSuccess == GL_FALSE) { GLchar messages[256]; glGetProgramInfoLog(handle, sizeof(messages), 0, messages); fprintf(stderr, "Error linking program: %s\n", messages); exit(1); } return handle; } private: static GLuint compileShader(const char *label, const char *shaderString, GLenum shaderType) { const GLuint handle = glCreateShader(shaderType); const int len = strlen(shaderString); glShaderSource(handle, 1, &shaderString, &len); glCompileShader(handle); GLint compileSuccess; glGetShaderiv(handle, GL_COMPILE_STATUS, &compileSuccess); if (compileSuccess == GL_FALSE) { GLchar messages[256]; glGetShaderInfoLog(handle, sizeof(messages), 0, messages); fprintf(stderr, "Error compiling %s shader: %s\n", label, messages); exit(1); } return handle; } }; // Encapsulates setting OpenGL's state to arbitrary values, and checking // whether the state matches those values. class KnownState { private: void gl_enable(GLenum cap, bool state) { (state ? glEnable : glDisable)(cap); } GLuint gl_gen(void (*fn)(GLsizei, GLuint *)) { GLuint val; (*fn)(1, &val); return val; } void check_value(const char *operation, const char *label, GLenum pname, GLint initial) { GLint val; glGetIntegerv(pname, &val); if (val != initial) { fprintf(stderr, "%s did not restore %s: initial value was %d (%#x), current value is %d (%#x)\n", operation, label, initial, initial, val, val); errors = true; } } void check_value(const char *operation, const char *label, GLenum pname, GLenum initial) { check_value(operation, label, pname, (GLint) initial); } void check_value(const char *operation, const char *label, GLenum pname, GLint initial[], int n=4) { GLint val[2048]; glGetIntegerv(pname, val); for (int i=0; i<n; i++) { if (val[i] != initial[i]) { fprintf(stderr, "%s did not restore %s: initial value was", operation, label); for (int j=0; j<n; j++) fprintf(stderr, " %d", initial[j]); fprintf(stderr, ", current value is"); for (int j=0; j<n; j++) fprintf(stderr, " %d", val[j]); fprintf(stderr, "\n"); errors = true; return; } } } void check_value(const char *operation, const char *label, GLenum pname, bool initial) { GLboolean val; glGetBooleanv(pname, &val); if (val != initial) { fprintf(stderr, "%s did not restore boolean %s: initial value was %s, current value is %s\n", operation, label, initial ? "true" : "false", val ? "true" : "false"); errors = true; } } void check_error(const char *label) { GLenum err = glGetError(); if (err != GL_NO_ERROR) { fprintf(stderr, "Error setting %s: OpenGL error %#x\n", label, err); errors = true; } } GLenum initial_active_texture; GLint initial_viewport[4]; GLuint initial_array_buffer_binding; GLuint initial_element_array_buffer_binding; GLuint initial_current_program; GLuint initial_framebuffer_binding; static const int ntextures = 10; GLuint initial_bound_textures[ntextures]; bool initial_cull_face; bool initial_depth_test; static const int nvertex_attribs = 10; bool initial_vertex_attrib_array_enabled[nvertex_attribs]; // The next two functions are stolen from opengl.cpp // and are used to parse the major/minor version of OpenGL // to see if vertex array objects are supported const char *parse_int(const char *str, int *val) { int v = 0; size_t i = 0; while (str[i] >= '0' && str[i] <= '9') { v = 10 * v + (str[i] - '0'); i++; } if (i > 0) { *val = v; return &str[i]; } return NULL; } const char *parse_opengl_version(const char *str, int *major, int *minor) { str = parse_int(str, major); if (str == NULL || *str != '.') { return NULL; } return parse_int(str + 1, minor); } GLuint initial_vertex_array_binding; public: // version of OpenGL int gl_major_version; int gl_minor_version; bool errors; // This sets most values to generated or arbitrary values, which the // halide calls would be unlikely to accidentally use. But for boolean // values, we want to be sure that halide is really restoring the // initial value, not just setting it to true or false. So we need to // be able to try both. void setup(bool boolval) { // parse the OpenGL version const char *version = (const char *)glGetString(GL_VERSION); parse_opengl_version(version, &gl_major_version, &gl_minor_version); glGenTextures(ntextures, initial_bound_textures); for (int i=0; i<ntextures; i++) { glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, initial_bound_textures[i]); } glActiveTexture(initial_active_texture = GL_TEXTURE3); for (int i=0; i<nvertex_attribs; i++) { if ( (initial_vertex_attrib_array_enabled[i] = boolval ) ) glEnableVertexAttribArray(i); else glDisableVertexAttribArray(i); char buf[256]; sprintf(buf, "vertex attrib array %d state", i); check_error(buf); } glUseProgram(initial_current_program = Program::handle()); glViewport(initial_viewport[0] = 111, initial_viewport[1] = 222, initial_viewport[2] = 333, initial_viewport[3] = 444); gl_enable(GL_CULL_FACE, initial_cull_face = boolval); gl_enable(GL_DEPTH_TEST, initial_depth_test = boolval); glBindBuffer(GL_ARRAY_BUFFER, initial_array_buffer_binding = gl_gen(glGenBuffers)); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, initial_element_array_buffer_binding = gl_gen(glGenBuffers)); glBindFramebuffer(GL_FRAMEBUFFER, initial_framebuffer_binding = gl_gen(glGenFramebuffers)); // Vertex array objects are only used by Halide if the OpenGL version >=3 if (gl_major_version >= 3) { glBindVertexArray(initial_vertex_array_binding = gl_gen(glGenVertexArrays)); check_error("known state"); } } void check(const char *operation) { check_value(operation, "ActiveTexture", GL_ACTIVE_TEXTURE, initial_active_texture); check_value(operation, "current program", GL_CURRENT_PROGRAM, initial_current_program); check_value(operation, "framebuffer binding", GL_FRAMEBUFFER_BINDING, initial_framebuffer_binding); check_value(operation, "array buffer binding", GL_ARRAY_BUFFER_BINDING, initial_array_buffer_binding); check_value(operation, "element array buffer binding", GL_ELEMENT_ARRAY_BUFFER_BINDING, initial_element_array_buffer_binding); check_value(operation, "viewport", GL_VIEWPORT, initial_viewport); check_value(operation, "GL_CULL_FACE", GL_CULL_FACE, initial_cull_face); check_value(operation, "GL_DEPTH_TEST", GL_DEPTH_TEST, initial_cull_face); // Vertex array objects are only used by Halide if the OpenGL version >=3 if (gl_major_version >= 3) { check_value(operation, "vertex array binding", GL_VERTEX_ARRAY_BINDING, initial_vertex_array_binding); } for (int i=0; i<ntextures; i++) { char buf[100]; sprintf(buf, "bound texture (unit %d)", i); glActiveTexture(GL_TEXTURE0 + i); check_value(operation, buf, GL_TEXTURE_BINDING_2D, initial_bound_textures[i]); } for (int i=0; i < nvertex_attribs; i++) { int initial = initial_vertex_attrib_array_enabled[i]; GLint val; glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &val); if (val != initial) { fprintf(stderr, "%s did not restore boolean VertexAttributeArrayEnabled(%d): initial value was %s, current value is %s\n", operation, i, initial ? "true" : "false", val ? "true" : "false"); errors = true; } } } }; using namespace Halide; int main() { KnownState known_state; Image<uint8_t> input(255, 10, 3); Buffer out(UInt(8), 255, 10, 3); Var x, y, c; Func g; g(x, y, c) = input(x, y, c); g.bound(c, 0, 3); g.glsl(x, y, c); g.realize(out); // let Halide initialize OpenGL known_state.setup(true); g.realize(out); known_state.check("realize"); known_state.setup(true); out.copy_to_host(); known_state.check("copy_to_host"); known_state.setup(false); g.realize(out); known_state.check("realize"); known_state.setup(false); out.copy_to_host(); known_state.check("copy_to_host"); if (known_state.errors) { return 1; } printf("Success!\n"); return 0; } #endif <commit_msg>Minor: versions don't need to be public.<commit_after>// Test doesn't build on windows, because OpenGL on windows is a nightmare. #ifdef _WIN32 #include <stdio.h> int main() { printf("Skipping test on Windows\n"); return 0; } #else #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <cstring> #include "../src/runtime/mini_opengl.h" #include "Halide.h" extern "C" void glGenTextures(GLsizei, GLuint *); extern "C" void glTexParameteri(GLenum, GLenum, GLint); extern "C" void glBindTexture(GLenum, GLuint); extern "C" void glTexImage2D(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *); extern "C" GLuint glCreateProgram(); extern "C" void glAttachShader(GLuint, GLuint); extern "C" void glLinkProgram(GLuint); extern "C" void glGetProgramiv(GLuint, GLenum, GLint *); extern "C" void glGetProgramInfoLog(GLuint, GLsizei, GLsizei *, GLchar *); extern "C" GLuint glCreateShader(GLenum); extern "C" void glShaderSource(GLuint, GLsizei, const GLchar **, const GLint *); extern "C" void glCompileShader(GLuint); extern "C" void glGetShaderiv(GLuint, GLenum, GLint *); extern "C" void glGetShaderInfoLog(GLuint, GLsizei, GLsizei *, GLchar *); extern "C" void glEnable(GLenum); extern "C" void glDisable(GLenum); extern "C" void glGetIntegerv(GLenum, GLint *); extern "C" void glGetBooleanv(GLenum, GLboolean *); extern "C" GLenum glGetError(); extern "C" void glActiveTexture(GLenum); extern "C" void glEnableVertexAttribArray(GLuint); extern "C" void glDisableVertexAttribArray(GLuint); extern "C" void glUseProgram(GLuint); extern "C" void glGenBuffers(GLsizei, GLuint *); extern "C" void glViewport(GLint, GLint, GLsizei, GLsizei); extern "C" void glGenFramebuffers(GLsizei, GLuint *); extern "C" void glBindBuffer(GLenum, GLuint); extern "C" void glBindFramebuffer(GLenum, GLuint); extern "C" void glGenVertexArrays(GLsizei, GLuint *); extern "C" void glBindVertexArray(GLuint); extern "C" void glGetVertexAttribiv(GLuint, GLenum, GLint *); extern "C" const GLubyte* glGetString(GLenum name); // Generates an arbitrary program. class Program { public: static GLuint handle() { const char *vertexShader = " \ attribute vec4 Position; \ attribute vec2 TexCoordIn; \ varying vec2 TexCoordOut; \ void main(void) { \ gl_Position = Position; \ TexCoordOut = TexCoordIn; \ }"; const char *fragmentShader = " \ varying vec2 TexCoordOut; \ uniform sampler2D Texture; \ void main(void) { \ gl_FragColor = texture2D(Texture, TexCoordOut); \ }"; GLuint handle = glCreateProgram(); glAttachShader(handle, compileShader("vertex", vertexShader, GL_VERTEX_SHADER)); glAttachShader(handle, compileShader("fragment", fragmentShader, GL_FRAGMENT_SHADER)); glLinkProgram(handle); GLint linkSuccess; glGetProgramiv(handle, GL_LINK_STATUS, &linkSuccess); if (linkSuccess == GL_FALSE) { GLchar messages[256]; glGetProgramInfoLog(handle, sizeof(messages), 0, messages); fprintf(stderr, "Error linking program: %s\n", messages); exit(1); } return handle; } private: static GLuint compileShader(const char *label, const char *shaderString, GLenum shaderType) { const GLuint handle = glCreateShader(shaderType); const int len = strlen(shaderString); glShaderSource(handle, 1, &shaderString, &len); glCompileShader(handle); GLint compileSuccess; glGetShaderiv(handle, GL_COMPILE_STATUS, &compileSuccess); if (compileSuccess == GL_FALSE) { GLchar messages[256]; glGetShaderInfoLog(handle, sizeof(messages), 0, messages); fprintf(stderr, "Error compiling %s shader: %s\n", label, messages); exit(1); } return handle; } }; // Encapsulates setting OpenGL's state to arbitrary values, and checking // whether the state matches those values. class KnownState { private: void gl_enable(GLenum cap, bool state) { (state ? glEnable : glDisable)(cap); } GLuint gl_gen(void (*fn)(GLsizei, GLuint *)) { GLuint val; (*fn)(1, &val); return val; } void check_value(const char *operation, const char *label, GLenum pname, GLint initial) { GLint val; glGetIntegerv(pname, &val); if (val != initial) { fprintf(stderr, "%s did not restore %s: initial value was %d (%#x), current value is %d (%#x)\n", operation, label, initial, initial, val, val); errors = true; } } void check_value(const char *operation, const char *label, GLenum pname, GLenum initial) { check_value(operation, label, pname, (GLint) initial); } void check_value(const char *operation, const char *label, GLenum pname, GLint initial[], int n=4) { GLint val[2048]; glGetIntegerv(pname, val); for (int i=0; i<n; i++) { if (val[i] != initial[i]) { fprintf(stderr, "%s did not restore %s: initial value was", operation, label); for (int j=0; j<n; j++) fprintf(stderr, " %d", initial[j]); fprintf(stderr, ", current value is"); for (int j=0; j<n; j++) fprintf(stderr, " %d", val[j]); fprintf(stderr, "\n"); errors = true; return; } } } void check_value(const char *operation, const char *label, GLenum pname, bool initial) { GLboolean val; glGetBooleanv(pname, &val); if (val != initial) { fprintf(stderr, "%s did not restore boolean %s: initial value was %s, current value is %s\n", operation, label, initial ? "true" : "false", val ? "true" : "false"); errors = true; } } void check_error(const char *label) { GLenum err = glGetError(); if (err != GL_NO_ERROR) { fprintf(stderr, "Error setting %s: OpenGL error %#x\n", label, err); errors = true; } } // version of OpenGL int gl_major_version; int gl_minor_version; GLenum initial_active_texture; GLint initial_viewport[4]; GLuint initial_array_buffer_binding; GLuint initial_element_array_buffer_binding; GLuint initial_current_program; GLuint initial_framebuffer_binding; static const int ntextures = 10; GLuint initial_bound_textures[ntextures]; bool initial_cull_face; bool initial_depth_test; static const int nvertex_attribs = 10; bool initial_vertex_attrib_array_enabled[nvertex_attribs]; // The next two functions are stolen from opengl.cpp // and are used to parse the major/minor version of OpenGL // to see if vertex array objects are supported const char *parse_int(const char *str, int *val) { int v = 0; size_t i = 0; while (str[i] >= '0' && str[i] <= '9') { v = 10 * v + (str[i] - '0'); i++; } if (i > 0) { *val = v; return &str[i]; } return NULL; } const char *parse_opengl_version(const char *str, int *major, int *minor) { str = parse_int(str, major); if (str == NULL || *str != '.') { return NULL; } return parse_int(str + 1, minor); } GLuint initial_vertex_array_binding; public: bool errors; // This sets most values to generated or arbitrary values, which the // halide calls would be unlikely to accidentally use. But for boolean // values, we want to be sure that halide is really restoring the // initial value, not just setting it to true or false. So we need to // be able to try both. void setup(bool boolval) { // parse the OpenGL version const char *version = (const char *)glGetString(GL_VERSION); parse_opengl_version(version, &gl_major_version, &gl_minor_version); glGenTextures(ntextures, initial_bound_textures); for (int i=0; i<ntextures; i++) { glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, initial_bound_textures[i]); } glActiveTexture(initial_active_texture = GL_TEXTURE3); for (int i=0; i<nvertex_attribs; i++) { if ( (initial_vertex_attrib_array_enabled[i] = boolval ) ) glEnableVertexAttribArray(i); else glDisableVertexAttribArray(i); char buf[256]; sprintf(buf, "vertex attrib array %d state", i); check_error(buf); } glUseProgram(initial_current_program = Program::handle()); glViewport(initial_viewport[0] = 111, initial_viewport[1] = 222, initial_viewport[2] = 333, initial_viewport[3] = 444); gl_enable(GL_CULL_FACE, initial_cull_face = boolval); gl_enable(GL_DEPTH_TEST, initial_depth_test = boolval); glBindBuffer(GL_ARRAY_BUFFER, initial_array_buffer_binding = gl_gen(glGenBuffers)); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, initial_element_array_buffer_binding = gl_gen(glGenBuffers)); glBindFramebuffer(GL_FRAMEBUFFER, initial_framebuffer_binding = gl_gen(glGenFramebuffers)); // Vertex array objects are only used by Halide if the OpenGL version >=3 if (gl_major_version >= 3) { glBindVertexArray(initial_vertex_array_binding = gl_gen(glGenVertexArrays)); check_error("known state"); } } void check(const char *operation) { check_value(operation, "ActiveTexture", GL_ACTIVE_TEXTURE, initial_active_texture); check_value(operation, "current program", GL_CURRENT_PROGRAM, initial_current_program); check_value(operation, "framebuffer binding", GL_FRAMEBUFFER_BINDING, initial_framebuffer_binding); check_value(operation, "array buffer binding", GL_ARRAY_BUFFER_BINDING, initial_array_buffer_binding); check_value(operation, "element array buffer binding", GL_ELEMENT_ARRAY_BUFFER_BINDING, initial_element_array_buffer_binding); check_value(operation, "viewport", GL_VIEWPORT, initial_viewport); check_value(operation, "GL_CULL_FACE", GL_CULL_FACE, initial_cull_face); check_value(operation, "GL_DEPTH_TEST", GL_DEPTH_TEST, initial_cull_face); // Vertex array objects are only used by Halide if the OpenGL version >=3 if (gl_major_version >= 3) { check_value(operation, "vertex array binding", GL_VERTEX_ARRAY_BINDING, initial_vertex_array_binding); } for (int i=0; i<ntextures; i++) { char buf[100]; sprintf(buf, "bound texture (unit %d)", i); glActiveTexture(GL_TEXTURE0 + i); check_value(operation, buf, GL_TEXTURE_BINDING_2D, initial_bound_textures[i]); } for (int i=0; i < nvertex_attribs; i++) { int initial = initial_vertex_attrib_array_enabled[i]; GLint val; glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &val); if (val != initial) { fprintf(stderr, "%s did not restore boolean VertexAttributeArrayEnabled(%d): initial value was %s, current value is %s\n", operation, i, initial ? "true" : "false", val ? "true" : "false"); errors = true; } } } }; using namespace Halide; int main() { KnownState known_state; Image<uint8_t> input(255, 10, 3); Buffer out(UInt(8), 255, 10, 3); Var x, y, c; Func g; g(x, y, c) = input(x, y, c); g.bound(c, 0, 3); g.glsl(x, y, c); g.realize(out); // let Halide initialize OpenGL known_state.setup(true); g.realize(out); known_state.check("realize"); known_state.setup(true); out.copy_to_host(); known_state.check("copy_to_host"); known_state.setup(false); g.realize(out); known_state.check("realize"); known_state.setup(false); out.copy_to_host(); known_state.check("copy_to_host"); if (known_state.errors) { return 1; } printf("Success!\n"); return 0; } #endif <|endoftext|>
<commit_before>#include "fly/parser/ini_parser.hpp" #include <gtest/gtest.h> #include <filesystem> //================================================================================================== class IniParserTest : public ::testing::Test { protected: fly::IniParser m_parser; }; //================================================================================================== TEST_F(IniParserTest, NonExistingPath) { auto parsed = m_parser.parse_file(std::filesystem::path("foo_abc") / "a.json"); ASSERT_TRUE(parsed.has_value()); fly::Json values = std::move(parsed.value()); EXPECT_EQ(values.size(), 0); } //================================================================================================== TEST_F(IniParserTest, NonExistingFile) { auto parsed = m_parser.parse_file(std::filesystem::temp_directory_path() / "a.json"); ASSERT_TRUE(parsed.has_value()); fly::Json values = std::move(parsed.value()); EXPECT_EQ(values.size(), 0); } //================================================================================================== TEST_F(IniParserTest, EmptyFile) { const std::string contents; auto parsed = m_parser.parse_string(contents); ASSERT_TRUE(parsed.has_value()); fly::Json values = std::move(parsed.value()); EXPECT_EQ(values.size(), 0); } //================================================================================================== TEST_F(IniParserTest, EmptySection) { const std::string contents("[section]"); auto parsed = m_parser.parse_string(contents); ASSERT_TRUE(parsed.has_value()); fly::Json values = std::move(parsed.value()); EXPECT_EQ(values.size(), 0); } //================================================================================================== TEST_F(IniParserTest, NonEmptySection) { const std::string contents( "[section]\n" "name=John Doe\n" "address=USA"); auto parsed = m_parser.parse_string(contents); ASSERT_TRUE(parsed.has_value()); fly::Json values = std::move(parsed.value()); EXPECT_EQ(values.size(), 1); EXPECT_EQ(values["section"].size(), 2); } //================================================================================================== TEST_F(IniParserTest, NonExistingSection) { const std::string contents( "[section]\n" "name=John Doe\n" "address=USA"); auto parsed = m_parser.parse_string(contents); ASSERT_TRUE(parsed.has_value()); fly::Json values = std::move(parsed.value()); EXPECT_EQ(values["section"].size(), 2); EXPECT_EQ(values["bad-section"].size(), 0); EXPECT_EQ(values["section-bad"].size(), 0); } //================================================================================================== TEST_F(IniParserTest, Comment) { const std::string contents( "[section]\n" "name=John Doe\n" "; [other-section]\n" "; name=Jane Doe\n"); auto parsed = m_parser.parse_string(contents); ASSERT_TRUE(parsed.has_value()); fly::Json values = std::move(parsed.value()); EXPECT_EQ(values.size(), 1); EXPECT_EQ(values["section"].size(), 1); EXPECT_EQ(values["other-section"].size(), 0); } //================================================================================================== TEST_F(IniParserTest, ErrantSpaces) { const std::string contents( " [section ] \n" "\t\t\n name=John Doe\t \n" "\taddress = USA\t \r \n"); auto parsed = m_parser.parse_string(contents); ASSERT_TRUE(parsed.has_value()); fly::Json values = std::move(parsed.value()); EXPECT_EQ(values.size(), 1); EXPECT_EQ(values["section"].size(), 2); } //================================================================================================== TEST_F(IniParserTest, QuotedValue) { const std::string contents( "[section]\n" "name=\" John Doe \"\n" "address= \t '\\tUSA'"); auto parsed = m_parser.parse_string(contents); ASSERT_TRUE(parsed.has_value()); fly::Json values = std::move(parsed.value()); EXPECT_EQ(values.size(), 1); EXPECT_EQ(values["section"].size(), 2); } //================================================================================================== TEST_F(IniParserTest, MutlipleSectionType) { const std::string contents( "[section1]\n" "name=John Doe\n" "age=26\n" "[section2]\n" "name=Jane Doe\n" "age=30.12\n" "[section3]\n" "name=Joe Doe\n" "noage=1\n"); auto parsed = m_parser.parse_string(contents); ASSERT_TRUE(parsed.has_value()); fly::Json values = std::move(parsed.value()); EXPECT_EQ(values.size(), 3); EXPECT_EQ(values["section1"].size(), 2); EXPECT_EQ(values["section2"].size(), 2); EXPECT_EQ(values["section3"].size(), 2); } //================================================================================================== TEST_F(IniParserTest, DuplicateSection) { const std::string contents1( "[section]\n" "name=John Doe\n" "[section]\n" "name=Jane Doe\n"); auto parsed1 = m_parser.parse_string(contents1); ASSERT_TRUE(parsed1.has_value()); fly::Json values1 = std::move(parsed1.value()); EXPECT_EQ(values1.size(), 1); EXPECT_EQ(values1["section"].size(), 1); EXPECT_EQ(values1["section"]["name"], "Jane Doe"); const std::string contents2( "[ \tsection]\n" "name=John Doe\n" "[section ]\n" "name=Jane Doe\n"); auto parsed2 = m_parser.parse_string(contents1); ASSERT_TRUE(parsed2.has_value()); fly::Json values2 = std::move(parsed2.value()); EXPECT_EQ(values2.size(), 1); EXPECT_EQ(values2["section"].size(), 1); EXPECT_EQ(values2["section"]["name"], "Jane Doe"); } //================================================================================================== TEST_F(IniParserTest, DuplicateValue) { const std::string contents( "[section]\n" "name=John Doe\n" "name=Jane Doe\n"); auto parsed = m_parser.parse_string(contents); ASSERT_TRUE(parsed.has_value()); fly::Json values = std::move(parsed.value()); EXPECT_EQ(values.size(), 1); EXPECT_EQ(values["section"].size(), 1); EXPECT_EQ(values["section"]["name"], "Jane Doe"); } //================================================================================================== TEST_F(IniParserTest, ImbalancedBrace) { const std::string contents1( "[section\n" "name=John Doe\n"); const std::string contents2( "section]\n" "name=John Doe\n"); EXPECT_FALSE(m_parser.parse_string(contents1).has_value()); EXPECT_FALSE(m_parser.parse_string(contents2).has_value()); } //================================================================================================== TEST_F(IniParserTest, ImbalancedQuote) { const std::string contents1( "[section]\n" "name=\"John Doe\n"); const std::string contents2( "[section]\n" "name=John Doe\"\n"); const std::string contents3( "[section]\n" "name='John Doe\n"); const std::string contents4( "[section]\n" "name=John Doe'\n"); const std::string contents5( "[section]\n" "name=\"John Doe'\n"); const std::string contents6( "[section]\n" "name='John Doe\"\n"); EXPECT_FALSE(m_parser.parse_string(contents1).has_value()); EXPECT_FALSE(m_parser.parse_string(contents2).has_value()); EXPECT_FALSE(m_parser.parse_string(contents3).has_value()); EXPECT_FALSE(m_parser.parse_string(contents4).has_value()); EXPECT_FALSE(m_parser.parse_string(contents5).has_value()); EXPECT_FALSE(m_parser.parse_string(contents6).has_value()); } //================================================================================================== TEST_F(IniParserTest, MisplacedQuote) { const std::string contents1( "[section]\n" "\"name\"=John Doe\n"); const std::string contents2( "[section]\n" "\'name\'=John Doe\n"); const std::string contents3( "[\"section\"]\n" "name=John Doe\n"); const std::string contents4( "[\'section\']\n" "name=John Doe\n"); const std::string contents5( "\"[section]\"\n" "name=John Doe\n"); const std::string contents6( "\'[section]\'\n" "name=John Doe\n"); EXPECT_FALSE(m_parser.parse_string(contents1).has_value()); EXPECT_FALSE(m_parser.parse_string(contents2).has_value()); EXPECT_FALSE(m_parser.parse_string(contents3).has_value()); EXPECT_FALSE(m_parser.parse_string(contents4).has_value()); EXPECT_FALSE(m_parser.parse_string(contents5).has_value()); EXPECT_FALSE(m_parser.parse_string(contents6).has_value()); } //================================================================================================== TEST_F(IniParserTest, MultipleAssignment) { const std::string contents1( "[section]\n" "name=John=Doe\n"); const std::string contents2( "[section]\n" "name=\"John=Doe\"\n"); auto parsed1 = m_parser.parse_string(contents1); ASSERT_TRUE(parsed1.has_value()); fly::Json values1 = std::move(parsed1.value()); EXPECT_EQ(values1.size(), 1); EXPECT_EQ(values1["section"].size(), 1); auto parsed2 = m_parser.parse_string(contents1); ASSERT_TRUE(parsed2.has_value()); fly::Json values2 = std::move(parsed2.value()); EXPECT_EQ(values2.size(), 1); EXPECT_EQ(values2["section"].size(), 1); } //================================================================================================== TEST_F(IniParserTest, MissingAssignment) { const std::string contents1( "[section]\n" "name\n"); const std::string contents2( "[section]\n" "name=\n"); EXPECT_FALSE(m_parser.parse_string(contents1).has_value()); EXPECT_FALSE(m_parser.parse_string(contents2).has_value()); } //================================================================================================== TEST_F(IniParserTest, EarlyAssignment) { const std::string contents1( "name=John Doe\n" "[section]\n"); const std::string contents2( "name=\n" "[section]\n"); const std::string contents3( "name\n" "[section]\n"); EXPECT_FALSE(m_parser.parse_string(contents1).has_value()); EXPECT_FALSE(m_parser.parse_string(contents2).has_value()); EXPECT_FALSE(m_parser.parse_string(contents3).has_value()); } //================================================================================================== TEST_F(IniParserTest, MultipleParse) { const std::string contents( "[section]\n" "name=John Doe\n" "address=USA"); for (int i = 0; i < 5; ++i) { auto parsed = m_parser.parse_string(contents); ASSERT_TRUE(parsed.has_value()); fly::Json values = std::move(parsed.value()); EXPECT_EQ(values.size(), 1); EXPECT_EQ(values["section"].size(), 2); } } //================================================================================================== TEST_F(IniParserTest, BadValue) { const std::string contents( "[section]\n" "name=John Doe\n" "address=\xff"); EXPECT_FALSE(m_parser.parse_string(contents).has_value()); } <commit_msg>Convert IniParser tests to Catch2<commit_after>#include "fly/parser/ini_parser.hpp" #include <catch2/catch.hpp> #include <filesystem> TEST_CASE("IniParser", "[parser]") { fly::IniParser parser; SECTION("Non-existing directory cannot be parsed") { auto parsed = parser.parse_file(std::filesystem::path("foo_abc") / "a.json"); CHECK_FALSE(parsed.has_value()); } SECTION("Non-existing file cannot be parsed") { auto parsed = parser.parse_file(std::filesystem::temp_directory_path() / "a.json"); CHECK_FALSE(parsed.has_value()); } SECTION("Empty file cannot be parsed") { const std::string contents; auto parsed = parser.parse_string(contents); CHECK_FALSE(parsed.has_value()); } SECTION("Empty section can be parsed") { const std::string contents("[section]"); auto parsed = parser.parse_string(contents); REQUIRE(parsed.has_value()); const fly::Json values = std::move(parsed.value()); CHECK(values.size() == 1); CHECK(values["section"].size() == 0); } SECTION("Single section with name-value pairs") { const std::string contents( "[section]\n" "name=John Doe\n" "address=USA"); auto parsed = parser.parse_string(contents); REQUIRE(parsed.has_value()); const fly::Json values = std::move(parsed.value()); CHECK(values.size() == 1); CHECK(values["section"].size() == 2); CHECK(values["section"]["name"] == "John Doe"); CHECK(values["section"]["address"] == "USA"); } SECTION("Multiple section with name-value pairs") { const std::string contents( "[section1]\n" "name=John Doe\n" "age=26\n" "[section2]\n" "name=Jane Doe\n" "age=30.12\n" "[section3]\n" "name=Joe Doe\n" "noage=1\n"); auto parsed = parser.parse_string(contents); REQUIRE(parsed.has_value()); const fly::Json values = std::move(parsed.value()); CHECK(values.size() == 3); CHECK(values["section1"].size() == 2); CHECK(values["section1"]["name"] == "John Doe"); CHECK(values["section1"]["age"] == "26"); CHECK(values["section2"].size() == 2); CHECK(values["section2"]["name"] == "Jane Doe"); CHECK(values["section2"]["age"] == "30.12"); CHECK(values["section3"].size() == 2); CHECK(values["section3"]["name"] == "Joe Doe"); CHECK(values["section3"]["noage"] == "1"); } SECTION("Only existing section names are parsed") { const std::string contents( "[section]\n" "name=John Doe\n" "address=USA"); auto parsed = parser.parse_string(contents); REQUIRE(parsed.has_value()); const fly::Json values = std::move(parsed.value()); CHECK(values["section"].size() == 2); CHECK_THROWS_AS(values["bad-section"], fly::JsonException); CHECK_THROWS_AS(values["section-bad"], fly::JsonException); } SECTION("Commented out sections are not parsed") { const std::string contents( "[section]\n" "name=John Doe\n" "; [other-section]\n" "; name=Jane Doe\n"); auto parsed = parser.parse_string(contents); REQUIRE(parsed.has_value()); const fly::Json values = std::move(parsed.value()); CHECK(values.size() == 1); CHECK(values["section"].size() == 1); CHECK_THROWS_AS(values["other-section"], fly::JsonException); } SECTION("Extra whitespace is ignored") { const std::string contents( " [section ] \n" "\t\t\n name=John Doe\t \n" "\taddress = USA\t \r \n"); auto parsed = parser.parse_string(contents); REQUIRE(parsed.has_value()); const fly::Json values = std::move(parsed.value()); CHECK(values.size() == 1); CHECK(values["section"].size() == 2); CHECK(values["section"]["name"] == "John Doe"); CHECK(values["section"]["address"] == "USA"); } SECTION("Extra whitespace between quotes is not ignored") { const std::string contents( "[section]\n" "name=\" John Doe \"\n" "address= \t '\\tUSA'"); auto parsed = parser.parse_string(contents); REQUIRE(parsed.has_value()); const fly::Json values = std::move(parsed.value()); CHECK(values.size() == 1); CHECK(values["section"].size() == 2); CHECK(values["section"]["name"] == " John Doe "); CHECK(values["section"]["address"] == "\\tUSA"); } SECTION("Duplicate sections override existing sections") { const std::string contents1( "[section]\n" "name=John Doe\n" "[section]\n" "name=Jane Doe\n"); auto parsed1 = parser.parse_string(contents1); REQUIRE(parsed1.has_value()); const fly::Json values1 = std::move(parsed1.value()); CHECK(values1.size() == 1); CHECK(values1["section"].size() == 1); CHECK(values1["section"]["name"] == "Jane Doe"); const std::string contents2( "[ \tsection]\n" "name=John Doe\n" "[section ]\n" "name=Jane Doe\n"); auto parsed2 = parser.parse_string(contents1); REQUIRE(parsed2.has_value()); const fly::Json values2 = std::move(parsed2.value()); CHECK(values2.size() == 1); CHECK(values2["section"].size() == 1); CHECK(values2["section"]["name"] == "Jane Doe"); } SECTION("Duplicate values override existing values") { const std::string contents( "[section]\n" "name=John Doe\n" "name=Jane Doe\n"); auto parsed = parser.parse_string(contents); REQUIRE(parsed.has_value()); const fly::Json values = std::move(parsed.value()); CHECK(values.size() == 1); CHECK(values["section"].size() == 1); CHECK(values["section"]["name"] == "Jane Doe"); } SECTION("Imbalanced braces on section names cannot be parsed") { const std::string contents1( "[section\n" "name=John Doe\n"); const std::string contents2( "section]\n" "name=John Doe\n"); CHECK_FALSE(parser.parse_string(contents1).has_value()); CHECK_FALSE(parser.parse_string(contents2).has_value()); } SECTION("Imbalanced quotes on values cannot be parsed") { const std::string contents1( "[section]\n" "name=\"John Doe\n"); const std::string contents2( "[section]\n" "name=John Doe\"\n"); const std::string contents3( "[section]\n" "name='John Doe\n"); const std::string contents4( "[section]\n" "name=John Doe'\n"); const std::string contents5( "[section]\n" "name=\"John Doe'\n"); const std::string contents6( "[section]\n" "name='John Doe\"\n"); CHECK_FALSE(parser.parse_string(contents1).has_value()); CHECK_FALSE(parser.parse_string(contents2).has_value()); CHECK_FALSE(parser.parse_string(contents3).has_value()); CHECK_FALSE(parser.parse_string(contents4).has_value()); CHECK_FALSE(parser.parse_string(contents5).has_value()); CHECK_FALSE(parser.parse_string(contents6).has_value()); } SECTION("Section names and values names cannot be quoted") { const std::string contents1( "[section]\n" "\"name\"=John Doe\n"); const std::string contents2( "[section]\n" "\'name\'=John Doe\n"); const std::string contents3( "[\"section\"]\n" "name=John Doe\n"); const std::string contents4( "[\'section\']\n" "name=John Doe\n"); const std::string contents5( "\"[section]\"\n" "name=John Doe\n"); const std::string contents6( "\'[section]\'\n" "name=John Doe\n"); CHECK_FALSE(parser.parse_string(contents1).has_value()); CHECK_FALSE(parser.parse_string(contents2).has_value()); CHECK_FALSE(parser.parse_string(contents3).has_value()); CHECK_FALSE(parser.parse_string(contents4).has_value()); CHECK_FALSE(parser.parse_string(contents5).has_value()); CHECK_FALSE(parser.parse_string(contents6).has_value()); } SECTION("Secondary assignment operators are captured as part of the value") { const std::string contents1( "[section]\n" "name=John=Doe\n"); const std::string contents2( "[section]\n" "name=\"John=Doe\"\n"); auto parsed1 = parser.parse_string(contents1); REQUIRE(parsed1.has_value()); const fly::Json values1 = std::move(parsed1.value()); CHECK(values1.size() == 1); CHECK(values1["section"].size() == 1); CHECK(values1["section"]["name"] == "John=Doe"); auto parsed2 = parser.parse_string(contents2); REQUIRE(parsed2.has_value()); const fly::Json values2 = std::move(parsed2.value()); CHECK(values2.size() == 1); CHECK(values2["section"].size() == 1); CHECK(values2["section"]["name"] == "John=Doe"); } SECTION("Missing an assignment operator cannot be parsed") { const std::string contents( "[section]\n" "name\n"); CHECK_FALSE(parser.parse_string(contents).has_value()); } SECTION("Empty values cannot be parsed") { const std::string contents( "[section]\n" "name=\n"); CHECK_FALSE(parser.parse_string(contents).has_value()); } SECTION("Assignments before a section name cannot be parsed") { const std::string contents1( "name=John Doe\n" "[section]\n"); const std::string contents2( "name=\n" "[section]\n"); const std::string contents3( "name\n" "[section]\n"); CHECK_FALSE(parser.parse_string(contents1).has_value()); CHECK_FALSE(parser.parse_string(contents2).has_value()); CHECK_FALSE(parser.parse_string(contents3).has_value()); } SECTION("Section names with invalid JSON string contents cannot be parsed") { const std::string contents( "[\xff]\n" "name=John Doe\n" "address=USA"); CHECK_FALSE(parser.parse_string(contents).has_value()); } SECTION("Value names with invalid JSON string contents cannot be parsed") { const std::string contents( "[section]\n" "\xff=John Doe\n" "address=USA"); CHECK_FALSE(parser.parse_string(contents).has_value()); } SECTION("Values with invalid JSON string contents cannot be parsed") { const std::string contents( "[section]\n" "name=John Doe\n" "address=\xff"); CHECK_FALSE(parser.parse_string(contents).has_value()); } SECTION("The parser is re-entrant") { const std::string contents( "[section]\n" "name=John Doe\n" "address=USA"); for (int i = 0; i < 5; ++i) { auto parsed = parser.parse_string(contents); REQUIRE(parsed.has_value()); const fly::Json values = std::move(parsed.value()); CHECK(values.size() == 1); CHECK(values["section"].size() == 2); CHECK(values["section"]["name"] == "John Doe"); CHECK(values["section"]["address"] == "USA"); } } } <|endoftext|>
<commit_before>// RUN: %clang_cc1 -analyze -std=c++11 -analyzer-checker=alpha.clone.CloneChecker -verify %s // expected-no-diagnostics int foo1(int src) { int dst = src; if (src < 100 && src > 0) { asm ("mov %1, %0\n\t" "add $1, %0" : "=r" (dst) : "r" (src)); } return dst; } // Identical to foo1 except that it adds two instead of one, so it's no clone. int foo2(int src) { int dst = src; if (src < 100 && src > 0) { asm ("mov %1, %0\n\t" "add $2, %0" : "=r" (dst) : "r" (src)); } return dst; } // Identical to foo1 except that its a volatile asm statement, so it's no clone. int foo3(int src) { int dst = src; if (src < 100 && src > 0) { asm volatile ("mov %1, %0\n\t" "add $1, %0" : "=r" (dst) : "r" (src)); } return dst; } <commit_msg>[analyzer] Hotfix for buildbot failure due to unspecified triple in r277449<commit_after>// RUN: %clang_cc1 -triple x86_64-unknown-linux -analyze -analyzer-checker=alpha.clone.CloneChecker -verify %s // expected-no-diagnostics int foo1(int src) { int dst = src; if (src < 100 && src > 0) { asm ("mov %1, %0\n\t" "add $1, %0" : "=r" (dst) : "r" (src)); } return dst; } // Identical to foo1 except that it adds two instead of one, so it's no clone. int foo2(int src) { int dst = src; if (src < 100 && src > 0) { asm ("mov %1, %0\n\t" "add $2, %0" : "=r" (dst) : "r" (src)); } return dst; } // Identical to foo1 except that its a volatile asm statement, so it's no clone. int foo3(int src) { int dst = src; if (src < 100 && src > 0) { asm volatile ("mov %1, %0\n\t" "add $1, %0" : "=r" (dst) : "r" (src)); } return dst; } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]){ double resultado = 0; for (int argumento=1; argumento < argc; argumento++) resultado += atof(argv[argumento]); printf("%lf\n", resultado); return EXIT_SUCCESS; } <commit_msg>Delete add.cpp<commit_after><|endoftext|>
<commit_before>#include "simplebicycle.h" #include <boost/math/tools/tuple.hpp> #include <boost/math/tools/roots.hpp> #include "constants.h" #include "parameters.h" namespace model { SimpleBicycle::SimpleBicycle(real_t v, real_t dt) : m_M(parameters::benchmark::M), m_C1(parameters::benchmark::C1), m_K0(parameters::benchmark::K0), m_K2(parameters::benchmark::K2), m_pose(BicyclePoseMessage_init_zero), m_v(0.0), m_dt(dt), m_T_m(0.0), m_w(parameters::benchmark::wheelbase), m_c(parameters::benchmark::trail), m_lambda(parameters::benchmark::steer_axis_tilt), m_rr(parameters::benchmark::rear_wheel_radius), m_rf(parameters::benchmark::front_wheel_radius) { set_moore_parameters(); set_v(v); reset_pose(); } void SimpleBicycle::set_v(real_t v) { m_v = v; m_C = v*m_C1; m_K = constants::g*m_K0 + v*v*m_K2; } void SimpleBicycle::set_dt(real_t dt) { m_dt = dt; } void SimpleBicycle::reset_pose() { m_x.setZero(); m_x_aux.setZero(); m_T_m = 0.0; m_pose = BicyclePoseMessage{}; /* reset pose to zero */ m_x_aux[auxiliary_state_index_t::pitch_angle] = solve_constraint_pitch(m_x, m_x_aux[auxiliary_state_index_t::pitch_angle]); m_pose.pitch = m_x_aux[auxiliary_state_index_t::pitch_angle]; } void SimpleBicycle::update(real_t roll_torque_input, real_t steer_torque_input, real_t yaw_angle_measurement, real_t steer_angle_measurement, real_t rear_wheel_angle_measurement) { (void)roll_torque_input; (void)steer_torque_input; (void)yaw_angle_measurement; update_state(steer_angle_measurement); m_x_aux = integrate_auxiliary_state(m_x, m_x_aux); m_x_aux[auxiliary_state_index_t::pitch_angle] = solve_constraint_pitch(m_x, m_x_aux[auxiliary_state_index_t::pitch_angle]); update_feedback_torque(); set_pose(); /* * The rear wheel angle is set outside of the 'set_pose' function because it has no * direct influence on the dynamics. The velocity is obtained from a numerical * derivative of the position signal (model-less) */ m_pose.rear_wheel = rear_wheel_angle_measurement; } void SimpleBicycle::set_moore_parameters() { m_d1 = std::cos(m_lambda)*(m_c + m_w - m_rr*std::tan(m_lambda)); m_d3 = -std::cos(m_lambda)*(m_c - m_rf*std::tan(m_lambda)); m_d2 = (m_rr + m_d1*std::sin(m_lambda) - m_rf + m_d3*std::sin(m_lambda)) / std::cos(m_lambda); } void SimpleBicycle::set_pose() { m_pose.timestamp += static_cast<decltype(m_pose.timestamp)>(m_dt * 1000); /* timestamp in milliseconds */ m_pose.x = m_x_aux[auxiliary_state_index_t::x]; m_pose.y = m_x_aux[auxiliary_state_index_t::y]; m_pose.pitch = m_x_aux[auxiliary_state_index_t::pitch_angle]; m_pose.yaw = m_x_aux[auxiliary_state_index_t::yaw_angle]; m_pose.roll = m_x[state_index_t::roll_angle]; m_pose.steer = m_x[state_index_t::steer_angle]; } /* * Simplified equations of motion are used to simulate the bicycle dynamics. * Roll/steer rate and acceleration terms are ignored resulting in: * (g*K0 + v^2*K2) [phi ] = [T_phi ] * [delta] = [T_delta] * */ void SimpleBicycle::update_state(real_t steer_angle_measurement) { real_t next_roll = -m_K(0, 1)/m_K(0, 0) * steer_angle_measurement; m_x[state_index_t::steer_rate] = (steer_angle_measurement - m_x[state_index_t::steer_angle])/m_dt; m_x[state_index_t::roll_rate] = (next_roll - m_x[state_index_t::roll_angle])/m_dt; m_x[state_index_t::steer_angle] = steer_angle_measurement; m_x[state_index_t::roll_angle] = next_roll; } void SimpleBicycle::update_feedback_torque() { m_T_m = -(m_K(1, 1) - m_K(0, 1)*m_K(1, 0)/m_K(0, 0))*m_x[state_index_t::steer_angle]; } SimpleBicycle::auxiliary_state_t SimpleBicycle::integrate_auxiliary_state(const state_t& x, const auxiliary_state_t& x_aux) { auxiliary_state_t x_out = x_aux; real_t yaw_rate = (m_v*x[state_index_t::steer_angle]+ m_c*x[state_index_t::steer_rate])/m_w*cos(m_lambda); real_t v = m_v; m_auxiliary_stepper.do_step([v, yaw_rate]( const auxiliary_state_t& x, auxiliary_state_t& dxdt, const real_t t) -> void { (void)t; dxdt[auxiliary_state_index_t::x] = v*std::cos(x[auxiliary_state_index_t::yaw_angle]); // xdot = v*cos(psi) dxdt[auxiliary_state_index_t::y] = v*std::sin(x[auxiliary_state_index_t::yaw_angle]); // ydot = v*sin(psi) dxdt[auxiliary_state_index_t::pitch_angle] = 0.0; // pitch is calculated separately dxdt[auxiliary_state_index_t::yaw_angle] = yaw_rate; // yawdot = (v*delta + c*deltadot)/w*cos(lambda) }, x_out, 0.0, m_dt); return x_out; } real_t SimpleBicycle::solve_constraint_pitch(const state_t& x, real_t guess) const { // constraint function generated by script 'generate_pitch.py'. static constexpr int digits = std::numeric_limits<real_t>::digits*2/3; static constexpr real_t two = static_cast<real_t>(2.0); static constexpr real_t one_point_five = static_cast<real_t>(1.5); static const real_t min = -constants::pi/2; static const real_t max = constants::pi/2; auto constraint_function = [this, x](real_t pitch)->boost::math::tuple<real_t, real_t> { return boost::math::make_tuple( ((m_rf*std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two) + (m_d3*std::sqrt(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two)) + m_rf*(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1])))*(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1])))*std::sqrt(std::pow(std::cos(x[0]), two)) + std::sqrt(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two))*(-m_d1*std::sqrt(std::pow(std::cos(x[0]), two))*std::sin(pitch) + m_d2*std::sqrt(std::pow(std::cos(x[0]), two))*std::cos(pitch) - m_rr*std::cos(x[0]))*std::cos(x[0]))/(std::sqrt(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two))*std::sqrt(std::pow(std::cos(x[0]), two))) , ((m_rf*std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two) + (m_d3*std::sqrt(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two)) + m_rf*(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1])))*(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1])))*std::sqrt(std::pow(std::cos(x[0]), two)) + std::sqrt(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two))*(-m_d1*std::sqrt(std::pow(std::cos(x[0]), two))*std::sin(pitch) + m_d2*std::sqrt(std::pow(std::cos(x[0]), two))*std::cos(pitch) - m_rr*std::cos(x[0]))*std::cos(x[0]))*((-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]))*std::cos(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(pitch)*std::cos(pitch)*std::pow(std::cos(x[0]), two))/(std::pow(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two), one_point_five)*std::sqrt(std::pow(std::cos(x[0]), two))) + ((-m_d1*std::sqrt(std::pow(std::cos(x[0]), two))*std::cos(pitch) - m_d2*std::sqrt(std::pow(std::cos(x[0]), two))*std::sin(pitch))*std::sqrt(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two))*std::cos(x[0]) + (-(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]))*std::cos(pitch)*std::cos(x[0])*std::cos(x[1]) - std::sin(pitch)*std::cos(pitch)*std::pow(std::cos(x[0]), two))*(-m_d1*std::sqrt(std::pow(std::cos(x[0]), two))*std::sin(pitch) + m_d2*std::sqrt(std::pow(std::cos(x[0]), two))*std::cos(pitch) - m_rr*std::cos(x[0]))*std::cos(x[0])/std::sqrt(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two)) + (-2*m_rf*std::sin(pitch)*std::cos(pitch)*std::pow(std::cos(x[0]), two) - (m_d3*std::sqrt(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two)) + m_rf*(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1])))*std::cos(pitch)*std::cos(x[0])*std::cos(x[1]) + (m_d3*(-(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]))*std::cos(pitch)*std::cos(x[0])*std::cos(x[1]) - std::sin(pitch)*std::cos(pitch)*std::pow(std::cos(x[0]), two))/std::sqrt(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two)) - m_rf*std::cos(pitch)*std::cos(x[0])*std::cos(x[1]))*(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1])))*std::sqrt(std::pow(std::cos(x[0]), two)))/(std::sqrt(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two))*std::sqrt(std::pow(std::cos(x[0]), two))) ); }; return boost::math::tools::newton_raphson_iterate(constraint_function, guess, min, max, digits); } } // namespace model <commit_msg>Set pitch angle minimum to 0.0 rad<commit_after>#include "simplebicycle.h" #include <boost/math/tools/tuple.hpp> #include <boost/math/tools/roots.hpp> #include "constants.h" #include "parameters.h" namespace model { SimpleBicycle::SimpleBicycle(real_t v, real_t dt) : m_M(parameters::benchmark::M), m_C1(parameters::benchmark::C1), m_K0(parameters::benchmark::K0), m_K2(parameters::benchmark::K2), m_pose(BicyclePoseMessage_init_zero), m_v(0.0), m_dt(dt), m_T_m(0.0), m_w(parameters::benchmark::wheelbase), m_c(parameters::benchmark::trail), m_lambda(parameters::benchmark::steer_axis_tilt), m_rr(parameters::benchmark::rear_wheel_radius), m_rf(parameters::benchmark::front_wheel_radius) { set_moore_parameters(); set_v(v); reset_pose(); } void SimpleBicycle::set_v(real_t v) { m_v = v; m_C = v*m_C1; m_K = constants::g*m_K0 + v*v*m_K2; } void SimpleBicycle::set_dt(real_t dt) { m_dt = dt; } void SimpleBicycle::reset_pose() { m_x.setZero(); m_x_aux.setZero(); m_T_m = 0.0; m_pose = BicyclePoseMessage{}; /* reset pose to zero */ m_x_aux[auxiliary_state_index_t::pitch_angle] = solve_constraint_pitch(m_x, m_x_aux[auxiliary_state_index_t::pitch_angle]); m_pose.pitch = m_x_aux[auxiliary_state_index_t::pitch_angle]; } void SimpleBicycle::update(real_t roll_torque_input, real_t steer_torque_input, real_t yaw_angle_measurement, real_t steer_angle_measurement, real_t rear_wheel_angle_measurement) { (void)roll_torque_input; (void)steer_torque_input; (void)yaw_angle_measurement; update_state(steer_angle_measurement); m_x_aux = integrate_auxiliary_state(m_x, m_x_aux); m_x_aux[auxiliary_state_index_t::pitch_angle] = solve_constraint_pitch(m_x, m_x_aux[auxiliary_state_index_t::pitch_angle]); update_feedback_torque(); set_pose(); /* * The rear wheel angle is set outside of the 'set_pose' function because it has no * direct influence on the dynamics. The velocity is obtained from a numerical * derivative of the position signal (model-less) */ m_pose.rear_wheel = rear_wheel_angle_measurement; } void SimpleBicycle::set_moore_parameters() { m_d1 = std::cos(m_lambda)*(m_c + m_w - m_rr*std::tan(m_lambda)); m_d3 = -std::cos(m_lambda)*(m_c - m_rf*std::tan(m_lambda)); m_d2 = (m_rr + m_d1*std::sin(m_lambda) - m_rf + m_d3*std::sin(m_lambda)) / std::cos(m_lambda); } void SimpleBicycle::set_pose() { m_pose.timestamp += static_cast<decltype(m_pose.timestamp)>(m_dt * 1000); /* timestamp in milliseconds */ m_pose.x = m_x_aux[auxiliary_state_index_t::x]; m_pose.y = m_x_aux[auxiliary_state_index_t::y]; m_pose.pitch = m_x_aux[auxiliary_state_index_t::pitch_angle]; m_pose.yaw = m_x_aux[auxiliary_state_index_t::yaw_angle]; m_pose.roll = m_x[state_index_t::roll_angle]; m_pose.steer = m_x[state_index_t::steer_angle]; } /* * Simplified equations of motion are used to simulate the bicycle dynamics. * Roll/steer rate and acceleration terms are ignored resulting in: * (g*K0 + v^2*K2) [phi ] = [T_phi ] * [delta] = [T_delta] * */ void SimpleBicycle::update_state(real_t steer_angle_measurement) { real_t next_roll = -m_K(0, 1)/m_K(0, 0) * steer_angle_measurement; m_x[state_index_t::steer_rate] = (steer_angle_measurement - m_x[state_index_t::steer_angle])/m_dt; m_x[state_index_t::roll_rate] = (next_roll - m_x[state_index_t::roll_angle])/m_dt; m_x[state_index_t::steer_angle] = steer_angle_measurement; m_x[state_index_t::roll_angle] = next_roll; } void SimpleBicycle::update_feedback_torque() { m_T_m = -(m_K(1, 1) - m_K(0, 1)*m_K(1, 0)/m_K(0, 0))*m_x[state_index_t::steer_angle]; } SimpleBicycle::auxiliary_state_t SimpleBicycle::integrate_auxiliary_state(const state_t& x, const auxiliary_state_t& x_aux) { auxiliary_state_t x_out = x_aux; real_t yaw_rate = (m_v*x[state_index_t::steer_angle]+ m_c*x[state_index_t::steer_rate])/m_w*cos(m_lambda); real_t v = m_v; m_auxiliary_stepper.do_step([v, yaw_rate]( const auxiliary_state_t& x, auxiliary_state_t& dxdt, const real_t t) -> void { (void)t; dxdt[auxiliary_state_index_t::x] = v*std::cos(x[auxiliary_state_index_t::yaw_angle]); // xdot = v*cos(psi) dxdt[auxiliary_state_index_t::y] = v*std::sin(x[auxiliary_state_index_t::yaw_angle]); // ydot = v*sin(psi) dxdt[auxiliary_state_index_t::pitch_angle] = 0.0; // pitch is calculated separately dxdt[auxiliary_state_index_t::yaw_angle] = yaw_rate; // yawdot = (v*delta + c*deltadot)/w*cos(lambda) }, x_out, 0.0, m_dt); return x_out; } real_t SimpleBicycle::solve_constraint_pitch(const state_t& x, real_t guess) const { // constraint function generated by script 'generate_pitch.py'. static constexpr int digits = std::numeric_limits<real_t>::digits*2/3; static constexpr real_t two = static_cast<real_t>(2.0); static constexpr real_t one_point_five = static_cast<real_t>(1.5); static const real_t min = static_cast<real_t>(0.0); static const real_t max = constants::pi/2; auto constraint_function = [this, x](real_t pitch)->boost::math::tuple<real_t, real_t> { return boost::math::make_tuple( ((m_rf*std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two) + (m_d3*std::sqrt(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two)) + m_rf*(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1])))*(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1])))*std::sqrt(std::pow(std::cos(x[0]), two)) + std::sqrt(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two))*(-m_d1*std::sqrt(std::pow(std::cos(x[0]), two))*std::sin(pitch) + m_d2*std::sqrt(std::pow(std::cos(x[0]), two))*std::cos(pitch) - m_rr*std::cos(x[0]))*std::cos(x[0]))/(std::sqrt(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two))*std::sqrt(std::pow(std::cos(x[0]), two))) , ((m_rf*std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two) + (m_d3*std::sqrt(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two)) + m_rf*(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1])))*(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1])))*std::sqrt(std::pow(std::cos(x[0]), two)) + std::sqrt(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two))*(-m_d1*std::sqrt(std::pow(std::cos(x[0]), two))*std::sin(pitch) + m_d2*std::sqrt(std::pow(std::cos(x[0]), two))*std::cos(pitch) - m_rr*std::cos(x[0]))*std::cos(x[0]))*((-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]))*std::cos(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(pitch)*std::cos(pitch)*std::pow(std::cos(x[0]), two))/(std::pow(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two), one_point_five)*std::sqrt(std::pow(std::cos(x[0]), two))) + ((-m_d1*std::sqrt(std::pow(std::cos(x[0]), two))*std::cos(pitch) - m_d2*std::sqrt(std::pow(std::cos(x[0]), two))*std::sin(pitch))*std::sqrt(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two))*std::cos(x[0]) + (-(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]))*std::cos(pitch)*std::cos(x[0])*std::cos(x[1]) - std::sin(pitch)*std::cos(pitch)*std::pow(std::cos(x[0]), two))*(-m_d1*std::sqrt(std::pow(std::cos(x[0]), two))*std::sin(pitch) + m_d2*std::sqrt(std::pow(std::cos(x[0]), two))*std::cos(pitch) - m_rr*std::cos(x[0]))*std::cos(x[0])/std::sqrt(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two)) + (-2*m_rf*std::sin(pitch)*std::cos(pitch)*std::pow(std::cos(x[0]), two) - (m_d3*std::sqrt(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two)) + m_rf*(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1])))*std::cos(pitch)*std::cos(x[0])*std::cos(x[1]) + (m_d3*(-(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]))*std::cos(pitch)*std::cos(x[0])*std::cos(x[1]) - std::sin(pitch)*std::cos(pitch)*std::pow(std::cos(x[0]), two))/std::sqrt(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two)) - m_rf*std::cos(pitch)*std::cos(x[0])*std::cos(x[1]))*(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1])))*std::sqrt(std::pow(std::cos(x[0]), two)))/(std::sqrt(std::pow(-std::sin(pitch)*std::cos(x[0])*std::cos(x[1]) + std::sin(x[0])*std::sin(x[1]), two) + std::pow(std::cos(pitch), two)*std::pow(std::cos(x[0]), two))*std::sqrt(std::pow(std::cos(x[0]), two))) ); }; return boost::math::tools::newton_raphson_iterate(constraint_function, guess, min, max, digits); } } // namespace model <|endoftext|>
<commit_before>/** @file Implementation of Parent Proxy routing @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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 "ParentConsistentHash.h" ParentConsistentHash::ParentConsistentHash(ParentRecord *parent_record) { int i; ink_assert(parent_record->num_parents > 0); parents[PRIMARY] = parent_record->parents; parents[SECONDARY] = parent_record->secondary_parents; ignore_query = parent_record->ignore_query; ink_zero(foundParents); chash[PRIMARY] = new ATSConsistentHash(); for (i = 0; i < parent_record->num_parents; i++) { chash[PRIMARY]->insert(&(parent_record->parents[i]), parent_record->parents[i].weight, (ATSHash64 *)&hash[PRIMARY]); } if (parent_record->num_secondary_parents > 0) { Debug("parent_select", "ParentConsistentHash(): initializing the secondary parents hash."); chash[SECONDARY] = new ATSConsistentHash(); for (i = 0; i < parent_record->num_secondary_parents; i++) { chash[SECONDARY]->insert(&(parent_record->secondary_parents[i]), parent_record->secondary_parents[i].weight, (ATSHash64 *)&hash[SECONDARY]); } } else { chash[SECONDARY] = NULL; } Debug("parent_select", "Using a consistent hash parent selection strategy."); } ParentConsistentHash::~ParentConsistentHash() { delete chash[PRIMARY]; delete chash[SECONDARY]; } uint64_t ParentConsistentHash::getPathHash(HttpRequestData *hrdata, ATSHash64 *h) { const char *tmp = NULL; int len; URL *url = hrdata->hdr->url_get(); // Always hash on '/' because paths returned by ATS are always stripped of it h->update("/", 1); tmp = url->path_get(&len); if (tmp) { h->update(tmp, len); } if (!ignore_query) { tmp = url->query_get(&len); if (tmp) { h->update("?", 1); h->update(tmp, len); } } h->final(); return h->get(); } void ParentConsistentHash::selectParent(const ParentSelectionPolicy *policy, bool first_call, ParentResult *result, RequestData *rdata) { ATSHash64Sip24 hash; ATSConsistentHash *fhash; HttpRequestData *request_info = static_cast<HttpRequestData *>(rdata); bool firstCall = first_call; bool parentRetry = false; bool wrap_around[2] = {false, false}; uint64_t path_hash = 0; uint32_t last_lookup; pRecord *prtmp = NULL, *pRec = NULL; Debug("parent_select", "ParentConsistentHash::%s(): Using a consistent hash parent selection strategy.", __func__); ink_assert(numParents(result) > 0 || result->rec->go_direct == true); // Should only get into this state if we are supposed to go direct. if (parents[PRIMARY] == NULL && parents[SECONDARY] == NULL) { if (result->rec->go_direct == true && result->rec->parent_is_proxy == true) { result->result = PARENT_DIRECT; } else { result->result = PARENT_FAIL; } result->hostname = NULL; result->port = 0; return; } // findParent() call if firstCall. if (firstCall) { last_lookup = PRIMARY; path_hash = getPathHash(request_info, (ATSHash64 *)&hash); fhash = chash[PRIMARY]; if (path_hash) { prtmp = (pRecord *)fhash->lookup_by_hashval(path_hash, &result->chashIter[last_lookup], &wrap_around[last_lookup]); if (prtmp) { pRec = (parents[last_lookup] + prtmp->idx); } } // else called by nextParent(). } else { if (chash[SECONDARY] != NULL) { last_lookup = SECONDARY; fhash = chash[SECONDARY]; path_hash = getPathHash(request_info, (ATSHash64 *)&hash); prtmp = (pRecord *)fhash->lookup_by_hashval(path_hash, &result->chashIter[last_lookup], &wrap_around[last_lookup]); if (prtmp) { pRec = (parents[last_lookup] + prtmp->idx); } } else { last_lookup = PRIMARY; fhash = chash[PRIMARY]; do { // search until we've selected a different parent. prtmp = (pRecord *)fhash->lookup(NULL, &result->chashIter[last_lookup], &wrap_around[last_lookup], &hash); if (prtmp) { pRec = (parents[last_lookup] + prtmp->idx); } } while (prtmp && strcmp(prtmp->hostname, result->hostname) == 0); } } // didn't find a parent or the parent is marked unavailable. if (!pRec || (pRec && !pRec->available)) { do { if (pRec && !pRec->available) { Debug("parent_select", "Parent.failedAt = %u, retry = %u, xact_start = %u", (unsigned int)pRec->failedAt, (unsigned int)policy->ParentRetryTime, (unsigned int)request_info->xact_start); if ((pRec->failedAt + policy->ParentRetryTime) < request_info->xact_start) { parentRetry = true; // make sure that the proper state is recorded in the result structure result->last_parent = pRec->idx; result->last_lookup = last_lookup; result->retry = parentRetry; result->result = PARENT_SPECIFIED; Debug("parent_select", "Down parent %s is now retryable, marked it available.", pRec->hostname); break; } } Debug("parent_select", "wrap_around[PRIMARY]: %d, wrap_around[SECONDARY]: %d", wrap_around[PRIMARY], wrap_around[SECONDARY]); if (!wrap_around[PRIMARY] || (chash[SECONDARY] != NULL)) { Debug("parent_select", "Selected parent %s is not available, looking up another parent.", pRec ? pRec->hostname:"[NULL]"); if (chash[SECONDARY] != NULL && !wrap_around[SECONDARY]) { fhash = chash[SECONDARY]; last_lookup = SECONDARY; } else { fhash = chash[PRIMARY]; last_lookup = PRIMARY; } if (firstCall) { prtmp = (pRecord *)fhash->lookup_by_hashval(path_hash, &result->chashIter[last_lookup], &wrap_around[last_lookup]); firstCall = false; } else { prtmp = (pRecord *)fhash->lookup(NULL, &result->chashIter[last_lookup], &wrap_around[last_lookup], &hash); } if (prtmp) { pRec = (parents[last_lookup] + prtmp->idx); Debug("parent_select", "Selected a new parent: %s.", pRec->hostname); } } if (wrap_around[PRIMARY] && chash[SECONDARY] == NULL) { Debug("parent_select", "No available parents."); break; } if (wrap_around[PRIMARY] && chash[SECONDARY] != NULL && wrap_around[SECONDARY]) { Debug("parent_select", "No available parents."); break; } } while (!prtmp || !pRec->available); } // use the available or marked for retry parent. if (pRec && (pRec->available || result->retry)) { result->result = PARENT_SPECIFIED; result->hostname = pRec->hostname; result->port = pRec->port; result->last_parent = pRec->idx; result->last_lookup = last_lookup; result->retry = parentRetry; ink_assert(result->hostname != NULL); ink_assert(result->port != 0); Debug("parent_select", "Chosen parent: %s.%d", result->hostname, result->port); } else { if (result->rec->go_direct == true && result->rec->parent_is_proxy == true) { result->result = PARENT_DIRECT; } else { result->result = PARENT_FAIL; } result->hostname = NULL; result->port = 0; result->retry = false; } return; } void ParentConsistentHash::markParentDown(const ParentSelectionPolicy *policy, ParentResult *result) { time_t now; pRecord *pRec; int new_fail_count = 0; Debug("parent_select", "Starting ParentConsistentHash::markParentDown()"); // Make sure that we are being called back with with a // result structure with a parent ink_assert(result->result == PARENT_SPECIFIED); if (result->result != PARENT_SPECIFIED) { return; } // If we were set through the API we currently have not failover // so just return fail if (result->is_api_result()) { return; } ink_assert((result->last_parent) < numParents(result)); pRec = parents[result->last_lookup] + result->last_parent; // If the parent has already been marked down, just increment // the failure count. If this is the first mark down on a // parent we need to both set the failure time and set // count to one. It's possible for the count and time get out // sync due there being no locks. Therefore the code should // handle this condition. If this was the result of a retry, we // must update move the failedAt timestamp to now so that we continue // negative cache the parent if (pRec->failedAt == 0 || result->retry == true) { // Reread the current time. We want this to be accurate since // it relates to how long the parent has been down. now = time(NULL); // Mark the parent as down ink_atomic_swap(&pRec->failedAt, now); // If this is clean mark down and not a failed retry, we // must set the count to reflect this if (result->retry == false) { new_fail_count = pRec->failCount = 1; } Note("Parent %s marked as down %s:%d", (result->retry) ? "retry" : "initially", pRec->hostname, pRec->port); } else { int old_count = ink_atomic_increment(&pRec->failCount, 1); Debug("parent_select", "Parent fail count increased to %d for %s:%d", old_count + 1, pRec->hostname, pRec->port); new_fail_count = old_count + 1; } if (new_fail_count > 0 && new_fail_count >= policy->FailThreshold) { Note("Failure threshold met, http parent proxy %s:%d marked down", pRec->hostname, pRec->port); ink_atomic_swap(&pRec->available, false); Debug("parent_select", "Parent %s:%d marked unavailable, pRec->available=%d", pRec->hostname, pRec->port, pRec->available); } } uint32_t ParentConsistentHash::numParents(ParentResult *result) const { uint32_t n = 0; switch (result->last_lookup) { case PRIMARY: n = result->rec->num_parents; break; case SECONDARY: n = result->rec->num_secondary_parents; break; } return n; } void ParentConsistentHash::markParentUp(ParentResult *result) { pRecord *pRec; // Make sure that we are being called back with with a // result structure with a parent that is being retried ink_release_assert(result->retry == true); ink_assert(result->result == PARENT_SPECIFIED); if (result->result != PARENT_SPECIFIED) { return; } // If we were set through the API we currently have not failover // so just return fail if (result->is_api_result()) { ink_assert(0); return; } ink_assert((result->last_parent) < numParents(result)); pRec = parents[result->last_lookup] + result->last_parent; ink_atomic_swap(&pRec->available, true); Debug("parent_select", "%s:%s(): marked %s:%d available.", __FILE__, __func__, pRec->hostname, pRec->port); ink_atomic_swap(&pRec->failedAt, (time_t)0); int old_count = ink_atomic_swap(&pRec->failCount, 0); if (old_count > 0) { Note("http parent proxy %s:%d restored", pRec->hostname, pRec->port); } } <commit_msg>TS-4743: clang-format<commit_after>/** @file Implementation of Parent Proxy routing @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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 "ParentConsistentHash.h" ParentConsistentHash::ParentConsistentHash(ParentRecord *parent_record) { int i; ink_assert(parent_record->num_parents > 0); parents[PRIMARY] = parent_record->parents; parents[SECONDARY] = parent_record->secondary_parents; ignore_query = parent_record->ignore_query; ink_zero(foundParents); chash[PRIMARY] = new ATSConsistentHash(); for (i = 0; i < parent_record->num_parents; i++) { chash[PRIMARY]->insert(&(parent_record->parents[i]), parent_record->parents[i].weight, (ATSHash64 *)&hash[PRIMARY]); } if (parent_record->num_secondary_parents > 0) { Debug("parent_select", "ParentConsistentHash(): initializing the secondary parents hash."); chash[SECONDARY] = new ATSConsistentHash(); for (i = 0; i < parent_record->num_secondary_parents; i++) { chash[SECONDARY]->insert(&(parent_record->secondary_parents[i]), parent_record->secondary_parents[i].weight, (ATSHash64 *)&hash[SECONDARY]); } } else { chash[SECONDARY] = NULL; } Debug("parent_select", "Using a consistent hash parent selection strategy."); } ParentConsistentHash::~ParentConsistentHash() { delete chash[PRIMARY]; delete chash[SECONDARY]; } uint64_t ParentConsistentHash::getPathHash(HttpRequestData *hrdata, ATSHash64 *h) { const char *tmp = NULL; int len; URL *url = hrdata->hdr->url_get(); // Always hash on '/' because paths returned by ATS are always stripped of it h->update("/", 1); tmp = url->path_get(&len); if (tmp) { h->update(tmp, len); } if (!ignore_query) { tmp = url->query_get(&len); if (tmp) { h->update("?", 1); h->update(tmp, len); } } h->final(); return h->get(); } void ParentConsistentHash::selectParent(const ParentSelectionPolicy *policy, bool first_call, ParentResult *result, RequestData *rdata) { ATSHash64Sip24 hash; ATSConsistentHash *fhash; HttpRequestData *request_info = static_cast<HttpRequestData *>(rdata); bool firstCall = first_call; bool parentRetry = false; bool wrap_around[2] = {false, false}; uint64_t path_hash = 0; uint32_t last_lookup; pRecord *prtmp = NULL, *pRec = NULL; Debug("parent_select", "ParentConsistentHash::%s(): Using a consistent hash parent selection strategy.", __func__); ink_assert(numParents(result) > 0 || result->rec->go_direct == true); // Should only get into this state if we are supposed to go direct. if (parents[PRIMARY] == NULL && parents[SECONDARY] == NULL) { if (result->rec->go_direct == true && result->rec->parent_is_proxy == true) { result->result = PARENT_DIRECT; } else { result->result = PARENT_FAIL; } result->hostname = NULL; result->port = 0; return; } // findParent() call if firstCall. if (firstCall) { last_lookup = PRIMARY; path_hash = getPathHash(request_info, (ATSHash64 *)&hash); fhash = chash[PRIMARY]; if (path_hash) { prtmp = (pRecord *)fhash->lookup_by_hashval(path_hash, &result->chashIter[last_lookup], &wrap_around[last_lookup]); if (prtmp) { pRec = (parents[last_lookup] + prtmp->idx); } } // else called by nextParent(). } else { if (chash[SECONDARY] != NULL) { last_lookup = SECONDARY; fhash = chash[SECONDARY]; path_hash = getPathHash(request_info, (ATSHash64 *)&hash); prtmp = (pRecord *)fhash->lookup_by_hashval(path_hash, &result->chashIter[last_lookup], &wrap_around[last_lookup]); if (prtmp) { pRec = (parents[last_lookup] + prtmp->idx); } } else { last_lookup = PRIMARY; fhash = chash[PRIMARY]; do { // search until we've selected a different parent. prtmp = (pRecord *)fhash->lookup(NULL, &result->chashIter[last_lookup], &wrap_around[last_lookup], &hash); if (prtmp) { pRec = (parents[last_lookup] + prtmp->idx); } } while (prtmp && strcmp(prtmp->hostname, result->hostname) == 0); } } // didn't find a parent or the parent is marked unavailable. if (!pRec || (pRec && !pRec->available)) { do { if (pRec && !pRec->available) { Debug("parent_select", "Parent.failedAt = %u, retry = %u, xact_start = %u", (unsigned int)pRec->failedAt, (unsigned int)policy->ParentRetryTime, (unsigned int)request_info->xact_start); if ((pRec->failedAt + policy->ParentRetryTime) < request_info->xact_start) { parentRetry = true; // make sure that the proper state is recorded in the result structure result->last_parent = pRec->idx; result->last_lookup = last_lookup; result->retry = parentRetry; result->result = PARENT_SPECIFIED; Debug("parent_select", "Down parent %s is now retryable, marked it available.", pRec->hostname); break; } } Debug("parent_select", "wrap_around[PRIMARY]: %d, wrap_around[SECONDARY]: %d", wrap_around[PRIMARY], wrap_around[SECONDARY]); if (!wrap_around[PRIMARY] || (chash[SECONDARY] != NULL)) { Debug("parent_select", "Selected parent %s is not available, looking up another parent.", pRec ? pRec->hostname : "[NULL]"); if (chash[SECONDARY] != NULL && !wrap_around[SECONDARY]) { fhash = chash[SECONDARY]; last_lookup = SECONDARY; } else { fhash = chash[PRIMARY]; last_lookup = PRIMARY; } if (firstCall) { prtmp = (pRecord *)fhash->lookup_by_hashval(path_hash, &result->chashIter[last_lookup], &wrap_around[last_lookup]); firstCall = false; } else { prtmp = (pRecord *)fhash->lookup(NULL, &result->chashIter[last_lookup], &wrap_around[last_lookup], &hash); } if (prtmp) { pRec = (parents[last_lookup] + prtmp->idx); Debug("parent_select", "Selected a new parent: %s.", pRec->hostname); } } if (wrap_around[PRIMARY] && chash[SECONDARY] == NULL) { Debug("parent_select", "No available parents."); break; } if (wrap_around[PRIMARY] && chash[SECONDARY] != NULL && wrap_around[SECONDARY]) { Debug("parent_select", "No available parents."); break; } } while (!prtmp || !pRec->available); } // use the available or marked for retry parent. if (pRec && (pRec->available || result->retry)) { result->result = PARENT_SPECIFIED; result->hostname = pRec->hostname; result->port = pRec->port; result->last_parent = pRec->idx; result->last_lookup = last_lookup; result->retry = parentRetry; ink_assert(result->hostname != NULL); ink_assert(result->port != 0); Debug("parent_select", "Chosen parent: %s.%d", result->hostname, result->port); } else { if (result->rec->go_direct == true && result->rec->parent_is_proxy == true) { result->result = PARENT_DIRECT; } else { result->result = PARENT_FAIL; } result->hostname = NULL; result->port = 0; result->retry = false; } return; } void ParentConsistentHash::markParentDown(const ParentSelectionPolicy *policy, ParentResult *result) { time_t now; pRecord *pRec; int new_fail_count = 0; Debug("parent_select", "Starting ParentConsistentHash::markParentDown()"); // Make sure that we are being called back with with a // result structure with a parent ink_assert(result->result == PARENT_SPECIFIED); if (result->result != PARENT_SPECIFIED) { return; } // If we were set through the API we currently have not failover // so just return fail if (result->is_api_result()) { return; } ink_assert((result->last_parent) < numParents(result)); pRec = parents[result->last_lookup] + result->last_parent; // If the parent has already been marked down, just increment // the failure count. If this is the first mark down on a // parent we need to both set the failure time and set // count to one. It's possible for the count and time get out // sync due there being no locks. Therefore the code should // handle this condition. If this was the result of a retry, we // must update move the failedAt timestamp to now so that we continue // negative cache the parent if (pRec->failedAt == 0 || result->retry == true) { // Reread the current time. We want this to be accurate since // it relates to how long the parent has been down. now = time(NULL); // Mark the parent as down ink_atomic_swap(&pRec->failedAt, now); // If this is clean mark down and not a failed retry, we // must set the count to reflect this if (result->retry == false) { new_fail_count = pRec->failCount = 1; } Note("Parent %s marked as down %s:%d", (result->retry) ? "retry" : "initially", pRec->hostname, pRec->port); } else { int old_count = ink_atomic_increment(&pRec->failCount, 1); Debug("parent_select", "Parent fail count increased to %d for %s:%d", old_count + 1, pRec->hostname, pRec->port); new_fail_count = old_count + 1; } if (new_fail_count > 0 && new_fail_count >= policy->FailThreshold) { Note("Failure threshold met, http parent proxy %s:%d marked down", pRec->hostname, pRec->port); ink_atomic_swap(&pRec->available, false); Debug("parent_select", "Parent %s:%d marked unavailable, pRec->available=%d", pRec->hostname, pRec->port, pRec->available); } } uint32_t ParentConsistentHash::numParents(ParentResult *result) const { uint32_t n = 0; switch (result->last_lookup) { case PRIMARY: n = result->rec->num_parents; break; case SECONDARY: n = result->rec->num_secondary_parents; break; } return n; } void ParentConsistentHash::markParentUp(ParentResult *result) { pRecord *pRec; // Make sure that we are being called back with with a // result structure with a parent that is being retried ink_release_assert(result->retry == true); ink_assert(result->result == PARENT_SPECIFIED); if (result->result != PARENT_SPECIFIED) { return; } // If we were set through the API we currently have not failover // so just return fail if (result->is_api_result()) { ink_assert(0); return; } ink_assert((result->last_parent) < numParents(result)); pRec = parents[result->last_lookup] + result->last_parent; ink_atomic_swap(&pRec->available, true); Debug("parent_select", "%s:%s(): marked %s:%d available.", __FILE__, __func__, pRec->hostname, pRec->port); ink_atomic_swap(&pRec->failedAt, (time_t)0); int old_count = ink_atomic_swap(&pRec->failCount, 0); if (old_count > 0) { Note("http parent proxy %s:%d restored", pRec->hostname, pRec->port); } } <|endoftext|>
<commit_before>#include "perftest.h" #if TEST_RAPIDJSON #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/prettywriter.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/filestream.h" #include "rapidjson/filereadstream.h" #ifdef RAPIDJSON_SSE2 #define SIMD_SUFFIX(name) name##_SSE2 #elif defined(RAPIDJSON_SSE42) #define SIMD_SUFFIX(name) name##_SSE42 #else #define SIMD_SUFFIX(name) name #endif using namespace rapidjson; class RapidJson : public PerfTest { public: RapidJson() : temp_(), doc_() {} virtual void SetUp() { PerfTest::SetUp(); // temp buffer for insitu parsing. temp_ = (char *)malloc(length_ + 1); // Parse as a document EXPECT_FALSE(doc_.Parse(json_).IsNull()); } virtual void TearDown() { PerfTest::TearDown(); free(temp_); } private: RapidJson(const RapidJson&); RapidJson& operator=(const RapidJson&); protected: char *temp_; Document doc_; }; TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseInsitu_DummyHandler)) { for (size_t i = 0; i < kTrialCount; i++) { memcpy(temp_, json_, length_ + 1); InsituStringStream s(temp_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse<kParseInsituFlag>(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseInsitu_DummyHandler_ValidateEncoding)) { for (size_t i = 0; i < kTrialCount; i++) { memcpy(temp_, json_, length_ + 1); InsituStringStream s(temp_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse<kParseInsituFlag | kParseValidateEncodingFlag>(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler)) { for (size_t i = 0; i < kTrialCount; i++) { StringStream s(json_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler_ValidateEncoding)) { for (size_t i = 0; i < kTrialCount; i++) { StringStream s(json_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse<kParseValidateEncodingFlag>(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(DocumentParseInsitu_MemoryPoolAllocator)) { //const size_t userBufferSize = 128 * 1024; //char* userBuffer = (char*)malloc(userBufferSize); for (size_t i = 0; i < kTrialCount; i++) { memcpy(temp_, json_, length_ + 1); //MemoryPoolAllocator<> allocator(userBuffer, userBufferSize); //Document doc(&allocator); Document doc; doc.ParseInsitu(temp_); ASSERT_TRUE(doc.IsObject()); //if (i == 0) { // size_t size = doc.GetAllocator().Size(); // size_t capacity = doc.GetAllocator().Capacity(); // size_t stack_capacity = doc.GetStackCapacity(); // size_t actual = size - stack_capacity; // std::cout << "Size:" << size << " Capacity:" << capacity << " Stack:" << stack_capacity << " Actual:" << actual << std::endl; //} } //free(userBuffer); } TEST_F(RapidJson, SIMD_SUFFIX(DocumentParse_MemoryPoolAllocator)) { //const size_t userBufferSize = 128 * 1024; //char* userBuffer = (char*)malloc(userBufferSize); for (size_t i = 0; i < kTrialCount; i++) { //MemoryPoolAllocator<> allocator(userBuffer, userBufferSize); //Document doc(&allocator); Document doc; doc.Parse(json_); ASSERT_TRUE(doc.IsObject()); //if (i == 0) { // size_t size = doc.GetAllocator().Size(); // size_t capacity = doc.GetAllocator().Capacity(); // size_t stack_capacity = doc.GetStackCapacity(); // size_t actual = size - stack_capacity; // std::cout << "Size:" << size << " Capacity:" << capacity << " Stack:" << stack_capacity << " Actual:" << actual << std::endl; //} } //free(userBuffer); } TEST_F(RapidJson, SIMD_SUFFIX(DocumentParse_CrtAllocator)) { for (size_t i = 0; i < kTrialCount; i++) { memcpy(temp_, json_, length_ + 1); GenericDocument<UTF8<>, CrtAllocator> doc; doc.Parse(temp_); ASSERT_TRUE(doc.IsObject()); } } template<typename T> size_t Traverse(const T& value) { size_t count = 1; switch(value.GetType()) { case kObjectType: for (typename T::ConstMemberIterator itr = value.MemberBegin(); itr != value.MemberEnd(); ++itr) { count++; // name count += Traverse(itr->value); } break; case kArrayType: for (typename T::ConstValueIterator itr = value.Begin(); itr != value.End(); ++itr) count += Traverse(*itr); break; default: // Do nothing. break; } return count; } TEST_F(RapidJson, DocumentTraverse) { for (size_t i = 0; i < kTrialCount; i++) { size_t count = Traverse(doc_); EXPECT_EQ(4339u, count); //if (i == 0) // std::cout << count << std::endl; } } #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Weffc++" #endif struct ValueCounter : public BaseReaderHandler<> { ValueCounter() : count_(1) {} // root void EndObject(SizeType memberCount) { count_ += memberCount * 2; } void EndArray(SizeType elementCount) { count_ += elementCount; } SizeType count_; }; #ifdef __GNUC__ #pragma GCC diagnostic pop #endif TEST_F(RapidJson, DocumentAccept) { for (size_t i = 0; i < kTrialCount; i++) { ValueCounter counter; doc_.Accept(counter); EXPECT_EQ(4339u, counter.count_); } } struct NullStream { NullStream() /*: length_(0)*/ {} void Put(char) { /*++length_;*/ } void Flush() {} //size_t length_; }; TEST_F(RapidJson, Writer_NullStream) { for (size_t i = 0; i < kTrialCount; i++) { NullStream s; Writer<NullStream> writer(s); doc_.Accept(writer); //if (i == 0) // std::cout << s.length_ << std::endl; } } TEST_F(RapidJson, Writer_StringBuffer) { for (size_t i = 0; i < kTrialCount; i++) { StringBuffer s(0, 1024 * 1024); Writer<StringBuffer> writer(s); doc_.Accept(writer); const char* str = s.GetString(); (void)str; //if (i == 0) // std::cout << strlen(str) << std::endl; } } TEST_F(RapidJson, PrettyWriter_StringBuffer) { for (size_t i = 0; i < kTrialCount; i++) { StringBuffer s(0, 2048 * 1024); PrettyWriter<StringBuffer> writer(s); writer.SetIndent(' ', 1); doc_.Accept(writer); const char* str = s.GetString(); (void)str; //if (i == 0) // std::cout << strlen(str) << std::endl; } } TEST_F(RapidJson, internal_Pow10) { double sum = 0; for (size_t i = 0; i < kTrialCount * kTrialCount; i++) sum += internal::Pow10(i & 255); EXPECT_GT(sum, 0.0); } TEST_F(RapidJson, SIMD_SUFFIX(Whitespace)) { for (size_t i = 0; i < kTrialCount; i++) { Document doc; ASSERT_TRUE(doc.Parse(whitespace_).IsArray()); } } TEST_F(RapidJson, UTF8_Validate) { NullStream os; for (size_t i = 0; i < kTrialCount; i++) { StringStream is(json_); bool result = true; while (is.Peek() != '\0') result &= UTF8<>::Validate(is, os); EXPECT_TRUE(result); } } // Depreciated. //TEST_F(RapidJson, FileStream_Read) { // for (size_t i = 0; i < kTrialCount; i++) { // FILE *fp = fopen(filename_, "rb"); // FileStream s(fp); // while (s.Take() != '\0') // ; // fclose(fp); // } //} TEST_F(RapidJson, FileReadStream) { for (size_t i = 0; i < kTrialCount; i++) { FILE *fp = fopen(filename_, "rb"); char buffer[65536]; FileReadStream s(fp, buffer, sizeof(buffer)); while (s.Take() != '\0') ; fclose(fp); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler_FileReadStream)) { for (size_t i = 0; i < kTrialCount; i++) { FILE *fp = fopen(filename_, "rb"); char buffer[65536]; FileReadStream s(fp, buffer, sizeof(buffer)); BaseReaderHandler<> h; Reader reader; reader.Parse(s, h); fclose(fp); } } #endif // TEST_RAPIDJSON <commit_msg>Add two basic performance tests.<commit_after>#include "perftest.h" #if TEST_RAPIDJSON #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/prettywriter.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/filestream.h" #include "rapidjson/filereadstream.h" #ifdef RAPIDJSON_SSE2 #define SIMD_SUFFIX(name) name##_SSE2 #elif defined(RAPIDJSON_SSE42) #define SIMD_SUFFIX(name) name##_SSE42 #else #define SIMD_SUFFIX(name) name #endif using namespace rapidjson; class RapidJson : public PerfTest { public: RapidJson() : temp_(), doc_() {} virtual void SetUp() { PerfTest::SetUp(); // temp buffer for insitu parsing. temp_ = (char *)malloc(length_ + 1); // Parse as a document EXPECT_FALSE(doc_.Parse(json_).IsNull()); } virtual void TearDown() { PerfTest::TearDown(); free(temp_); } private: RapidJson(const RapidJson&); RapidJson& operator=(const RapidJson&); protected: char *temp_; Document doc_; }; TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseInsitu_DummyHandler)) { for (size_t i = 0; i < kTrialCount; i++) { memcpy(temp_, json_, length_ + 1); InsituStringStream s(temp_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse<kParseInsituFlag>(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseInsitu_DummyHandler_ValidateEncoding)) { for (size_t i = 0; i < kTrialCount; i++) { memcpy(temp_, json_, length_ + 1); InsituStringStream s(temp_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse<kParseInsituFlag | kParseValidateEncodingFlag>(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler)) { for (size_t i = 0; i < kTrialCount; i++) { StringStream s(json_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseIterative_DummyHandler)) { for (size_t i = 0; i < kTrialCount; i++) { StringStream s(json_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse<kParseIterativeFlag>(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseIterativeInsitu_DummyHandler)) { for (size_t i = 0; i < kTrialCount; i++) { StringStream s(json_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse<kParseIterativeFlag|kParseInsituFlag>(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler_ValidateEncoding)) { for (size_t i = 0; i < kTrialCount; i++) { StringStream s(json_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse<kParseValidateEncodingFlag>(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(DocumentParseInsitu_MemoryPoolAllocator)) { //const size_t userBufferSize = 128 * 1024; //char* userBuffer = (char*)malloc(userBufferSize); for (size_t i = 0; i < kTrialCount; i++) { memcpy(temp_, json_, length_ + 1); //MemoryPoolAllocator<> allocator(userBuffer, userBufferSize); //Document doc(&allocator); Document doc; doc.ParseInsitu(temp_); ASSERT_TRUE(doc.IsObject()); //if (i == 0) { // size_t size = doc.GetAllocator().Size(); // size_t capacity = doc.GetAllocator().Capacity(); // size_t stack_capacity = doc.GetStackCapacity(); // size_t actual = size - stack_capacity; // std::cout << "Size:" << size << " Capacity:" << capacity << " Stack:" << stack_capacity << " Actual:" << actual << std::endl; //} } //free(userBuffer); } TEST_F(RapidJson, SIMD_SUFFIX(DocumentParse_MemoryPoolAllocator)) { //const size_t userBufferSize = 128 * 1024; //char* userBuffer = (char*)malloc(userBufferSize); for (size_t i = 0; i < kTrialCount; i++) { //MemoryPoolAllocator<> allocator(userBuffer, userBufferSize); //Document doc(&allocator); Document doc; doc.Parse(json_); ASSERT_TRUE(doc.IsObject()); //if (i == 0) { // size_t size = doc.GetAllocator().Size(); // size_t capacity = doc.GetAllocator().Capacity(); // size_t stack_capacity = doc.GetStackCapacity(); // size_t actual = size - stack_capacity; // std::cout << "Size:" << size << " Capacity:" << capacity << " Stack:" << stack_capacity << " Actual:" << actual << std::endl; //} } //free(userBuffer); } TEST_F(RapidJson, SIMD_SUFFIX(DocumentParse_CrtAllocator)) { for (size_t i = 0; i < kTrialCount; i++) { memcpy(temp_, json_, length_ + 1); GenericDocument<UTF8<>, CrtAllocator> doc; doc.Parse(temp_); ASSERT_TRUE(doc.IsObject()); } } template<typename T> size_t Traverse(const T& value) { size_t count = 1; switch(value.GetType()) { case kObjectType: for (typename T::ConstMemberIterator itr = value.MemberBegin(); itr != value.MemberEnd(); ++itr) { count++; // name count += Traverse(itr->value); } break; case kArrayType: for (typename T::ConstValueIterator itr = value.Begin(); itr != value.End(); ++itr) count += Traverse(*itr); break; default: // Do nothing. break; } return count; } TEST_F(RapidJson, DocumentTraverse) { for (size_t i = 0; i < kTrialCount; i++) { size_t count = Traverse(doc_); EXPECT_EQ(4339u, count); //if (i == 0) // std::cout << count << std::endl; } } #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Weffc++" #endif struct ValueCounter : public BaseReaderHandler<> { ValueCounter() : count_(1) {} // root void EndObject(SizeType memberCount) { count_ += memberCount * 2; } void EndArray(SizeType elementCount) { count_ += elementCount; } SizeType count_; }; #ifdef __GNUC__ #pragma GCC diagnostic pop #endif TEST_F(RapidJson, DocumentAccept) { for (size_t i = 0; i < kTrialCount; i++) { ValueCounter counter; doc_.Accept(counter); EXPECT_EQ(4339u, counter.count_); } } struct NullStream { NullStream() /*: length_(0)*/ {} void Put(char) { /*++length_;*/ } void Flush() {} //size_t length_; }; TEST_F(RapidJson, Writer_NullStream) { for (size_t i = 0; i < kTrialCount; i++) { NullStream s; Writer<NullStream> writer(s); doc_.Accept(writer); //if (i == 0) // std::cout << s.length_ << std::endl; } } TEST_F(RapidJson, Writer_StringBuffer) { for (size_t i = 0; i < kTrialCount; i++) { StringBuffer s(0, 1024 * 1024); Writer<StringBuffer> writer(s); doc_.Accept(writer); const char* str = s.GetString(); (void)str; //if (i == 0) // std::cout << strlen(str) << std::endl; } } TEST_F(RapidJson, PrettyWriter_StringBuffer) { for (size_t i = 0; i < kTrialCount; i++) { StringBuffer s(0, 2048 * 1024); PrettyWriter<StringBuffer> writer(s); writer.SetIndent(' ', 1); doc_.Accept(writer); const char* str = s.GetString(); (void)str; //if (i == 0) // std::cout << strlen(str) << std::endl; } } TEST_F(RapidJson, internal_Pow10) { double sum = 0; for (size_t i = 0; i < kTrialCount * kTrialCount; i++) sum += internal::Pow10(i & 255); EXPECT_GT(sum, 0.0); } TEST_F(RapidJson, SIMD_SUFFIX(Whitespace)) { for (size_t i = 0; i < kTrialCount; i++) { Document doc; ASSERT_TRUE(doc.Parse(whitespace_).IsArray()); } } TEST_F(RapidJson, UTF8_Validate) { NullStream os; for (size_t i = 0; i < kTrialCount; i++) { StringStream is(json_); bool result = true; while (is.Peek() != '\0') result &= UTF8<>::Validate(is, os); EXPECT_TRUE(result); } } // Depreciated. //TEST_F(RapidJson, FileStream_Read) { // for (size_t i = 0; i < kTrialCount; i++) { // FILE *fp = fopen(filename_, "rb"); // FileStream s(fp); // while (s.Take() != '\0') // ; // fclose(fp); // } //} TEST_F(RapidJson, FileReadStream) { for (size_t i = 0; i < kTrialCount; i++) { FILE *fp = fopen(filename_, "rb"); char buffer[65536]; FileReadStream s(fp, buffer, sizeof(buffer)); while (s.Take() != '\0') ; fclose(fp); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler_FileReadStream)) { for (size_t i = 0; i < kTrialCount; i++) { FILE *fp = fopen(filename_, "rb"); char buffer[65536]; FileReadStream s(fp, buffer, sizeof(buffer)); BaseReaderHandler<> h; Reader reader; reader.Parse(s, h); fclose(fp); } } #endif // TEST_RAPIDJSON <|endoftext|>
<commit_before>#include "perftest.h" #if TEST_RAPIDJSON #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/prettywriter.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/filestream.h" #include "rapidjson/filereadstream.h" #ifdef RAPIDJSON_SSE2 #define SIMD_SUFFIX(name) name##_SSE2 #elif defined(RAPIDJSON_SSE42) #define SIMD_SUFFIX(name) name##_SSE42 #else #define SIMD_SUFFIX(name) name #endif using namespace rapidjson; class RapidJson : public PerfTest { public: RapidJson() : temp_(), doc_() {} virtual void SetUp() { PerfTest::SetUp(); // temp buffer for insitu parsing. temp_ = (char *)malloc(length_ + 1); // Parse as a document EXPECT_FALSE(doc_.Parse(json_).IsNull()); } virtual void TearDown() { PerfTest::TearDown(); free(temp_); } private: RapidJson(const RapidJson&); RapidJson& operator=(const RapidJson&); protected: char *temp_; Document doc_; }; TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseInsitu_DummyHandler)) { for (size_t i = 0; i < kTrialCount; i++) { memcpy(temp_, json_, length_ + 1); InsituStringStream s(temp_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse<kParseInsituFlag>(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseInsitu_DummyHandler_ValidateEncoding)) { for (size_t i = 0; i < kTrialCount; i++) { memcpy(temp_, json_, length_ + 1); InsituStringStream s(temp_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse<kParseInsituFlag | kParseValidateEncodingFlag>(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler)) { for (size_t i = 0; i < kTrialCount; i++) { StringStream s(json_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseIterative_DummyHandler)) { for (size_t i = 0; i < kTrialCount; i++) { StringStream s(json_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse<kParseIterativeFlag>(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseIterativeInsitu_DummyHandler)) { for (size_t i = 0; i < kTrialCount; i++) { StringStream s(json_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse<kParseIterativeFlag|kParseInsituFlag>(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler_ValidateEncoding)) { for (size_t i = 0; i < kTrialCount; i++) { StringStream s(json_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse<kParseValidateEncodingFlag>(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(DocumentParseInsitu_MemoryPoolAllocator)) { //const size_t userBufferSize = 128 * 1024; //char* userBuffer = (char*)malloc(userBufferSize); for (size_t i = 0; i < kTrialCount; i++) { memcpy(temp_, json_, length_ + 1); //MemoryPoolAllocator<> allocator(userBuffer, userBufferSize); //Document doc(&allocator); Document doc; doc.ParseInsitu(temp_); ASSERT_TRUE(doc.IsObject()); //if (i == 0) { // size_t size = doc.GetAllocator().Size(); // size_t capacity = doc.GetAllocator().Capacity(); // size_t stack_capacity = doc.GetStackCapacity(); // size_t actual = size - stack_capacity; // std::cout << "Size:" << size << " Capacity:" << capacity << " Stack:" << stack_capacity << " Actual:" << actual << std::endl; //} } //free(userBuffer); } TEST_F(RapidJson, SIMD_SUFFIX(DocumentParse_MemoryPoolAllocator)) { //const size_t userBufferSize = 128 * 1024; //char* userBuffer = (char*)malloc(userBufferSize); for (size_t i = 0; i < kTrialCount; i++) { //MemoryPoolAllocator<> allocator(userBuffer, userBufferSize); //Document doc(&allocator); Document doc; doc.Parse(json_); ASSERT_TRUE(doc.IsObject()); //if (i == 0) { // size_t size = doc.GetAllocator().Size(); // size_t capacity = doc.GetAllocator().Capacity(); // size_t stack_capacity = doc.GetStackCapacity(); // size_t actual = size - stack_capacity; // std::cout << "Size:" << size << " Capacity:" << capacity << " Stack:" << stack_capacity << " Actual:" << actual << std::endl; //} } //free(userBuffer); } TEST_F(RapidJson, SIMD_SUFFIX(DocumentParse_CrtAllocator)) { for (size_t i = 0; i < kTrialCount; i++) { memcpy(temp_, json_, length_ + 1); GenericDocument<UTF8<>, CrtAllocator> doc; doc.Parse(temp_); ASSERT_TRUE(doc.IsObject()); } } template<typename T> size_t Traverse(const T& value) { size_t count = 1; switch(value.GetType()) { case kObjectType: for (typename T::ConstMemberIterator itr = value.MemberBegin(); itr != value.MemberEnd(); ++itr) { count++; // name count += Traverse(itr->value); } break; case kArrayType: for (typename T::ConstValueIterator itr = value.Begin(); itr != value.End(); ++itr) count += Traverse(*itr); break; default: // Do nothing. break; } return count; } TEST_F(RapidJson, DocumentTraverse) { for (size_t i = 0; i < kTrialCount; i++) { size_t count = Traverse(doc_); EXPECT_EQ(4339u, count); //if (i == 0) // std::cout << count << std::endl; } } #ifdef __GNUC__ RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(effc++) #endif struct ValueCounter : public BaseReaderHandler<> { ValueCounter() : count_(1) {} // root bool EndObject(SizeType memberCount) { count_ += memberCount * 2; return true; } bool EndArray(SizeType elementCount) { count_ += elementCount; return true; } SizeType count_; }; #ifdef __GNUC__ RAPIDJSON_DIAG_POP #endif TEST_F(RapidJson, DocumentAccept) { for (size_t i = 0; i < kTrialCount; i++) { ValueCounter counter; doc_.Accept(counter); EXPECT_EQ(4339u, counter.count_); } } struct NullStream { NullStream() /*: length_(0)*/ {} void Put(char) { /*++length_;*/ } void Flush() {} //size_t length_; }; TEST_F(RapidJson, Writer_NullStream) { for (size_t i = 0; i < kTrialCount; i++) { NullStream s; Writer<NullStream> writer(s); doc_.Accept(writer); //if (i == 0) // std::cout << s.length_ << std::endl; } } TEST_F(RapidJson, Writer_StringBuffer) { for (size_t i = 0; i < kTrialCount; i++) { StringBuffer s(0, 1024 * 1024); Writer<StringBuffer> writer(s); doc_.Accept(writer); const char* str = s.GetString(); (void)str; //if (i == 0) // std::cout << strlen(str) << std::endl; } } TEST_F(RapidJson, PrettyWriter_StringBuffer) { for (size_t i = 0; i < kTrialCount; i++) { StringBuffer s(0, 2048 * 1024); PrettyWriter<StringBuffer> writer(s); writer.SetIndent(' ', 1); doc_.Accept(writer); const char* str = s.GetString(); (void)str; //if (i == 0) // std::cout << strlen(str) << std::endl; } } TEST_F(RapidJson, internal_Pow10) { double sum = 0; for (size_t i = 0; i < kTrialCount * kTrialCount; i++) sum += internal::Pow10(int(i & 255)); EXPECT_GT(sum, 0.0); } TEST_F(RapidJson, SIMD_SUFFIX(Whitespace)) { for (size_t i = 0; i < kTrialCount; i++) { Document doc; ASSERT_TRUE(doc.Parse(whitespace_).IsArray()); } } TEST_F(RapidJson, UTF8_Validate) { NullStream os; for (size_t i = 0; i < kTrialCount; i++) { StringStream is(json_); bool result = true; while (is.Peek() != '\0') result &= UTF8<>::Validate(is, os); EXPECT_TRUE(result); } } // Depreciated. //TEST_F(RapidJson, FileStream_Read) { // for (size_t i = 0; i < kTrialCount; i++) { // FILE *fp = fopen(filename_, "rb"); // FileStream s(fp); // while (s.Take() != '\0') // ; // fclose(fp); // } //} TEST_F(RapidJson, FileReadStream) { for (size_t i = 0; i < kTrialCount; i++) { FILE *fp = fopen(filename_, "rb"); char buffer[65536]; FileReadStream s(fp, buffer, sizeof(buffer)); while (s.Take() != '\0') ; fclose(fp); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler_FileReadStream)) { for (size_t i = 0; i < kTrialCount; i++) { FILE *fp = fopen(filename_, "rb"); char buffer[65536]; FileReadStream s(fp, buffer, sizeof(buffer)); BaseReaderHandler<> h; Reader reader; reader.Parse(s, h); fclose(fp); } } #endif // TEST_RAPIDJSON <commit_msg>Add perf test cases for document using iterative parsing<commit_after>#include "perftest.h" #if TEST_RAPIDJSON #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/prettywriter.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/filestream.h" #include "rapidjson/filereadstream.h" #ifdef RAPIDJSON_SSE2 #define SIMD_SUFFIX(name) name##_SSE2 #elif defined(RAPIDJSON_SSE42) #define SIMD_SUFFIX(name) name##_SSE42 #else #define SIMD_SUFFIX(name) name #endif using namespace rapidjson; class RapidJson : public PerfTest { public: RapidJson() : temp_(), doc_() {} virtual void SetUp() { PerfTest::SetUp(); // temp buffer for insitu parsing. temp_ = (char *)malloc(length_ + 1); // Parse as a document EXPECT_FALSE(doc_.Parse(json_).IsNull()); } virtual void TearDown() { PerfTest::TearDown(); free(temp_); } private: RapidJson(const RapidJson&); RapidJson& operator=(const RapidJson&); protected: char *temp_; Document doc_; }; TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseInsitu_DummyHandler)) { for (size_t i = 0; i < kTrialCount; i++) { memcpy(temp_, json_, length_ + 1); InsituStringStream s(temp_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse<kParseInsituFlag>(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseInsitu_DummyHandler_ValidateEncoding)) { for (size_t i = 0; i < kTrialCount; i++) { memcpy(temp_, json_, length_ + 1); InsituStringStream s(temp_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse<kParseInsituFlag | kParseValidateEncodingFlag>(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler)) { for (size_t i = 0; i < kTrialCount; i++) { StringStream s(json_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseIterative_DummyHandler)) { for (size_t i = 0; i < kTrialCount; i++) { StringStream s(json_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse<kParseIterativeFlag>(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseIterativeInsitu_DummyHandler)) { for (size_t i = 0; i < kTrialCount; i++) { StringStream s(json_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse<kParseIterativeFlag|kParseInsituFlag>(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler_ValidateEncoding)) { for (size_t i = 0; i < kTrialCount; i++) { StringStream s(json_); BaseReaderHandler<> h; Reader reader; EXPECT_TRUE(reader.Parse<kParseValidateEncodingFlag>(s, h)); } } TEST_F(RapidJson, SIMD_SUFFIX(DocumentParseInsitu_MemoryPoolAllocator)) { for (size_t i = 0; i < kTrialCount; i++) { memcpy(temp_, json_, length_ + 1); Document doc; doc.ParseInsitu(temp_); ASSERT_TRUE(doc.IsObject()); } } TEST_F(RapidJson, SIMD_SUFFIX(DocumentParseIterativeInsitu_MemoryPoolAllocator)) { for (size_t i = 0; i < kTrialCount; i++) { memcpy(temp_, json_, length_ + 1); Document doc; doc.ParseInsitu<kParseIterativeFlag>(temp_); ASSERT_TRUE(doc.IsObject()); } } TEST_F(RapidJson, SIMD_SUFFIX(DocumentParse_MemoryPoolAllocator)) { for (size_t i = 0; i < kTrialCount; i++) { Document doc; doc.Parse(json_); ASSERT_TRUE(doc.IsObject()); } } TEST_F(RapidJson, SIMD_SUFFIX(DocumentParseIterative_MemoryPoolAllocator)) { for (size_t i = 0; i < kTrialCount; i++) { Document doc; doc.Parse<kParseIterativeFlag>(json_); ASSERT_TRUE(doc.IsObject()); } } TEST_F(RapidJson, SIMD_SUFFIX(DocumentParse_CrtAllocator)) { for (size_t i = 0; i < kTrialCount; i++) { memcpy(temp_, json_, length_ + 1); GenericDocument<UTF8<>, CrtAllocator> doc; doc.Parse(temp_); ASSERT_TRUE(doc.IsObject()); } } template<typename T> size_t Traverse(const T& value) { size_t count = 1; switch(value.GetType()) { case kObjectType: for (typename T::ConstMemberIterator itr = value.MemberBegin(); itr != value.MemberEnd(); ++itr) { count++; // name count += Traverse(itr->value); } break; case kArrayType: for (typename T::ConstValueIterator itr = value.Begin(); itr != value.End(); ++itr) count += Traverse(*itr); break; default: // Do nothing. break; } return count; } TEST_F(RapidJson, DocumentTraverse) { for (size_t i = 0; i < kTrialCount; i++) { size_t count = Traverse(doc_); EXPECT_EQ(4339u, count); //if (i == 0) // std::cout << count << std::endl; } } #ifdef __GNUC__ RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(effc++) #endif struct ValueCounter : public BaseReaderHandler<> { ValueCounter() : count_(1) {} // root bool EndObject(SizeType memberCount) { count_ += memberCount * 2; return true; } bool EndArray(SizeType elementCount) { count_ += elementCount; return true; } SizeType count_; }; #ifdef __GNUC__ RAPIDJSON_DIAG_POP #endif TEST_F(RapidJson, DocumentAccept) { for (size_t i = 0; i < kTrialCount; i++) { ValueCounter counter; doc_.Accept(counter); EXPECT_EQ(4339u, counter.count_); } } struct NullStream { NullStream() /*: length_(0)*/ {} void Put(char) { /*++length_;*/ } void Flush() {} //size_t length_; }; TEST_F(RapidJson, Writer_NullStream) { for (size_t i = 0; i < kTrialCount; i++) { NullStream s; Writer<NullStream> writer(s); doc_.Accept(writer); //if (i == 0) // std::cout << s.length_ << std::endl; } } TEST_F(RapidJson, Writer_StringBuffer) { for (size_t i = 0; i < kTrialCount; i++) { StringBuffer s(0, 1024 * 1024); Writer<StringBuffer> writer(s); doc_.Accept(writer); const char* str = s.GetString(); (void)str; //if (i == 0) // std::cout << strlen(str) << std::endl; } } TEST_F(RapidJson, PrettyWriter_StringBuffer) { for (size_t i = 0; i < kTrialCount; i++) { StringBuffer s(0, 2048 * 1024); PrettyWriter<StringBuffer> writer(s); writer.SetIndent(' ', 1); doc_.Accept(writer); const char* str = s.GetString(); (void)str; //if (i == 0) // std::cout << strlen(str) << std::endl; } } TEST_F(RapidJson, internal_Pow10) { double sum = 0; for (size_t i = 0; i < kTrialCount * kTrialCount; i++) sum += internal::Pow10(int(i & 255)); EXPECT_GT(sum, 0.0); } TEST_F(RapidJson, SIMD_SUFFIX(Whitespace)) { for (size_t i = 0; i < kTrialCount; i++) { Document doc; ASSERT_TRUE(doc.Parse(whitespace_).IsArray()); } } TEST_F(RapidJson, UTF8_Validate) { NullStream os; for (size_t i = 0; i < kTrialCount; i++) { StringStream is(json_); bool result = true; while (is.Peek() != '\0') result &= UTF8<>::Validate(is, os); EXPECT_TRUE(result); } } // Depreciated. //TEST_F(RapidJson, FileStream_Read) { // for (size_t i = 0; i < kTrialCount; i++) { // FILE *fp = fopen(filename_, "rb"); // FileStream s(fp); // while (s.Take() != '\0') // ; // fclose(fp); // } //} TEST_F(RapidJson, FileReadStream) { for (size_t i = 0; i < kTrialCount; i++) { FILE *fp = fopen(filename_, "rb"); char buffer[65536]; FileReadStream s(fp, buffer, sizeof(buffer)); while (s.Take() != '\0') ; fclose(fp); } } TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler_FileReadStream)) { for (size_t i = 0; i < kTrialCount; i++) { FILE *fp = fopen(filename_, "rb"); char buffer[65536]; FileReadStream s(fp, buffer, sizeof(buffer)); BaseReaderHandler<> h; Reader reader; reader.Parse(s, h); fclose(fp); } } #endif // TEST_RAPIDJSON <|endoftext|>
<commit_before>// transcode.cpp // #include <iostream> #include <Utils/convert_adaptor.h> #include <Utils/utf8iso88591codecvt.h> #include <Utils/iso88591utf8codecvt.h> #include <Utils/rot13codecvt.h> #include <Utils/base64codecvt.h> #include <Utils/utf8ucs2codecvt.h> #include <Utils/utf16utf8codecvt.h> #include <Utils/utf16beucs2codecvt.h> #include <Utils/utf16leucs2codecvt.h> int main(int argc, const char* argv[]) { Arabica::convert::iconvert_adaptor<wchar_t, std::char_traits<wchar_t>, char, std::char_traits<char> > ia(std::cin); Arabica::convert::oconvert_adaptor<wchar_t, std::char_traits<wchar_t>, char, std::char_traits<char> > oa(std::cout); ia.imbue(std::locale(ia.getloc(), new Arabica::convert::utf8ucs2codecvt())); oa.imbue(std::locale(oa.getloc(), new Arabica::convert::utf16beucs2codecvt())); while(ia) { oa << static_cast<wchar_t>(ia.get()); oa.flush(); } // while return 0; } // main <commit_msg>*** empty log message ***<commit_after>// transcode.cpp // #include <iostream> #include <Utils/convert_adaptor.h> #include <Utils/utf8iso88591codecvt.h> #include <Utils/iso88591utf8codecvt.h> #include <Utils/rot13codecvt.h> #include <Utils/base64codecvt.h> #include <Utils/utf8ucs2codecvt.h> #include <Utils/utf16utf8codecvt.h> #include <Utils/utf16beucs2codecvt.h> #include <Utils/utf16leucs2codecvt.h> using namespace Arabica::convert; typedef iconvert_adaptor<wchar_t, std::char_traits<wchar_t>, char, std::char_traits<char> > Widener; typedef oconvert_adaptor<wchar_t, std::char_traits<wchar_t>, char, std::char_traits<char> > Narrower; iconvert_adaptor<char> iByteConvertor(std::cin); Widener iCharAdaptor(iByteConvertor); oconvert_adaptor<char> oByteConvertor(std::cout); Narrower oCharAdaptor(oByteConvertor); void imbueCodecvts(int argc, const char* argv[]); int main(int argc, const char* argv[]) { imbueCodecvts(argc, argv); int count = 0; wchar_t c = iCharAdaptor.get(); while(!iCharAdaptor.eof()) { oCharAdaptor << c; if(count == 1024) { oCharAdaptor.flush(); oByteConvertor.flush(); count = 0; } // if ... c = iCharAdaptor.get(); } oCharAdaptor.flush(); oByteConvertor.flush(); return 0; } // main void imbueCodecvts(int argc, const char* argv[]) { oCharAdaptor.imbue(std::locale(oCharAdaptor.getloc(), new utf16beucs2codecvt())); for(int i = 1; i < argc; ++i) { std::string io(argv[i]); bool input = true; if(io == "-i" || io == "--input") input = true; else if(io == "-o" || io == "--output") input = false; else { std::cerr << argv[0] << " [(-i|--input) input-encoding] [(-o|--output) output-encoding] " << std::endl; std::exit(0); } // ++i; if(i >= argc) { std::cerr << argv[0] << " [(-i|--input) input-encoding] [(-o|--output) output-encoding] " << std::endl; std::exit(0); } // std::string cvt(argv[i]); if(cvt == "rot13") { if(input) iByteConvertor.imbue(std::locale(iByteConvertor.getloc(), new rot13codecvt())); else oByteConvertor.imbue(std::locale(oByteConvertor.getloc(), new rot13codecvt())); } if(cvt == "base64") { if(input) iByteConvertor.imbue(std::locale(iByteConvertor.getloc(), new base64codecvt())); else oByteConvertor.imbue(std::locale(oByteConvertor.getloc(), new base64codecvt())); } if(cvt == "utf8") { if(input) iCharAdaptor.imbue(std::locale(iCharAdaptor.getloc(), new utf8ucs2codecvt())); else oCharAdaptor.imbue(std::locale(oCharAdaptor.getloc(), new utf8ucs2codecvt())); } if(cvt == "utf16be") { if(input) iCharAdaptor.imbue(std::locale(iCharAdaptor.getloc(), new utf16beucs2codecvt())); else oCharAdaptor.imbue(std::locale(oCharAdaptor.getloc(), new utf16beucs2codecvt())); } if(cvt == "utf16le") { if(input) iCharAdaptor.imbue(std::locale(iCharAdaptor.getloc(), new utf16leucs2codecvt())); else oCharAdaptor.imbue(std::locale(oCharAdaptor.getloc(), new utf16leucs2codecvt())); } } // for ... } // imbueCodeCvts <|endoftext|>
<commit_before>/*! * \page bomsforforecaster_cpp Command-Line Test to Demonstrate How To Test the RMOL Project * \code */ // ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <cassert> #include <limits> #include <sstream> #include <fstream> #include <string> // Boost Unit Test Framework (UTF) #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE OptimiseTestSuite #include <boost/test/unit_test.hpp> // StdAir #include <stdair/basic/BasLogParams.hpp> #include <stdair/basic/BasDBParams.hpp> #include <stdair/service/Logger.hpp> // RMOL #include <rmol/RMOL_Service.hpp> #include <rmol/config/rmol-paths.hpp> namespace boost_utf = boost::unit_test; // (Boost) Unit Test XML Report std::ofstream utfReportStream ("bomsforforecaster_utfresults.xml"); /** * Configuration for the Boost Unit Test Framework (UTF) */ struct UnitTestConfig { /** Constructor. */ UnitTestConfig() { boost_utf::unit_test_log.set_stream (utfReportStream); boost_utf::unit_test_log.set_format (boost_utf::XML); boost_utf::unit_test_log.set_threshold_level (boost_utf::log_test_units); //boost_utf::unit_test_log.set_threshold_level (boost_utf::log_successful_tests); } /** Destructor. */ ~UnitTestConfig() { } }; namespace RMOL { /**-------------- BOM: Booking class/bucket data ----------------------- */ struct BookingClassData { // Attributes double _bookingCount; double _fare; double _sellupFactor; bool _censorshipFlag; // Constructer BookingClassData (const double iBookingCount, const double iFare, const double iSellupFactor, const bool iCensorshipFlag) : _bookingCount(iBookingCount), _fare(iFare), _sellupFactor(iSellupFactor), _censorshipFlag(iCensorshipFlag) { } // Getters double getFare () const { return _fare; } bool getCensorshipFlag () const { return _censorshipFlag; } // Display std::string toString() const { std::ostringstream oStr; oStr << std::endl << "[Booking class data information]" << std::endl << "Booking counter: " << _bookingCount << std::endl << "Fare: " << _fare << std::endl << "Sell-up Factor: " << _sellupFactor << std::endl << "censorshipFlag: " << _censorshipFlag << std::endl; return oStr.str(); } }; /**-------------- BOM: Set of BookingClassData ----------------------- */ struct BookingClassDataSet { typedef std::vector<BookingClassData*> BookingClassDataList_T; // Attributes int _numberOfClass; double _minimumFare; bool _censorshipFlag; // true if any of the classes is censored BookingClassDataList_T _bookingClassDataList; // Constructor BookingClassDataSet () : _numberOfClass(0), _minimumFare(0), _censorshipFlag(false) { } // Add BookingClassData void addBookingClassData (BookingClassData& ioBookingClassData) { _bookingClassDataList.push_back (&ioBookingClassData); } // Getters unsigned int getNumberOfClass () const { return _bookingClassDataList.size(); } double getMinimumFare () const { return _minimumFare; } bool getCensorshipFlag () const { return _censorshipFlag; } // Setters void setMinimumFare (const double iMinFare) { _minimumFare = iMinFare; } void setCensorshipFlag (const bool iCensorshipFlag) { _censorshipFlag = iCensorshipFlag; } // compute minimum fare void updateMinimumFare() { double minFare = std::numeric_limits<double>::max(); BookingClassDataList_T::iterator itBookingClassDataList; for (itBookingClassDataList = _bookingClassDataList.begin(); itBookingClassDataList != _bookingClassDataList.end(); ++itBookingClassDataList) { BookingClassData* lBookingClassData = *itBookingClassDataList; assert (lBookingClassData != NULL); const double lFare = lBookingClassData->getFare(); if (lFare < minFare) { minFare = lFare; } } // setMinimumFare(minFare); } // compute censorship flag for the data set void updateCensorshipFlag () { bool censorshipFlag = false; BookingClassDataList_T::iterator itBookingClassDataList; for (itBookingClassDataList = _bookingClassDataList.begin(); itBookingClassDataList != _bookingClassDataList.end(); ++itBookingClassDataList) { BookingClassData* lBookingClassData = *itBookingClassDataList; assert (lBookingClassData != NULL); const bool lCensorshipFlagOfAClass = lBookingClassData->getCensorshipFlag(); if (lCensorshipFlagOfAClass) { censorshipFlag = true; break; } } // setCensorshipFlag(censorshipFlag); } // Display std::string toString() const { std::ostringstream oStr; oStr << std::endl << "[Booking class data set information]" << std::endl << "Number of classes: " << _numberOfClass << std::endl << "Minimum fare: " << _minimumFare << std::endl << "The data of the class set are sensored: " << _censorshipFlag << std::endl; return oStr.str(); } }; // /**-------------- BOM : Q-Forecaster ----------------------- */ // struct QForecaster { // // Function focused BOM // // 1. calculate sell up probability for Q-eq // // 2. calculate Q-Equivalent Booking // double calculateQEqBooking (BookingClassDataSet& iBookingClassDataSet) { // double lQEqBooking = 0.0; // double lMinFare = iBookingClassDataSet.getMinimumFare(); // return lQEqBooking; // } // /* Calculate Q-equivalent demand // [<- performed by unconstrainer if necessary (Using ExpMax BOM)] // */ // // 3. Partition to each class // // // }; } // /////////////// Main: Unit Test Suite ////////////// // Set the UTF configuration (re-direct the output to a specific file) BOOST_GLOBAL_FIXTURE (UnitTestConfig); /** * Main test suite */ BOOST_AUTO_TEST_SUITE (master_test_suite) /** * Test the forecasting techniques. */ BOOST_AUTO_TEST_CASE (rmol_forecaster) { // Output log File std::string lLogFilename ("bomsforforecaster.log"); std::ofstream logOutputFile; // Open and clean the log outputfile logOutputFile.open (lLogFilename.c_str()); logOutputFile.clear(); // Cabin capacity (it must be greater then 100 here) const double cabinCapacity = 100.0; // Initialise the RMOL service const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile); // Initialise the RMOL service RMOL::RMOL_Service rmolService (lLogParams); // Cabin capacity (it must be greater then 100 here) const double lCabinCapacity = 100.0; // Build a sample BOM tree rmolService.buildSampleBom(); // Register BCDataSet RMOL::BookingClassDataSet lBookingClassDataSet; // Register BookingClassData RMOL::BookingClassData QClassData (10, 100, 1, false); RMOL::BookingClassData MClassData (5, 150, 0.8, true); RMOL::BookingClassData BClassData (0, 200, 0.6, false); RMOL::BookingClassData YClassData (0, 300, 0.3, false); // Display STDAIR_LOG_DEBUG (QClassData.toString()); STDAIR_LOG_DEBUG (MClassData.toString()); STDAIR_LOG_DEBUG (BClassData.toString()); STDAIR_LOG_DEBUG (YClassData.toString()); // Add BookingClassData into the BCDataSet lBookingClassDataSet.addBookingClassData (QClassData); lBookingClassDataSet.addBookingClassData (MClassData); lBookingClassDataSet.addBookingClassData (BClassData); lBookingClassDataSet.addBookingClassData (YClassData); // DEBUG STDAIR_LOG_DEBUG (lBookingClassDataSet.toString()); // Number of classes const unsigned int lNoOfClass = lBookingClassDataSet.getNumberOfClass(); // DEBUG STDAIR_LOG_DEBUG ("Number of Classes: " << lNoOfClass); // Minimum fare BOOST_CHECK_NO_THROW (lBookingClassDataSet.updateMinimumFare()); const double lMinFare = lBookingClassDataSet.getMinimumFare(); // DEBUG STDAIR_LOG_DEBUG ("Minimum fare: " << lMinFare); // Censorship flag BOOST_CHECK_NO_THROW (lBookingClassDataSet.updateCensorshipFlag()); const bool lCensorshipFlag = lBookingClassDataSet.getCensorshipFlag(); // DEBUG STDAIR_LOG_DEBUG ("Censorship Flag: " << lCensorshipFlag); // Close the log output file logOutputFile.close(); } // End the test suite BOOST_AUTO_TEST_SUITE_END() /*! * \endcode */ <commit_msg>[Test] Removed unused capacity variable from the bomsforecaster test.<commit_after>/*! * \page bomsforforecaster_cpp Command-Line Test to Demonstrate How To Test the RMOL Project * \code */ // ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <cassert> #include <limits> #include <sstream> #include <fstream> #include <string> // Boost Unit Test Framework (UTF) #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE OptimiseTestSuite #include <boost/test/unit_test.hpp> // StdAir #include <stdair/basic/BasLogParams.hpp> #include <stdair/basic/BasDBParams.hpp> #include <stdair/service/Logger.hpp> // RMOL #include <rmol/RMOL_Service.hpp> #include <rmol/config/rmol-paths.hpp> namespace boost_utf = boost::unit_test; // (Boost) Unit Test XML Report std::ofstream utfReportStream ("bomsforforecaster_utfresults.xml"); /** * Configuration for the Boost Unit Test Framework (UTF) */ struct UnitTestConfig { /** Constructor. */ UnitTestConfig() { boost_utf::unit_test_log.set_stream (utfReportStream); boost_utf::unit_test_log.set_format (boost_utf::XML); boost_utf::unit_test_log.set_threshold_level (boost_utf::log_test_units); //boost_utf::unit_test_log.set_threshold_level (boost_utf::log_successful_tests); } /** Destructor. */ ~UnitTestConfig() { } }; namespace RMOL { /**-------------- BOM: Booking class/bucket data ----------------------- */ struct BookingClassData { // Attributes double _bookingCount; double _fare; double _sellupFactor; bool _censorshipFlag; // Constructer BookingClassData (const double iBookingCount, const double iFare, const double iSellupFactor, const bool iCensorshipFlag) : _bookingCount(iBookingCount), _fare(iFare), _sellupFactor(iSellupFactor), _censorshipFlag(iCensorshipFlag) { } // Getters double getFare () const { return _fare; } bool getCensorshipFlag () const { return _censorshipFlag; } // Display std::string toString() const { std::ostringstream oStr; oStr << std::endl << "[Booking class data information]" << std::endl << "Booking counter: " << _bookingCount << std::endl << "Fare: " << _fare << std::endl << "Sell-up Factor: " << _sellupFactor << std::endl << "censorshipFlag: " << _censorshipFlag << std::endl; return oStr.str(); } }; /**-------------- BOM: Set of BookingClassData ----------------------- */ struct BookingClassDataSet { typedef std::vector<BookingClassData*> BookingClassDataList_T; // Attributes int _numberOfClass; double _minimumFare; bool _censorshipFlag; // true if any of the classes is censored BookingClassDataList_T _bookingClassDataList; // Constructor BookingClassDataSet () : _numberOfClass(0), _minimumFare(0), _censorshipFlag(false) { } // Add BookingClassData void addBookingClassData (BookingClassData& ioBookingClassData) { _bookingClassDataList.push_back (&ioBookingClassData); } // Getters unsigned int getNumberOfClass () const { return _bookingClassDataList.size(); } double getMinimumFare () const { return _minimumFare; } bool getCensorshipFlag () const { return _censorshipFlag; } // Setters void setMinimumFare (const double iMinFare) { _minimumFare = iMinFare; } void setCensorshipFlag (const bool iCensorshipFlag) { _censorshipFlag = iCensorshipFlag; } // compute minimum fare void updateMinimumFare() { double minFare = std::numeric_limits<double>::max(); BookingClassDataList_T::iterator itBookingClassDataList; for (itBookingClassDataList = _bookingClassDataList.begin(); itBookingClassDataList != _bookingClassDataList.end(); ++itBookingClassDataList) { BookingClassData* lBookingClassData = *itBookingClassDataList; assert (lBookingClassData != NULL); const double lFare = lBookingClassData->getFare(); if (lFare < minFare) { minFare = lFare; } } // setMinimumFare(minFare); } // compute censorship flag for the data set void updateCensorshipFlag () { bool censorshipFlag = false; BookingClassDataList_T::iterator itBookingClassDataList; for (itBookingClassDataList = _bookingClassDataList.begin(); itBookingClassDataList != _bookingClassDataList.end(); ++itBookingClassDataList) { BookingClassData* lBookingClassData = *itBookingClassDataList; assert (lBookingClassData != NULL); const bool lCensorshipFlagOfAClass = lBookingClassData->getCensorshipFlag(); if (lCensorshipFlagOfAClass) { censorshipFlag = true; break; } } // setCensorshipFlag(censorshipFlag); } // Display std::string toString() const { std::ostringstream oStr; oStr << std::endl << "[Booking class data set information]" << std::endl << "Number of classes: " << _numberOfClass << std::endl << "Minimum fare: " << _minimumFare << std::endl << "The data of the class set are sensored: " << _censorshipFlag << std::endl; return oStr.str(); } }; // /**-------------- BOM : Q-Forecaster ----------------------- */ // struct QForecaster { // // Function focused BOM // // 1. calculate sell up probability for Q-eq // // 2. calculate Q-Equivalent Booking // double calculateQEqBooking (BookingClassDataSet& iBookingClassDataSet) { // double lQEqBooking = 0.0; // double lMinFare = iBookingClassDataSet.getMinimumFare(); // return lQEqBooking; // } // /* Calculate Q-equivalent demand // [<- performed by unconstrainer if necessary (Using ExpMax BOM)] // */ // // 3. Partition to each class // // // }; } // /////////////// Main: Unit Test Suite ////////////// // Set the UTF configuration (re-direct the output to a specific file) BOOST_GLOBAL_FIXTURE (UnitTestConfig); /** * Main test suite */ BOOST_AUTO_TEST_SUITE (master_test_suite) /** * Test the forecasting techniques. */ BOOST_AUTO_TEST_CASE (rmol_forecaster) { // Output log File std::string lLogFilename ("bomsforforecaster.log"); std::ofstream logOutputFile; // Open and clean the log outputfile logOutputFile.open (lLogFilename.c_str()); logOutputFile.clear(); // Initialise the RMOL service const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile); // Initialise the RMOL service RMOL::RMOL_Service rmolService (lLogParams); // Build a sample BOM tree rmolService.buildSampleBom(); // Register BCDataSet RMOL::BookingClassDataSet lBookingClassDataSet; // Register BookingClassData RMOL::BookingClassData QClassData (10, 100, 1, false); RMOL::BookingClassData MClassData (5, 150, 0.8, true); RMOL::BookingClassData BClassData (0, 200, 0.6, false); RMOL::BookingClassData YClassData (0, 300, 0.3, false); // Display STDAIR_LOG_DEBUG (QClassData.toString()); STDAIR_LOG_DEBUG (MClassData.toString()); STDAIR_LOG_DEBUG (BClassData.toString()); STDAIR_LOG_DEBUG (YClassData.toString()); // Add BookingClassData into the BCDataSet lBookingClassDataSet.addBookingClassData (QClassData); lBookingClassDataSet.addBookingClassData (MClassData); lBookingClassDataSet.addBookingClassData (BClassData); lBookingClassDataSet.addBookingClassData (YClassData); // DEBUG STDAIR_LOG_DEBUG (lBookingClassDataSet.toString()); // Number of classes const unsigned int lNoOfClass = lBookingClassDataSet.getNumberOfClass(); // DEBUG STDAIR_LOG_DEBUG ("Number of Classes: " << lNoOfClass); // Minimum fare BOOST_CHECK_NO_THROW (lBookingClassDataSet.updateMinimumFare()); const double lMinFare = lBookingClassDataSet.getMinimumFare(); // DEBUG STDAIR_LOG_DEBUG ("Minimum fare: " << lMinFare); // Censorship flag BOOST_CHECK_NO_THROW (lBookingClassDataSet.updateCensorshipFlag()); const bool lCensorshipFlag = lBookingClassDataSet.getCensorshipFlag(); // DEBUG STDAIR_LOG_DEBUG ("Censorship Flag: " << lCensorshipFlag); // Close the log output file logOutputFile.close(); } // End the test suite BOOST_AUTO_TEST_SUITE_END() /*! * \endcode */ <|endoftext|>
<commit_before>#include <algorithm> #include <iterator> #include <string> #include <nek/utility/swap.hpp> #include <gtest/gtest.h> TEST(swap_test, primitive) { // setup int const expect1 = 1; int actual1 = expect1; int const expect2 = 2; int actual2 = expect2; // exercise nek::swap(actual1, actual2); // verify EXPECT_EQ(expect1, actual2); EXPECT_EQ(expect2, actual1); } TEST(swap_test, std_string) { // setup std::string const expect1 = "abc"; std::string actual1 = expect1; std::string const expect2 = "def"; std::string actual2 = expect2; // exercise nek::swap(actual1, actual2); // verify EXPECT_EQ(expect1, actual2); EXPECT_EQ(expect2, actual1); } TEST(swap_test, array_of_int) { // setup int const expect1[] = {1, 2, 3}; int actual1[3]; std::copy(std::begin(expect1), std::end(expect1), std::begin(actual1)); int const expect2[] = {10, 20, 30}; int actual2[3]; std::copy(std::begin(expect2), std::end(expect2), std::begin(actual2)); // exersice nek::swap(actual1, actual2); // verify EXPECT_TRUE(std::equal(std::begin(expect1), std::end(expect1), std::begin(actual2))); EXPECT_TRUE(std::equal(std::begin(expect2), std::end(expect2), std::begin(actual1))); } <commit_msg>remove unneccesary head<commit_after>#include <algorithm> #include <string> #include <nek/utility/swap.hpp> #include <gtest/gtest.h> TEST(swap_test, primitive) { // setup int const expect1 = 1; int actual1 = expect1; int const expect2 = 2; int actual2 = expect2; // exercise nek::swap(actual1, actual2); // verify EXPECT_EQ(expect1, actual2); EXPECT_EQ(expect2, actual1); } TEST(swap_test, std_string) { // setup std::string const expect1 = "abc"; std::string actual1 = expect1; std::string const expect2 = "def"; std::string actual2 = expect2; // exercise nek::swap(actual1, actual2); // verify EXPECT_EQ(expect1, actual2); EXPECT_EQ(expect2, actual1); } TEST(swap_test, array_of_int) { // setup int const expect1[] = {1, 2, 3}; int actual1[3]; std::copy(std::begin(expect1), std::end(expect1), std::begin(actual1)); int const expect2[] = {10, 20, 30}; int actual2[3]; std::copy(std::begin(expect2), std::end(expect2), std::begin(actual2)); // exersice nek::swap(actual1, actual2); // verify EXPECT_TRUE(std::equal(std::begin(expect1), std::end(expect1), std::begin(actual2))); EXPECT_TRUE(std::equal(std::begin(expect2), std::end(expect2), std::begin(actual1))); } <|endoftext|>
<commit_before>#include <flutter/dart_project.h> #include <flutter/flutter_view_controller.h> #include <windows.h> #include <vector> #include "flutter_window.h" #include "run_loop.h" #include "window_configuration.h" int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, _In_ wchar_t* command_line, _In_ int show_command) { // Attach to console when present (e.g., 'flutter run') or create a // new console when running with a debugger. if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { ::AllocConsole(); } RunLoop run_loop; flutter::DartProject project(L"data"); #ifndef _DEBUG project.SetEngineSwitches({"--disable-dart-asserts"}); #endif FlutterWindow window(&run_loop, project); Win32Window::Point origin(kFlutterWindowOriginX, kFlutterWindowOriginY); Win32Window::Size size(kFlutterWindowWidth, kFlutterWindowHeight); if (!window.CreateAndShow(kFlutterWindowTitle, origin, size)) { return EXIT_FAILURE; } window.SetQuitOnClose(true); run_loop.Run(); return EXIT_SUCCESS; } <commit_msg>Update Windows runner from template<commit_after>#include <flutter/dart_project.h> #include <flutter/flutter_view_controller.h> #include <windows.h> #include <vector> #include "flutter_window.h" #include "run_loop.h" #include "window_configuration.h" int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, _In_ wchar_t* command_line, _In_ int show_command) { // Attach to console when present (e.g., 'flutter run') or create a // new console when running with a debugger. if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { ::AllocConsole(); } // Initialize COM, so that it is available for use in the library and/or plugins. ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); RunLoop run_loop; flutter::DartProject project(L"data"); #ifndef _DEBUG project.SetEngineSwitches({"--disable-dart-asserts"}); #endif FlutterWindow window(&run_loop, project); Win32Window::Point origin(kFlutterWindowOriginX, kFlutterWindowOriginY); Win32Window::Size size(kFlutterWindowWidth, kFlutterWindowHeight); if (!window.CreateAndShow(kFlutterWindowTitle, origin, size)) { return EXIT_FAILURE; } window.SetQuitOnClose(true); run_loop.Run(); ::CoUninitialize(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "kernel.h" #include "ilwisdata.h" #include "domain.h" #include "range.h" #include "datadefinition.h" #include "columndefinition.h" #include "connectorinterface.h" #include "geos/geom/Coordinate.h" #include "coordinate.h" #include "table.h" #include "basetable.h" #include "domainitem.h" #include "itemdomain.h" #include "tablemerger.h" using namespace Ilwis; BaseTable::BaseTable() : Table(), _rows(0), _columns(0), _dataloaded(false) { } BaseTable::BaseTable(const Resource& resource) : Table(resource), _rows(0), _columns(0),_dataloaded(false) { } BaseTable::~BaseTable() { } quint32 BaseTable::recordCount() const { return _rows; } quint32 BaseTable::columnCount() const { return _columns; } void BaseTable::recordCount(quint32 r) { _rows = r; } bool BaseTable::createTable() { if (!isValid()) { kernel()->issues()->log(TR("Not created, Table %1 already exists").arg(name()), IssueObject::itWarning); return false; } if ( _columnDefinitionsByName.size() == 0) { kernel()->issues()->log(TR("Trying to create table %1 with zero columns").arg(name())); return false; } return true; } bool BaseTable::addColumn(const ColumnDefinition& def){ if ( isReadOnly()) return false; changed(true); if ( _columnDefinitionsByName.contains(def.name())) { //kernel()->issues()->log(TR("Adding duplicate column %1 to %2").arg(def.name(), name()),IssueObject::itWarning); return false; } ColumnDefinition coldef = def; coldef.columnindex(_columnDefinitionsByIndex.size()); _columnDefinitionsByName[coldef.name()] = coldef; _columnDefinitionsByIndex[coldef.columnindex()] = _columnDefinitionsByName[coldef.name()]; _columns = _columnDefinitionsByName.size(); return true; } bool BaseTable::addColumn(const QString &name, const IDomain& domain) { if ( isReadOnly()) return false; changed(true); if ( _columnDefinitionsByName.contains(name)) { kernel()->issues()->log(TR("Adding duplicate column %1").arg(name),IssueObject::itWarning); return false; } _columnDefinitionsByName[name] = ColumnDefinition(name, domain,_columnDefinitionsByName.size()); _columnDefinitionsByIndex[_columnDefinitionsByName[name].id()] = _columnDefinitionsByName[name]; _columns = _columnDefinitionsByName.size(); return true; } bool BaseTable::addColumn(const QString &name, const QString &domainname) { IDomain dom; if(!dom.prepare(domainname)) return false; return addColumn(name, dom); } IlwisTypes BaseTable::ilwisType() const { return itTABLE; } ColumnDefinition BaseTable::columndefinition(const QString &nme) const { auto iter = _columnDefinitionsByName.find(nme); if ( iter != _columnDefinitionsByName.end()) { if (iter.value().isChanged()) { int index = columnIndex(nme); const_cast<BaseTable *>(this)->adjustRange(index); } return iter.value(); } return ColumnDefinition(); } ColumnDefinition BaseTable::columndefinition(quint32 index) const { auto iter = _columnDefinitionsByIndex.find(index); if ( iter != _columnDefinitionsByIndex.end()) { if (iter.value().isChanged()) { const_cast<BaseTable *>(this)->adjustRange(index); } return iter.value(); } return ColumnDefinition(); } ColumnDefinition &BaseTable::columndefinition(quint32 index) { if ( _columnDefinitionsByIndex[index].isChanged()) { adjustRange(index); } return _columnDefinitionsByIndex[index]; } void BaseTable::columndefinition(const ColumnDefinition &coldef) { if ( coldef.id() >= _columnDefinitionsByIndex.size()) { addColumn(coldef.name(), coldef.datadef().domain<>()); } else { auto iter1 = _columnDefinitionsByIndex.find(coldef.id()); auto iter2 = _columnDefinitionsByName.find(coldef.name()); if ( iter1 != _columnDefinitionsByIndex.end()) { _columnDefinitionsByName.remove(iter1.value().name()); _columnDefinitionsByIndex.remove(coldef.id()); }else if ( iter2 != _columnDefinitionsByName.end()) { _columnDefinitionsByIndex.remove(iter2.value().id()); _columnDefinitionsByName.remove(coldef.name()); } _columnDefinitionsByName[coldef.name()] = coldef; _columnDefinitionsByIndex[coldef.id()] = coldef; } } bool BaseTable::prepare() { if (!IlwisObject::prepare()) return false; return true; } bool BaseTable::isValid() const { return _rows != 0 && _columns != 0; } bool BaseTable::initLoad() { if ( !this->isValid()) { kernel()->issues()->log(TR(ERR_NO_INITIALIZED_1).arg("table")); return false; } if (!_dataloaded) { _dataloaded = true; // to prevent other inits to pass through here if (!connector().isNull() && ! connector()->loadData(this)) { kernel()->issues()->log(TR(ERR_COULD_NOT_LOAD_2).arg("table", name())); _dataloaded = false; return false; } } return true; } void BaseTable::dataLoaded(bool yesno) { _dataloaded = yesno; } void BaseTable::copyTo(IlwisObject *obj) { IlwisObject::copyTo(obj); BaseTable *btable = static_cast<BaseTable *>(obj); btable->_columns = _columns; btable->_columnDefinitionsByIndex = _columnDefinitionsByIndex; btable->_columnDefinitionsByName = _columnDefinitionsByName; btable->_dataloaded = _dataloaded; for(const auto& def : _columnDefinitionsByIndex) { std::vector<QVariant> colvalues = column(def.name()); btable->column(def.name(), colvalues); } btable->_rows = _rows; } quint32 BaseTable::columnIndex(const QString &nme) const { auto iter = _columnDefinitionsByName.find(nme); if ( iter == _columnDefinitionsByName.end()) { //kernel()->issues()->log(TR(ERR_COLUMN_MISSING_2).arg(nme).arg(name()),IssueObject::itWarning); return iUNDEF; } return iter.value().id(); } void BaseTable::columnCount(int cnt) { if ( isReadOnly()) return ; changed(true); if ( cnt >= 0) _columns = cnt; } bool BaseTable::merge(const IlwisObject *obj, int options) { if (obj == 0 || ! hasType(obj->ilwisType(), itTABLE)) return false; if ( isReadOnly()) return false ; changed(true); ITable tblTarget(this); ITable tblSource(static_cast<Table *>(const_cast<IlwisObject *>(obj))); TableMerger merger; merger.copyColumns(tblSource, tblTarget, options); return true; } bool BaseTable::isDataLoaded() const { return _dataloaded; } void BaseTable::adjustRange(int index) { ColumnDefinition& coldef = _columnDefinitionsByIndex[index]; if (!coldef.isValid()) return; if( hasType(coldef.datadef().domain<>()->ilwisType(), itNUMERICDOMAIN)) { SPNumericRange rng = coldef.datadef().range<NumericRange>(); std::vector<QVariant> values = column(coldef.id()); if ( values.size() > 0 && !rng.isNull()) { double vmin=1e208, vmax=-1e208; bool hasfraction = true; for(const QVariant& var : values ){ double v = var.toDouble(); if ( !isNumericalUndef(v)) vmin = std::min(vmin, v) ; v = var.toDouble(); if (!isNumericalUndef(v)) { vmax = std::max(vmax, v) ; } hasfraction |= (v - (qint64)v != 0); } if ( vmin != 1e208 && vmax != -1e208) { //something has changed rng->min(vmin); rng->max(vmax); if (!hasfraction) rng->resolution(1); _columnDefinitionsByName[coldef.name()].datadef() = coldef.datadef(); } } } else if ( hasType(coldef.datadef().domain<>()->ilwisType(), itITEMDOMAIN)) { SPItemRange rng = coldef.datadef().range<ItemRange>(); SPItemRange rngDomain = coldef.datadef().domain<>()->range<ItemRange>(); std::vector<QVariant> values = column(coldef.id()); if ( values.size() > 0 && !rng.isNull()) { rng->clear(); for(auto qval : values) { quint32 id = qval.toUInt(); SPDomainItem item = rngDomain->item(id); if ( !item.isNull()) { rng->add(item->clone()); } } _columnDefinitionsByName[coldef.name()] = coldef; } } coldef.changed(false); } QVariant BaseTable::checkInput(const QVariant& inputVar, quint32 columnIndex) { QVariant actualval= inputVar; if ( QString(inputVar.typeName()) == "QString"){ QString txt = inputVar.toString(); ColumnDefinition& coldef = columndefinition(columnIndex); if ( !coldef.isValid()) return QVariant(); if ( hasType(coldef.datadef().domain<>()->ilwisType(),itTEXTDOMAIN)) { return actualval; } if ( hasType(coldef.datadef().domain<>()->ilwisType(),itITEMDOMAIN) && txt == sUNDEF){ return QVariant((int)iUNDEF); } if ( hasType(coldef.datadef().domain<>()->ilwisType(),itNUMERICDOMAIN) && txt == sUNDEF){ return rUNDEF; } bool ok; double v = inputVar.toDouble(&ok); if ( ok ){ actualval = v; } else { SPItemRange rng1 = coldef.datadef().domain<>()->range<ItemRange>(); if (rng1.isNull()){ WARN2(WARN_INVALID_OBJECT," type for non-ItemDomain of item "+ txt, "column "+coldef.name()); return QVariant(rUNDEF); } SPItemRange rng2 = coldef.datadef().range<ItemRange>(); SPDomainItem item = rng1->item(txt); if ( item.isNull()){ WARN2(WARN_INVALID_OBJECT,"domain item '"+txt+"'", "column "+coldef.name()); return QVariant((int)iUNDEF); } if ( !rng2->contains(item->name())){ rng2->add(item->clone()); } actualval = item->raw(); } } return actualval; } void BaseTable::initValuesColumn(const ColumnDefinition& def){ if ( !def.isValid()){ ERROR2(WARN_INVALID_OBJECT,TR("column definition"), name()); return; } IlwisTypes valueType = def.datadef().domain<>()->valueType(); std::vector<QVariant> col(recordCount()); for(auto& var : col) { if ( hasType(valueType, itINTEGER | itDOMAINITEM)) var = QVariant((int)iUNDEF); else if ( hasType(valueType, itDOUBLE | itFLOAT)) var = QVariant(rUNDEF); else if ( hasType(valueType, itSTRING)) var = QVariant(sUNDEF); else if ( hasType(valueType, itCOORDINATE)) var.setValue(crdUNDEF); } column(def.name(),col); } void BaseTable::initRecord(std::vector<QVariant> &values) const { values.resize(columnCount()); for(int i=0; i < columnCount(); ++i) { const ColumnDefinition &coldef = const_cast<BaseTable *>(this)->columndefinition(i); if ( hasType(coldef.datadef().domain<>()->ilwisType(),itTEXTDOMAIN)) { values[i] = sUNDEF; } if ( hasType(coldef.datadef().domain<>()->ilwisType(),itITEMDOMAIN) ){ values[i] = QVariant((int)iUNDEF); } if ( hasType(coldef.datadef().domain<>()->ilwisType(),itNUMERICDOMAIN)){ values[i] = rUNDEF; } } } <commit_msg>better handling of the checkinput method. automatic recalculating ranges is removed from he getter of columndef. Costs too much performance. The checkinput method now takes care of this ( in a direct way, not by recalculation of the whole column)<commit_after>#include "kernel.h" #include "ilwisdata.h" #include "domain.h" #include "range.h" #include "datadefinition.h" #include "columndefinition.h" #include "connectorinterface.h" #include "geos/geom/Coordinate.h" #include "coordinate.h" #include "table.h" #include "basetable.h" #include "domainitem.h" #include "itemdomain.h" #include "tablemerger.h" using namespace Ilwis; BaseTable::BaseTable() : Table(), _rows(0), _columns(0), _dataloaded(false) { } BaseTable::BaseTable(const Resource& resource) : Table(resource), _rows(0), _columns(0),_dataloaded(false) { } BaseTable::~BaseTable() { } quint32 BaseTable::recordCount() const { return _rows; } quint32 BaseTable::columnCount() const { return _columns; } void BaseTable::recordCount(quint32 r) { _rows = r; } bool BaseTable::createTable() { if (!isValid()) { kernel()->issues()->log(TR("Not created, Table %1 already exists").arg(name()), IssueObject::itWarning); return false; } if ( _columnDefinitionsByName.size() == 0) { kernel()->issues()->log(TR("Trying to create table %1 with zero columns").arg(name())); return false; } return true; } bool BaseTable::addColumn(const ColumnDefinition& def){ if ( isReadOnly()) return false; changed(true); if ( _columnDefinitionsByName.contains(def.name())) { return false; } ColumnDefinition coldef = def; coldef.columnindex(_columnDefinitionsByIndex.size()); _columnDefinitionsByName[coldef.name()] = coldef; _columnDefinitionsByIndex[coldef.columnindex()] = _columnDefinitionsByName[coldef.name()]; _columns = _columnDefinitionsByName.size(); return true; } bool BaseTable::addColumn(const QString &name, const IDomain& domain) { if ( isReadOnly()) return false; changed(true); if ( _columnDefinitionsByName.contains(name)) { return false; } _columnDefinitionsByName[name] = ColumnDefinition(name, domain,_columnDefinitionsByName.size()); _columnDefinitionsByIndex[_columnDefinitionsByName[name].id()] = _columnDefinitionsByName[name]; _columns = _columnDefinitionsByName.size(); return true; } bool BaseTable::addColumn(const QString &name, const QString &domainname) { IDomain dom; if(!dom.prepare(domainname)) return false; return addColumn(name, dom); } IlwisTypes BaseTable::ilwisType() const { return itTABLE; } ColumnDefinition BaseTable::columndefinition(const QString &nme) const { auto iter = _columnDefinitionsByName.find(nme); if ( iter != _columnDefinitionsByName.end()) { if (iter.value().isChanged()) { int index = columnIndex(nme); const_cast<BaseTable *>(this)->adjustRange(index); } return iter.value(); } return ColumnDefinition(); } ColumnDefinition BaseTable::columndefinition(quint32 index) const { auto iter = _columnDefinitionsByIndex.find(index); if ( iter != _columnDefinitionsByIndex.end()) { if (iter.value().isChanged()) { const_cast<BaseTable *>(this)->adjustRange(index); } return iter.value(); } return ColumnDefinition(); } ColumnDefinition &BaseTable::columndefinition(quint32 index) { if ( index < _columnDefinitionsByIndex.size()) return _columnDefinitionsByIndex[index]; throw ErrorObject(TR(QString("Invalid column index used").arg(name()))); } void BaseTable::columndefinition(const ColumnDefinition &coldef) { if ( coldef.id() >= _columnDefinitionsByIndex.size()) { addColumn(coldef.name(), coldef.datadef().domain<>()); } else { auto iter1 = _columnDefinitionsByIndex.find(coldef.id()); auto iter2 = _columnDefinitionsByName.find(coldef.name()); if ( iter1 != _columnDefinitionsByIndex.end()) { _columnDefinitionsByName.remove(iter1.value().name()); _columnDefinitionsByIndex.remove(coldef.id()); }else if ( iter2 != _columnDefinitionsByName.end()) { _columnDefinitionsByIndex.remove(iter2.value().id()); _columnDefinitionsByName.remove(coldef.name()); } _columnDefinitionsByName[coldef.name()] = coldef; _columnDefinitionsByIndex[coldef.id()] = coldef; } } bool BaseTable::prepare() { if (!IlwisObject::prepare()) return false; return true; } bool BaseTable::isValid() const { return _rows != 0 && _columns != 0; } bool BaseTable::initLoad() { if ( !this->isValid()) { kernel()->issues()->log(TR(ERR_NO_INITIALIZED_1).arg("table")); return false; } if (!_dataloaded) { _dataloaded = true; // to prevent other inits to pass through here if (!connector().isNull() && ! connector()->loadData(this)) { kernel()->issues()->log(TR(ERR_COULD_NOT_LOAD_2).arg("table", name())); _dataloaded = false; return false; } } return true; } void BaseTable::dataLoaded(bool yesno) { _dataloaded = yesno; } void BaseTable::copyTo(IlwisObject *obj) { IlwisObject::copyTo(obj); BaseTable *btable = static_cast<BaseTable *>(obj); btable->_columns = _columns; btable->_columnDefinitionsByIndex = _columnDefinitionsByIndex; btable->_columnDefinitionsByName = _columnDefinitionsByName; btable->_dataloaded = _dataloaded; for(const auto& def : _columnDefinitionsByIndex) { std::vector<QVariant> colvalues = column(def.name()); btable->column(def.name(), colvalues); } btable->_rows = _rows; } quint32 BaseTable::columnIndex(const QString &nme) const { auto iter = _columnDefinitionsByName.find(nme); if ( iter == _columnDefinitionsByName.end()) { //kernel()->issues()->log(TR(ERR_COLUMN_MISSING_2).arg(nme).arg(name()),IssueObject::itWarning); return iUNDEF; } return iter.value().id(); } void BaseTable::columnCount(int cnt) { if ( isReadOnly()) return ; changed(true); if ( cnt >= 0) _columns = cnt; } bool BaseTable::merge(const IlwisObject *obj, int options) { if (obj == 0 || ! hasType(obj->ilwisType(), itTABLE)) return false; if ( isReadOnly()) return false ; changed(true); ITable tblTarget(this); ITable tblSource(static_cast<Table *>(const_cast<IlwisObject *>(obj))); TableMerger merger; merger.copyColumns(tblSource, tblTarget, options); return true; } bool BaseTable::isDataLoaded() const { return _dataloaded; } void BaseTable::adjustRange(int index) { ColumnDefinition& coldef = _columnDefinitionsByIndex[index]; if (!coldef.isValid()) return; if( hasType(coldef.datadef().domain<>()->ilwisType(), itNUMERICDOMAIN)) { SPNumericRange rng = coldef.datadef().range<NumericRange>(); std::vector<QVariant> values = column(coldef.id()); if ( values.size() > 0 && !rng.isNull()) { double vmin=1e208, vmax=-1e208; bool hasfraction = true; for(const QVariant& var : values ){ double v = var.toDouble(); if ( !isNumericalUndef(v)) vmin = std::min(vmin, v) ; v = var.toDouble(); if (!isNumericalUndef(v)) { vmax = std::max(vmax, v) ; } hasfraction |= (v - (qint64)v != 0); } if ( vmin != 1e208 && vmax != -1e208) { //something has changed rng->min(vmin); rng->max(vmax); if (!hasfraction) rng->resolution(1); _columnDefinitionsByName[coldef.name()].datadef() = coldef.datadef(); } } } else if ( hasType(coldef.datadef().domain<>()->ilwisType(), itITEMDOMAIN)) { SPItemRange rng = coldef.datadef().range<ItemRange>(); SPItemRange rngDomain = coldef.datadef().domain<>()->range<ItemRange>(); std::vector<QVariant> values = column(coldef.id()); if ( values.size() > 0 && !rng.isNull()) { rng->clear(); for(auto qval : values) { quint32 id = qval.toUInt(); SPDomainItem item = rngDomain->item(id); if ( !item.isNull()) { rng->add(item->clone()); } } _columnDefinitionsByName[coldef.name()] = coldef; } } coldef.changed(false); } QVariant BaseTable::checkInput(const QVariant& inputVar, quint32 columnIndex) { QVariant actualval= inputVar; ColumnDefinition& coldef = columndefinition(columnIndex); QString typenm = inputVar.typeName(); IlwisTypes domtype = coldef.datadef().domain<>()->ilwisType(); if ( domtype == itITEMDOMAIN){ if ( inputVar == sUNDEF){ return QVariant((int)iUNDEF); } else if ( typenm == "QString"){ actualval = coldef.datadef().domain<>()->impliedValue(inputVar); SPItemRange rng1 = coldef.datadef().domain<>()->range<ItemRange>(); SPItemRange rng2 = coldef.datadef().range<ItemRange>(); SPDomainItem item = rng1->item(inputVar.toString()); if ( item.isNull()){ return QVariant((int)iUNDEF); } if ( !rng2->contains(item->name())){ rng2->add(item->clone()); } actualval = item->raw(); } }else if ( domtype == itNUMERICDOMAIN){ bool ok; double v = typenm == "QString" ? coldef.datadef().domain<>()->impliedValue(inputVar).toDouble(&ok) : actualval.toDouble(&ok); if (!ok || isNumericalUndef(v)) return rUNDEF; SPNumericRange rng = coldef.datadef().range<NumericRange>(); if ( !rng.isNull()){ rng->add(v); } } else if ( domtype == itTEXTDOMAIN){ if ( typenm != "QString") return sUNDEF; } return actualval; } void BaseTable::initValuesColumn(const ColumnDefinition& def){ if ( !def.isValid()){ ERROR2(WARN_INVALID_OBJECT,TR("column definition"), name()); return; } IlwisTypes valueType = def.datadef().domain<>()->valueType(); std::vector<QVariant> col(recordCount()); for(auto& var : col) { if ( hasType(valueType, itINTEGER | itDOMAINITEM)) var = QVariant((int)iUNDEF); else if ( hasType(valueType, itDOUBLE | itFLOAT)) var = QVariant(rUNDEF); else if ( hasType(valueType, itSTRING)) var = QVariant(sUNDEF); else if ( hasType(valueType, itCOORDINATE)) var.setValue(crdUNDEF); } column(def.name(),col); } void BaseTable::initRecord(std::vector<QVariant> &values) const { values.resize(columnCount()); for(int i=0; i < columnCount(); ++i) { const ColumnDefinition &coldef = const_cast<BaseTable *>(this)->columndefinition(i); if ( hasType(coldef.datadef().domain<>()->ilwisType(),itTEXTDOMAIN)) { values[i] = sUNDEF; } if ( hasType(coldef.datadef().domain<>()->ilwisType(),itITEMDOMAIN) ){ values[i] = QVariant((int)iUNDEF); } if ( hasType(coldef.datadef().domain<>()->ilwisType(),itNUMERICDOMAIN)){ values[i] = rUNDEF; } } } void BaseTable::removeRecord(quint32 rec) { --_rows; } <|endoftext|>
<commit_before>/// HEADER #include <csapex_optimization/optimizer.h> /// PROJECT #include <csapex/msg/io.h> #include <csapex/utility/register_apex_plugin.h> #include <csapex/param/parameter_factory.h> #include <csapex/model/node_modifier.h> #include <csapex/param/range_parameter.h> #include <csapex/msg/generic_value_message.hpp> #include <csapex/msg/any_message.h> #include <csapex/signal/event.h> #include <csapex/param/trigger_parameter.h> #include <csapex/msg/end_of_sequence_message.h> #include <csapex/model/token.h> #include <csapex/model/node_handle.h> using namespace csapex; using namespace csapex::connection_types; Optimizer::Optimizer() : last_fitness_(std::numeric_limits<double>::infinity()), best_fitness_(-std::numeric_limits<double>::infinity()), init_(false), optimization_running_(false), validation_running_(false), can_send_next_parameters_(false) { } void Optimizer::setupParameters(Parameterizable& parameters) { parameters.addParameter(csapex::param::ParameterFactory::declareTrigger("start"), [this](csapex::param::Parameter*) { start(); }); parameters.addParameter(csapex::param::ParameterFactory::declareTrigger("finish"), [this](csapex::param::Parameter*) { finish(); }); stop_ = csapex::param::ParameterFactory::declareTrigger("stop").build<param::TriggerParameter>(); parameters.addParameter(stop_, [this](csapex::param::Parameter*) { doStop(); }); parameters.addParameter(csapex::param::ParameterFactory::declareTrigger("set best"), [this](csapex::param::Parameter*) { stop(); setBest(); }); } void Optimizer::setup(NodeModifier& node_modifier) { slot_fitness_ = node_modifier.addTypedSlot<GenericValueMessage<double>>("Fitness", [this](const TokenPtr& token) { if(!optimization_running_) { return; } auto m = token->getTokenData(); if(std::dynamic_pointer_cast<connection_types::EndOfSequenceMessage const>(m)) { finish(); } else { if(auto vm = std::dynamic_pointer_cast<connection_types::GenericValueMessage<double> const>(m)){ fitness_ = vm->value; } can_send_next_parameters_ = true; yield(); } }); out_last_fitness_ = node_modifier.addOutput<double>("Last Fitness"); out_best_fitness_ = node_modifier.addOutput<double>("Best Fitness"); trigger_start_evaluation_ = node_modifier.addEvent("Evaluate"); trigger_iteration_finished = node_modifier.addEvent<connection_types::GenericValueMessage<double>>("Iteration finished"); reset(); } bool Optimizer::canProcess() const { return validation_running_ || (optimization_running_ && can_send_next_parameters_); } void Optimizer::process() { if(optimization_running_) { apex_assert(can_send_next_parameters_); can_send_next_parameters_ = false; } if(best_fitness_ != std::numeric_limits<double>::infinity()) { msg::publish(out_best_fitness_, best_fitness_); } if(last_fitness_ != std::numeric_limits<double>::infinity()) { msg::publish(out_last_fitness_, last_fitness_); } } void Optimizer::reset() { Node::reset(); last_fitness_ = std::numeric_limits<double>::infinity(); best_fitness_ = -std::numeric_limits<double>::infinity(); } void Optimizer::start() { node_handle_->setWarning("optimization started"); reset(); init_ = false; optimization_running_ = true; validation_running_ = false; can_send_next_parameters_ = true; trigger_start_evaluation_->trigger(); yield(); } void Optimizer::stop() { stop_->trigger(); connection_types::GenericValueMessage<double>::Ptr msg = std::make_shared<connection_types::GenericValueMessage<double>>(); msg->value = best_fitness_; trigger_iteration_finished->triggerWith(std::make_shared<Token>(msg)); } void Optimizer::doStop() { node_handle_->setWarning("optimization stopped, setting best values"); optimization_running_ = false; setBest(); validation_running_ = true; trigger_start_evaluation_->trigger(); yield(); } void Optimizer::finish() { if(validation_running_) { validation_running_ = false; return; } if(!optimization_running_) { return; } last_fitness_ = fitness_; if(best_fitness_ < fitness_) { ainfo << "got better fitness: " << fitness_ << ", best was " << best_fitness_ << std::endl; best_fitness_ = fitness_; best_parameters_.clear(); for(param::ParameterPtr p : getPersistentParameters()) { best_parameters_[p->getUUID()] = param::ParameterFactory::clone(p); } } if(generateNextParameterSet()) { trigger_start_evaluation_->trigger(); can_send_next_parameters_ = true; yield(); } else { stop(); } } void Optimizer::setBest() { for(param::ParameterPtr p : getPersistentParameters()) { p->setValueFrom(*best_parameters_.at(p->getUUID()));; } } <commit_msg>optimizers should minimize<commit_after>/// HEADER #include <csapex_optimization/optimizer.h> /// PROJECT #include <csapex/msg/io.h> #include <csapex/utility/register_apex_plugin.h> #include <csapex/param/parameter_factory.h> #include <csapex/model/node_modifier.h> #include <csapex/param/range_parameter.h> #include <csapex/msg/generic_value_message.hpp> #include <csapex/msg/any_message.h> #include <csapex/signal/event.h> #include <csapex/param/trigger_parameter.h> #include <csapex/msg/end_of_sequence_message.h> #include <csapex/model/token.h> #include <csapex/model/node_handle.h> using namespace csapex; using namespace csapex::connection_types; Optimizer::Optimizer() : last_fitness_(std::numeric_limits<double>::infinity()), best_fitness_(std::numeric_limits<double>::infinity()), init_(false), optimization_running_(false), validation_running_(false), can_send_next_parameters_(false) { } void Optimizer::setupParameters(Parameterizable& parameters) { parameters.addParameter(csapex::param::ParameterFactory::declareTrigger("start"), [this](csapex::param::Parameter*) { start(); }); parameters.addParameter(csapex::param::ParameterFactory::declareTrigger("finish"), [this](csapex::param::Parameter*) { finish(); }); stop_ = csapex::param::ParameterFactory::declareTrigger("stop").build<param::TriggerParameter>(); parameters.addParameter(stop_, [this](csapex::param::Parameter*) { doStop(); }); parameters.addParameter(csapex::param::ParameterFactory::declareTrigger("set best"), [this](csapex::param::Parameter*) { stop(); setBest(); }); } void Optimizer::setup(NodeModifier& node_modifier) { slot_fitness_ = node_modifier.addTypedSlot<GenericValueMessage<double>>("Fitness", [this](const TokenPtr& token) { if(!optimization_running_) { return; } auto m = token->getTokenData(); if(std::dynamic_pointer_cast<connection_types::EndOfSequenceMessage const>(m)) { finish(); } else { if(auto vm = std::dynamic_pointer_cast<connection_types::GenericValueMessage<double> const>(m)){ fitness_ = vm->value; } can_send_next_parameters_ = true; yield(); } }); out_last_fitness_ = node_modifier.addOutput<double>("Last Fitness"); out_best_fitness_ = node_modifier.addOutput<double>("Best Fitness"); trigger_start_evaluation_ = node_modifier.addEvent("Evaluate"); trigger_iteration_finished = node_modifier.addEvent<connection_types::GenericValueMessage<double>>("Iteration finished"); reset(); } bool Optimizer::canProcess() const { return validation_running_ || (optimization_running_ && can_send_next_parameters_); } void Optimizer::process() { if(optimization_running_) { apex_assert(can_send_next_parameters_); can_send_next_parameters_ = false; } if(best_fitness_ != std::numeric_limits<double>::infinity()) { msg::publish(out_best_fitness_, best_fitness_); } if(last_fitness_ != std::numeric_limits<double>::infinity()) { msg::publish(out_last_fitness_, last_fitness_); } } void Optimizer::reset() { Node::reset(); last_fitness_ = std::numeric_limits<double>::infinity(); best_fitness_ = std::numeric_limits<double>::infinity(); } void Optimizer::start() { node_handle_->setWarning("optimization started"); reset(); init_ = false; optimization_running_ = true; validation_running_ = false; can_send_next_parameters_ = true; trigger_start_evaluation_->trigger(); yield(); } void Optimizer::stop() { stop_->trigger(); connection_types::GenericValueMessage<double>::Ptr msg = std::make_shared<connection_types::GenericValueMessage<double>>(); msg->value = best_fitness_; trigger_iteration_finished->triggerWith(std::make_shared<Token>(msg)); } void Optimizer::doStop() { node_handle_->setWarning("optimization stopped, setting best values"); optimization_running_ = false; setBest(); validation_running_ = true; trigger_start_evaluation_->trigger(); yield(); } void Optimizer::finish() { if(validation_running_) { validation_running_ = false; return; } if(!optimization_running_) { return; } last_fitness_ = fitness_; if(best_fitness_ > fitness_) { ainfo << "got better fitness: " << fitness_ << ", best was " << best_fitness_ << std::endl; best_fitness_ = fitness_; best_parameters_.clear(); for(param::ParameterPtr p : getPersistentParameters()) { best_parameters_[p->getUUID()] = param::ParameterFactory::clone(p); } } if(generateNextParameterSet()) { trigger_start_evaluation_->trigger(); can_send_next_parameters_ = true; yield(); } else { stop(); } } void Optimizer::setBest() { for(param::ParameterPtr p : getPersistentParameters()) { p->setValueFrom(*best_parameters_.at(p->getUUID()));; } } <|endoftext|>
<commit_before>#include <Salamandre-stats/stats.hpp> #include <Salamandre-daemon/Daemon.hpp> #include <Salamandre-daemon/ServerBroadcast.hpp> #include <Salamandre-daemon/define.hpp> #include <utils/log.hpp> #include <sys/types.h> #include <sys/stat.h> #include <sys/file.h> #include <fcntl.h> #include <unistd.h> #include <iostream> #include <csignal> #include <tclap/CmdLine.h> namespace salamandre { Daemon* daemon = nullptr; int fd_pid; } void stop_server_handler(int sig) { utils::log::info("Stop","Recv signal",sig,"Stoping server.\n Please wait."); if(salamandre::daemon) salamandre::daemon->stop(); close(salamandre::fd_pid); } void daemonize(std::string log_path, std::string pid_path) { int pid = fork(); if (pid < 0) { std::cerr << "Unable to fork, exiting" << std::endl; exit(1); } else if( pid != 0) { // Parent process, exiting std::cout << "Turning into background... PID: " << pid << std::endl; exit(0); } // Detaching from any controlling terminal if (setsid() == -1) { perror("Unable to detach from terminal"); exit(1); } salamandre::fd_pid = ::open(pid_path.c_str(), O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (salamandre::fd_pid == -1) { ::perror("Unable to create and open the pid_file"); ::close(salamandre::fd_pid); ::exit(1); } if (flock(salamandre::fd_pid, LOCK_EX | LOCK_NB) != 0) { ::perror("Unable to lock the pid_file, is the daemon already running ?"); ::close(salamandre::fd_pid); ::exit(1); } ::ftruncate(salamandre::fd_pid, 0); char buffer[32]; ::snprintf(buffer, 32, "%d", ::getpid()); ::write(salamandre::fd_pid, buffer, strlen(buffer)); ::syncfs(salamandre::fd_pid); std::ifstream in("/dev/null"); std::cin.rdbuf(in.rdbuf()); // That should be the good solution, but it causes segfaults /* std::ofstream out(log_path.c_str()); std::cout.rdbuf(out.rdbuf()); std::cerr.rdbuf(out.rdbuf()); */ FILE * log_file = ::fopen(log_path.c_str(), "a"); ::close(STDOUT_FILENO); ::dup(::fileno(log_file)); ::dup2(STDOUT_FILENO, STDERR_FILENO); ::close(::fileno(log_file)); } int main(int argc,char* argv[]) { int gui_port = 3842; int server_port = 3843; int broadcast_port = 5001; std::string node_file_path; bool local_only = false; bool daemon = false; std::string path = argv[0]; try { TCLAP::CmdLine cmd("Salamandre Daemon", ' ', DAEMON_VERSION); TCLAP::ValueArg<int> gui_port_arg("g", "gui-port", "Port for the GUI", false, gui_port, "int", cmd); TCLAP::ValueArg<int> server_port_arg("s", "server-port", "Port for the server to listen", false, server_port, "int", cmd); TCLAP::ValueArg<std::string> nodes_file_arg("f", "nodes-file", "File containing node list", false, "", "string", cmd); TCLAP::SwitchArg local_switch("l", "local", "Whether daemon sould run stricly locally", cmd, false); TCLAP::SwitchArg daemon_switch("d", "daemonize", "Start the server in a daemon", cmd, false); cmd.parse(argc, argv); local_only = local_switch.getValue(); gui_port = gui_port_arg.getValue(); server_port = server_port_arg.getValue(); node_file_path = nodes_file_arg.getValue(); daemon = daemon_switch.getValue(); } catch(TCLAP::ArgException &e) { utils::log::critical(1,"Args ","error",e.error(),"for arg",e.argId()); } std::cout<<"Daemon start on:" <<"\n\tgui listen on port : "<<gui_port <<"\n\tfile server listen on port : "<<server_port <<"\n\tbrodcast server listen on port: "<<broadcast_port <<"\n\tlocal only : "<<local_only <<"\nPress ^C to exit" <<std::endl<<std::endl; std::signal(SIGINT, stop_server_handler); std::signal(SIGTERM, stop_server_handler); if (daemon) { daemonize("salamandre.log", "salamandre.pid"); } try { salamandre::Daemon::init(); if (!node_file_path.empty()) { salamandre::stats::Stats::load(node_file_path.c_str()); } salamandre::daemon = new salamandre::Daemon(path, gui_port,server_port,broadcast_port,local_only); salamandre::daemon->start(); salamandre::daemon->wait(); delete salamandre::daemon; salamandre::daemon = nullptr; salamandre::Daemon::close(); } catch(ntw::SocketExeption& e) { utils::log::error("Socket error",e.what()); } utils::log::info("End","Daemon is now close, Good bye"); if (daemon) { ::unlink("salamandre.pid"); } return 0; } <commit_msg>Better way to close log_file<commit_after>#include <Salamandre-stats/stats.hpp> #include <Salamandre-daemon/Daemon.hpp> #include <Salamandre-daemon/ServerBroadcast.hpp> #include <Salamandre-daemon/define.hpp> #include <utils/log.hpp> #include <sys/types.h> #include <sys/stat.h> #include <sys/file.h> #include <fcntl.h> #include <unistd.h> #include <iostream> #include <csignal> #include <tclap/CmdLine.h> namespace salamandre { Daemon* daemon = nullptr; int fd_pid; } void stop_server_handler(int sig) { utils::log::info("Stop","Recv signal",sig,"Stoping server.\n Please wait."); if(salamandre::daemon) salamandre::daemon->stop(); close(salamandre::fd_pid); } void daemonize(std::string log_path, std::string pid_path) { int pid = fork(); if (pid < 0) { std::cerr << "Unable to fork, exiting" << std::endl; exit(1); } else if( pid != 0) { // Parent process, exiting std::cout << "Turning into background... PID: " << pid << std::endl; exit(0); } // Detaching from any controlling terminal if (setsid() == -1) { perror("Unable to detach from terminal"); exit(1); } salamandre::fd_pid = ::open(pid_path.c_str(), O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (salamandre::fd_pid == -1) { ::perror("Unable to create and open the pid_file"); ::close(salamandre::fd_pid); ::exit(1); } if (flock(salamandre::fd_pid, LOCK_EX | LOCK_NB) != 0) { ::perror("Unable to lock the pid_file, is the daemon already running ?"); ::close(salamandre::fd_pid); ::exit(1); } ::ftruncate(salamandre::fd_pid, 0); char buffer[32]; ::snprintf(buffer, 32, "%d", ::getpid()); ::write(salamandre::fd_pid, buffer, strlen(buffer)); ::syncfs(salamandre::fd_pid); std::ifstream in("/dev/null"); std::cin.rdbuf(in.rdbuf()); // That should be the good solution, but it causes segfaults /* std::ofstream out(log_path.c_str()); std::cout.rdbuf(out.rdbuf()); std::cerr.rdbuf(out.rdbuf()); */ FILE * log_file = ::fopen(log_path.c_str(), "a"); ::close(STDOUT_FILENO); ::dup(::fileno(log_file)); ::dup2(STDOUT_FILENO, STDERR_FILENO); ::fclose(log_file); } int main(int argc,char* argv[]) { int gui_port = 3842; int server_port = 3843; int broadcast_port = 5001; std::string node_file_path; bool local_only = false; bool daemon = false; std::string path = argv[0]; try { TCLAP::CmdLine cmd("Salamandre Daemon", ' ', DAEMON_VERSION); TCLAP::ValueArg<int> gui_port_arg("g", "gui-port", "Port for the GUI", false, gui_port, "int", cmd); TCLAP::ValueArg<int> server_port_arg("s", "server-port", "Port for the server to listen", false, server_port, "int", cmd); TCLAP::ValueArg<std::string> nodes_file_arg("f", "nodes-file", "File containing node list", false, "", "string", cmd); TCLAP::SwitchArg local_switch("l", "local", "Whether daemon sould run stricly locally", cmd, false); TCLAP::SwitchArg daemon_switch("d", "daemonize", "Start the server in a daemon", cmd, false); cmd.parse(argc, argv); local_only = local_switch.getValue(); gui_port = gui_port_arg.getValue(); server_port = server_port_arg.getValue(); node_file_path = nodes_file_arg.getValue(); daemon = daemon_switch.getValue(); } catch(TCLAP::ArgException &e) { utils::log::critical(1,"Args ","error",e.error(),"for arg",e.argId()); } std::cout<<"Daemon start on:" <<"\n\tgui listen on port : "<<gui_port <<"\n\tfile server listen on port : "<<server_port <<"\n\tbrodcast server listen on port: "<<broadcast_port <<"\n\tlocal only : "<<local_only <<"\nPress ^C to exit" <<std::endl<<std::endl; std::signal(SIGINT, stop_server_handler); std::signal(SIGTERM, stop_server_handler); if (daemon) { daemonize("salamandre.log", "salamandre.pid"); } try { salamandre::Daemon::init(); if (!node_file_path.empty()) { salamandre::stats::Stats::load(node_file_path.c_str()); } salamandre::daemon = new salamandre::Daemon(path, gui_port,server_port,broadcast_port,local_only); salamandre::daemon->start(); salamandre::daemon->wait(); delete salamandre::daemon; salamandre::daemon = nullptr; salamandre::Daemon::close(); } catch(ntw::SocketExeption& e) { utils::log::error("Socket error",e.what()); } utils::log::info("End","Daemon is now close, Good bye"); if (daemon) { ::unlink("salamandre.pid"); } return 0; } <|endoftext|>
<commit_before>/* * qiesmap.cpp * * Copyright (c) 2016 Tobias Wood. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ #include <getopt.h> #include <iostream> #include <Eigen/Dense> #include <Eigen/Eigenvalues> #include "QI/Util.h" #include "QI/Sequences/SteadyStateSequence.cpp" #include "Filters/ApplyAlgorithmFilter.h" using namespace std; using namespace Eigen; class ESAlgo : public Algorithm<complex<double>> { protected: size_t m_size = 0; shared_ptr<QI::SSFP_GS> m_sequence = nullptr; public: size_t numInputs() const override { return 1; } size_t numConsts() const override { return 1; } size_t numOutputs() const override { return 6; } const vector<string> & names() const { static vector<string> _names = {"M", "T1", "T2", "th", "a", "b"}; return _names; } size_t dataSize() const override { return m_size; } void setSize(const size_t s) { m_size = s; } virtual TArray defaultConsts() override { // B1 TArray def = TArray::Ones(1); return def; } void SetSequence(const shared_ptr<QI::SSFP_GS> &s) { m_sequence = s;} ArrayXd solveEig(const MatrixXd &A, const MatrixXd &B) const { RealQZ<MatrixXd> qz(A, B); VectorXd v = ArrayXd::Zero(A.cols()); const MatrixXd &mS = qz.matrixS(); const MatrixXd &mT = qz.matrixT(); const MatrixXd &mZT = qz.matrixZ().transpose(); int sInd = 0; double sVal = numeric_limits<double>::infinity(); for (int i = 0; i < 6; i++) { const double a = mS.coeffRef(i,i); const double b = mT.coeffRef(i,i); const double l = fabs(a / b); if (l < sVal) { sVal = l; sInd = i; } } v(sInd) = 1.0; const double a = qz.matrixS().coeffRef(sInd,sInd); const double b = qz.matrixT().coeffRef(sInd,sInd); for (int j = sInd-1; j >= 0; j--) { const int st = j+1; const int sz = sInd-j; v.coeffRef(j) = -v.segment(st,sz).transpose().cwiseProduct(b*mS.block(j,st,1,sz) - a*mT.block(j,st,1,sz)).sum() / (b*mS.coeffRef(j,j) - a*mT.coeffRef(j,j)); } v = (mZT * v).normalized(); return v; } MatrixXd buildS(const ArrayXd &x, const ArrayXd &y) const { Matrix<double, Dynamic, 6> D(x.rows(), 6); D.col(0) = x*x; D.col(1) = x*y; D.col(2) = y*y; D.col(3) = x; D.col(4) = y; D.col(5).setConstant(1); return D.transpose() * D; } MatrixXd fitzC() const { typedef Matrix<double, 6, 6> Matrix6d; Matrix6d C = Matrix6d::Zero(); // Fitzgibbon et al C(0,2) = -2; C(1,1) = 1; C(2,0) = -2; return C; } MatrixXd hyperC(const ArrayXd &x, const ArrayXd &y) const { typedef Matrix<double, 6, 6> Matrix6d; Matrix6d C = Matrix6d::Zero(); // Fitzgibbon et al //C(0,2) = -2; C(1,1) = 1; C(2,0) = -2; // Hyper Ellipse const double N = x.cols(); const double xc = x.sum() / N; const double yc = y.sum() / N; const double sx = x.square().sum() / N; const double sy = y.square().sum() / N; const double xy = (x * y).sum() / N; C << 6*sx, 6*xy, sx+sy, 6*xc, 2*yc, 1, 6*xy, 4*(sx+sy), 6*xy, 4*yc, 4*xc, 0, sx + sy, 6*xy, 6*sy, 2*xc, 6*yc, 1, 6*xc, 4*yc, 2*xc, 4, 0, 0, 2*yc, 4*xc, 6*yc, 0, 4, 0, 1, 0, 1, 0, 0, 0; return C; } void apply(const TInput &data, const TArray &inputs, TArray &outputs, TArray &resids, TIterations &its) const override { typedef Matrix<double, 6, 6> Matrix6d; typedef Matrix<double, 6, 1> Vector6d; const double B1 = inputs[0]; const double scale = data.abs().maxCoeff(); ArrayXd x = data.real() / scale; ArrayXd y = data.imag() / scale; MatrixXd S = buildS(x, y); Matrix6d C = hyperC(x, y); ArrayXd Z = solveEig(S, C); const double za = Z[0]; const double zb = Z[1]/2; const double zc = Z[2]; const double zd = Z[3]/2; const double zf = Z[4]/2; const double zg = Z[5]; const double dsc=(zb*zb-za*zc); const double xc = (zc*zd-zb*zf)/dsc; const double yc = (za*zf-zb*zd)/dsc; const double th = atan2(yc,xc); double A = sqrt((2*(za*(zf*zf)+zc*(zd*zd)+zg*(zb*zb)-2*zb*zd*zf-za*zc*zg))/(dsc*(sqrt((za-zc)*(za-zc) + 4*zb*zb)-(za+zc)))); double B = sqrt((2*(za*(zf*zf)+zc*(zd*zd)+zg*(zb*zb)-2*zb*zd*zf-za*zc*zg))/(dsc*(-sqrt((za-zc)*(za-zc) + 4*zb*zb)-(za+zc)))); if (A > B) { std::swap(A, B); } //cout << "Z " << Z.transpose() << endl; //cout << "dsc " << dsc << " xc " << xc << " yc " << yc << " A " << A << " B " << B << endl; const double c = sqrt(xc*xc+yc*yc); const double b = (-c*A + sqrt(c*c*A*A - (c*c + B*B)*(A*A - B*B)))/(c*c + B*B); const double a = B / (b*B + c*sqrt(1-b*b)); const double M = scale*c*(1-b*b)/(1-a*b); const double TR = m_sequence->TR(); const double ca = cos(B1 * m_sequence->flip()[0]); const double T1 = -TR / (log(a*(1.+ca-a*b*ca)-b) - log(a*(1.+ca-a*b)-b*ca)); const double T2 = -TR / log(a); outputs[0] = M; outputs[1] = T1; outputs[2] = T2; outputs[3] = th; outputs[4] = a; outputs[5] = b; } }; //****************************************************************************** // Arguments / Usage //****************************************************************************** const string usage { "Usage is: qiesmap [options] input \n\ \n\ A utility for calculating T1,T2,PD and f0 maps from SSFP data.\n\ Input must be a single complex image with at least 6 phase increments.\n\ \n\ Options:\n\ --help, -h : Print this message.\n\ --verbose, -v : Print more information.\n\ --out, -o path : Specify an output prefix.\n\ --mask, -m file : Mask input with specified file.\n\ --B1, -b file : B1 Map file (ratio)\n\ --threads, -T N : Use N threads (default=hardware limit).\n" }; bool verbose = false; static size_t num_threads = 4; static string outPrefix; const struct option long_opts[] = { {"help", no_argument, 0, 'h'}, {"verbose", no_argument, 0, 'v'}, {"out", required_argument, 0, 'o'}, {"mask", required_argument, 0, 'm'}, {"B1", required_argument, 0, 'b'}, {"threads", required_argument, 0, 'T'}, {0, 0, 0, 0} }; const char *short_opts = "hvo:m:b:T:"; //****************************************************************************** // Main //****************************************************************************** int main(int argc, char **argv) { Eigen::initParallel(); QI::VolumeF::Pointer mask = ITK_NULLPTR; QI::VolumeF::Pointer B1 = ITK_NULLPTR; shared_ptr<ESAlgo> algo = make_shared<ESAlgo>(); int indexptr = 0, c; while ((c = getopt_long(argc, argv, short_opts, long_opts, &indexptr)) != -1) { switch (c) { case 'v': verbose = true; break; case 'm': if (verbose) cout << "Opening mask file " << optarg << endl; mask = QI::ReadImage(optarg); break; case 'o': outPrefix = optarg; if (verbose) cout << "Output prefix will be: " << outPrefix << endl; break; case 'b': if (verbose) cout << "Opening B1 file: " << optarg << endl; B1 = QI::ReadImage(optarg); break; case 'T': num_threads = stoi(optarg); if (num_threads == 0) num_threads = std::thread::hardware_concurrency(); break; case 'h': cout << QI::GetVersion() << endl << usage << endl; return EXIT_SUCCESS; case '?': // getopt will print an error message return EXIT_FAILURE; default: cout << "Unhandled option " << string(1, c) << endl; return EXIT_FAILURE; } } if ((argc - optind) != 1) { cout << "Incorrect number of arguments." << endl << usage << endl; return EXIT_FAILURE; } string inputFilename = argv[optind++]; if (verbose) cout << "Opening file: " << inputFilename << endl; auto data = QI::ReadVectorImage<complex<float>>(inputFilename); shared_ptr<QI::SSFP_GS> seq = make_shared<QI::SSFP_GS>(cin, true); auto apply = itk::ApplyAlgorithmFilter<ESAlgo, complex<float>>::New(); algo->setSize(data->GetNumberOfComponentsPerPixel()); algo->SetSequence(seq); apply->SetAlgorithm(algo); apply->SetPoolsize(num_threads); apply->SetInput(0, data); if (mask) apply->SetMask(mask); if (B1) apply->SetConst(0, B1); if (verbose) { cout << "Processing" << endl; auto monitor = QI::GenericMonitor::New(); apply->AddObserver(itk::ProgressEvent(), monitor); } apply->Update(); if (verbose) { cout << "Elapsed time was " << apply->GetTotalTime() << "s" << endl; cout << "Mean time per voxel was " << apply->GetMeanTime() << "s" << endl; cout << "Writing results files." << endl; } outPrefix = outPrefix + "ES_"; for (int i = 0; i < algo->numOutputs(); i++) { QI::WriteImage(apply->GetOutput(i), outPrefix + algo->names().at(i) + QI::OutExt()); } if (verbose) cout << "Finished." << endl; return EXIT_SUCCESS; } <commit_msg>BUG: Missing factor of sqrt(E2) on M<commit_after>/* * qiesmap.cpp * * Copyright (c) 2016 Tobias Wood. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ #include <getopt.h> #include <iostream> #include <Eigen/Dense> #include <Eigen/Eigenvalues> #include "QI/Util.h" #include "QI/Sequences/SteadyStateSequence.cpp" #include "Filters/ApplyAlgorithmFilter.h" using namespace std; using namespace Eigen; class ESAlgo : public Algorithm<complex<double>> { protected: size_t m_size = 0; shared_ptr<QI::SSFP_GS> m_sequence = nullptr; public: size_t numInputs() const override { return 1; } size_t numConsts() const override { return 1; } size_t numOutputs() const override { return 6; } const vector<string> & names() const { static vector<string> _names = {"M", "T1", "T2", "th", "a", "b"}; return _names; } size_t dataSize() const override { return m_size; } void setSize(const size_t s) { m_size = s; } virtual TArray defaultConsts() override { // B1 TArray def = TArray::Ones(1); return def; } void SetSequence(const shared_ptr<QI::SSFP_GS> &s) { m_sequence = s;} ArrayXd solveEig(const MatrixXd &A, const MatrixXd &B) const { RealQZ<MatrixXd> qz(A, B); VectorXd v = ArrayXd::Zero(A.cols()); const MatrixXd &mS = qz.matrixS(); const MatrixXd &mT = qz.matrixT(); const MatrixXd &mZT = qz.matrixZ().transpose(); int sInd = 0; double sVal = numeric_limits<double>::infinity(); for (int i = 0; i < 6; i++) { const double a = mS.coeffRef(i,i); const double b = mT.coeffRef(i,i); const double l = fabs(a / b); if (l < sVal) { sVal = l; sInd = i; } } v(sInd) = 1.0; const double a = qz.matrixS().coeffRef(sInd,sInd); const double b = qz.matrixT().coeffRef(sInd,sInd); for (int j = sInd-1; j >= 0; j--) { const int st = j+1; const int sz = sInd-j; v.coeffRef(j) = -v.segment(st,sz).transpose().cwiseProduct(b*mS.block(j,st,1,sz) - a*mT.block(j,st,1,sz)).sum() / (b*mS.coeffRef(j,j) - a*mT.coeffRef(j,j)); } v = (mZT * v).normalized(); return v; } MatrixXd buildS(const ArrayXd &x, const ArrayXd &y) const { Matrix<double, Dynamic, 6> D(x.rows(), 6); D.col(0) = x*x; D.col(1) = x*y; D.col(2) = y*y; D.col(3) = x; D.col(4) = y; D.col(5).setConstant(1); return D.transpose() * D; } MatrixXd fitzC() const { typedef Matrix<double, 6, 6> Matrix6d; Matrix6d C = Matrix6d::Zero(); // Fitzgibbon et al C(0,2) = -2; C(1,1) = 1; C(2,0) = -2; return C; } MatrixXd hyperC(const ArrayXd &x, const ArrayXd &y) const { typedef Matrix<double, 6, 6> Matrix6d; Matrix6d C = Matrix6d::Zero(); // Fitzgibbon et al //C(0,2) = -2; C(1,1) = 1; C(2,0) = -2; // Hyper Ellipse const double N = x.cols(); const double xc = x.sum() / N; const double yc = y.sum() / N; const double sx = x.square().sum() / N; const double sy = y.square().sum() / N; const double xy = (x * y).sum() / N; C << 6*sx, 6*xy, sx+sy, 6*xc, 2*yc, 1, 6*xy, 4*(sx+sy), 6*xy, 4*yc, 4*xc, 0, sx + sy, 6*xy, 6*sy, 2*xc, 6*yc, 1, 6*xc, 4*yc, 2*xc, 4, 0, 0, 2*yc, 4*xc, 6*yc, 0, 4, 0, 1, 0, 1, 0, 0, 0; return C; } void apply(const TInput &data, const TArray &inputs, TArray &outputs, TArray &resids, TIterations &its) const override { typedef Matrix<double, 6, 6> Matrix6d; typedef Matrix<double, 6, 1> Vector6d; const double B1 = inputs[0]; const double scale = data.abs().maxCoeff(); ArrayXd x = data.real() / scale; ArrayXd y = data.imag() / scale; MatrixXd S = buildS(x, y); Matrix6d C = hyperC(x, y); ArrayXd Z = solveEig(S, C); const double za = Z[0]; const double zb = Z[1]/2; const double zc = Z[2]; const double zd = Z[3]/2; const double zf = Z[4]/2; const double zg = Z[5]; const double dsc=(zb*zb-za*zc); const double xc = (zc*zd-zb*zf)/dsc; const double yc = (za*zf-zb*zd)/dsc; const double th = atan2(yc,xc); double A = sqrt((2*(za*(zf*zf)+zc*(zd*zd)+zg*(zb*zb)-2*zb*zd*zf-za*zc*zg))/(dsc*(sqrt((za-zc)*(za-zc) + 4*zb*zb)-(za+zc)))); double B = sqrt((2*(za*(zf*zf)+zc*(zd*zd)+zg*(zb*zb)-2*zb*zd*zf-za*zc*zg))/(dsc*(-sqrt((za-zc)*(za-zc) + 4*zb*zb)-(za+zc)))); if (A > B) { std::swap(A, B); } //cout << "Z " << Z.transpose() << endl; //cout << "dsc " << dsc << " xc " << xc << " yc " << yc << " A " << A << " B " << B << endl; const double c = sqrt(xc*xc+yc*yc); const double b = (-c*A + sqrt(c*c*A*A - (c*c + B*B)*(A*A - B*B)))/(c*c + B*B); const double a = B / (b*B + c*sqrt(1-b*b)); const double TR = m_sequence->TR(); const double ca = cos(B1 * m_sequence->flip()[0]); const double T1 = -TR / (log(a-b + (1.-a*b)*a*ca) - log(a*(1.-a*b) + (a-b)*ca)); const double T2 = -TR / log(a); const double M = (scale/sqrt(a))*c*(1-b*b)/(1-a*b); outputs[0] = M; outputs[1] = T1; outputs[2] = T2; outputs[3] = th; outputs[4] = a; outputs[5] = b; } }; //****************************************************************************** // Arguments / Usage //****************************************************************************** const string usage { "Usage is: qiesmap [options] input \n\ \n\ A utility for calculating T1,T2,PD and f0 maps from SSFP data.\n\ Input must be a single complex image with at least 6 phase increments.\n\ \n\ Options:\n\ --help, -h : Print this message.\n\ --verbose, -v : Print more information.\n\ --out, -o path : Specify an output prefix.\n\ --mask, -m file : Mask input with specified file.\n\ --B1, -b file : B1 Map file (ratio)\n\ --threads, -T N : Use N threads (default=hardware limit).\n" }; bool verbose = false; static size_t num_threads = 4; static string outPrefix; const struct option long_opts[] = { {"help", no_argument, 0, 'h'}, {"verbose", no_argument, 0, 'v'}, {"out", required_argument, 0, 'o'}, {"mask", required_argument, 0, 'm'}, {"B1", required_argument, 0, 'b'}, {"threads", required_argument, 0, 'T'}, {0, 0, 0, 0} }; const char *short_opts = "hvo:m:b:T:"; //****************************************************************************** // Main //****************************************************************************** int main(int argc, char **argv) { Eigen::initParallel(); QI::VolumeF::Pointer mask = ITK_NULLPTR; QI::VolumeF::Pointer B1 = ITK_NULLPTR; shared_ptr<ESAlgo> algo = make_shared<ESAlgo>(); int indexptr = 0, c; while ((c = getopt_long(argc, argv, short_opts, long_opts, &indexptr)) != -1) { switch (c) { case 'v': verbose = true; break; case 'm': if (verbose) cout << "Opening mask file " << optarg << endl; mask = QI::ReadImage(optarg); break; case 'o': outPrefix = optarg; if (verbose) cout << "Output prefix will be: " << outPrefix << endl; break; case 'b': if (verbose) cout << "Opening B1 file: " << optarg << endl; B1 = QI::ReadImage(optarg); break; case 'T': num_threads = stoi(optarg); if (num_threads == 0) num_threads = std::thread::hardware_concurrency(); break; case 'h': cout << QI::GetVersion() << endl << usage << endl; return EXIT_SUCCESS; case '?': // getopt will print an error message return EXIT_FAILURE; default: cout << "Unhandled option " << string(1, c) << endl; return EXIT_FAILURE; } } if ((argc - optind) != 1) { cout << "Incorrect number of arguments." << endl << usage << endl; return EXIT_FAILURE; } string inputFilename = argv[optind++]; if (verbose) cout << "Opening file: " << inputFilename << endl; auto data = QI::ReadVectorImage<complex<float>>(inputFilename); shared_ptr<QI::SSFP_GS> seq = make_shared<QI::SSFP_GS>(cin, true); auto apply = itk::ApplyAlgorithmFilter<ESAlgo, complex<float>>::New(); algo->setSize(data->GetNumberOfComponentsPerPixel()); algo->SetSequence(seq); apply->SetAlgorithm(algo); apply->SetPoolsize(num_threads); apply->SetInput(0, data); if (mask) apply->SetMask(mask); if (B1) apply->SetConst(0, B1); if (verbose) { cout << "Processing" << endl; auto monitor = QI::GenericMonitor::New(); apply->AddObserver(itk::ProgressEvent(), monitor); } apply->Update(); if (verbose) { cout << "Elapsed time was " << apply->GetTotalTime() << "s" << endl; cout << "Mean time per voxel was " << apply->GetMeanTime() << "s" << endl; cout << "Writing results files." << endl; } outPrefix = outPrefix + "ES_"; for (int i = 0; i < algo->numOutputs(); i++) { QI::WriteImage(apply->GetOutput(i), outPrefix + algo->names().at(i) + QI::OutExt()); } if (verbose) cout << "Finished." << endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// ///////////////////////////////////////////////////////////////// // Generated by dtkPluginGenerator // ///////////////////////////////////////////////////////////////// #include "itkProcessRegistrationDiffeomorphicDemons.h" #include <dtkCore/dtkAbstractData.h> #include <dtkCore/dtkAbstractDataFactory.h> #include <dtkCore/dtkAbstractProcessFactory.h> // ///////////////////////////////////////////////////////////////// // // ///////////////////////////////////////////////////////////////// #include "itkImageRegistrationMethod.h" #include "itkImage.h" #include "itkResampleImageFilter.h" #include "itkCastImageFilter.h" #include "time.h" #include <DiffeomorphicDemons/rpiDiffeomorphicDemons.hxx> #include <rpiCommonTools.hxx> // ///////////////////////////////////////////////////////////////// // itkProcessRegistrationDiffeomorphicDemonsDiffeomorphicDemonsPrivate // ///////////////////////////////////////////////////////////////// class itkProcessRegistrationDiffeomorphicDemonsPrivate { public: itkProcessRegistrationDiffeomorphicDemons * proc; template <class PixelType> int update(void); template < typename TFixedImage, typename TMovingImage > bool write(const QString&); void * registrationMethod ; std::vector<unsigned int> iterations; unsigned char updateRule; unsigned char gradientType; float maximumUpdateStepLength; float updateFieldStandardDeviation; float displacementFieldStandardDeviation; bool useHistogramMatching; }; // ///////////////////////////////////////////////////////////////// // itkProcessRegistrationDiffeomorphicDemons // ///////////////////////////////////////////////////////////////// itkProcessRegistrationDiffeomorphicDemons::itkProcessRegistrationDiffeomorphicDemons(void) : itkProcessRegistration(), d(new itkProcessRegistrationDiffeomorphicDemonsPrivate) { d->proc = this; d->registrationMethod = NULL ; d->updateRule = 0; d->gradientType = 0; d->maximumUpdateStepLength = 2.0; d->updateFieldStandardDeviation = 0.0; d->displacementFieldStandardDeviation = 1.5; d->useHistogramMatching = false; } itkProcessRegistrationDiffeomorphicDemons::~itkProcessRegistrationDiffeomorphicDemons(void) { d->proc = NULL; switch(fixedImageType()){ //only float will be used here, diffeoMorphic demons only work on float and double. default: { typedef itk::Image< float, 3 > RegImageType; delete static_cast<rpi::DiffeomorphicDemons< RegImageType, RegImageType, float > *>(d->registrationMethod); } break; } d->registrationMethod = NULL; delete d; d = NULL; } bool itkProcessRegistrationDiffeomorphicDemons::registered(void) { return dtkAbstractProcessFactory::instance()->registerProcessType("itkProcessRegistrationDiffeomorphicDemons", createitkProcessRegistrationDiffeomorphicDemons); } QString itkProcessRegistrationDiffeomorphicDemons::description(void) const { return "itkProcessRegistrationDiffeomorphicDemons"; } // ///////////////////////////////////////////////////////////////// // Templated Version of update // ///////////////////////////////////////////////////////////////// template <typename PixelType> int itkProcessRegistrationDiffeomorphicDemonsPrivate::update(void) { typedef itk::Image< PixelType, 3 > FixedImageType; typedef itk::Image< PixelType, 3 > MovingImageType; //unfortunately diffeomorphic demons only work with double or float types... // so we need to use a cast filter. typedef itk::Image< float, 3 > RegImageType; typedef float TransformScalarType; typedef rpi::DiffeomorphicDemons< RegImageType, RegImageType, TransformScalarType > RegistrationType; RegistrationType * registration = new RegistrationType; registrationMethod = registration; typedef itk::CastImageFilter< FixedImageType, RegImageType > CastFilterType; typename CastFilterType::Pointer caster = CastFilterType::New(); caster->SetInput((const FixedImageType*)proc->fixedImage().GetPointer()); caster->Update(); registration->SetFixedImage(caster->GetOutput()); typedef itk::CastImageFilter< MovingImageType, RegImageType > CastFilterMovingType; typename CastFilterType::Pointer casterMov = CastFilterType::New(); casterMov->SetInput((const MovingImageType*)proc->movingImage().GetPointer()); casterMov->Update(); registration->SetMovingImage(casterMov->GetOutput()); registration->SetNumberOfIterations(iterations); registration->SetMaximumUpdateStepLength(maximumUpdateStepLength); registration->SetUpdateFieldStandardDeviation(updateFieldStandardDeviation); registration->SetDisplacementFieldStandardDeviation(displacementFieldStandardDeviation); registration->SetUseHistogramMatching(useHistogramMatching); // Set update rule switch( updateRule ) { case 0: registration->SetUpdateRule( RegistrationType::UPDATE_DIFFEOMORPHIC ); break; case 1: registration->SetUpdateRule( RegistrationType::UPDATE_ADDITIVE ); break; case 2: registration->SetUpdateRule( RegistrationType::UPDATE_COMPOSITIVE ); break; default: throw std::runtime_error( "Update rule must fit in the range [0,2]." ); } // Set gradient type switch( gradientType ) { case 0: registration->SetGradientType( RegistrationType::GRADIENT_SYMMETRIZED ); break; case 1: registration->SetGradientType( RegistrationType::GRADIENT_FIXED_IMAGE ); break; case 2: registration->SetGradientType( RegistrationType::GRADIENT_WARPED_MOVING_IMAGE ); break; case 3: registration->SetGradientType( RegistrationType::GRADIENT_MAPPED_MOVING_IMAGE ); break; default: throw std::runtime_error( "Gradient type must fit in the range [0,3]." ); } // Print method parameters qDebug() << "METHOD PARAMETERS"; qDebug() << " Max number of iterations : " << QString::fromStdString(rpi::VectorToString(registration->GetNumberOfIterations())); qDebug() << " Update rule : " << registration->GetUpdateRule(); qDebug() << " Maximum step length : " << registration->GetMaximumUpdateStepLength()<< " (voxel unit)"; qDebug() << " Gradient type : " << registration->GetGradientType(); qDebug() << " Update field standard deviation : " << registration->GetUpdateFieldStandardDeviation() << " (voxel unit)"; qDebug() << " Displacement field standard deviation : " << registration->GetDisplacementFieldStandardDeviation() << " (voxel unit)"; qDebug() << " Use histogram matching? : " << registration->GetUseHistogramMatching(); // Run the registration time_t t1 = clock(); try { registration->StartRegistration(); } catch( std::exception & err ) { qDebug() << "ExceptionObject caught ! (startRegistration)" << err.what(); return 1; } time_t t2 = clock(); qDebug() << "Elasped time: " << (double)(t2-t1)/(double)CLOCKS_PER_SEC; typedef itk::ResampleImageFilter< MovingImageType,MovingImageType,TransformScalarType > ResampleFilterType; typename ResampleFilterType::Pointer resampler = ResampleFilterType::New(); resampler->SetTransform(registration->GetTransformation()); resampler->SetInput((const MovingImageType*)proc->movingImage().GetPointer()); resampler->SetSize( proc->fixedImage()->GetLargestPossibleRegion().GetSize() ); resampler->SetOutputOrigin( proc->fixedImage()->GetOrigin() ); resampler->SetOutputSpacing( proc->fixedImage()->GetSpacing() ); resampler->SetOutputDirection( proc->fixedImage()->GetDirection() ); resampler->SetDefaultPixelValue( 0 ); try { resampler->Update(); } catch (itk::ExceptionObject &e) { qDebug() << e.GetDescription(); return 1; } itk::ImageBase<3>::Pointer result = resampler->GetOutput(); qDebug() << "Resampled? "; result->DisconnectPipeline(); if (proc->output()) proc->output()->setData (result); return 0; } int itkProcessRegistrationDiffeomorphicDemons::update(itkProcessRegistration::ImageType imgType) { if(fixedImage().IsNull() || movingImage().IsNull()) return 1; switch (imgType){ //unfortunately diffeomorphic demons only work on float or double pixels... case itkProcessRegistration::UCHAR: return d->update<unsigned char>(); break; case itkProcessRegistration::CHAR: return d->update<char>(); break; case itkProcessRegistration::USHORT: return d->update<unsigned short>(); break; case itkProcessRegistration::SHORT: return d->update<short>(); break; case itkProcessRegistration::UINT: return d->update<unsigned int>(); break; case itkProcessRegistration::INT: return d->update<int>(); break; case itkProcessRegistration::ULONG: return d->update<unsigned long>(); break; case itkProcessRegistration::LONG: return d->update<long>(); break; case itkProcessRegistration::DOUBLE: return d->update<double>(); break; default: return d->update<float>(); break; } } bool itkProcessRegistrationDiffeomorphicDemons::writeTransform(const QString& file) { typedef float PixelType; typedef float TransformScalarType; typedef itk::Image< PixelType, 3 > RegImageType; //normaly should use long switch cases, but here we know we work with float3 data. if (rpi::DiffeomorphicDemons<RegImageType,RegImageType,TransformScalarType> * registration = static_cast<rpi::DiffeomorphicDemons<RegImageType,RegImageType,TransformScalarType> *>(d->registrationMethod)) { try{ rpi::writeDisplacementFieldTransformation<TransformScalarType, RegImageType::ImageDimension>( registration->GetTransformation(), file.toStdString()); } catch (std::exception) { return false; } return true; } else { return false; } } // ///////////////////////////////////////////////////////////////// // Process parameters // ///////////////////////////////////////////////////////////////// void itkProcessRegistrationDiffeomorphicDemons::setUpdateRule(unsigned char updateRule) { d->updateRule = updateRule; } void itkProcessRegistrationDiffeomorphicDemons::setGradientType(unsigned char gradientType) { d->gradientType = gradientType; } void itkProcessRegistrationDiffeomorphicDemons::setMaximumUpdateLength(float maximumUpdateStepLength) { d->maximumUpdateStepLength = maximumUpdateStepLength; } void itkProcessRegistrationDiffeomorphicDemons::setUpdateFieldStandardDeviation(float updateFieldStandardDeviation) { d->updateFieldStandardDeviation = updateFieldStandardDeviation; } void itkProcessRegistrationDiffeomorphicDemons::setDisplacementFieldStandardDeviation(float displacementFieldStandardDeviation) { d->displacementFieldStandardDeviation = displacementFieldStandardDeviation; } void itkProcessRegistrationDiffeomorphicDemons::setUseHistogramMatching(bool useHistogramMatching) { d->useHistogramMatching = useHistogramMatching; } void itkProcessRegistrationDiffeomorphicDemons::setNumberOfIterations(std::vector<unsigned int> iterations) { d->iterations = iterations; } // ///////////////////////////////////////////////////////////////// // Type instanciation // ///////////////////////////////////////////////////////////////// dtkAbstractProcess *createitkProcessRegistrationDiffeomorphicDemons(void) { return new itkProcessRegistrationDiffeomorphicDemons; } <commit_msg>diffeomorphic demon is working with the base class<commit_after>// ///////////////////////////////////////////////////////////////// // Generated by dtkPluginGenerator // ///////////////////////////////////////////////////////////////// #include "itkProcessRegistrationDiffeomorphicDemons.h" #include <dtkCore/dtkAbstractData.h> #include <dtkCore/dtkAbstractDataFactory.h> #include <dtkCore/dtkAbstractProcessFactory.h> // ///////////////////////////////////////////////////////////////// // // ///////////////////////////////////////////////////////////////// #include "itkImageRegistrationMethod.h" #include "itkImage.h" #include "itkResampleImageFilter.h" #include "itkCastImageFilter.h" #include "time.h" #include <DiffeomorphicDemons/rpiDiffeomorphicDemons.hxx> #include <rpiCommonTools.hxx> // ///////////////////////////////////////////////////////////////// // itkProcessRegistrationDiffeomorphicDemonsDiffeomorphicDemonsPrivate // ///////////////////////////////////////////////////////////////// class itkProcessRegistrationDiffeomorphicDemonsPrivate { public: itkProcessRegistrationDiffeomorphicDemons * proc; template <class PixelType> int update(void); template < typename TFixedImage, typename TMovingImage > bool write(const QString&); void * registrationMethod ; std::vector<unsigned int> iterations; unsigned char updateRule; unsigned char gradientType; float maximumUpdateStepLength; float updateFieldStandardDeviation; float displacementFieldStandardDeviation; bool useHistogramMatching; }; // ///////////////////////////////////////////////////////////////// // itkProcessRegistrationDiffeomorphicDemons // ///////////////////////////////////////////////////////////////// itkProcessRegistrationDiffeomorphicDemons::itkProcessRegistrationDiffeomorphicDemons(void) : itkProcessRegistration(), d(new itkProcessRegistrationDiffeomorphicDemonsPrivate) { d->proc = this; d->registrationMethod = NULL ; d->updateRule = 0; d->gradientType = 0; d->maximumUpdateStepLength = 2.0; d->updateFieldStandardDeviation = 0.0; d->displacementFieldStandardDeviation = 1.5; d->useHistogramMatching = false; } itkProcessRegistrationDiffeomorphicDemons::~itkProcessRegistrationDiffeomorphicDemons(void) { d->proc = NULL; switch(fixedImageType()){ //only float will be used here, diffeoMorphic demons only work on float and double. default: { typedef itk::Image< float, 3 > RegImageType; delete static_cast<rpi::DiffeomorphicDemons< RegImageType, RegImageType, float > *>(d->registrationMethod); } break; } d->registrationMethod = NULL; delete d; d = NULL; } bool itkProcessRegistrationDiffeomorphicDemons::registered(void) { return dtkAbstractProcessFactory::instance()->registerProcessType("itkProcessRegistrationDiffeomorphicDemons", createitkProcessRegistrationDiffeomorphicDemons); } QString itkProcessRegistrationDiffeomorphicDemons::description(void) const { return "itkProcessRegistrationDiffeomorphicDemons"; } // ///////////////////////////////////////////////////////////////// // Templated Version of update // ///////////////////////////////////////////////////////////////// template <typename PixelType> int itkProcessRegistrationDiffeomorphicDemonsPrivate::update(void) { typedef itk::Image< PixelType, 3 > FixedImageType; typedef itk::Image< PixelType, 3 > MovingImageType; //unfortunately diffeomorphic demons only work with double or float types... // so we need to use a cast filter. typedef itk::Image< float, 3 > RegImageType; typedef float TransformScalarType; typedef rpi::DiffeomorphicDemons< RegImageType, RegImageType, TransformScalarType > RegistrationType; RegistrationType * registration = new RegistrationType; registrationMethod = registration; typedef itk::CastImageFilter< FixedImageType, RegImageType > CastFilterType; typename CastFilterType::Pointer caster = CastFilterType::New(); caster->SetInput((const FixedImageType*)proc->fixedImage().GetPointer()); caster->Update(); registration->SetFixedImage(caster->GetOutput()); typedef itk::CastImageFilter< MovingImageType, RegImageType > CastFilterMovingType; typename CastFilterType::Pointer casterMov = CastFilterType::New(); casterMov->SetInput((const MovingImageType*)proc->movingImages()[0].GetPointer()); casterMov->Update(); registration->SetMovingImage(casterMov->GetOutput()); registration->SetNumberOfIterations(iterations); registration->SetMaximumUpdateStepLength(maximumUpdateStepLength); registration->SetUpdateFieldStandardDeviation(updateFieldStandardDeviation); registration->SetDisplacementFieldStandardDeviation(displacementFieldStandardDeviation); registration->SetUseHistogramMatching(useHistogramMatching); // Set update rule switch( updateRule ) { case 0: registration->SetUpdateRule( RegistrationType::UPDATE_DIFFEOMORPHIC ); break; case 1: registration->SetUpdateRule( RegistrationType::UPDATE_ADDITIVE ); break; case 2: registration->SetUpdateRule( RegistrationType::UPDATE_COMPOSITIVE ); break; default: throw std::runtime_error( "Update rule must fit in the range [0,2]." ); } // Set gradient type switch( gradientType ) { case 0: registration->SetGradientType( RegistrationType::GRADIENT_SYMMETRIZED ); break; case 1: registration->SetGradientType( RegistrationType::GRADIENT_FIXED_IMAGE ); break; case 2: registration->SetGradientType( RegistrationType::GRADIENT_WARPED_MOVING_IMAGE ); break; case 3: registration->SetGradientType( RegistrationType::GRADIENT_MAPPED_MOVING_IMAGE ); break; default: throw std::runtime_error( "Gradient type must fit in the range [0,3]." ); } // Print method parameters qDebug() << "METHOD PARAMETERS"; qDebug() << " Max number of iterations : " << QString::fromStdString(rpi::VectorToString(registration->GetNumberOfIterations())); qDebug() << " Update rule : " << registration->GetUpdateRule(); qDebug() << " Maximum step length : " << registration->GetMaximumUpdateStepLength()<< " (voxel unit)"; qDebug() << " Gradient type : " << registration->GetGradientType(); qDebug() << " Update field standard deviation : " << registration->GetUpdateFieldStandardDeviation() << " (voxel unit)"; qDebug() << " Displacement field standard deviation : " << registration->GetDisplacementFieldStandardDeviation() << " (voxel unit)"; qDebug() << " Use histogram matching? : " << registration->GetUseHistogramMatching(); // Run the registration time_t t1 = clock(); try { registration->StartRegistration(); } catch( std::exception & err ) { qDebug() << "ExceptionObject caught ! (startRegistration)" << err.what(); return 1; } time_t t2 = clock(); qDebug() << "Elasped time: " << (double)(t2-t1)/(double)CLOCKS_PER_SEC; typedef itk::ResampleImageFilter< MovingImageType,MovingImageType,TransformScalarType > ResampleFilterType; typename ResampleFilterType::Pointer resampler = ResampleFilterType::New(); resampler->SetTransform(registration->GetTransformation()); resampler->SetInput((const MovingImageType*)proc->movingImages()[0].GetPointer()); resampler->SetSize( proc->fixedImage()->GetLargestPossibleRegion().GetSize() ); resampler->SetOutputOrigin( proc->fixedImage()->GetOrigin() ); resampler->SetOutputSpacing( proc->fixedImage()->GetSpacing() ); resampler->SetOutputDirection( proc->fixedImage()->GetDirection() ); resampler->SetDefaultPixelValue( 0 ); try { resampler->Update(); } catch (itk::ExceptionObject &e) { qDebug() << e.GetDescription(); return 1; } itk::ImageBase<3>::Pointer result = resampler->GetOutput(); qDebug() << "Resampled? "; result->DisconnectPipeline(); if (proc->output()) proc->output()->setData (result); return 0; } int itkProcessRegistrationDiffeomorphicDemons::update(itkProcessRegistration::ImageType imgType) { if(fixedImage().IsNull() || movingImages().isEmpty()) return 1; switch (imgType){ //unfortunately diffeomorphic demons only work on float or double pixels... case itkProcessRegistration::UCHAR: return d->update<unsigned char>(); break; case itkProcessRegistration::CHAR: return d->update<char>(); break; case itkProcessRegistration::USHORT: return d->update<unsigned short>(); break; case itkProcessRegistration::SHORT: return d->update<short>(); break; case itkProcessRegistration::UINT: return d->update<unsigned int>(); break; case itkProcessRegistration::INT: return d->update<int>(); break; case itkProcessRegistration::ULONG: return d->update<unsigned long>(); break; case itkProcessRegistration::LONG: return d->update<long>(); break; case itkProcessRegistration::DOUBLE: return d->update<double>(); break; default: return d->update<float>(); break; } } bool itkProcessRegistrationDiffeomorphicDemons::writeTransform(const QString& file) { typedef float PixelType; typedef float TransformScalarType; typedef itk::Image< PixelType, 3 > RegImageType; //normaly should use long switch cases, but here we know we work with float3 data. if (rpi::DiffeomorphicDemons<RegImageType,RegImageType,TransformScalarType> * registration = static_cast<rpi::DiffeomorphicDemons<RegImageType,RegImageType,TransformScalarType> *>(d->registrationMethod)) { try{ rpi::writeDisplacementFieldTransformation<TransformScalarType, RegImageType::ImageDimension>( registration->GetTransformation(), file.toStdString()); } catch (std::exception) { return false; } return true; } else { return false; } } // ///////////////////////////////////////////////////////////////// // Process parameters // ///////////////////////////////////////////////////////////////// void itkProcessRegistrationDiffeomorphicDemons::setUpdateRule(unsigned char updateRule) { d->updateRule = updateRule; } void itkProcessRegistrationDiffeomorphicDemons::setGradientType(unsigned char gradientType) { d->gradientType = gradientType; } void itkProcessRegistrationDiffeomorphicDemons::setMaximumUpdateLength(float maximumUpdateStepLength) { d->maximumUpdateStepLength = maximumUpdateStepLength; } void itkProcessRegistrationDiffeomorphicDemons::setUpdateFieldStandardDeviation(float updateFieldStandardDeviation) { d->updateFieldStandardDeviation = updateFieldStandardDeviation; } void itkProcessRegistrationDiffeomorphicDemons::setDisplacementFieldStandardDeviation(float displacementFieldStandardDeviation) { d->displacementFieldStandardDeviation = displacementFieldStandardDeviation; } void itkProcessRegistrationDiffeomorphicDemons::setUseHistogramMatching(bool useHistogramMatching) { d->useHistogramMatching = useHistogramMatching; } void itkProcessRegistrationDiffeomorphicDemons::setNumberOfIterations(std::vector<unsigned int> iterations) { d->iterations = iterations; } // ///////////////////////////////////////////////////////////////// // Type instanciation // ///////////////////////////////////////////////////////////////// dtkAbstractProcess *createitkProcessRegistrationDiffeomorphicDemons(void) { return new itkProcessRegistrationDiffeomorphicDemons; } <|endoftext|>
<commit_before>/******************************************************************************************* author: Tyler Nowak date: 11/13/2016 This algorithm is a serial implementation of Strassen's matrix multiplication algorithm. *******************************************************************************************/ #include <iostream> #include <time.h> #include <iomanip> #include <string> #include <math.h> using namespace std; void FillMatrix(double matrix[], int dimension, int maxInt); void StrassenMult(double matrix1[], double matrix2[], double matrix3[], int dim); void FillSubmatrices(double matrix[], int dim, double sub1[], double sub2[], double sub3[], double sub4[], int subDim); void AddMatrices(double matrix1[], double matrix2[], double matrix3[], int dim); void SubtractMatrices(double matrix1[], double matrix2[], double matrix3[], int dim); void DisplayMatrix(double matrix[], int dim); void FillWithQuads(double quad1[], double quad2[], double quad3[], double quad4[], int subDim, double matrix[], int dim); int main(int argc, char* argv[]) { int dim; // row/col dim of input matrices int maxInt; // number of possible element values double* firstMatrix = NULL; // first input matrix double* secondMatrix = NULL; // second input matrix double* resultMatrix = NULL; // matrix mult result // Check for correct argument count if (argc != 3) { cerr << "Incorrect number or args!\n"; return 1; } // Set matrix dimension and max element size dim = stoi(argv[1]); maxInt = stoi(argv[2]); // Check for valid dimension if ((log(dim) / log(2)) != (int)(log(dim) / log(2))) // dim must be 2^x { cerr << "Invalid dimension!\n"; return 1; } // Check for valid maxInt if (maxInt < 0) { cerr << "Invalid max integer!\n"; return 1; } // Initialize matrices firstMatrix = new double[dim * dim]; secondMatrix = new double[dim * dim]; resultMatrix = new double[dim * dim]; // Initialize random number generator srand(time(NULL)); // Fill first matrix FillMatrix(firstMatrix, dim, maxInt); // Fill second matrix FillMatrix(secondMatrix, dim, maxInt); // Multiply the two matrices using Strassen's algorithm StrassenMult(firstMatrix, secondMatrix, resultMatrix, dim); // Display first matrix cout << "First matrix:\n"; DisplayMatrix(firstMatrix, dim); // Display second matrix cout << "\n\nSecond matrix:\n"; DisplayMatrix(secondMatrix, dim); // Display result matrix cout << "\n\nResult matrix:\n"; DisplayMatrix(resultMatrix, dim); cout << endl; // Deallocate matrices delete [] firstMatrix; delete [] secondMatrix; delete [] resultMatrix; return 0; } // Fill a matrix of a specified dimension with random integers void FillMatrix(double matrix[], int dim, int maxInt) { for (int i=0; i<(dim*dim); i++) matrix[i] = rand() % maxInt; // 0 <= matrix element < maxInt } // Multiply two matrices using Strassen's algorithm void StrassenMult(double matrix1[], double matrix2[], double matrix3[], int dim) { // Check for matrices with 1 element if (dim == 1) { matrix3[0] = matrix1[0] * matrix2[0]; // only int multipication needed return; } if (dim == 2) { double p1, p2, p3, p4, p5, p6, p7; // hold results of Strassen's 7 equations // Find 7 equation results for 2 x 2 matrices p1 = matrix1[0] * (matrix2[1] - matrix2[3]); // a(f-h) p2 = (matrix1[0] + matrix1[1]) * matrix2[3]; // (a+b)h p3 = (matrix1[2] + matrix1[3]) * matrix2[0]; // (c+d)e p4 = matrix1[3] * (matrix2[2] - matrix2[0]); // d(g-e) p5 = (matrix1[0] + matrix1[3]) * (matrix2[0] + matrix2[3]); // (a+d)(e+h) p6 = (matrix1[1] - matrix1[3]) * (matrix2[2] + matrix2[3]); // (b-d)(g+h) p7 = (matrix1[0] - matrix1[2]) * (matrix2[0] + matrix2[1]); // (a-c)(e+f) // Fill result matrix3 based on p1-p7 matrix3[0] = p5 + p4 - p2 + p6; matrix3[1] = p1 + p2; matrix3[2] = p3 + p4; matrix3[3] = p1 + p5 - p3 - p7; } else { int subDim = dim / 2; // dim for each quadrant of the matrices int numElements = subDim * subDim; // number of elements in sub-matrices // Initialize sub-matrices double* a = new double[numElements]; // top, left quadrant of matrix1 double* b = new double[numElements]; // top, right quadrant of matrix1 double* c = new double[numElements]; // bottom, left quadrant of matrix1 double* d = new double[numElements]; // bottom, right quadrant of matrix1 double* e = new double[numElements]; // top, left quadrant of matrix2 double* f = new double[numElements]; // top, right quadrant of matrix2 double* g = new double[numElements]; // bottom, left quadrant of matrix2 double* h = new double[numElements]; // bottom, right quadrant of matrix2 double* result1 = new double[numElements]; // the result of a sub-matrix operation double* result2 = new double[numElements]; // the result of a sub-matrix operation double* m1 = new double[numElements]; // matrix with result of Strassen's eq. 1 double* m2 = new double[numElements]; // matrix with result of Strassen's eq. 2 double* m3 = new double[numElements]; // matrix with result of Strassen's eq. 3 double* m4 = new double[numElements]; // matrix with result of Strassen's eq. 4 double* m5 = new double[numElements]; // matrix with result of Strassen's eq. 5 double* m6 = new double[numElements]; // matrix with result of Strassen's eq. 6 double* m7 = new double[numElements]; // matrix with result of Strassen's eq. 7 double* quad1 = new double[numElements]; // top, left quadrant of matrix3 double* quad2 = new double[numElements]; // top, right quadrant of matrix3 double* quad3 = new double[numElements]; // bottom, left quadrant of matrix3 double* quad4 = new double[numElements]; // bottom, right quadrant of matrix3 // Fill sub-matrices a-h from matrix1 and matrix2 FillSubmatrices(matrix1, dim, a, b, c, d, subDim); FillSubmatrices(matrix2, dim, e, f, g, h, subDim); // Find matrices m1-m7 with results for equations 1-7 SubtractMatrices(f, h, result1, subDim); // f-h StrassenMult(a, result1, m1, subDim); // a(f-h) AddMatrices(a, b, result1, subDim); // a+b StrassenMult(result1, h, m2, subDim); // (a+b)h AddMatrices(c, d, result1, subDim); // c+d StrassenMult(result1, e, m3, subDim); // (c+d)e SubtractMatrices(g, e, result1, subDim); // g-e StrassenMult(d, result1, m4, subDim); // d(g-e) AddMatrices(a, d, result1, subDim); // a+d AddMatrices(e, h, result2, subDim); // e+h StrassenMult(result1, result2, m5, subDim); // (a+d)(e+h) SubtractMatrices(b, d, result1, subDim); // b-d AddMatrices(g, h, result2, subDim); // g+h StrassenMult(result1, result2, m6, subDim); // (b-d)(g+h) SubtractMatrices(a, c, result1, subDim); // a-c AddMatrices(e, f, result2, subDim); // e+f StrassenMult(result1, result2, m7, subDim); // (a-c)(e+f) // Determine quadrants of matrix3 based on m1-m7 AddMatrices(m5, m4, result1, subDim); // m5+m4 SubtractMatrices(result1, m2, result2, subDim); // m5+m4-m2 AddMatrices(result2, m6, quad1, subDim); // m5+m4-m2+m6 AddMatrices(m1, m2, quad2, subDim); // m1+m2 AddMatrices(m3, m4, quad3, subDim); // m3+m4 AddMatrices(m1, m5, result1, subDim); // m1+m5 SubtractMatrices(result1, m3, result2, subDim); // m1+m5-m3 SubtractMatrices(result2, m7, quad4, subDim); // m1+m5-m3-m7 // Fill matrix3 from quadrants FillWithQuads(quad1, quad2, quad3, quad4, subDim, matrix3, dim); // Deallocate sub-matrices delete [] a; delete [] b; delete [] c; delete [] d; delete [] e; delete [] f; delete [] g; delete [] h; delete [] result1; delete [] result2; delete [] m1; delete [] m2; delete [] m3; delete [] m4; delete [] m5; delete [] m6; delete [] m7; delete [] quad1; delete [] quad2; delete [] quad3; delete [] quad4; } } // Divide a matrix up by quadrant into 4 sub-matrices. They are // sub1, sub2, sub3, and sub4 starting in the top, left quadrant // of the matrix, going left to right, and top to bottom. void FillSubmatrices(double matrix[], int dim, double sub1[], double sub2[], double sub3[], double sub4[], int subDim) { int index1 = 0; // index of a sub-matrix 1 element int index2 = 0; // index of a sub-matrix 2 element int index3 = 0; // index of a sub-matrix 3 element int index4 = 0; // index of a sub-matrix 4 element int matrixElement = 0; // index of a matrix element for (int row=0; row<subDim; row++) for (int col=0; col<dim; col++) { if (col < subDim) { // Set sub1 element from matrix quadrant 1 sub1[index1] = matrix[matrixElement]; index1++; } else { // Set sub2 element from matrix quadrant 2 sub2[index2] = matrix[matrixElement]; index2++; } matrixElement++; } for (int row=subDim; row<dim; row++) for (int col=0; col<dim; col++) { if (col < subDim) { // Set sub3 element from matrix quadrant 3 sub3[index3] = matrix[matrixElement]; index3++; } else { // Set sub4 element from matrix quadrant 4 sub4[index4] = matrix[matrixElement]; index4++; } matrixElement++; } } // Add two matrices together into a result matrix void AddMatrices(double matrix1[], double matrix2[], double matrix3[], int dim) { for (int i=0; i<(dim*dim); i++) matrix3[i] = matrix1[i] + matrix2[i]; } // Subtract two matrices. Subtract matrix2 from matrix1 and put the difference // into a result matrix. void SubtractMatrices(double matrix1[], double matrix2[], double matrix3[], int dim) { for (int i=0; i<(dim*dim); i++) matrix3[i] = matrix1[i] - matrix2[i]; } // Display a matrix void DisplayMatrix(double matrix[], int dim) { for (int i=0; i<(dim*dim); i++) { if (i % dim == 0) // return at end of matrix line cout << endl; cout << " " << matrix[i]; } cout << endl << endl; } // Fill a matrix with elements from four separate quadrant sub-matrices void FillWithQuads(double quad1[], double quad2[], double quad3[], double quad4[], int subDim, double matrix[], int dim) { int index1 = 0; // index of a quad1 element int index2 = 0; // index of a quad2 element int index3 = 0; // index of a quad3 element int index4 = 0; // index of a quad4 element int matrixElement = 0; // index of a matrix element for (int row=0; row<subDim; row++) for (int col=0; col<dim; col++) { if (col < subDim) { // Set matrix element from quad1 matrix[matrixElement] = quad1[index1]; index1++; } else { // Set matrix element from quad2 matrix[matrixElement] = quad2[index2]; index2++; } matrixElement++; } for (int row=subDim; row<dim; row++) for (int col=0; col<dim; col++) { if (col < subDim) { // Set matrix element from quad3 matrix[matrixElement] = quad3[index3]; index3++; } else { // Set matrix element from quad4 matrix[matrixElement] = quad4[index4]; index4++; } matrixElement++; } }<commit_msg>Timer added<commit_after>/******************************************************************************************* This algorithm is a serial implementation of Strassen's matrix multiplication algorithm. To compile/run in linux: mpicxx -std=c++11 -g -Wall -o serial StrassenSerial.cpp ./serial [dimension] [max integer] *******************************************************************************************/ #include <iostream> #include <time.h> #include <iomanip> #include <string> #include <math.h> #include <chrono> using namespace std; void FillMatrix(double matrix[], int dimension, int maxInt); void StrassenMult(double matrix1[], double matrix2[], double matrix3[], int dim); void FillSubmatrices(double matrix[], int dim, double sub1[], double sub2[], double sub3[], double sub4[], int subDim); void AddMatrices(double matrix1[], double matrix2[], double matrix3[], int dim); void SubtractMatrices(double matrix1[], double matrix2[], double matrix3[], int dim); void DisplayMatrix(double matrix[], int dim); void FillWithQuads(double quad1[], double quad2[], double quad3[], double quad4[], int subDim, double matrix[], int dim); int main(int argc, char* argv[]) { int dim; // row/col dim of input matrices int maxInt; // number of possible element values double* firstMatrix = NULL; // first input matrix double* secondMatrix = NULL; // second input matrix double* resultMatrix = NULL; // matrix mult result // Check for correct argument count if (argc != 3) { cerr << "Incorrect number or args!\n"; return 1; } // Set matrix dimension and max element size dim = stoi(argv[1]); maxInt = stoi(argv[2]); // Check for valid dimension if ((log(dim) / log(2)) != (int)(log(dim) / log(2))) // dim must be 2^x { cerr << "Invalid dimension!\n"; return 1; } // Check for valid maxInt if (maxInt < 0) { cerr << "Invalid max integer!\n"; return 1; } // Initialize matrices firstMatrix = new double[dim * dim]; secondMatrix = new double[dim * dim]; resultMatrix = new double[dim * dim]; // Initialize random number generator srand(time(NULL)); // Fill first matrix FillMatrix(firstMatrix, dim, maxInt); // Fill second matrix FillMatrix(secondMatrix, dim, maxInt); // Multiply the two matrices using Strassen's algorithm chrono::high_resolution_clock::time_point startTime = // time before matrix mult chrono::high_resolution_clock::now(); StrassenMult(firstMatrix, secondMatrix, resultMatrix, dim); chrono::high_resolution_clock::time_point endTime = // time after matrix mult chrono::high_resolution_clock::now(); chrono::duration<double> elapsedTime = // elapsed time chrono::duration_cast<chrono::duration<double>>(endTime - startTime); // Display results printf("\nMultiplication of dimension %d matrices took %f" " seconds\n\n", dim, elapsedTime.count()); /*printf("first matrix:\n"); DisplayMatrix(firstMatrix, dim); printf("second matrix:\n"); DisplayMatrix(secondMatrix, dim); printf("result:\n"); DisplayMatrix(resultMatrix, dim);*/ // Deallocate matrices delete [] firstMatrix; delete [] secondMatrix; delete [] resultMatrix; return 0; } // Fill a matrix of a specified dimension with random integers void FillMatrix(double matrix[], int dim, int maxInt) { if (maxInt == 0) for (int i=0; i<(dim*dim); i++) matrix[i] = 1; else for (int i=0; i<(dim*dim); i++) matrix[i] = rand() % maxInt; // 0 <= matrix element < maxInt } // Multiply two matrices using Strassen's algorithm void StrassenMult(double matrix1[], double matrix2[], double matrix3[], int dim) { // Check for matrices with 1 element if (dim == 1) { matrix3[0] = matrix1[0] * matrix2[0]; // only int multipication needed return; } if (dim == 2) { double p1, p2, p3, p4, p5, p6, p7; // hold results of Strassen's 7 equations // Find 7 equation results for 2 x 2 matrices p1 = matrix1[0] * (matrix2[1] - matrix2[3]); // a(f-h) p2 = (matrix1[0] + matrix1[1]) * matrix2[3]; // (a+b)h p3 = (matrix1[2] + matrix1[3]) * matrix2[0]; // (c+d)e p4 = matrix1[3] * (matrix2[2] - matrix2[0]); // d(g-e) p5 = (matrix1[0] + matrix1[3]) * (matrix2[0] + matrix2[3]); // (a+d)(e+h) p6 = (matrix1[1] - matrix1[3]) * (matrix2[2] + matrix2[3]); // (b-d)(g+h) p7 = (matrix1[0] - matrix1[2]) * (matrix2[0] + matrix2[1]); // (a-c)(e+f) // Fill result matrix3 based on p1-p7 matrix3[0] = p5 + p4 - p2 + p6; matrix3[1] = p1 + p2; matrix3[2] = p3 + p4; matrix3[3] = p1 + p5 - p3 - p7; } else { int subDim = dim / 2; // dim for each quadrant of the matrices int numElements = subDim * subDim; // number of elements in sub-matrices // Initialize sub-matrices double* a = new double[numElements]; // top, left quadrant of matrix1 double* b = new double[numElements]; // top, right quadrant of matrix1 double* c = new double[numElements]; // bottom, left quadrant of matrix1 double* d = new double[numElements]; // bottom, right quadrant of matrix1 double* e = new double[numElements]; // top, left quadrant of matrix2 double* f = new double[numElements]; // top, right quadrant of matrix2 double* g = new double[numElements]; // bottom, left quadrant of matrix2 double* h = new double[numElements]; // bottom, right quadrant of matrix2 double* result1 = new double[numElements]; // the result of a sub-matrix operation double* result2 = new double[numElements]; // the result of a sub-matrix operation double* m1 = new double[numElements]; // matrix with result of Strassen's eq. 1 double* m2 = new double[numElements]; // matrix with result of Strassen's eq. 2 double* m3 = new double[numElements]; // matrix with result of Strassen's eq. 3 double* m4 = new double[numElements]; // matrix with result of Strassen's eq. 4 double* m5 = new double[numElements]; // matrix with result of Strassen's eq. 5 double* m6 = new double[numElements]; // matrix with result of Strassen's eq. 6 double* m7 = new double[numElements]; // matrix with result of Strassen's eq. 7 double* quad1 = new double[numElements]; // top, left quadrant of matrix3 double* quad2 = new double[numElements]; // top, right quadrant of matrix3 double* quad3 = new double[numElements]; // bottom, left quadrant of matrix3 double* quad4 = new double[numElements]; // bottom, right quadrant of matrix3 // Fill sub-matrices a-h from matrix1 and matrix2 FillSubmatrices(matrix1, dim, a, b, c, d, subDim); FillSubmatrices(matrix2, dim, e, f, g, h, subDim); // Find matrices m1-m7 with results for equations 1-7 SubtractMatrices(f, h, result1, subDim); // f-h StrassenMult(a, result1, m1, subDim); // a(f-h) AddMatrices(a, b, result1, subDim); // a+b StrassenMult(result1, h, m2, subDim); // (a+b)h AddMatrices(c, d, result1, subDim); // c+d StrassenMult(result1, e, m3, subDim); // (c+d)e SubtractMatrices(g, e, result1, subDim); // g-e StrassenMult(d, result1, m4, subDim); // d(g-e) AddMatrices(a, d, result1, subDim); // a+d AddMatrices(e, h, result2, subDim); // e+h StrassenMult(result1, result2, m5, subDim); // (a+d)(e+h) SubtractMatrices(b, d, result1, subDim); // b-d AddMatrices(g, h, result2, subDim); // g+h StrassenMult(result1, result2, m6, subDim); // (b-d)(g+h) SubtractMatrices(a, c, result1, subDim); // a-c AddMatrices(e, f, result2, subDim); // e+f StrassenMult(result1, result2, m7, subDim); // (a-c)(e+f) // Determine quadrants of matrix3 based on m1-m7 AddMatrices(m5, m4, result1, subDim); // m5+m4 SubtractMatrices(result1, m2, result2, subDim); // m5+m4-m2 AddMatrices(result2, m6, quad1, subDim); // m5+m4-m2+m6 AddMatrices(m1, m2, quad2, subDim); // m1+m2 AddMatrices(m3, m4, quad3, subDim); // m3+m4 AddMatrices(m1, m5, result1, subDim); // m1+m5 SubtractMatrices(result1, m3, result2, subDim); // m1+m5-m3 SubtractMatrices(result2, m7, quad4, subDim); // m1+m5-m3-m7 // Fill matrix3 from quadrants FillWithQuads(quad1, quad2, quad3, quad4, subDim, matrix3, dim); // Deallocate sub-matrices delete [] a; delete [] b; delete [] c; delete [] d; delete [] e; delete [] f; delete [] g; delete [] h; delete [] result1; delete [] result2; delete [] m1; delete [] m2; delete [] m3; delete [] m4; delete [] m5; delete [] m6; delete [] m7; delete [] quad1; delete [] quad2; delete [] quad3; delete [] quad4; } } // Divide a matrix up by quadrant into 4 sub-matrices. They are // sub1, sub2, sub3, and sub4 starting in the top, left quadrant // of the matrix, going left to right, and top to bottom. void FillSubmatrices(double matrix[], int dim, double sub1[], double sub2[], double sub3[], double sub4[], int subDim) { int index1 = 0; // index of a sub-matrix 1 element int index2 = 0; // index of a sub-matrix 2 element int index3 = 0; // index of a sub-matrix 3 element int index4 = 0; // index of a sub-matrix 4 element int matrixElement = 0; // index of a matrix element for (int row=0; row<subDim; row++) for (int col=0; col<dim; col++) { if (col < subDim) { // Set sub1 element from matrix quadrant 1 sub1[index1] = matrix[matrixElement]; index1++; } else { // Set sub2 element from matrix quadrant 2 sub2[index2] = matrix[matrixElement]; index2++; } matrixElement++; } for (int row=subDim; row<dim; row++) for (int col=0; col<dim; col++) { if (col < subDim) { // Set sub3 element from matrix quadrant 3 sub3[index3] = matrix[matrixElement]; index3++; } else { // Set sub4 element from matrix quadrant 4 sub4[index4] = matrix[matrixElement]; index4++; } matrixElement++; } } // Add two matrices together into a result matrix void AddMatrices(double matrix1[], double matrix2[], double matrix3[], int dim) { for (int i=0; i<(dim*dim); i++) matrix3[i] = matrix1[i] + matrix2[i]; } // Subtract two matrices. Subtract matrix2 from matrix1 and put the difference // into a result matrix. void SubtractMatrices(double matrix1[], double matrix2[], double matrix3[], int dim) { for (int i=0; i<(dim*dim); i++) matrix3[i] = matrix1[i] - matrix2[i]; } // Display a matrix void DisplayMatrix(double matrix[], int dim) { for (int i=0; i<(dim*dim); i++) { if (i % dim == 0) // return at end of matrix line cout << endl; cout << " " << matrix[i]; } cout << endl << endl; } // Fill a matrix with elements from four separate quadrant sub-matrices void FillWithQuads(double quad1[], double quad2[], double quad3[], double quad4[], int subDim, double matrix[], int dim) { int index1 = 0; // index of a quad1 element int index2 = 0; // index of a quad2 element int index3 = 0; // index of a quad3 element int index4 = 0; // index of a quad4 element int matrixElement = 0; // index of a matrix element for (int row=0; row<subDim; row++) for (int col=0; col<dim; col++) { if (col < subDim) { // Set matrix element from quad1 matrix[matrixElement] = quad1[index1]; index1++; } else { // Set matrix element from quad2 matrix[matrixElement] = quad2[index2]; index2++; } matrixElement++; } for (int row=subDim; row<dim; row++) for (int col=0; col<dim; col++) { if (col < subDim) { // Set matrix element from quad3 matrix[matrixElement] = quad3[index3]; index3++; } else { // Set matrix element from quad4 matrix[matrixElement] = quad4[index4]; index4++; } matrixElement++; } }<|endoftext|>
<commit_before> #include "mock.hpp" #include <d2/logging.hpp> #include <algorithm> #include <boost/move/move.hpp> #include <boost/range/adaptors.hpp> #include <boost/range/algorithm.hpp> #include <cstddef> #include <ostream> #include <vector> static std::size_t const THREADS = 10; static std::size_t const NOISE_MUTEXES_PER_THREAD = 10; int main() { auto noise = [&] { std::vector<mock_mutex> mutexes(NOISE_MUTEXES_PER_THREAD); boost::for_each(mutexes, [](mock_mutex& m) { m.lock(); }); boost::for_each(mutexes | boost::adaptors::reversed, [](mock_mutex& m) { m.unlock(); }); }; mock_mutex A, B; mock_thread t0([&] { A.lock(); B.lock(); B.unlock(); A.unlock(); }); mock_thread t1([&] { B.lock(); A.lock(); A.unlock(); B.unlock(); }); std::vector<mock_thread> threads; threads.push_back(boost::move(t0)); threads.push_back(boost::move(t1)); std::generate_n(boost::back_move_inserter(threads), THREADS - 2, [&] { return mock_thread(noise); }); boost::range::random_shuffle(threads); d2::set_event_sink(&std::cout); d2::enable_event_logging(); boost::for_each(threads, [](mock_thread& t) { t.start(); }); boost::for_each(threads, [](mock_thread& t) { t.join(); }); d2::disable_event_logging(); } <commit_msg>Refactoring.<commit_after> #include "mock.hpp" #include <d2/logging.hpp> #include <algorithm> #include <boost/move/move.hpp> #include <boost/range/adaptors.hpp> #include <boost/range/algorithm.hpp> #include <cstddef> #include <ostream> #include <vector> static std::size_t const NOISE_THREADS = 10; static std::size_t const MUTEXES_PER_NOISE_THREAD = 10; int main() { auto noise = [&] { std::vector<mock_mutex> mutexes(MUTEXES_PER_NOISE_THREAD); boost::for_each(mutexes, [](mock_mutex& m) { m.lock(); }); boost::for_each(mutexes | boost::adaptors::reversed, [](mock_mutex& m) { m.unlock(); }); }; mock_mutex A, B; mock_thread t0([&] { A.lock(); B.lock(); B.unlock(); A.unlock(); }); mock_thread t1([&] { B.lock(); A.lock(); A.unlock(); B.unlock(); }); std::vector<mock_thread> threads; threads.push_back(boost::move(t0)); threads.push_back(boost::move(t1)); std::generate_n(boost::back_move_inserter(threads), NOISE_THREADS, [&] { return mock_thread(noise); }); boost::range::random_shuffle(threads); d2::set_event_sink(&std::cout); d2::enable_event_logging(); boost::for_each(threads, [](mock_thread& t) { t.start(); }); boost::for_each(threads, [](mock_thread& t) { t.join(); }); d2::disable_event_logging(); } <|endoftext|>
<commit_before>//============================================================================================================= /** * @file main.cpp * @author Lorenz Esch Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>; * Lorenz Esch <lorenz.esch@tu-ilmenau.de>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date July, 2016 * * @section LICENSE * * Copyright (C) 2016, Lorenz Esch and Matti Hamalainen. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of MNE-CPP authors nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * @brief Example of using the MNE-CPP Disp3D library * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include <disp3D/engine/view/view3D.h> #include <disp3D/engine/control/control3dwidget.h> #include <disp3D/engine/model/items/sourceactivity/mneestimatetreeitem.h> #include <disp3D/engine/model/items/sensordata/sensordatatreeitem.h> #include <disp3D/engine/model/data3Dtreemodel.h> #include <fs/surfaceset.h> #include <fs/annotationset.h> #include <mne/mne_sourceestimate.h> #include <mne/mne_bem.h> #include <fiff/fiff_dig_point_set.h> #include <inverse/minimumNorm/minimumnorm.h> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QApplication> #include <QMainWindow> #include <QCommandLineParser> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace DISP3DLIB; using namespace MNELIB; using namespace FSLIB; using namespace FIFFLIB; using namespace INVERSELIB; //************************************************************************************************************* //============================================================================================================= // MAIN //============================================================================================================= //============================================================================================================= /** * The function main marks the entry point of the program. * By default, main has the storage class extern. * * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started. * @return the value that was set to exit() (which is 0 if exit() is called via quit()). */ int main(int argc, char *argv[]) { QApplication a(argc, argv); // Command Line Parser QCommandLineParser parser; parser.setApplicationDescription("Disp3D Example"); parser.addHelpOption(); QCommandLineOption surfOption("surfType", "Surface type <type>.", "type", "inflated"); QCommandLineOption annotOption("annotType", "Annotation type <type>.", "type", "aparc.a2009s"); QCommandLineOption hemiOption("hemi", "Selected hemisphere <hemi>.", "hemi", "2"); QCommandLineOption subjectOption("subject", "Selected subject <subject>.", "subject", "sample"); QCommandLineOption subjectPathOption("subjectPath", "Selected subject path <subjectPath>.", "subjectPath", "./MNE-sample-data/subjects"); QCommandLineOption sourceLocOption("doSourceLoc", "Do real time source localization.", "doSourceLoc", "true"); QCommandLineOption fwdOption("fwd", "Path to forwad solution <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif"); QCommandLineOption invOpOption("inv", "Path to inverse operator <file>.", "file", ""); QCommandLineOption clustOption("doClust", "Path to clustered inverse operator <doClust>.", "doClust", "true"); QCommandLineOption covFileOption("cov", "Path to the covariance <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis-cov.fif"); QCommandLineOption evokedFileOption("ave", "Path to the evoked/average <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis-ave.fif"); QCommandLineOption methodOption("method", "Inverse estimation <method>, i.e., 'MNE', 'dSPM' or 'sLORETA'.", "method", "dSPM");//"MNE" | "dSPM" | "sLORETA" QCommandLineOption snrOption("snr", "The SNR value used for computation <snr>.", "snr", "3.0");//3.0;//0.1;//3.0; QCommandLineOption evokedIndexOption("aveIdx", "The average <index> to choose from the average file.", "index", "3"); parser.addOption(surfOption); parser.addOption(annotOption); parser.addOption(hemiOption); parser.addOption(subjectOption); parser.addOption(subjectPathOption); parser.addOption(sourceLocOption); parser.addOption(fwdOption); parser.addOption(invOpOption); parser.addOption(clustOption); parser.addOption(covFileOption); parser.addOption(evokedFileOption); parser.addOption(methodOption); parser.addOption(snrOption); parser.addOption(evokedIndexOption); parser.process(a); bool bAddRtSourceLoc = false; if(parser.value(sourceLocOption) == "false" || parser.value(sourceLocOption) == "0") { bAddRtSourceLoc = false; } else if(parser.value(sourceLocOption) == "true" || parser.value(sourceLocOption) == "1") { bAddRtSourceLoc = true; } bool bDoClustering = false; if(parser.value(clustOption) == "false" || parser.value(clustOption) == "0") { bDoClustering = false; } else if(parser.value(clustOption) == "true" || parser.value(clustOption) == "1") { bDoClustering = true; } //Inits SurfaceSet tSurfSet (parser.value(subjectOption), parser.value(hemiOption).toInt(), parser.value(surfOption), parser.value(subjectPathOption)); AnnotationSet tAnnotSet (parser.value(subjectOption), parser.value(hemiOption).toInt(), parser.value(annotOption), parser.value(subjectPathOption)); QFile t_fileFwd(parser.value(fwdOption)); MNEForwardSolution t_Fwd(t_fileFwd); MNEForwardSolution t_clusteredFwd; QString t_sFileClusteredInverse(parser.value(invOpOption)); QFile t_fileCov(parser.value(covFileOption)); QFile t_fileEvoked(parser.value(evokedFileOption)); //######################################################################################## // // Source Estimate START // //######################################################################################## // Load data QPair<QVariant, QVariant> baseline(QVariant(), 0); MNESourceEstimate sourceEstimate; FiffEvoked evoked(t_fileEvoked, parser.value(evokedIndexOption).toInt(), baseline); if(bAddRtSourceLoc) { double snr = parser.value(snrOption).toDouble(); double lambda2 = 1.0 / pow(snr, 2); QString method(parser.value(methodOption)); // Load data t_fileEvoked.close(); if(evoked.isEmpty()) return 1; std::cout << std::endl; std::cout << "Evoked description: " << evoked.comment.toUtf8().constData() << std::endl; if(t_Fwd.isEmpty()) return 1; FiffCov noise_cov(t_fileCov); // regularize noise covariance noise_cov = noise_cov.regularize(evoked.info, 0.05, 0.05, 0.1, true); // // Cluster forward solution; // if(bDoClustering) { t_clusteredFwd = t_Fwd.cluster_forward_solution(tAnnotSet, 40); } else { t_clusteredFwd = t_Fwd; } // // make an inverse operators // FiffInfo info = evoked.info; MNEInverseOperator inverse_operator(info, t_clusteredFwd, noise_cov, 0.2f, 0.8f); if(!t_sFileClusteredInverse.isEmpty()) { QFile t_fileClusteredInverse(t_sFileClusteredInverse); inverse_operator.write(t_fileClusteredInverse); } // // Compute inverse solution // MinimumNorm minimumNorm(inverse_operator, lambda2, method); sourceEstimate = minimumNorm.calculateInverse(evoked); if(sourceEstimate.isEmpty()) return 1; // View activation time-series std::cout << "\nsourceEstimate:\n" << sourceEstimate.data.block(0,0,10,10) << std::endl; std::cout << "time\n" << sourceEstimate.times.block(0,0,1,10) << std::endl; std::cout << "timeMin\n" << sourceEstimate.times[0] << std::endl; std::cout << "timeMax\n" << sourceEstimate.times[sourceEstimate.times.size()-1] << std::endl; std::cout << "time step\n" << sourceEstimate.tstep << std::endl; } //######################################################################################## // //Source Estimate END // //######################################################################################## //Create 3D data model Data3DTreeModel::SPtr p3DDataModel = Data3DTreeModel::SPtr(new Data3DTreeModel()); //Add fressurfer surface set including both hemispheres p3DDataModel->addSurfaceSet(parser.value(subjectOption), "MRI", tSurfSet, tAnnotSet); //Read and show BEM QFile t_fileBem("./MNE-sample-data/subjects/sample/bem/sample-head.fif"); MNEBem t_Bem(t_fileBem); p3DDataModel->addBemData(parser.value(subjectOption), "BEM", t_Bem); //Read and show sensor helmets QFile t_filesensorSurfaceVV("./resources/sensorSurfaces/306m_rt.fif"); MNEBem t_sensorSurfaceVV(t_filesensorSurfaceVV); p3DDataModel->addMegSensorInfo("Sensors", "VectorView", t_sensorSurfaceVV, evoked.info.chs); // Read & show digitizer points QFile t_fileDig("./MNE-sample-data/MEG/sample/sample_audvis-ave.fif"); FiffDigPointSet t_Dig(t_fileDig); p3DDataModel->addDigitizerData(parser.value(subjectOption), evoked.comment, t_Dig); // // example matrix, for 60 sensors (passed fiff evoked object holds 60 EEG sensors) and for 1000 values per sensor // MatrixXd temp(306, 1000); // for (int row = 0; row < temp.rows(); ++row) { // for (int col = 0; col < temp.cols(); ++col) { // temp(row, col) = (10 * sin((float) col * (2 * 3.141592f / 500)) + 10) / 2; // } // } // //add sensor item for MEG data // if (SensorDataTreeItem* ourItem = p3DDataModel->addSensorData("Sensors", "Measurment Data", evoked.data, t_sensorSurfaceVV[0], evoked, "MEG")) { // ourItem->setLoopState(true); // ourItem->setTimeInterval(17); // ourItem->setNumberAverages(1); // ourItem->setStreamingActive(false); // ourItem->setNormalization(QVector3D(0.0, 0.5, 1.0)); // ourItem->setColortable("Hot"); // } //add sensor item for EEG data if (SensorDataTreeItem* ourItem = p3DDataModel->addSensorData(parser.value(subjectOption), evoked.comment, evoked.data, t_Bem[0], evoked, "EEG")) { ourItem->setLoopState(true); ourItem->setTimeInterval(17); ourItem->setNumberAverages(1); ourItem->setStreamingActive(false); ourItem->setNormalization(QVector3D(0.0, 0.5, 1.0)); ourItem->setColortable("Hot"); } if(bAddRtSourceLoc) { //Add rt source loc data and init some visualization values if(MneEstimateTreeItem* pRTDataItem = p3DDataModel->addSourceData(parser.value(subjectOption), evoked.comment, sourceEstimate, t_clusteredFwd)) { pRTDataItem->setLoopState(true); pRTDataItem->setTimeInterval(17); pRTDataItem->setNumberAverages(1); pRTDataItem->setStreamingActive(false); pRTDataItem->setNormalization(QVector3D(0.0,0.5,10.0)); pRTDataItem->setVisualizationType("Smoothing based"); pRTDataItem->setColortable("Hot"); } } //Create the 3D view View3D::SPtr testWindow = View3D::SPtr(new View3D()); testWindow->setModel(p3DDataModel); testWindow->show(); Control3DWidget::SPtr control3DWidget = Control3DWidget::SPtr(new Control3DWidget()); control3DWidget->init(p3DDataModel, testWindow); control3DWidget->show(); return a.exec(); } <commit_msg>[SWP-24] Added better normalization thresholds and a FiffPointSet to test sensorProjecting<commit_after>//============================================================================================================= /** * @file main.cpp * @author Lorenz Esch Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>; * Lorenz Esch <lorenz.esch@tu-ilmenau.de>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date July, 2016 * * @section LICENSE * * Copyright (C) 2016, Lorenz Esch and Matti Hamalainen. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of MNE-CPP authors nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * @brief Example of using the MNE-CPP Disp3D library * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include <disp3D/engine/view/view3D.h> #include <disp3D/engine/control/control3dwidget.h> #include <disp3D/engine/model/items/sourceactivity/mneestimatetreeitem.h> #include <disp3D/engine/model/items/sensordata/sensordatatreeitem.h> #include <disp3D/engine/model/data3Dtreemodel.h> #include <fs/surfaceset.h> #include <fs/annotationset.h> #include <mne/mne_sourceestimate.h> #include <mne/mne_bem.h> #include <fiff/fiff_dig_point_set.h> #include <inverse/minimumNorm/minimumnorm.h> #include <geometryInfo/geometryinfo.h> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QApplication> #include <QMainWindow> #include <QCommandLineParser> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace DISP3DLIB; using namespace MNELIB; using namespace FSLIB; using namespace FIFFLIB; using namespace INVERSELIB; using namespace GEOMETRYINFO; //************************************************************************************************************* //============================================================================================================= // MAIN //============================================================================================================= //============================================================================================================= /** * The function main marks the entry point of the program. * By default, main has the storage class extern. * * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started. * @return the value that was set to exit() (which is 0 if exit() is called via quit()). */ int main(int argc, char *argv[]) { QApplication a(argc, argv); // Command Line Parser QCommandLineParser parser; parser.setApplicationDescription("Disp3D Example"); parser.addHelpOption(); QCommandLineOption surfOption("surfType", "Surface type <type>.", "type", "inflated"); QCommandLineOption annotOption("annotType", "Annotation type <type>.", "type", "aparc.a2009s"); QCommandLineOption hemiOption("hemi", "Selected hemisphere <hemi>.", "hemi", "2"); QCommandLineOption subjectOption("subject", "Selected subject <subject>.", "subject", "sample"); QCommandLineOption subjectPathOption("subjectPath", "Selected subject path <subjectPath>.", "subjectPath", "./MNE-sample-data/subjects"); QCommandLineOption sourceLocOption("doSourceLoc", "Do real time source localization.", "doSourceLoc", "true"); QCommandLineOption fwdOption("fwd", "Path to forwad solution <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif"); QCommandLineOption invOpOption("inv", "Path to inverse operator <file>.", "file", ""); QCommandLineOption clustOption("doClust", "Path to clustered inverse operator <doClust>.", "doClust", "true"); QCommandLineOption covFileOption("cov", "Path to the covariance <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis-cov.fif"); QCommandLineOption evokedFileOption("ave", "Path to the evoked/average <file>.", "file", "./MNE-sample-data/MEG/sample/sample_audvis-ave.fif"); QCommandLineOption methodOption("method", "Inverse estimation <method>, i.e., 'MNE', 'dSPM' or 'sLORETA'.", "method", "dSPM");//"MNE" | "dSPM" | "sLORETA" QCommandLineOption snrOption("snr", "The SNR value used for computation <snr>.", "snr", "3.0");//3.0;//0.1;//3.0; QCommandLineOption evokedIndexOption("aveIdx", "The average <index> to choose from the average file.", "index", "3"); parser.addOption(surfOption); parser.addOption(annotOption); parser.addOption(hemiOption); parser.addOption(subjectOption); parser.addOption(subjectPathOption); parser.addOption(sourceLocOption); parser.addOption(fwdOption); parser.addOption(invOpOption); parser.addOption(clustOption); parser.addOption(covFileOption); parser.addOption(evokedFileOption); parser.addOption(methodOption); parser.addOption(snrOption); parser.addOption(evokedIndexOption); parser.process(a); bool bAddRtSourceLoc = false; if(parser.value(sourceLocOption) == "false" || parser.value(sourceLocOption) == "0") { bAddRtSourceLoc = false; } else if(parser.value(sourceLocOption) == "true" || parser.value(sourceLocOption) == "1") { bAddRtSourceLoc = true; } bool bDoClustering = false; if(parser.value(clustOption) == "false" || parser.value(clustOption) == "0") { bDoClustering = false; } else if(parser.value(clustOption) == "true" || parser.value(clustOption) == "1") { bDoClustering = true; } //Inits SurfaceSet tSurfSet (parser.value(subjectOption), parser.value(hemiOption).toInt(), parser.value(surfOption), parser.value(subjectPathOption)); AnnotationSet tAnnotSet (parser.value(subjectOption), parser.value(hemiOption).toInt(), parser.value(annotOption), parser.value(subjectPathOption)); QFile t_fileFwd(parser.value(fwdOption)); MNEForwardSolution t_Fwd(t_fileFwd); MNEForwardSolution t_clusteredFwd; QString t_sFileClusteredInverse(parser.value(invOpOption)); QFile t_fileCov(parser.value(covFileOption)); QFile t_fileEvoked(parser.value(evokedFileOption)); //######################################################################################## // // Source Estimate START // //######################################################################################## // Load data QPair<QVariant, QVariant> baseline(QVariant(), 0); MNESourceEstimate sourceEstimate; FiffEvoked evoked(t_fileEvoked, parser.value(evokedIndexOption).toInt(), baseline); if(bAddRtSourceLoc) { double snr = parser.value(snrOption).toDouble(); double lambda2 = 1.0 / pow(snr, 2); QString method(parser.value(methodOption)); // Load data t_fileEvoked.close(); if(evoked.isEmpty()) return 1; std::cout << std::endl; std::cout << "Evoked description: " << evoked.comment.toUtf8().constData() << std::endl; if(t_Fwd.isEmpty()) return 1; FiffCov noise_cov(t_fileCov); // regularize noise covariance noise_cov = noise_cov.regularize(evoked.info, 0.05, 0.05, 0.1, true); // // Cluster forward solution; // if(bDoClustering) { t_clusteredFwd = t_Fwd.cluster_forward_solution(tAnnotSet, 40); } else { t_clusteredFwd = t_Fwd; } // // make an inverse operators // FiffInfo info = evoked.info; MNEInverseOperator inverse_operator(info, t_clusteredFwd, noise_cov, 0.2f, 0.8f); if(!t_sFileClusteredInverse.isEmpty()) { QFile t_fileClusteredInverse(t_sFileClusteredInverse); inverse_operator.write(t_fileClusteredInverse); } // // Compute inverse solution // MinimumNorm minimumNorm(inverse_operator, lambda2, method); sourceEstimate = minimumNorm.calculateInverse(evoked); if(sourceEstimate.isEmpty()) return 1; // View activation time-series std::cout << "\nsourceEstimate:\n" << sourceEstimate.data.block(0,0,10,10) << std::endl; std::cout << "time\n" << sourceEstimate.times.block(0,0,1,10) << std::endl; std::cout << "timeMin\n" << sourceEstimate.times[0] << std::endl; std::cout << "timeMax\n" << sourceEstimate.times[sourceEstimate.times.size()-1] << std::endl; std::cout << "time step\n" << sourceEstimate.tstep << std::endl; } //######################################################################################## // //Source Estimate END // //######################################################################################## //Create 3D data model Data3DTreeModel::SPtr p3DDataModel = Data3DTreeModel::SPtr(new Data3DTreeModel()); //Add fressurfer surface set including both hemispheres p3DDataModel->addSurfaceSet(parser.value(subjectOption), "MRI", tSurfSet, tAnnotSet); //Read and show BEM QFile t_fileBem("./MNE-sample-data/subjects/sample/bem/sample-head.fif"); MNEBem t_Bem(t_fileBem); p3DDataModel->addBemData(parser.value(subjectOption), "BEM", t_Bem); //Read and show sensor helmets QFile t_filesensorSurfaceVV("./resources/sensorSurfaces/306m_rt.fif"); MNEBem t_sensorSurfaceVV(t_filesensorSurfaceVV); p3DDataModel->addMegSensorInfo("Sensors", "VectorView", t_sensorSurfaceVV, evoked.info.chs); // Read & show digitizer points QFile t_fileDig("./MNE-sample-data/MEG/sample/sample_audvis-ave.fif"); FiffDigPointSet t_Dig(t_fileDig); p3DDataModel->addDigitizerData(parser.value(subjectOption), evoked.comment, t_Dig); //############################################### FiffDigPointSet testPointSet; // positions of EEG and MEG sensors QVector<Vector3f> eegSensors; QVector<Vector3f> megSensors; //currently not used //fill both QVectors with the right sensor positions for( const FiffChInfo &info : evoked.info.chs) { //EEG if(info.kind == FIFFV_EEG_CH) { eegSensors.push_back(info.chpos.r0); } //MEG if(info.kind == FIFFV_MEG_CH) { megSensors.push_back(info.chpos.r0); } } QSharedPointer<QVector<qint32>> mappedSubSet = GeometryInfo::projectSensor(t_Bem[0], eegSensors); for(int i = 0; i < mappedSubSet->size(); i++) { FiffDigPoint tempPoint; tempPoint.r[0] = t_Bem[0].rr(mappedSubSet->at(i), 0); tempPoint.r[1] = t_Bem[0].rr(mappedSubSet->at(i), 1); tempPoint.r[2] = t_Bem[0].rr(mappedSubSet->at(i), 2); tempPoint.kind = FIFFV_POINT_HPI; testPointSet << tempPoint; } p3DDataModel->addDigitizerData("test", evoked.comment, testPointSet); //############################################### // // example matrix, for 60 sensors (passed fiff evoked object holds 60 EEG sensors) and for 1000 values per sensor // MatrixXd temp(306, 1000); // for (int row = 0; row < temp.rows(); ++row) { // for (int col = 0; col < temp.cols(); ++col) { // temp(row, col) = (10 * sin((float) col * (2 * 3.141592f / 500)) + 10) / 2; // } // } // //add sensor item for MEG data // if (SensorDataTreeItem* pMegSensorTreeItem = p3DDataModel->addSensorData("Sensors", "Measurment Data", evoked.data, t_sensorSurfaceVV[0], evoked, "MEG")) { // pMegSensorTreeItem->setLoopState(true); // pMegSensorTreeItem->setTimeInterval(17); // pMegSensorTreeItem->setNumberAverages(1); // pMegSensorTreeItem->setStreamingActive(false); // pMegSensorTreeItem->setNormalization(QVector3D(0.0, 0.5, 1.0)); // pMegSensorTreeItem->setColortable("Hot"); // } //add sensor item for EEG data if (SensorDataTreeItem* pEegSensorTreeItem = p3DDataModel->addSensorData(parser.value(subjectOption), evoked.comment, evoked.data, t_Bem[0], evoked, "EEG")) { pEegSensorTreeItem->setLoopState(true); pEegSensorTreeItem->setTimeInterval(17); pEegSensorTreeItem->setNumberAverages(1); pEegSensorTreeItem->setStreamingActive(false); pEegSensorTreeItem->setNormalization(QVector3D(-8.09203e-13, -5.54059e-13, 8.22682e-13)); pEegSensorTreeItem->setColortable("Hot"); } if(bAddRtSourceLoc) { //Add rt source loc data and init some visualization values if(MneEstimateTreeItem* pRTDataItem = p3DDataModel->addSourceData(parser.value(subjectOption), evoked.comment, sourceEstimate, t_clusteredFwd)) { pRTDataItem->setLoopState(true); pRTDataItem->setTimeInterval(17); pRTDataItem->setNumberAverages(1); pRTDataItem->setStreamingActive(false); pRTDataItem->setNormalization(QVector3D(0.0,0.5,10.0)); pRTDataItem->setVisualizationType("Smoothing based"); pRTDataItem->setColortable("Hot"); } } //Create the 3D view View3D::SPtr testWindow = View3D::SPtr(new View3D()); testWindow->setModel(p3DDataModel); testWindow->show(); Control3DWidget::SPtr control3DWidget = Control3DWidget::SPtr(new Control3DWidget()); control3DWidget->init(p3DDataModel, testWindow); control3DWidget->show(); return a.exec(); } <|endoftext|>
<commit_before> #include <stdio.h> #include <dpdk/dpdk.h> uint8_t port0_mac[6]; uint8_t port1_mac[6]; constexpr size_t n_queues = 4; int l2fwd(void*) { const size_t n_ports = rte_eth_dev_count(); while (true) { for (size_t pid=0; pid<n_ports; pid++) { for (size_t qid=0; qid<n_queues; qid++) { constexpr size_t BURSTSZ = 32; rte_mbuf* mbufs[BURSTSZ]; size_t nb_recv = rte_eth_rx_burst(pid, qid, mbufs, BURSTSZ); if (nb_recv == 0) continue; for (size_t i=0; i<nb_recv; i++) { if (pid==0) { // printf("0->1\n"); // uint8_t dst[] = { 0xa0, 0x36, 0x9f, 0x3e, 0xa0, 0x8a }; uint8_t dst[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; uint8_t* p = rte_pktmbuf_mtod(mbufs[i], uint8_t*); memcpy(p+0, dst, 6); memcpy(p+6, port1_mac, 6); } else if (pid==1) { // printf("1->0\n"); // uint8_t dst[] = { 0xa0, 0x36, 0x9f, 0x3e, 0x7b, 0x7a }; uint8_t dst[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; uint8_t* p = rte_pktmbuf_mtod(mbufs[i], uint8_t*); memcpy(p+0, dst, 6); memcpy(p+6, port0_mac, 6); } rte_eth_tx_burst(pid^1, qid, &mbufs[i], 1); } } } } } inline std::string print_mac(uint8_t* addr) { std::string s; for (size_t i=0; i<6; i++) { s += dpdk::format("%02x%s", addr[i], i<5?":":""); } return s; } int main(int argc, char** argv) { dpdk::dpdk_boot(argc, argv); struct rte_eth_conf port_conf; dpdk::init_portconf(&port_conf); struct rte_mempool* mp = dpdk::mp_alloc("RXMBUFMP"); size_t n_ports = rte_eth_dev_count(); if (n_ports == 0) throw dpdk::exception("no ethdev"); printf("%zd ports found \n", n_ports); for (size_t i=0; i<n_ports; i++) { dpdk::port_configure(i, n_queues, n_queues, &port_conf, mp); } rte_eth_macaddr_get(0, (ether_addr*)port0_mac); rte_eth_macaddr_get(1, (ether_addr*)port1_mac); printf("port0: %s \n", print_mac(port0_mac).c_str()); printf("port1: %s \n", print_mac(port1_mac).c_str()); l2fwd(nullptr); // rte_eal_remote_launch(l2fwd, nullptr, 1); // rte_eal_mp_wait_lcore(); } <commit_msg>2017.12.19-17:33<commit_after> #include <stdio.h> #include <dpdk/dpdk.h> struct ether_addr dst[2]; struct ether_addr src[2]; constexpr size_t n_queues = 4; int l2fwd(void*) { const size_t n_ports = rte_eth_dev_count(); while (true) { for (size_t pid=0; pid<n_ports; pid++) { for (size_t qid=0; qid<n_queues; qid++) { constexpr size_t BURSTSZ = 32; rte_mbuf* mbufs[BURSTSZ]; size_t nb_recv = rte_eth_rx_burst(pid, qid, mbufs, BURSTSZ); if (nb_recv == 0) continue; for (size_t i=0; i<nb_recv; i++) { uint8_t* p = rte_pktmbuf_mtod(mbufs[i], uint8_t*); memcpy(p+0, &src[pid], 6); memcpy(p+6, &dst[pid], 6); } rte_eth_tx_burst(pid^1, qid, mbufs, nb_recv); } } } } std::string to_str(const ether_addr* addr) { std::string s; for (size_t i=0; i<6; i++) { s += dpdk::format("%02x%s", addr->addr_bytes[i], i<5?":":""); } return s; } int main(int argc, char** argv) { dpdk::dpdk_boot(argc, argv); struct rte_eth_conf port_conf; dpdk::init_portconf(&port_conf); struct rte_mempool* mp = dpdk::mp_alloc("RXMBUFMP", 0, 8192); size_t n_ports = rte_eth_dev_count(); if (n_ports == 0) throw dpdk::exception("no ethdev"); printf("%zd ports found \n", n_ports); for (size_t i=0; i<n_ports; i++) { dpdk::port_configure(i, n_queues, n_queues, &port_conf, mp); } dst[0].addr_bytes[0] = 0x33; dst[0].addr_bytes[1] = 0x33; dst[0].addr_bytes[2] = 0x33; dst[0].addr_bytes[3] = 0x33; dst[0].addr_bytes[4] = 0x33; dst[0].addr_bytes[5] = 0x33; dst[1].addr_bytes[0] = 0xa0; dst[1].addr_bytes[1] = 0x36; dst[1].addr_bytes[2] = 0x9f; dst[1].addr_bytes[3] = 0x39; dst[1].addr_bytes[4] = 0x10; dst[1].addr_bytes[5] = 0x4c; rte_eth_macaddr_get(0, &src[0]); rte_eth_macaddr_get(1, &src[1]); printf("flow[0->1]: %s -> %s \n", to_str(&src[0]).c_str(), to_str(&dst[0]).c_str()); printf("flow[1->0]: %s -> %s \n", to_str(&src[1]).c_str(), to_str(&dst[1]).c_str()); rte_eal_remote_launch(l2fwd, nullptr, 1); rte_eal_mp_wait_lcore(); } <|endoftext|>
<commit_before>#include <algorithm> #include <iostream> #include <sstream> #include <vector> #include "math.h" #include "visualizer.hpp" #include "setupAide.hpp" #include "occa.hpp" #include "occa/array.hpp" #if OCCA_GL_ENABLED visualizer vis; GLuint screenTexID; #endif setupAide setup; const tFloat DEPTH_OF_FIELD = 2.5; const tFloat EYE_DISTANCE_FROM_NEAR_FIELD = 2.2; const tFloat DEG_TO_RAD = (M_PI / 180.0); tFloat viewAngle = 150.0 * DEG_TO_RAD; tFloat lightAngle = 0; tFloat3 lightDirection; tFloat3 viewDirectionY, viewDirectionX; tFloat3 nearFieldLocation; tFloat3 eyeLocation; int frame = 0; int width, height; int batchSize; tFloat pixel, halfPixel; double startTime, endTime; std::string deviceInfo; occa::kernel rayMarcher; occa::array<char> rgba; inline tFloat3 ortho(const tFloat3 &v) { const tFloat inv = 1.0 / sqrt(v.x*v.x + v.z*v.z); return tFloat3(-inv*v.z, v.y, inv*v.x); } void readSetupFile(); void setupRenderer(); void setupOCCA(); void setupGL(); void updateScene(); void render(); void updateRGB(); tFloat castShadow(const tFloat3 &rayLocation, const tFloat min, const tFloat max, const tFloat k); std::string shapeFunction; #if OCCA_GL_ENABLED void glRun(); #endif int main(int argc, char **argv) { readSetupFile(); updateScene(); setupOCCA(); #if OCCA_GL_ENABLED glRun(); #else while(true) { const double frameStartTime = occa::currentTime(); if (frame % 360 == 0) startTime = frameStartTime; rayMarcher(rgba, lightDirection, viewDirectionY, viewDirectionX, nearFieldLocation, eyeLocation); occa::finish(); const double frameEndTime = occa::currentTime(); std::cout << "Time Taken (Frame): " << (frameEndTime - frameStartTime) << '\r'; if (frame % 360 == 355) { endTime = frameEndTime; std::cout << "Time Taken (Cycle): " << (endTime - startTime) << '\n'; } ++frame; updateScene(); } #endif return 0; } #if OCCA_GL_ENABLED void glRun() { vis.setup("Raytracer Demo", width, height); vis.setExternalFunction(render); vis.createViewports(1,1); vis.getViewport(0,0).light_f = false; vis.getViewport(0,0).hasCamera_f = false; vis.setOutlineColor(0, 0, 0); vis.setBackground(0, 0, (GLfloat) 0, (GLfloat) 0, (GLfloat) 0); vis.pause(0, 0); setupRenderer(); vis.start(); } #endif void readSetupFile() { setup.read("setuprc"); setup.getArgs("DEVICE INFO", deviceInfo); setup.getArgs("SHAPE FUNCTION", shapeFunction); setup.getArgs("WIDTH" , width); setup.getArgs("HEIGHT", height); setup.getArgs("BATCH_SIZE", batchSize); std::cout << "DEVICE INFO = " << deviceInfo << '\n' << "SHAPE FUNCTION = " << shapeFunction << '\n' << "WIDTH = " << width << '\n' << "HEIGHT = " << height << '\n'; } void updateScene() { ++frame; lightAngle += DEG_TO_RAD; viewAngle += DEG_TO_RAD; const tFloat3 lightLocation = tFloat3(0.5 * DEPTH_OF_FIELD * cos(lightAngle), 0.5 * DEPTH_OF_FIELD, 0.5 * DEPTH_OF_FIELD * sin(lightAngle)); nearFieldLocation = tFloat3(0.5 * DEPTH_OF_FIELD * cos(viewAngle), 0, 0.5 * DEPTH_OF_FIELD * sin(viewAngle)); const tFloat3 viewDirection = -occa::normalize(nearFieldLocation); lightDirection = occa::normalize(lightLocation); viewDirectionX = ortho(viewDirection); viewDirectionY = occa::cross(viewDirectionX, viewDirection); eyeLocation = nearFieldLocation - (EYE_DISTANCE_FROM_NEAR_FIELD * viewDirection); // NF - ReverseLocation pixel = DEPTH_OF_FIELD / (0.5*(height + width)); halfPixel = 0.5 * pixel; } void setupOCCA() { occa::setDevice(deviceInfo); rgba.allocate(4, width, height); for(int x = 0; x < width; ++x) { for(int y = 0; y < height; ++y) { rgba(3,x,y) = 255; } } occa::kernelInfo kInfo; kInfo.addDefine("WIDTH" , width); kInfo.addDefine("HEIGHT" , height); kInfo.addDefine("BATCH_SIZE" , batchSize); kInfo.addDefine("SHAPE_FUNCTION", shapeFunction); kInfo.addDefine("PIXEL" , pixel); kInfo.addDefine("HALF_PIXEL" , halfPixel); if (sizeof(tFloat) == sizeof(float)) { kInfo.addDefine("tFloat" , "float"); kInfo.addDefine("tFloat3", "float3"); } else { kInfo.addDefine("tFloat" , "double"); kInfo.addDefine("tFloat3", "double3"); } rayMarcher = occa::buildKernel("rayMarcher.okl", "rayMarcher", kInfo); } #if OCCA_GL_ENABLED void setupRenderer() { glEnable(GL_TEXTURE_2D); glGenTextures(1, &screenTexID); glBindTexture(GL_TEXTURE_2D, screenTexID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glDisable(GL_TEXTURE_2D); } void render() { vis.placeViewport(0,0); rayMarcher(rgba, lightDirection, viewDirectionY, viewDirectionX, nearFieldLocation, eyeLocation); occa::finish(); updateScene(); glColor3f(1.0, 1.0, 1.0); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, screenTexID); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, rgba.data()); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex2f(-1,-1); glTexCoord2f(1.0, 0.0); glVertex2f( 1,-1); glTexCoord2f(1.0, 1.0); glVertex2f( 1, 1); glTexCoord2f(0.0, 1.0); glVertex2f(-1, 1); glEnd(); glDisable(GL_TEXTURE_2D); } #endif void updateRGB() { } <commit_msg>[Examples/Mandelbulb] Prints cycle time<commit_after>#include <algorithm> #include <iostream> #include <sstream> #include <vector> #include "math.h" #include "visualizer.hpp" #include "setupAide.hpp" #include "occa.hpp" #include "occa/array.hpp" #if OCCA_GL_ENABLED visualizer vis; GLuint screenTexID; #endif setupAide setup; const tFloat DEPTH_OF_FIELD = 2.5; const tFloat EYE_DISTANCE_FROM_NEAR_FIELD = 2.2; const tFloat DEG_TO_RAD = (M_PI / 180.0); tFloat viewAngle = 150.0 * DEG_TO_RAD; tFloat lightAngle = 0; tFloat3 lightDirection; tFloat3 viewDirectionY, viewDirectionX; tFloat3 nearFieldLocation; tFloat3 eyeLocation; int frame = 0; int width, height; int batchSize; tFloat pixel, halfPixel; double startTime, endTime; std::string deviceInfo; occa::kernel rayMarcher; occa::array<char> rgba; inline tFloat3 ortho(const tFloat3 &v) { const tFloat inv = 1.0 / sqrt(v.x*v.x + v.z*v.z); return tFloat3(-inv*v.z, v.y, inv*v.x); } void readSetupFile(); void setupRenderer(); void setupOCCA(); void setupGL(); void updateScene(); void render(); void updateRGB(); tFloat castShadow(const tFloat3 &rayLocation, const tFloat min, const tFloat max, const tFloat k); std::string shapeFunction; #if OCCA_GL_ENABLED void glRun(); #endif int main(int argc, char **argv) { readSetupFile(); updateScene(); setupOCCA(); startTime = occa::currentTime(); #if OCCA_GL_ENABLED glRun(); #else while(true) { const double frameStartTime = occa::currentTime(); rayMarcher(rgba, lightDirection, viewDirectionY, viewDirectionX, nearFieldLocation, eyeLocation); occa::finish(); const double frameEndTime = occa::currentTime(); std::cout << "Time Taken (Frame): " << (frameEndTime - frameStartTime) << '\n'; if (frame % 360 == 359) { endTime = frameEndTime; std::cout << "Time Taken (Cycle): " << (endTime - startTime) << '\n'; break; } ++frame; updateScene(); } #endif return 0; } #if OCCA_GL_ENABLED void glRun() { vis.setup("Raytracer Demo", width, height); vis.setExternalFunction(render); vis.createViewports(1,1); vis.getViewport(0,0).light_f = false; vis.getViewport(0,0).hasCamera_f = false; vis.setOutlineColor(0, 0, 0); vis.setBackground(0, 0, (GLfloat) 0, (GLfloat) 0, (GLfloat) 0); vis.pause(0, 0); setupRenderer(); vis.start(); } #endif void readSetupFile() { setup.read("setuprc"); setup.getArgs("DEVICE INFO", deviceInfo); setup.getArgs("SHAPE FUNCTION", shapeFunction); setup.getArgs("WIDTH" , width); setup.getArgs("HEIGHT", height); setup.getArgs("BATCH_SIZE", batchSize); std::cout << "DEVICE INFO = " << deviceInfo << '\n' << "SHAPE FUNCTION = " << shapeFunction << '\n' << "WIDTH = " << width << '\n' << "HEIGHT = " << height << '\n'; } void updateScene() { ++frame; lightAngle += DEG_TO_RAD; viewAngle += DEG_TO_RAD; const tFloat3 lightLocation = tFloat3(0.5 * DEPTH_OF_FIELD * cos(lightAngle), 0.5 * DEPTH_OF_FIELD, 0.5 * DEPTH_OF_FIELD * sin(lightAngle)); nearFieldLocation = tFloat3(0.5 * DEPTH_OF_FIELD * cos(viewAngle), 0, 0.5 * DEPTH_OF_FIELD * sin(viewAngle)); const tFloat3 viewDirection = -occa::normalize(nearFieldLocation); lightDirection = occa::normalize(lightLocation); viewDirectionX = ortho(viewDirection); viewDirectionY = occa::cross(viewDirectionX, viewDirection); eyeLocation = nearFieldLocation - (EYE_DISTANCE_FROM_NEAR_FIELD * viewDirection); // NF - ReverseLocation pixel = DEPTH_OF_FIELD / (0.5*(height + width)); halfPixel = 0.5 * pixel; } void setupOCCA() { occa::setDevice(deviceInfo); rgba.allocate(4, width, height); for(int x = 0; x < width; ++x) { for(int y = 0; y < height; ++y) { rgba(3,x,y) = 255; } } occa::kernelInfo kInfo; kInfo.addDefine("WIDTH" , width); kInfo.addDefine("HEIGHT" , height); kInfo.addDefine("BATCH_SIZE" , batchSize); kInfo.addDefine("SHAPE_FUNCTION", shapeFunction); kInfo.addDefine("PIXEL" , pixel); kInfo.addDefine("HALF_PIXEL" , halfPixel); if (sizeof(tFloat) == sizeof(float)) { kInfo.addDefine("tFloat" , "float"); kInfo.addDefine("tFloat3", "float3"); } else { kInfo.addDefine("tFloat" , "double"); kInfo.addDefine("tFloat3", "double3"); } rayMarcher = occa::buildKernel("rayMarcher.okl", "rayMarcher", kInfo); } #if OCCA_GL_ENABLED void setupRenderer() { glEnable(GL_TEXTURE_2D); glGenTextures(1, &screenTexID); glBindTexture(GL_TEXTURE_2D, screenTexID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glDisable(GL_TEXTURE_2D); } void render() { vis.placeViewport(0,0); rayMarcher(rgba, lightDirection, viewDirectionY, viewDirectionX, nearFieldLocation, eyeLocation); occa::finish(); updateScene(); glColor3f(1.0, 1.0, 1.0); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, screenTexID); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, rgba.data()); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex2f(-1,-1); glTexCoord2f(1.0, 0.0); glVertex2f( 1,-1); glTexCoord2f(1.0, 1.0); glVertex2f( 1, 1); glTexCoord2f(0.0, 1.0); glVertex2f(-1, 1); glEnd(); glDisable(GL_TEXTURE_2D); } #endif void updateRGB() { } <|endoftext|>
<commit_before>/* This is an example file shipped by 'Aleph - A Library for Exploring Persistent Homology'. This example demonstrates how to load a network---a graph---from a variety of input files. The graph will subsequently be expanded to a simplicial complex and the persistent homology of the graph will be calculated. Demonstrated classes: - aleph::PersistenceDiagram - aleph::geometry::RipsExpander - aleph::topology::EdgeListReader - aleph::topology::GMLReader - aleph::topology::PajekReader - aleph::topology::Simplex - aleph::topology::SimplicialComplex - aleph::topology::filtrations::Data Demonstrated functions: - aleph::calculatePersistenceDiagrams - aleph::utilities::extension - Betti numbers of persistence diagrams - Simplicial complex sorting (for filtrations) Original author: Bastian Rieck */ #include "geometry/RipsExpander.hh" #include "topology/io/EdgeLists.hh" #include "topology/io/GML.hh" #include "topology/io/Pajek.hh" #include "persistentHomology/Calculation.hh" #include "topology/Simplex.hh" #include "topology/SimplicialComplex.hh" #include "topology/filtrations/Data.hh" #include "utilities/Filesystem.hh" #include <iostream> #include <fstream> #include <string> #include <vector> void usage() { std::cerr << "Usage: network_analysis FILE [DIMENSION]\n" << "\n" << "Loads a weighted network (graph) from FILE, expands it up to\n" << "the specified DIMENSION, and calculates persistence diagrams\n" << "of the weight function of the input.\n" << "\n" << "Diagrams will be written to STDOUT in a gnuplot-like style.\n" << "\n"; } int main( int argc, char** argv ) { // We have to specify the required data type and vertex type for the // simplex class here. These settings are generic and should cover // most situations. If your weights are floats or even integers, you // can of course change it here. Likewise, if your simplicial complex // is very small, you could use `short` instead of `unsigned` to // represent all possible values for vertices. using DataType = double; using VertexType = unsigned; // These are just given for convenience. It makes declaring an // instance of a simplicial complex much easier. using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; if( argc <= 1 ) { usage(); return -1; } // By convention, simplicial complexes are always called K (or L if // you need two of them). This is probably bad style. ;) SimplicialComplex K; // Reading ----------------------------------------------------------- std::string filename = argv[1]; std::cerr << "* Reading '" << filename << "'..."; // For supporting different graph formats, Aleph offers different // loader classes. Every loader class uses the same interface for // reading simplicial complexes, via `operator()()`. // // Some loader classes support special features of a given format // such as label reading. Here, we do not make use of any of them // because we are only interested in demonstrating the expansion. // // Every reader attempts to read edge weights from the file. They // are assigned to the 1-simplices in the simplicial complex. { auto extension = aleph::utilities::extension( filename ); if( extension == ".gml" ) { aleph::topology::io::GMLReader reader; reader( filename, K ); } else if( extension == ".net" ) { aleph::topology::io::PajekReader reader; reader( filename, K ); } else { aleph::topology::io::EdgeListReader reader; reader( filename, K ); } } std::cerr << "finished\n" << "* Extracted simplicial complex with " << K.size() << " simplices\n"; // Rips expansion ---------------------------------------------------- // // The Rips expander is a generic class for expanding a graph into a // higher-dimensional simplicial complex. This follows the procedure // described in: // // Fast construction of the Vietoris--Rips complex // Afra Zomorodian // Computers & Graphics, Volume 34, Issue 3, pp. 263-–271 // // Formally speaking, the algorithm creates a k-simplex for subsets // of simplices in which k+1 simplices have pairwise intersections. // // Hence, if all three edges of a triangle are present, a 2-simplex // will be added to the simplicial complex. std::cerr << "* Expanding simplicial complex..."; aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander; if( argc >= 3 ) K = ripsExpander( K, static_cast<unsigned>( std::stoul( argv[2] ) ) ); // This leaves the simplicial complex untouched. The simplices with // highest dimension are the edges, i.e. the 1-simplices. else K = ripsExpander( K, 1 ); // This tells the expander to use the maximum weight of the faces of // a simplex in order to assign the weight of the simplex. Thus, the // simplicial complex models a sublevel set filtration after sorting // it with the appropriate functor. K = ripsExpander.assignMaximumWeight( K ); std::cerr << "...finished\n" << "* Expanded complex has dimension " << K.dimension() << "\n" << "* Expanded complex has " << K.size() << " simplices\n"; std::cerr << "* Establishing filtration order..."; // A filtration is an ordering of K in which faces precede co-faces in // order to ensure that the ordering represents a growing complex. The // functor used below sorts simplices based on their data. It hence is // just another way of expressing the weights specified in the graph. // // The data-based filtration ensures that upon coinciding weights, the // lower-dimensional simplex will precede the higher-dimensional one. K.sort( aleph::topology::filtrations::Data<Simplex>() ); std::cerr << "...finished\n"; // Persistent homology calculation ----------------------------------- // // This uses a convenience function. It expects a simplicial complex // in filtration order, calculates it persistent homology using the // default algorithms, and returns a vector of persistence diagrams. std::cerr << "* Calculating persistent homology..."; auto diagrams = aleph::calculatePersistenceDiagrams( K ); std::cerr << "...finished\n"; for( auto&& D : diagrams ) { // This removes all features with a persistence of zero. They only // clutter up the diagram. D.removeDiagonal(); // This 'header' contains some informative entries about the // persistence diagram. // // The Betti number counts how many simplices are without a // partner in the diagram. // // Notice that the diagram has pre-defined output operator; // if you do not like the output, you may of course iterate // over the points in the diagram yourself. std::cout << "# Persistence diagram <" << filename << ">\n" << "#\n" << "# Dimension : " << D.dimension() << "\n" << "# Entries : " << D.size() << "\n" << "# Betti number: " << D.betti() << "\n" << D << "\n\n"; } } <commit_msg>Fixed comments for network analysis example<commit_after>/* This is an example file shipped by 'Aleph - A Library for Exploring Persistent Homology'. This example demonstrates how to load a network---a graph---from a variety of input files. The graph will subsequently be expanded to a simplicial complex and the persistent homology of the graph will be calculated. Demonstrated classes: - aleph::PersistenceDiagram - aleph::geometry::RipsExpander - aleph::topology::io::EdgeListReader - aleph::topology::io::GMLReader - aleph::topology::io::PajekReader - aleph::topology::Simplex - aleph::topology::SimplicialComplex - aleph::topology::filtrations::Data Demonstrated functions: - aleph::calculatePersistenceDiagrams - aleph::utilities::extension - Betti numbers of persistence diagrams - Simplicial complex sorting (for filtrations) Original author: Bastian Rieck */ #include "geometry/RipsExpander.hh" #include "topology/io/EdgeLists.hh" #include "topology/io/GML.hh" #include "topology/io/Pajek.hh" #include "persistentHomology/Calculation.hh" #include "topology/Simplex.hh" #include "topology/SimplicialComplex.hh" #include "topology/filtrations/Data.hh" #include "utilities/Filesystem.hh" #include <iostream> #include <fstream> #include <string> #include <vector> void usage() { std::cerr << "Usage: network_analysis FILE [DIMENSION]\n" << "\n" << "Loads a weighted network (graph) from FILE, expands it up to\n" << "the specified DIMENSION, and calculates persistence diagrams\n" << "of the weight function of the input.\n" << "\n" << "Diagrams will be written to STDOUT in a gnuplot-like style.\n" << "\n"; } int main( int argc, char** argv ) { // We have to specify the required data type and vertex type for the // simplex class here. These settings are generic and should cover // most situations. If your weights are floats or even integers, you // can of course change it here. Likewise, if your simplicial complex // is very small, you could use `short` instead of `unsigned` to // represent all possible values for vertices. using DataType = double; using VertexType = unsigned; // These are just given for convenience. It makes declaring an // instance of a simplicial complex much easier. using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; if( argc <= 1 ) { usage(); return -1; } // By convention, simplicial complexes are always called K (or L if // you need two of them). This is probably bad style. ;) SimplicialComplex K; // Reading ----------------------------------------------------------- std::string filename = argv[1]; std::cerr << "* Reading '" << filename << "'..."; // For supporting different graph formats, Aleph offers different // loader classes. Every loader class uses the same interface for // reading simplicial complexes, via `operator()()`. // // Some loader classes support special features of a given format // such as label reading. Here, we do not make use of any of them // because we are only interested in demonstrating the expansion. // // Every reader attempts to read edge weights from the file. They // are assigned to the 1-simplices in the simplicial complex. { auto extension = aleph::utilities::extension( filename ); if( extension == ".gml" ) { aleph::topology::io::GMLReader reader; reader( filename, K ); } else if( extension == ".net" ) { aleph::topology::io::PajekReader reader; reader( filename, K ); } else { aleph::topology::io::EdgeListReader reader; reader( filename, K ); } } std::cerr << "finished\n" << "* Extracted simplicial complex with " << K.size() << " simplices\n"; // Rips expansion ---------------------------------------------------- // // The Rips expander is a generic class for expanding a graph into a // higher-dimensional simplicial complex. This follows the procedure // described in: // // Fast construction of the Vietoris--Rips complex // Afra Zomorodian // Computers & Graphics, Volume 34, Issue 3, pp. 263-–271 // // Formally speaking, the algorithm creates a k-simplex for subsets // of simplices in which k+1 simplices have pairwise intersections. // // Hence, if all three edges of a triangle are present, a 2-simplex // will be added to the simplicial complex. std::cerr << "* Expanding simplicial complex..."; aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander; if( argc >= 3 ) K = ripsExpander( K, static_cast<unsigned>( std::stoul( argv[2] ) ) ); // This leaves the simplicial complex untouched. The simplices with // highest dimension are the edges, i.e. the 1-simplices. else K = ripsExpander( K, 1 ); // This tells the expander to use the maximum weight of the faces of // a simplex in order to assign the weight of the simplex. Thus, the // simplicial complex models a sublevel set filtration after sorting // it with the appropriate functor. K = ripsExpander.assignMaximumWeight( K ); std::cerr << "...finished\n" << "* Expanded complex has dimension " << K.dimension() << "\n" << "* Expanded complex has " << K.size() << " simplices\n"; std::cerr << "* Establishing filtration order..."; // A filtration is an ordering of K in which faces precede co-faces in // order to ensure that the ordering represents a growing complex. The // functor used below sorts simplices based on their data. It hence is // just another way of expressing the weights specified in the graph. // // The data-based filtration ensures that upon coinciding weights, the // lower-dimensional simplex will precede the higher-dimensional one. K.sort( aleph::topology::filtrations::Data<Simplex>() ); std::cerr << "...finished\n"; // Persistent homology calculation ----------------------------------- // // This uses a convenience function. It expects a simplicial complex // in filtration order, calculates it persistent homology using the // default algorithms, and returns a vector of persistence diagrams. std::cerr << "* Calculating persistent homology..."; auto diagrams = aleph::calculatePersistenceDiagrams( K ); std::cerr << "...finished\n"; for( auto&& D : diagrams ) { // This removes all features with a persistence of zero. They only // clutter up the diagram. D.removeDiagonal(); // This 'header' contains some informative entries about the // persistence diagram. // // The Betti number counts how many simplices are without a // partner in the diagram. // // Notice that the diagram has pre-defined output operator; // if you do not like the output, you may of course iterate // over the points in the diagram yourself. std::cout << "# Persistence diagram <" << filename << ">\n" << "#\n" << "# Dimension : " << D.dimension() << "\n" << "# Entries : " << D.size() << "\n" << "# Betti number: " << D.betti() << "\n" << D << "\n\n"; } } <|endoftext|>
<commit_before>/* OpenSceneGraph example, osgpick. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* osgpick sample * demonstrate use of osgUtil/PickVisitor for picking in a HUD or * in a 3d scene, */ #include <osgUtil/Optimizer> #include <osgDB/ReadFile> #include <osgViewer/Viewer> #include <osg/Material> #include <osg/Geode> #include <osg/BlendFunc> #include <osg/Depth> #include <osg/Projection> #include <osg/MatrixTransform> #include <osg/Camera> #include <osg/io_utils> #include <osgText/Text> #include <sstream> // class to handle events with a pick class PickHandler : public osgGA::GUIEventHandler { public: PickHandler(osgText::Text* updateText): _updateText(updateText) {} ~PickHandler() {} bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa); virtual void pick(osgViewer::Viewer* viewer, const osgGA::GUIEventAdapter& ea); void setLabel(const std::string& name) { if (_updateText.get()) _updateText->setText(name); } protected: osg::ref_ptr<osgText::Text> _updateText; }; bool PickHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa) { switch(ea.getEventType()) { case(osgGA::GUIEventAdapter::FRAME): { osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>(&aa); if (viewer) pick(viewer,ea); return false; } default: return false; } } void PickHandler::pick(osgViewer::Viewer* viewer, const osgGA::GUIEventAdapter& ea) { osgUtil::LineSegmentIntersector::Intersections intersections; std::string gdlist=""; if (viewer->computeIntersections(ea.getX(),ea.getY(),intersections)) { for(osgUtil::LineSegmentIntersector::Intersections::iterator hitr = intersections.begin(); hitr != intersections.end(); ++hitr) { std::ostringstream os; if (!hitr->nodePath.empty() && !(hitr->nodePath.back()->getName().empty())) { // the geodes are identified by name. os<<"Object \""<<hitr->nodePath.back()->getName()<<"\""<<std::endl; } else if (hitr->drawable.valid()) { os<<"Object \""<<hitr->drawable->className()<<"\""<<std::endl; } os<<" local coords vertex("<< hitr->getLocalIntersectPoint()<<")"<<" normal("<<hitr->getLocalIntersectNormal()<<")"<<std::endl; os<<" world coords vertex("<< hitr->getWorldIntersectPoint()<<")"<<" normal("<<hitr->getWorldIntersectNormal()<<")"<<std::endl; const osgUtil::LineSegmentIntersector::Intersection::IndexList& vil = hitr->indexList; for(unsigned int i=0;i<vil.size();++i) { os<<" vertex indices ["<<i<<"] = "<<vil[i]<<std::endl; } gdlist += os.str(); } } setLabel(gdlist); } osg::Node* createHUD(osgText::Text* updateText) { // create the hud. derived from osgHud.cpp // adds a set of quads, each in a separate Geode - which can be picked individually // eg to be used as a menuing/help system! // Can pick texts too! osg::Camera* hudCamera = new osg::Camera; hudCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF); hudCamera->setProjectionMatrixAsOrtho2D(0,1280,0,1024); hudCamera->setViewMatrix(osg::Matrix::identity()); hudCamera->setRenderOrder(osg::Camera::POST_RENDER); hudCamera->setClearMask(GL_DEPTH_BUFFER_BIT); std::string timesFont("fonts/times.ttf"); // turn lighting off for the text and disable depth test to ensure its always ontop. osg::Vec3 position(150.0f,800.0f,0.0f); osg::Vec3 delta(0.0f,-60.0f,0.0f); { osg::Geode* geode = new osg::Geode(); osg::StateSet* stateset = geode->getOrCreateStateSet(); stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF); stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF); geode->setName("simple"); hudCamera->addChild(geode); osgText::Text* text = new osgText::Text; geode->addDrawable( text ); text->setFont(timesFont); text->setText("Picking in Head Up Displays is simple!"); text->setPosition(position); position += delta; } for (int i=0; i<5; i++) { osg::Vec3 dy(0.0f,-30.0f,0.0f); osg::Vec3 dx(120.0f,0.0f,0.0f); osg::Geode* geode = new osg::Geode(); osg::StateSet* stateset = geode->getOrCreateStateSet(); const char *opts[]={"One", "Two", "Three", "January", "Feb", "2003"}; osg::Geometry *quad=new osg::Geometry; stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF); stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF); std::string name="subOption"; name += " "; name += std::string(opts[i]); geode->setName(name); osg::Vec3Array* vertices = new osg::Vec3Array(4); // 1 quad osg::Vec4Array* colors = new osg::Vec4Array; colors = new osg::Vec4Array; colors->push_back(osg::Vec4(0.8-0.1*i,0.1*i,0.2*i, 1.0)); quad->setColorArray(colors); quad->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE); (*vertices)[0]=position; (*vertices)[1]=position+dx; (*vertices)[2]=position+dx+dy; (*vertices)[3]=position+dy; quad->setVertexArray(vertices); quad->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4)); geode->addDrawable(quad); hudCamera->addChild(geode); position += delta; } { // this displays what has been selected osg::Geode* geode = new osg::Geode(); osg::StateSet* stateset = geode->getOrCreateStateSet(); stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF); stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF); geode->setName("The text label"); geode->addDrawable( updateText ); hudCamera->addChild(geode); updateText->setCharacterSize(20.0f); updateText->setFont(timesFont); updateText->setColor(osg::Vec4(1.0f,1.0f,0.0f,1.0f)); updateText->setText(""); updateText->setPosition(position); updateText->setDataVariance(osg::Object::DYNAMIC); position += delta; } return hudCamera; } int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // construct the viewer. osgViewer::Viewer viewer; // read the scene from the list of file specified commandline args. osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments); // if not loaded assume no arguments passed in, try use default mode instead. if (!scene) scene = osgDB::readNodeFile("fountain.osg"); osg::ref_ptr<osg::Group> group = dynamic_cast<osg::Group*>(scene.get()); if (!group) { group = new osg::Group; group->addChild(scene.get()); } osg::ref_ptr<osgText::Text> updateText = new osgText::Text; // add the HUD subgraph. group->addChild(createHUD(updateText.get())); // add the handler for doing the picking viewer.addEventHandler(new PickHandler(updateText.get())); // set the scene to render viewer.setSceneData(group.get()); return viewer.run(); } <commit_msg>From Jean-Sebastien Guay and Robert Osfield, added optional --CompositeViewer path into osgpick to illustrate how to do picking in both viewers and as unit test for picking.<commit_after>/* OpenSceneGraph example, osgpick. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* osgpick sample * demonstrate use of osgUtil/PickVisitor for picking in a HUD or * in a 3d scene, */ #include <osgUtil/Optimizer> #include <osgDB/ReadFile> #include <osgViewer/Viewer> #include <osgViewer/CompositeViewer> #include <osg/Material> #include <osg/Geode> #include <osg/BlendFunc> #include <osg/Depth> #include <osg/Projection> #include <osg/MatrixTransform> #include <osg/Camera> #include <osg/io_utils> #include <osgText/Text> #include <sstream> // class to handle events with a pick class PickHandler : public osgGA::GUIEventHandler { public: PickHandler(osgText::Text* updateText): _updateText(updateText) {} ~PickHandler() {} bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa); virtual void pick(osgViewer::View* view, const osgGA::GUIEventAdapter& ea); void setLabel(const std::string& name) { if (_updateText.get()) _updateText->setText(name); } protected: osg::ref_ptr<osgText::Text> _updateText; }; bool PickHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa) { switch(ea.getEventType()) { case(osgGA::GUIEventAdapter::PUSH): { osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa); if (view) pick(view,ea); return false; } default: return false; } } void PickHandler::pick(osgViewer::View* view, const osgGA::GUIEventAdapter& ea) { osgUtil::LineSegmentIntersector::Intersections intersections; std::string gdlist=""; float x = ea.getX(); float y = ea.getY(); if (view->computeIntersections(x,y,intersections)) { for(osgUtil::LineSegmentIntersector::Intersections::iterator hitr = intersections.begin(); hitr != intersections.end(); ++hitr) { std::ostringstream os; if (!hitr->nodePath.empty() && !(hitr->nodePath.back()->getName().empty())) { // the geodes are identified by name. os<<"Object \""<<hitr->nodePath.back()->getName()<<"\""<<std::endl; } else if (hitr->drawable.valid()) { os<<"Object \""<<hitr->drawable->className()<<"\""<<std::endl; } os<<" local coords vertex("<< hitr->getLocalIntersectPoint()<<")"<<" normal("<<hitr->getLocalIntersectNormal()<<")"<<std::endl; os<<" world coords vertex("<< hitr->getWorldIntersectPoint()<<")"<<" normal("<<hitr->getWorldIntersectNormal()<<")"<<std::endl; const osgUtil::LineSegmentIntersector::Intersection::IndexList& vil = hitr->indexList; for(unsigned int i=0;i<vil.size();++i) { os<<" vertex indices ["<<i<<"] = "<<vil[i]<<std::endl; } gdlist += os.str(); } } setLabel(gdlist); } osg::Node* createHUD(osgText::Text* updateText) { // create the hud. derived from osgHud.cpp // adds a set of quads, each in a separate Geode - which can be picked individually // eg to be used as a menuing/help system! // Can pick texts too! osg::Camera* hudCamera = new osg::Camera; hudCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF); hudCamera->setProjectionMatrixAsOrtho2D(0,1280,0,1024); hudCamera->setViewMatrix(osg::Matrix::identity()); hudCamera->setRenderOrder(osg::Camera::POST_RENDER); hudCamera->setClearMask(GL_DEPTH_BUFFER_BIT); std::string timesFont("fonts/times.ttf"); // turn lighting off for the text and disable depth test to ensure its always ontop. osg::Vec3 position(150.0f,800.0f,0.0f); osg::Vec3 delta(0.0f,-60.0f,0.0f); { osg::Geode* geode = new osg::Geode(); osg::StateSet* stateset = geode->getOrCreateStateSet(); stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF); stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF); geode->setName("simple"); hudCamera->addChild(geode); osgText::Text* text = new osgText::Text; geode->addDrawable( text ); text->setFont(timesFont); text->setText("Picking in Head Up Displays is simple!"); text->setPosition(position); position += delta; } for (int i=0; i<5; i++) { osg::Vec3 dy(0.0f,-30.0f,0.0f); osg::Vec3 dx(120.0f,0.0f,0.0f); osg::Geode* geode = new osg::Geode(); osg::StateSet* stateset = geode->getOrCreateStateSet(); const char *opts[]={"One", "Two", "Three", "January", "Feb", "2003"}; osg::Geometry *quad=new osg::Geometry; stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF); stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF); std::string name="subOption"; name += " "; name += std::string(opts[i]); geode->setName(name); osg::Vec3Array* vertices = new osg::Vec3Array(4); // 1 quad osg::Vec4Array* colors = new osg::Vec4Array; colors = new osg::Vec4Array; colors->push_back(osg::Vec4(0.8-0.1*i,0.1*i,0.2*i, 1.0)); quad->setColorArray(colors); quad->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE); (*vertices)[0]=position; (*vertices)[1]=position+dx; (*vertices)[2]=position+dx+dy; (*vertices)[3]=position+dy; quad->setVertexArray(vertices); quad->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4)); geode->addDrawable(quad); hudCamera->addChild(geode); position += delta; } { // this displays what has been selected osg::Geode* geode = new osg::Geode(); osg::StateSet* stateset = geode->getOrCreateStateSet(); stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF); stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF); geode->setName("The text label"); geode->addDrawable( updateText ); hudCamera->addChild(geode); updateText->setCharacterSize(20.0f); updateText->setFont(timesFont); updateText->setColor(osg::Vec4(1.0f,1.0f,0.0f,1.0f)); updateText->setText(""); updateText->setPosition(position); updateText->setDataVariance(osg::Object::DYNAMIC); position += delta; } return hudCamera; } int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // read the scene from the list of file specified commandline args. osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments); // if not loaded assume no arguments passed in, try use default mode instead. if (!scene) scene = osgDB::readNodeFile("fountain.osg"); osg::ref_ptr<osg::Group> group = dynamic_cast<osg::Group*>(scene.get()); if (!group) { group = new osg::Group; group->addChild(scene.get()); } osg::ref_ptr<osgText::Text> updateText = new osgText::Text; // add the HUD subgraph. group->addChild(createHUD(updateText.get())); if (arguments.read("--CompositeViewer")) { osg::ref_ptr<osgViewer::View> view = new osgViewer::View; // add the handler for doing the picking view->addEventHandler(new PickHandler(updateText.get())); // set the scene to render view->setSceneData(group.get()); view->setUpViewAcrossAllScreens(); osgViewer::CompositeViewer viewer; viewer.addView(view.get()); return viewer.run(); } else { osgViewer::Viewer viewer; // add the handler for doing the picking viewer.addEventHandler(new PickHandler(updateText.get())); // set the scene to render viewer.setSceneData(group.get()); return viewer.run(); } } <|endoftext|>
<commit_before>// @(#)root/roofitcore:$name: $:$id$ // Authors: Wouter Verkerke November 2007 // C/C++ headers #include <list> #include <iostream> #include <iomanip> // ROOT headers #include "TWebFile.h" #include "TSystem.h" #include "TString.h" #include "TROOT.h" #include "TFile.h" #include "TBenchmark.h" // RooFit headers #include "RooNumIntConfig.h" #include "RooResolutionModel.h" #include "RooAbsData.h" #include "RooTrace.h" #include "RooMath.h" #include "RooUnitTest.h" // Tests file #include "stressHistFactory_tests.cxx" using namespace std ; using namespace RooFit ; //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*// // // // RooStats Unit Test S.T.R.E.S.S. Suite // // Authors: Ioan Gabriel Bucur, Lorenzo Moneta, Wouter Verkerke // // // //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*// //------------------------------------------------------------------------ void StatusPrint(const Int_t id, const TString &title, const Int_t status, const Int_t lineWidth) { // Print test program number and its title TString header = TString::Format("Test %d : %s ", id, title.Data()); cout << left << setw(lineWidth) << setfill('.') << header << " " << (status > 0 ? "OK" : (status < 0 ? "SKIPPED" : "FAILED")) << endl; } //______________________________________________________________________________ Int_t stressHistFactory(const char* refFile, Bool_t writeRef, Int_t verbose, Bool_t allTests, Bool_t oneTest, Int_t testNumber, Bool_t dryRun) { // width of lines when printing test results const Int_t lineWidth = 120; // Save memory directory location RooUnitTest::setMemDir(gDirectory) ; std::cout << "using reference file " << refFile << std::endl; TFile* fref = 0 ; if (!dryRun) { if (TString(refFile).Contains("http:")) { if (writeRef) { cout << "stressHistFactory ERROR: reference file must be local file in writing mode" << endl ; return -1 ; } fref = new TWebFile(refFile) ; } else { fref = new TFile(refFile, writeRef ? "RECREATE" : "") ; } if (fref->IsZombie()) { cout << "stressHistFactory ERROR: cannot open reference file " << refFile << endl ; return -1; } } if (dryRun) { // Preload singletons here so they don't show up in trace accounting RooNumIntConfig::defaultConfig() ; RooResolutionModel::identity() ; RooTrace::active(1) ; } // Add dedicated logging stream for errors that will remain active in silent mode RooMsgService::instance().addStream(RooFit::ERROR) ; cout << left << setw(lineWidth) << setfill('*') << "" << endl; cout << "*" << setw(lineWidth - 2) << setfill(' ') << " Histfactory S.T.R.E.S.S. suite " << "*" << endl; cout << setw(lineWidth) << setfill('*') << "" << endl; cout << setw(lineWidth) << setfill('*') << "" << endl; TStopwatch timer; timer.Start(); list<RooUnitTest*> testList; testList.push_back(new PdfComparison(fref, writeRef, verbose)); TString suiteType = TString::Format(" Starting S.T.R.E.S.S. %s", allTests ? "full suite" : (oneTest ? TString::Format("test %d", testNumber).Data() : "basic suite") ); cout << "*" << setw(lineWidth - 3) << setfill(' ') << suiteType << " *" << endl; cout << setw(lineWidth) << setfill('*') << "" << endl; gBenchmark->Start("stressHistFactory"); int nFailed = 0; { Int_t i; list<RooUnitTest*>::iterator iter; if (oneTest && (testNumber <= 0 || (UInt_t) testNumber > testList.size())) { cout << "Tests are numbered from 1 to " << testList.size() << endl; return -1; } else { for (iter = testList.begin(), i = 1; iter != testList.end(); iter++, i++) { if (!oneTest || testNumber == i) { int status = (*iter)->isTestAvailable() ? (*iter)->runTest() : -1; StatusPrint(i, (*iter)->GetName(), status , lineWidth); if (!status) nFailed++; } delete *iter; } } } if (dryRun) { RooTrace::dump(); } gBenchmark->Stop("stressHistFactory"); //Print table with results Bool_t UNIX = strcmp(gSystem->GetName(), "Unix") == 0; cout << setw(lineWidth) << setfill('*') << "" << endl; if (UNIX) { TString sp = gSystem->GetFromPipe("uname -a"); cout << "* SYS: " << sp << endl; if (strstr(gSystem->GetBuildNode(), "Linux")) { sp = gSystem->GetFromPipe("lsb_release -d -s"); cout << "* SYS: " << sp << endl; } if (strstr(gSystem->GetBuildNode(), "Darwin")) { sp = gSystem->GetFromPipe("sw_vers -productVersion"); sp += " Mac OS X "; cout << "* SYS: " << sp << endl; } } else { const Char_t *os = gSystem->Getenv("OS"); if (!os) cout << "* SYS: Windows 95" << endl; else cout << "* SYS: " << os << " " << gSystem->Getenv("PROCESSOR_IDENTIFIER") << endl; } cout << setw(lineWidth) << setfill('*') << "" << endl; gBenchmark->Print("stressHistFactory"); #ifdef __CINT__ Double_t reftime = 186.34; //pcbrun4 interpreted #else Double_t reftime = 93.59; //pcbrun4 compiled #endif const Double_t rootmarks = 860 * reftime / gBenchmark->GetCpuTime("stressHistFactory"); cout << setw(lineWidth) << setfill('*') << "" << endl; cout << TString::Format("* ROOTMARKS = %6.1f * Root %-8s %d/%d", rootmarks, gROOT->GetVersion(), gROOT->GetVersionDate(), gROOT->GetVersionTime()) << endl; cout << setw(lineWidth) << setfill('*') << "" << endl; // NOTE: The function TStopwatch::CpuTime() calls Tstopwatch::Stop(), so you do not need to stop the timer separately. cout << "Time at the end of job = " << timer.CpuTime() << " seconds" << endl; if (fref) { fref->Close() ; delete fref ; } delete gBenchmark ; gBenchmark = 0 ; return nFailed; } //_____________________________batch only_____________________ #ifndef __CINT__ int main(int argc, const char *argv[]) { Bool_t doWrite = kFALSE; Int_t verbose = 0; Bool_t allTests = kFALSE; Bool_t oneTest = kFALSE; Int_t testNumber = 0; Bool_t dryRun = kFALSE; string refFileName = "$ROOTSYS/test/stressHistFactory_ref.root" ; // Parse command line arguments for (Int_t i = 1 ; i < argc ; i++) { string arg = argv[i] ; if (arg == "-f") { cout << "stressHistFactory: using reference file " << argv[i + 1] << endl ; refFileName = argv[++i] ; } else if (arg == "-w") { cout << "stressHistFactory: running in writing mode to update reference file" << endl ; doWrite = kTRUE ; } else if (arg == "-mc") { cout << "stressHistFactory: running in memcheck mode, no regression tests are performed" << endl; dryRun = kTRUE; } else if (arg == "-v") { cout << "stressHistFactory: running in verbose mode" << endl; verbose = 1; } else if (arg == "-vv") { cout << "stressHistFactory: running in very verbose mode" << endl; verbose = 2; } else if (arg == "-a") { cout << "stressHistFactory: deploying full suite of tests" << endl; allTests = kTRUE; } else if (arg == "-n") { cout << "stressHistFactory: running single test" << endl; oneTest = kTRUE; testNumber = atoi(argv[++i]); } else if (arg == "-d") { cout << "stressHistFactory: setting gDebug to " << argv[i + 1] << endl; gDebug = atoi(argv[++i]); } else if (arg == "-h") { cout << "usage: stressHistFactory [ options ] " << endl; cout << "" << endl; cout << " -f <file> : use given reference file instead of default (" << refFileName << ")" << endl; cout << " -w : write reference file, instead of reading file and running comparison tests" << endl; cout << " -n N : only run test with sequential number N" << endl; cout << " -a : run full suite of tests (default is basic suite); this overrides the -n single test option" << endl; cout << " -mc : memory check mode, no regression test are performed. Set this flag when running with valgrind" << endl; cout << " -vs : use vector-based storage for all datasets (default is tree-based storage)" << endl; cout << " -v/-vv : set verbose mode (show result of each regression test) or very verbose mode (show all roofit output as well)" << endl; cout << " -d N : set ROOT gDebug flag to N" << endl ; cout << " " << endl ; return 0 ; } } // Disable caching of complex error function calculation, as we don't // want to write out the cache file as part of the validation procedure RooMath::cacheCERF(kFALSE) ; gBenchmark = new TBenchmark(); return stressHistFactory(refFileName.c_str(), doWrite, verbose, allTests, oneTest, testNumber, dryRun); } #endif <commit_msg>cosider skipped tests as failed ones<commit_after>// @(#)root/roofitcore:$name: $:$id$ // Authors: Wouter Verkerke November 2007 // C/C++ headers #include <list> #include <iostream> #include <iomanip> // ROOT headers #include "TWebFile.h" #include "TSystem.h" #include "TString.h" #include "TROOT.h" #include "TFile.h" #include "TBenchmark.h" // RooFit headers #include "RooNumIntConfig.h" #include "RooResolutionModel.h" #include "RooAbsData.h" #include "RooTrace.h" #include "RooMath.h" #include "RooUnitTest.h" // Tests file #include "stressHistFactory_tests.cxx" using namespace std ; using namespace RooFit ; //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*// // // // RooStats Unit Test S.T.R.E.S.S. Suite // // Authors: Ioan Gabriel Bucur, Lorenzo Moneta, Wouter Verkerke // // // //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*// //------------------------------------------------------------------------ void StatusPrint(const Int_t id, const TString &title, const Int_t status, const Int_t lineWidth) { // Print test program number and its title TString header = TString::Format("Test %d : %s ", id, title.Data()); cout << left << setw(lineWidth) << setfill('.') << header << " " << (status > 0 ? "OK" : (status < 0 ? "SKIPPED" : "FAILED")) << endl; } //______________________________________________________________________________ Int_t stressHistFactory(const char* refFile, Bool_t writeRef, Int_t verbose, Bool_t allTests, Bool_t oneTest, Int_t testNumber, Bool_t dryRun) { // width of lines when printing test results const Int_t lineWidth = 120; // Save memory directory location RooUnitTest::setMemDir(gDirectory) ; std::cout << "using reference file " << refFile << std::endl; TFile* fref = 0 ; if (!dryRun) { if (TString(refFile).Contains("http:")) { if (writeRef) { cout << "stressHistFactory ERROR: reference file must be local file in writing mode" << endl ; return -1 ; } fref = new TWebFile(refFile) ; } else { fref = new TFile(refFile, writeRef ? "RECREATE" : "") ; } if (fref->IsZombie()) { cout << "stressHistFactory ERROR: cannot open reference file " << refFile << endl ; return -1; } } if (dryRun) { // Preload singletons here so they don't show up in trace accounting RooNumIntConfig::defaultConfig() ; RooResolutionModel::identity() ; RooTrace::active(1) ; } // Add dedicated logging stream for errors that will remain active in silent mode RooMsgService::instance().addStream(RooFit::ERROR) ; cout << left << setw(lineWidth) << setfill('*') << "" << endl; cout << "*" << setw(lineWidth - 2) << setfill(' ') << " Histfactory S.T.R.E.S.S. suite " << "*" << endl; cout << setw(lineWidth) << setfill('*') << "" << endl; cout << setw(lineWidth) << setfill('*') << "" << endl; TStopwatch timer; timer.Start(); list<RooUnitTest*> testList; testList.push_back(new PdfComparison(fref, writeRef, verbose)); TString suiteType = TString::Format(" Starting S.T.R.E.S.S. %s", allTests ? "full suite" : (oneTest ? TString::Format("test %d", testNumber).Data() : "basic suite") ); cout << "*" << setw(lineWidth - 3) << setfill(' ') << suiteType << " *" << endl; cout << setw(lineWidth) << setfill('*') << "" << endl; gBenchmark->Start("stressHistFactory"); int nFailed = 0; { Int_t i; list<RooUnitTest*>::iterator iter; if (oneTest && (testNumber <= 0 || (UInt_t) testNumber > testList.size())) { cout << "Tests are numbered from 1 to " << testList.size() << endl; return -1; } else { for (iter = testList.begin(), i = 1; iter != testList.end(); iter++, i++) { if (!oneTest || testNumber == i) { int status = (*iter)->isTestAvailable() ? (*iter)->runTest() : -1; StatusPrint(i, (*iter)->GetName(), status , lineWidth); if (status <= 0) nFailed++; // successfull tests return a positive number } delete *iter; } } } if (dryRun) { RooTrace::dump(); } gBenchmark->Stop("stressHistFactory"); //Print table with results Bool_t UNIX = strcmp(gSystem->GetName(), "Unix") == 0; cout << setw(lineWidth) << setfill('*') << "" << endl; if (UNIX) { TString sp = gSystem->GetFromPipe("uname -a"); cout << "* SYS: " << sp << endl; if (strstr(gSystem->GetBuildNode(), "Linux")) { sp = gSystem->GetFromPipe("lsb_release -d -s"); cout << "* SYS: " << sp << endl; } if (strstr(gSystem->GetBuildNode(), "Darwin")) { sp = gSystem->GetFromPipe("sw_vers -productVersion"); sp += " Mac OS X "; cout << "* SYS: " << sp << endl; } } else { const Char_t *os = gSystem->Getenv("OS"); if (!os) cout << "* SYS: Windows 95" << endl; else cout << "* SYS: " << os << " " << gSystem->Getenv("PROCESSOR_IDENTIFIER") << endl; } cout << setw(lineWidth) << setfill('*') << "" << endl; gBenchmark->Print("stressHistFactory"); Double_t reftime = 2.4; //maclm compiled const Double_t rootmarks = 860 * reftime / gBenchmark->GetCpuTime("stressHistFactory"); cout << setw(lineWidth) << setfill('*') << "" << endl; cout << TString::Format("* ROOTMARKS = %6.1f * Root %-8s %d/%d", rootmarks, gROOT->GetVersion(), gROOT->GetVersionDate(), gROOT->GetVersionTime()) << endl; cout << setw(lineWidth) << setfill('*') << "" << endl; // NOTE: The function TStopwatch::CpuTime() calls Tstopwatch::Stop(), so you do not need to stop the timer separately. cout << "Time at the end of job = " << timer.CpuTime() << " seconds" << endl; if (fref) { fref->Close() ; delete fref ; } delete gBenchmark ; gBenchmark = 0 ; return nFailed; } //_____________________________batch only_____________________ #ifndef __CINT__ int main(int argc, const char *argv[]) { Bool_t doWrite = kFALSE; Int_t verbose = 0; Bool_t allTests = kFALSE; Bool_t oneTest = kFALSE; Int_t testNumber = 0; Bool_t dryRun = kFALSE; string refFileName = "$ROOTSYS/test/stressHistFactory_ref.root" ; // Parse command line arguments for (Int_t i = 1 ; i < argc ; i++) { string arg = argv[i] ; if (arg == "-f") { cout << "stressHistFactory: using reference file " << argv[i + 1] << endl ; refFileName = argv[++i] ; } else if (arg == "-w") { cout << "stressHistFactory: running in writing mode to update reference file" << endl ; doWrite = kTRUE ; } else if (arg == "-mc") { cout << "stressHistFactory: running in memcheck mode, no regression tests are performed" << endl; dryRun = kTRUE; } else if (arg == "-v") { cout << "stressHistFactory: running in verbose mode" << endl; verbose = 1; } else if (arg == "-vv") { cout << "stressHistFactory: running in very verbose mode" << endl; verbose = 2; } else if (arg == "-a") { cout << "stressHistFactory: deploying full suite of tests" << endl; allTests = kTRUE; } else if (arg == "-n") { cout << "stressHistFactory: running single test" << endl; oneTest = kTRUE; testNumber = atoi(argv[++i]); } else if (arg == "-d") { cout << "stressHistFactory: setting gDebug to " << argv[i + 1] << endl; gDebug = atoi(argv[++i]); } else if (arg == "-h") { cout << "usage: stressHistFactory [ options ] " << endl; cout << "" << endl; cout << " -f <file> : use given reference file instead of default (" << refFileName << ")" << endl; cout << " -w : write reference file, instead of reading file and running comparison tests" << endl; cout << " -n N : only run test with sequential number N" << endl; cout << " -a : run full suite of tests (default is basic suite); this overrides the -n single test option" << endl; cout << " -mc : memory check mode, no regression test are performed. Set this flag when running with valgrind" << endl; cout << " -vs : use vector-based storage for all datasets (default is tree-based storage)" << endl; cout << " -v/-vv : set verbose mode (show result of each regression test) or very verbose mode (show all roofit output as well)" << endl; cout << " -d N : set ROOT gDebug flag to N" << endl ; cout << " " << endl ; return 0 ; } } // Disable caching of complex error function calculation, as we don't // want to write out the cache file as part of the validation procedure RooMath::cacheCERF(kFALSE) ; gBenchmark = new TBenchmark(); return stressHistFactory(refFileName.c_str(), doWrite, verbose, allTests, oneTest, testNumber, dryRun); } #endif <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "simple_graph/list_graph.hpp" #include "simple_graph/bellman_ford.hpp" namespace { class ListGraphUndirectedTest : public ::testing::Test { protected: simple_graph::ListGraph<false, int, ssize_t> g; }; TEST_F(ListGraphUndirectedTest, test_bellman_ford_long) { for (size_t i = 0; i < 8; ++i) { g.add_vertex(simple_graph::Vertex<int>(i)); } EXPECT_EQ(8, g.vertex_num()); g.add_edge(simple_graph::Edge<ssize_t>(0, 1, 1)); g.add_edge(simple_graph::Edge<ssize_t>(1, 2, 2)); g.add_edge(simple_graph::Edge<ssize_t>(2, 3, 3)); g.add_edge(simple_graph::Edge<ssize_t>(3, 4, 4)); g.add_edge(simple_graph::Edge<ssize_t>(4, 7, 5)); g.add_edge(simple_graph::Edge<ssize_t>(0, 5, 20)); g.add_edge(simple_graph::Edge<ssize_t>(5, 6, 20)); g.add_edge(simple_graph::Edge<ssize_t>(6, 7, 20)); std::vector<size_t> path; EXPECT_EQ(true, simple_graph::bellman_ford(g, 0, 7, &path)); EXPECT_EQ(6, path.size()); EXPECT_EQ(0, path[0]); EXPECT_EQ(1, path[1]); EXPECT_EQ(4, path[4]); } TEST_F(ListGraphUndirectedTest, test_bellman_ford_short) { for (size_t i = 0; i < 8; ++i) { g.add_vertex(simple_graph::Vertex<int>(i)); } EXPECT_EQ(8, g.vertex_num()); g.add_edge(simple_graph::Edge<ssize_t>(0, 1, 1)); g.add_edge(simple_graph::Edge<ssize_t>(1, 2, 2)); g.add_edge(simple_graph::Edge<ssize_t>(2, 3, 3)); g.add_edge(simple_graph::Edge<ssize_t>(3, 4, 4)); g.add_edge(simple_graph::Edge<ssize_t>(4, 7, 5)); g.add_edge(simple_graph::Edge<ssize_t>(0, 5, 1)); g.add_edge(simple_graph::Edge<ssize_t>(5, 6, 1)); g.add_edge(simple_graph::Edge<ssize_t>(6, 7, 1)); std::vector<size_t> path; EXPECT_EQ(true, simple_graph::bellman_ford(g, 0, 7, &path)); EXPECT_EQ(4, path.size()); EXPECT_EQ(0, path[0]); EXPECT_EQ(5, path[1]); EXPECT_EQ(6, path[2]); EXPECT_EQ(7, path[3]); } TEST_F(ListGraphUndirectedTest, test_bellman_ford_negative_weigths) { for (size_t i = 0; i < 8; ++i) { g.add_vertex(simple_graph::Vertex<int>(i)); } EXPECT_EQ(8, g.vertex_num()); g.add_edge(simple_graph::Edge<ssize_t>(0, 1, -1)); g.add_edge(simple_graph::Edge<ssize_t>(1, 2, -2)); g.add_edge(simple_graph::Edge<ssize_t>(2, 3, -3)); g.add_edge(simple_graph::Edge<ssize_t>(3, 4, -4)); g.add_edge(simple_graph::Edge<ssize_t>(4, 7, -5)); g.add_edge(simple_graph::Edge<ssize_t>(0, 5, -1)); g.add_edge(simple_graph::Edge<ssize_t>(5, 6, -1)); g.add_edge(simple_graph::Edge<ssize_t>(6, 7, -1)); std::vector<size_t> path; ASSERT_EQ(true, simple_graph::bellman_ford(g, 0, 7, &path)); ASSERT_EQ(6, path.size()); EXPECT_EQ(0, path[0]); EXPECT_EQ(1, path[1]); EXPECT_EQ(4, path[4]); } } // namespace int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Fix Bellman-Ford algorithm tests<commit_after>#include <gtest/gtest.h> #include "simple_graph/list_graph.hpp" #include "simple_graph/bellman_ford.hpp" namespace { class ListGraphUndirectedTest : public ::testing::Test { protected: simple_graph::ListGraph<false, int, ssize_t> g; }; TEST_F(ListGraphUndirectedTest, test_bellman_ford_long) { for (size_t i = 0; i < 8; ++i) { g.add_vertex(simple_graph::Vertex<int>(i)); } ASSERT_EQ(8, g.vertex_num()); g.add_edge(simple_graph::Edge<ssize_t>(0, 1, 1)); g.add_edge(simple_graph::Edge<ssize_t>(1, 2, 2)); g.add_edge(simple_graph::Edge<ssize_t>(2, 3, 3)); g.add_edge(simple_graph::Edge<ssize_t>(3, 4, 4)); g.add_edge(simple_graph::Edge<ssize_t>(4, 7, 5)); g.add_edge(simple_graph::Edge<ssize_t>(0, 5, 20)); g.add_edge(simple_graph::Edge<ssize_t>(5, 6, 20)); g.add_edge(simple_graph::Edge<ssize_t>(6, 7, 20)); std::vector<size_t> path; EXPECT_EQ(true, simple_graph::bellman_ford(g, 0, 7, &path)); EXPECT_EQ(6, path.size()); EXPECT_EQ(0, path[0]); EXPECT_EQ(1, path[1]); EXPECT_EQ(4, path[4]); } TEST_F(ListGraphUndirectedTest, test_bellman_ford_short) { for (size_t i = 0; i < 8; ++i) { g.add_vertex(simple_graph::Vertex<int>(i)); } ASSERT_EQ(8, g.vertex_num()); g.add_edge(simple_graph::Edge<ssize_t>(0, 1, 1)); g.add_edge(simple_graph::Edge<ssize_t>(1, 2, 2)); g.add_edge(simple_graph::Edge<ssize_t>(2, 3, 3)); g.add_edge(simple_graph::Edge<ssize_t>(3, 4, 4)); g.add_edge(simple_graph::Edge<ssize_t>(4, 7, 5)); g.add_edge(simple_graph::Edge<ssize_t>(0, 5, 1)); g.add_edge(simple_graph::Edge<ssize_t>(5, 6, 1)); g.add_edge(simple_graph::Edge<ssize_t>(6, 7, 1)); std::vector<size_t> path; EXPECT_EQ(true, simple_graph::bellman_ford(g, 0, 7, &path)); EXPECT_EQ(4, path.size()); EXPECT_EQ(0, path[0]); EXPECT_EQ(5, path[1]); EXPECT_EQ(6, path[2]); EXPECT_EQ(7, path[3]); } TEST_F(ListGraphUndirectedTest, test_bellman_ford_no_path) { for (size_t i = 0; i < 4; ++i) { g.add_vertex(simple_graph::Vertex<int>(i)); } ASSERT_EQ(4, g.vertex_num()); g.add_edge(simple_graph::Edge<ssize_t>(0, 1, 1)); g.add_edge(simple_graph::Edge<ssize_t>(2, 3, 3)); std::vector<size_t> path; EXPECT_EQ(false, simple_graph::bellman_ford(g, 0, 3, &path)); EXPECT_EQ(0, path.size()); } TEST_F(ListGraphUndirectedTest, test_bellman_ford_negative_weigths) { for (size_t i = 0; i < 8; ++i) { g.add_vertex(simple_graph::Vertex<int>(i)); } ASSERT_EQ(8, g.vertex_num()); g.add_edge(simple_graph::Edge<ssize_t>(0, 1, -1)); g.add_edge(simple_graph::Edge<ssize_t>(1, 2, -2)); g.add_edge(simple_graph::Edge<ssize_t>(2, 3, -3)); g.add_edge(simple_graph::Edge<ssize_t>(3, 4, -4)); g.add_edge(simple_graph::Edge<ssize_t>(4, 7, -5)); g.add_edge(simple_graph::Edge<ssize_t>(0, 5, -1)); g.add_edge(simple_graph::Edge<ssize_t>(5, 6, -1)); g.add_edge(simple_graph::Edge<ssize_t>(6, 7, -1)); std::vector<size_t> path; ASSERT_EQ(true, simple_graph::bellman_ford(g, 0, 7, &path)); ASSERT_EQ(6, path.size()); EXPECT_EQ(0, path[0]); EXPECT_EQ(1, path[1]); EXPECT_EQ(4, path[4]); } TEST_F(ListGraphUndirectedTest, test_bellman_ford_negative_cycles) { for (size_t i = 0; i < 5; ++i) { g.add_vertex(simple_graph::Vertex<int>(i)); } ASSERT_EQ(5, g.vertex_num()); g.add_edge(simple_graph::Edge<ssize_t>(0, 1, -1)); g.add_edge(simple_graph::Edge<ssize_t>(1, 2, -1)); g.add_edge(simple_graph::Edge<ssize_t>(2, 0, -1)); g.add_edge(simple_graph::Edge<ssize_t>(2, 3, 2)); g.add_edge(simple_graph::Edge<ssize_t>(3, 4, 2)); std::vector<size_t> path; EXPECT_EQ(false, simple_graph::bellman_ford(g, 0, 4, &path)); EXPECT_EQ(0, path.size()); } } // namespace int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>// --------------------------------------------------------------------- // $Id: graph_coloring_03.cc 30045 2013-07-18 19:18:00Z maier $ // // Copyright (C) 2003 - 2013 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- // Check that graph coloring works on hp-mesh. #include "../tests.h" #include <fstream> #include <vector> #include <deal.II/base/graph_coloring.h> #include <deal.II/fe/fe_q.h> #include <deal.II/hp/dof_handler.h> #include <deal.II/hp/fe_values.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/grid/tria_accessor.h> #include <deal.II/grid/tria_iterator.h> #include <deal.II/grid/tria.h> template <int dim> void check() { // Create the Triangulation and the DoFHandler Triangulation<dim> triangulation; GridGenerator::hyper_cube(triangulation); triangulation.refine_global(2); hp::FECollection<dim> fe_collection; for (unsigned int degree=1; degree<4; ++degree) fe_collection.push_back(FE_Q<dim>(degree)); hp::DoFHandler<dim> dof_handler(triangulation); typename hp::DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(); for (unsigned int degree=1; cell!=dof_handler.end(); ++cell,++degree) cell->set_active_fe_index(degree%3); dof_handler.distribute_dofs(fe_collection); // Create an adapted mesh for (cell=dof_handler.begin_active(); cell<dof_handler.end(); ++cell) if ((cell->center()[0]==0.625) && (cell->center()[1]==0.625)) cell->set_refine_flag(); triangulation.execute_coarsening_and_refinement(); dof_handler.distribute_dofs(fe_collection); // Create the coloring std::vector<std::vector<typename hp::DoFHandler<dim>::active_cell_iterator> > coloring( graph_coloring::make_graph_coloring(dof_handler.begin_active(),dof_handler.end())); // Output the coloring for (unsigned int color=0; color<coloring.size(); ++color) { deallog<<"Color: "<<color<<std::endl; for (unsigned int i=0; i<coloring[color].size(); ++i) for (unsigned int j=0; j<dim; ++j) deallog<<coloring[color][i]->center()[j]<<" "; deallog<<std::endl; } } int main() { std::ofstream logfile("graph_coloring_03/output"); deallog<<std::setprecision(4); deallog<<std::fixed; deallog.attach(logfile); deallog.depth_console(0); check<2> (); return 0; } <commit_msg>Fix output file name.<commit_after>// --------------------------------------------------------------------- // $Id: graph_coloring_03.cc 30045 2013-07-18 19:18:00Z maier $ // // Copyright (C) 2003 - 2013 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- // Check that graph coloring works on hp-mesh. #include "../tests.h" #include <fstream> #include <vector> #include <deal.II/base/graph_coloring.h> #include <deal.II/fe/fe_q.h> #include <deal.II/hp/dof_handler.h> #include <deal.II/hp/fe_values.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/grid/tria_accessor.h> #include <deal.II/grid/tria_iterator.h> #include <deal.II/grid/tria.h> template <int dim> void check() { // Create the Triangulation and the DoFHandler Triangulation<dim> triangulation; GridGenerator::hyper_cube(triangulation); triangulation.refine_global(2); hp::FECollection<dim> fe_collection; for (unsigned int degree=1; degree<4; ++degree) fe_collection.push_back(FE_Q<dim>(degree)); hp::DoFHandler<dim> dof_handler(triangulation); typename hp::DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(); for (unsigned int degree=1; cell!=dof_handler.end(); ++cell,++degree) cell->set_active_fe_index(degree%3); dof_handler.distribute_dofs(fe_collection); // Create an adapted mesh for (cell=dof_handler.begin_active(); cell<dof_handler.end(); ++cell) if ((cell->center()[0]==0.625) && (cell->center()[1]==0.625)) cell->set_refine_flag(); triangulation.execute_coarsening_and_refinement(); dof_handler.distribute_dofs(fe_collection); // Create the coloring std::vector<std::vector<typename hp::DoFHandler<dim>::active_cell_iterator> > coloring( graph_coloring::make_graph_coloring(dof_handler.begin_active(),dof_handler.end())); // Output the coloring for (unsigned int color=0; color<coloring.size(); ++color) { deallog<<"Color: "<<color<<std::endl; for (unsigned int i=0; i<coloring[color].size(); ++i) for (unsigned int j=0; j<dim; ++j) deallog<<coloring[color][i]->center()[j]<<" "; deallog<<std::endl; } } int main() { std::ofstream logfile("output"); deallog<<std::setprecision(4); deallog<<std::fixed; deallog.attach(logfile); deallog.depth_console(0); check<2> (); return 0; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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 _DBHELPER_DBCHARSET_HXX_ #define _DBHELPER_DBCHARSET_HXX_ #include <comphelper/stl_types.hxx> #include <rtl/textenc.h> #include <rtl/tencinfo.h> #include <rtl/ustring.hxx> #include "connectivity/dbtoolsdllapi.hxx" //......................................................................... namespace dbtools { //......................................................................... //========================================================================= //= OCharsetMap //========================================================================= /** is a class which translates between different charset representations. <p>The set of recognized charsets is very limited: only the ones which are database relevant are implemented at the moment</p> <p>Possible representations are: <ul> <li><b>IANA names.</b> Have a look at <A href="http://www.iana.org/assignments/character-sets">this document</A> for more details</li> <li><b>rtl_TextEncoding</b></li> </ul> </p> */ class OOO_DLLPUBLIC_DBTOOLS OCharsetMap { protected: DECLARE_STL_STDKEY_SET( rtl_TextEncoding, TextEncBag ); TextEncBag m_aEncodings; public: class CharsetIterator; friend class OCharsetMap::CharsetIterator; typedef CharsetIterator iterator; typedef CharsetIterator const_iterator; OCharsetMap(); virtual ~OCharsetMap(); struct IANA { }; /** find the given text encoding in the map. @return the <em>end</em> iterator if the encoding could not be found. */ CharsetIterator find(const rtl_TextEncoding _eEncoding) const; /** find the given IANA name in the map. @return the <em>end</em> iterator if the IANA name could not be found. */ CharsetIterator find(const ::rtl::OUString& _rIanaName, const IANA&) const; sal_Int32 size() const { ensureConstructed( ); return m_aEncodings.size(); } /// get access to the first element of the charset collection CharsetIterator begin() const; /// get access to the (last + 1st) element of the charset collection CharsetIterator end() const; protected: // needed because we want to call a virtual method during construction void lateConstruct(); inline void ensureConstructed( ) const { if ( m_aEncodings.empty() ) const_cast< OCharsetMap* >( this )->lateConstruct(); } virtual sal_Bool approveEncoding( const rtl_TextEncoding _eEncoding, const rtl_TextEncodingInfo& _rInfo ) const; }; //------------------------------------------------------------------------- //- CharsetIteratorDerefHelper //------------------------------------------------------------------------- class OOO_DLLPUBLIC_DBTOOLS CharsetIteratorDerefHelper { friend class OCharsetMap::CharsetIterator; rtl_TextEncoding m_eEncoding; ::rtl::OUString m_aIanaName; public: CharsetIteratorDerefHelper(const CharsetIteratorDerefHelper& _rSource); rtl_TextEncoding getEncoding() const { return m_eEncoding; } ::rtl::OUString getIanaName() const { return m_aIanaName; } protected: CharsetIteratorDerefHelper( const rtl_TextEncoding _eEncoding, const ::rtl::OUString& _rIanaName ); }; //------------------------------------------------------------------------- //- OCharsetMap::CharsetIterator //------------------------------------------------------------------------- class OOO_DLLPUBLIC_DBTOOLS OCharsetMap::CharsetIterator { friend class OCharsetMap; friend OOO_DLLPUBLIC_DBTOOLS bool operator==(const CharsetIterator& lhs, const CharsetIterator& rhs); friend bool operator!=(const CharsetIterator& lhs, const CharsetIterator& rhs) { return !(lhs == rhs); } // friend sal_Int32 operator-(const CharsetIterator& lhs, const CharsetIterator& rhs); protected: const OCharsetMap* m_pContainer; OCharsetMap::TextEncBag::const_iterator m_aPos; public: CharsetIterator(const CharsetIterator& _rSource); ~CharsetIterator(); CharsetIteratorDerefHelper operator*() const; // no -> operator // this would require us to a) store CharsetIteratorDerefHelper instances ourself so that we // can return a pointer or b) introduce a -> operator on the CharsetIteratorDerefHelper, too. /// prefix increment const CharsetIterator& operator++(); /// postfix increment const CharsetIterator operator++(int) { CharsetIterator hold(*this); ++*this; return hold; } /// prefix decrement const CharsetIterator& operator--(); /// postfix decrement const CharsetIterator operator--(int) { CharsetIterator hold(*this); --*this; return hold; } protected: CharsetIterator(const OCharsetMap* _pContainer, OCharsetMap::TextEncBag::const_iterator _aPos ); }; //......................................................................... } // namespace dbtools //......................................................................... #endif // _DBHELPER_DBCHARSET_HXX_ /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>-Werror=conversion<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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 _DBHELPER_DBCHARSET_HXX_ #define _DBHELPER_DBCHARSET_HXX_ #include "sal/config.h" #include <cstddef> #include <comphelper/stl_types.hxx> #include <rtl/textenc.h> #include <rtl/tencinfo.h> #include <rtl/ustring.hxx> #include "connectivity/dbtoolsdllapi.hxx" //......................................................................... namespace dbtools { //......................................................................... //========================================================================= //= OCharsetMap //========================================================================= /** is a class which translates between different charset representations. <p>The set of recognized charsets is very limited: only the ones which are database relevant are implemented at the moment</p> <p>Possible representations are: <ul> <li><b>IANA names.</b> Have a look at <A href="http://www.iana.org/assignments/character-sets">this document</A> for more details</li> <li><b>rtl_TextEncoding</b></li> </ul> </p> */ class OOO_DLLPUBLIC_DBTOOLS OCharsetMap { protected: DECLARE_STL_STDKEY_SET( rtl_TextEncoding, TextEncBag ); TextEncBag m_aEncodings; public: class CharsetIterator; friend class OCharsetMap::CharsetIterator; typedef CharsetIterator iterator; typedef CharsetIterator const_iterator; OCharsetMap(); virtual ~OCharsetMap(); struct IANA { }; /** find the given text encoding in the map. @return the <em>end</em> iterator if the encoding could not be found. */ CharsetIterator find(const rtl_TextEncoding _eEncoding) const; /** find the given IANA name in the map. @return the <em>end</em> iterator if the IANA name could not be found. */ CharsetIterator find(const ::rtl::OUString& _rIanaName, const IANA&) const; std::size_t size() const { ensureConstructed( ); return m_aEncodings.size(); } /// get access to the first element of the charset collection CharsetIterator begin() const; /// get access to the (last + 1st) element of the charset collection CharsetIterator end() const; protected: // needed because we want to call a virtual method during construction void lateConstruct(); inline void ensureConstructed( ) const { if ( m_aEncodings.empty() ) const_cast< OCharsetMap* >( this )->lateConstruct(); } virtual sal_Bool approveEncoding( const rtl_TextEncoding _eEncoding, const rtl_TextEncodingInfo& _rInfo ) const; }; //------------------------------------------------------------------------- //- CharsetIteratorDerefHelper //------------------------------------------------------------------------- class OOO_DLLPUBLIC_DBTOOLS CharsetIteratorDerefHelper { friend class OCharsetMap::CharsetIterator; rtl_TextEncoding m_eEncoding; ::rtl::OUString m_aIanaName; public: CharsetIteratorDerefHelper(const CharsetIteratorDerefHelper& _rSource); rtl_TextEncoding getEncoding() const { return m_eEncoding; } ::rtl::OUString getIanaName() const { return m_aIanaName; } protected: CharsetIteratorDerefHelper( const rtl_TextEncoding _eEncoding, const ::rtl::OUString& _rIanaName ); }; //------------------------------------------------------------------------- //- OCharsetMap::CharsetIterator //------------------------------------------------------------------------- class OOO_DLLPUBLIC_DBTOOLS OCharsetMap::CharsetIterator { friend class OCharsetMap; friend OOO_DLLPUBLIC_DBTOOLS bool operator==(const CharsetIterator& lhs, const CharsetIterator& rhs); friend bool operator!=(const CharsetIterator& lhs, const CharsetIterator& rhs) { return !(lhs == rhs); } // friend sal_Int32 operator-(const CharsetIterator& lhs, const CharsetIterator& rhs); protected: const OCharsetMap* m_pContainer; OCharsetMap::TextEncBag::const_iterator m_aPos; public: CharsetIterator(const CharsetIterator& _rSource); ~CharsetIterator(); CharsetIteratorDerefHelper operator*() const; // no -> operator // this would require us to a) store CharsetIteratorDerefHelper instances ourself so that we // can return a pointer or b) introduce a -> operator on the CharsetIteratorDerefHelper, too. /// prefix increment const CharsetIterator& operator++(); /// postfix increment const CharsetIterator operator++(int) { CharsetIterator hold(*this); ++*this; return hold; } /// prefix decrement const CharsetIterator& operator--(); /// postfix decrement const CharsetIterator operator--(int) { CharsetIterator hold(*this); --*this; return hold; } protected: CharsetIterator(const OCharsetMap* _pContainer, OCharsetMap::TextEncBag::const_iterator _aPos ); }; //......................................................................... } // namespace dbtools //......................................................................... #endif // _DBHELPER_DBCHARSET_HXX_ /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AColumn.cxx,v $ * * $Revision: 1.24 $ * * last change: $Author: hr $ $Date: 2006-06-20 01:12:11 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CONNECTIVITY_ADO_COLUMN_HXX_ #include "ado/AColumn.hxx" #endif #ifndef _CONNECTIVITY_ADO_ACONNECTION_HXX_ #include "ado/AConnection.hxx" #endif #ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_ #include "ado/Awrapado.hxx" #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_ #include <com/sun/star/sdbc/ColumnValue.hpp> #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif #ifndef _CONNECTIVITY_ADO_CATALOG_HXX_ #include "ado/ACatalog.hxx" #endif using namespace ::comphelper; using namespace connectivity::ado; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::sdbc; void WpADOColumn::Create() { HRESULT hr = -1; _ADOColumn* pColumn = NULL; hr = CoCreateInstance(ADOS::CLSID_ADOCOLUMN_25, NULL, CLSCTX_INPROC_SERVER, ADOS::IID_ADOCOLUMN_25, (void**)&pColumn ); if( !FAILED( hr ) ) { operator=( pColumn ); pColumn->Release( ); } } // ------------------------------------------------------------------------- OAdoColumn::OAdoColumn(sal_Bool _bCase,OConnection* _pConnection,_ADOColumn* _pColumn) : connectivity::sdbcx::OColumn(::rtl::OUString(),::rtl::OUString(),::rtl::OUString(),0,0,0,0,sal_False,sal_False,sal_False,_bCase) ,m_pConnection(_pConnection) { construct(); OSL_ENSURE(_pColumn,"Column can not be null!"); m_aColumn = WpADOColumn(_pColumn); // m_aColumn.put_ParentCatalog(_pConnection->getAdoCatalog()->getCatalog()); fillPropertyValues(); } // ------------------------------------------------------------------------- OAdoColumn::OAdoColumn(sal_Bool _bCase,OConnection* _pConnection) : connectivity::sdbcx::OColumn(_bCase) ,m_pConnection(_pConnection) { m_aColumn.Create(); m_aColumn.put_ParentCatalog(_pConnection->getAdoCatalog()->getCatalog()); construct(); fillPropertyValues(); m_Type = DataType::OTHER; } //-------------------------------------------------------------------------- Sequence< sal_Int8 > OAdoColumn::getUnoTunnelImplementationId() { static ::cppu::OImplementationId * pId = 0; if (! pId) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if (! pId) { static ::cppu::OImplementationId aId; pId = &aId; } } return pId->getImplementationId(); } // com::sun::star::lang::XUnoTunnel //------------------------------------------------------------------ sal_Int64 OAdoColumn::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException) { return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(), rId.getConstArray(), 16 ) ) ? reinterpret_cast< sal_Int64 >( this ) : OColumn_ADO::getSomething(rId); } // ------------------------------------------------------------------------- void OAdoColumn::construct() { sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY; registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISASCENDING), PROPERTY_ID_ISASCENDING, nAttrib,&m_IsAscending, ::getBooleanCppuType()); registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_RELATEDCOLUMN), PROPERTY_ID_RELATEDCOLUMN, nAttrib,&m_ReferencedColumn, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL))); } // ----------------------------------------------------------------------------- void OAdoColumn::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue)throw (Exception) { if(m_aColumn.IsValid()) { const sal_Char* pAdoPropertyName = NULL; switch(nHandle) { case PROPERTY_ID_ISASCENDING: m_aColumn.put_SortOrder(::cppu::any2bool(rValue) ? adSortAscending : adSortDescending); break; case PROPERTY_ID_RELATEDCOLUMN: { ::rtl::OUString aVal; rValue >>= aVal; m_aColumn.put_RelatedColumn(aVal); } break; case PROPERTY_ID_NAME: { ::rtl::OUString aVal; rValue >>= aVal; m_aColumn.put_Name(aVal); } break; case PROPERTY_ID_TYPE: { sal_Int32 nVal=0; rValue >>= nVal; m_aColumn.put_Type(ADOS::MapJdbc2ADOType(nVal,m_pConnection->getEngineType())); } break; case PROPERTY_ID_TYPENAME: // rValue <<= m_pTable->getCatalog()->getConnection()->getTypeInfo()->find(); break; case PROPERTY_ID_PRECISION: { sal_Int32 nVal=0; rValue >>= nVal; m_aColumn.put_Precision(nVal); } break; case PROPERTY_ID_SCALE: { sal_Int32 nVal=0; rValue >>= nVal; m_aColumn.put_NumericScale((sal_Int8)nVal); } break; case PROPERTY_ID_ISNULLABLE: { sal_Int32 nVal=0; rValue >>= nVal; if ( nVal == ColumnValue::NULLABLE ) m_aColumn.put_Attributes( adColNullable ); } break; case PROPERTY_ID_ISROWVERSION: break; case PROPERTY_ID_ISAUTOINCREMENT: OTools::putValue( m_aColumn.get_Properties(), ::rtl::OUString::createFromAscii( "Autoincrement" ), getBOOL( rValue ) ); break; case PROPERTY_ID_DESCRIPTION: pAdoPropertyName = "Default"; break; case PROPERTY_ID_DEFAULTVALUE: pAdoPropertyName = "Description"; break; } if ( pAdoPropertyName ) OTools::putValue( m_aColumn.get_Properties(), ::rtl::OUString::createFromAscii( pAdoPropertyName ), getString( rValue ) ); } OColumn_ADO::setFastPropertyValue_NoBroadcast(nHandle,rValue); } // ----------------------------------------------------------------------------- void OAdoColumn::fillPropertyValues() { if(m_aColumn.IsValid()) { m_IsAscending = m_aColumn.get_SortOrder() == adSortAscending; m_ReferencedColumn = m_aColumn.get_RelatedColumn(); m_Name = m_aColumn.get_Name(); m_Precision = m_aColumn.get_Precision(); m_Scale = m_aColumn.get_NumericScale(); m_IsNullable = ((m_aColumn.get_Attributes() & adColNullable) == adColNullable) ? ColumnValue::NULLABLE : ColumnValue::NO_NULLS; DataTypeEnum eType = m_aColumn.get_Type(); m_IsCurrency = (eType == adCurrency); m_Type = ADOS::MapADOType2Jdbc(eType); sal_Bool bForceTo = sal_True; const OTypeInfoMap* pTypeInfoMap = m_pConnection->getTypeInfo(); const OExtendedTypeInfo* pTypeInfo = OConnection::getTypeInfoFromType(*m_pConnection->getTypeInfo(),eType,::rtl::OUString(),m_Precision,m_Scale,bForceTo); if ( pTypeInfo ) m_TypeName = pTypeInfo->aSimpleType.aTypeName; else if ( eType == adVarBinary && ADOS::isJetEngine(m_pConnection->getEngineType()) ) { ::comphelper::TStringMixEqualFunctor aCase(sal_False); OTypeInfoMap::const_iterator aFind = ::std::find_if(pTypeInfoMap->begin(), pTypeInfoMap->end(), ::std::compose1( ::std::bind2nd(aCase, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("VarBinary"))), ::std::compose1( ::std::mem_fun(&OExtendedTypeInfo::getDBName), ::std::select2nd<OTypeInfoMap::value_type>()) ) ); if ( aFind != pTypeInfoMap->end() ) // change column type if necessary { eType = aFind->first; pTypeInfo = aFind->second; } if ( !pTypeInfo ) { pTypeInfo = OConnection::getTypeInfoFromType(*m_pConnection->getTypeInfo(),adBinary,::rtl::OUString(),m_Precision,m_Scale,bForceTo); eType = adBinary; } if ( pTypeInfo ) { m_TypeName = pTypeInfo->aSimpleType.aTypeName; m_Type = ADOS::MapADOType2Jdbc(eType); } } // fill some specific props { WpADOProperties aProps( m_aColumn.get_Properties() ); if ( aProps.IsValid() ) { m_IsAutoIncrement = OTools::getValue( aProps, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Autoincrement")) ); m_Description = OTools::getValue( aProps, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Description")) ); m_DefaultValue = OTools::getValue( aProps, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Default")) ); #if OSL_DEBUG_LEVEL > 0 sal_Int32 nCount = aProps.GetItemCount(); for (sal_Int32 i = 0; i<nCount; ++i) { WpADOProperty aProp = aProps.GetItem(i); ::rtl::OUString sName = aProp.GetName(); ::rtl::OUString sVal = aProp.GetValue(); } #endif } } } } // ----------------------------------------------------------------------------- WpADOColumn OAdoColumn::getColumnImpl() const { return m_aColumn; } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void SAL_CALL OAdoColumn::acquire() throw(::com::sun::star::uno::RuntimeException) { OColumn_ADO::acquire(); } // ----------------------------------------------------------------------------- void SAL_CALL OAdoColumn::release() throw(::com::sun::star::uno::RuntimeException) { OColumn_ADO::release(); } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS pchfix02 (1.24.58); FILE MERGED 2006/09/01 17:21:54 kaib 1.24.58.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AColumn.cxx,v $ * * $Revision: 1.25 $ * * last change: $Author: obo $ $Date: 2006-09-17 02:11:15 $ * * 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_connectivity.hxx" #ifndef _CONNECTIVITY_ADO_COLUMN_HXX_ #include "ado/AColumn.hxx" #endif #ifndef _CONNECTIVITY_ADO_ACONNECTION_HXX_ #include "ado/AConnection.hxx" #endif #ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_ #include "ado/Awrapado.hxx" #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_ #include <com/sun/star/sdbc/ColumnValue.hpp> #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif #ifndef _CONNECTIVITY_ADO_CATALOG_HXX_ #include "ado/ACatalog.hxx" #endif using namespace ::comphelper; using namespace connectivity::ado; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::sdbc; void WpADOColumn::Create() { HRESULT hr = -1; _ADOColumn* pColumn = NULL; hr = CoCreateInstance(ADOS::CLSID_ADOCOLUMN_25, NULL, CLSCTX_INPROC_SERVER, ADOS::IID_ADOCOLUMN_25, (void**)&pColumn ); if( !FAILED( hr ) ) { operator=( pColumn ); pColumn->Release( ); } } // ------------------------------------------------------------------------- OAdoColumn::OAdoColumn(sal_Bool _bCase,OConnection* _pConnection,_ADOColumn* _pColumn) : connectivity::sdbcx::OColumn(::rtl::OUString(),::rtl::OUString(),::rtl::OUString(),0,0,0,0,sal_False,sal_False,sal_False,_bCase) ,m_pConnection(_pConnection) { construct(); OSL_ENSURE(_pColumn,"Column can not be null!"); m_aColumn = WpADOColumn(_pColumn); // m_aColumn.put_ParentCatalog(_pConnection->getAdoCatalog()->getCatalog()); fillPropertyValues(); } // ------------------------------------------------------------------------- OAdoColumn::OAdoColumn(sal_Bool _bCase,OConnection* _pConnection) : connectivity::sdbcx::OColumn(_bCase) ,m_pConnection(_pConnection) { m_aColumn.Create(); m_aColumn.put_ParentCatalog(_pConnection->getAdoCatalog()->getCatalog()); construct(); fillPropertyValues(); m_Type = DataType::OTHER; } //-------------------------------------------------------------------------- Sequence< sal_Int8 > OAdoColumn::getUnoTunnelImplementationId() { static ::cppu::OImplementationId * pId = 0; if (! pId) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if (! pId) { static ::cppu::OImplementationId aId; pId = &aId; } } return pId->getImplementationId(); } // com::sun::star::lang::XUnoTunnel //------------------------------------------------------------------ sal_Int64 OAdoColumn::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException) { return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(), rId.getConstArray(), 16 ) ) ? reinterpret_cast< sal_Int64 >( this ) : OColumn_ADO::getSomething(rId); } // ------------------------------------------------------------------------- void OAdoColumn::construct() { sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY; registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISASCENDING), PROPERTY_ID_ISASCENDING, nAttrib,&m_IsAscending, ::getBooleanCppuType()); registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_RELATEDCOLUMN), PROPERTY_ID_RELATEDCOLUMN, nAttrib,&m_ReferencedColumn, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL))); } // ----------------------------------------------------------------------------- void OAdoColumn::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue)throw (Exception) { if(m_aColumn.IsValid()) { const sal_Char* pAdoPropertyName = NULL; switch(nHandle) { case PROPERTY_ID_ISASCENDING: m_aColumn.put_SortOrder(::cppu::any2bool(rValue) ? adSortAscending : adSortDescending); break; case PROPERTY_ID_RELATEDCOLUMN: { ::rtl::OUString aVal; rValue >>= aVal; m_aColumn.put_RelatedColumn(aVal); } break; case PROPERTY_ID_NAME: { ::rtl::OUString aVal; rValue >>= aVal; m_aColumn.put_Name(aVal); } break; case PROPERTY_ID_TYPE: { sal_Int32 nVal=0; rValue >>= nVal; m_aColumn.put_Type(ADOS::MapJdbc2ADOType(nVal,m_pConnection->getEngineType())); } break; case PROPERTY_ID_TYPENAME: // rValue <<= m_pTable->getCatalog()->getConnection()->getTypeInfo()->find(); break; case PROPERTY_ID_PRECISION: { sal_Int32 nVal=0; rValue >>= nVal; m_aColumn.put_Precision(nVal); } break; case PROPERTY_ID_SCALE: { sal_Int32 nVal=0; rValue >>= nVal; m_aColumn.put_NumericScale((sal_Int8)nVal); } break; case PROPERTY_ID_ISNULLABLE: { sal_Int32 nVal=0; rValue >>= nVal; if ( nVal == ColumnValue::NULLABLE ) m_aColumn.put_Attributes( adColNullable ); } break; case PROPERTY_ID_ISROWVERSION: break; case PROPERTY_ID_ISAUTOINCREMENT: OTools::putValue( m_aColumn.get_Properties(), ::rtl::OUString::createFromAscii( "Autoincrement" ), getBOOL( rValue ) ); break; case PROPERTY_ID_DESCRIPTION: pAdoPropertyName = "Default"; break; case PROPERTY_ID_DEFAULTVALUE: pAdoPropertyName = "Description"; break; } if ( pAdoPropertyName ) OTools::putValue( m_aColumn.get_Properties(), ::rtl::OUString::createFromAscii( pAdoPropertyName ), getString( rValue ) ); } OColumn_ADO::setFastPropertyValue_NoBroadcast(nHandle,rValue); } // ----------------------------------------------------------------------------- void OAdoColumn::fillPropertyValues() { if(m_aColumn.IsValid()) { m_IsAscending = m_aColumn.get_SortOrder() == adSortAscending; m_ReferencedColumn = m_aColumn.get_RelatedColumn(); m_Name = m_aColumn.get_Name(); m_Precision = m_aColumn.get_Precision(); m_Scale = m_aColumn.get_NumericScale(); m_IsNullable = ((m_aColumn.get_Attributes() & adColNullable) == adColNullable) ? ColumnValue::NULLABLE : ColumnValue::NO_NULLS; DataTypeEnum eType = m_aColumn.get_Type(); m_IsCurrency = (eType == adCurrency); m_Type = ADOS::MapADOType2Jdbc(eType); sal_Bool bForceTo = sal_True; const OTypeInfoMap* pTypeInfoMap = m_pConnection->getTypeInfo(); const OExtendedTypeInfo* pTypeInfo = OConnection::getTypeInfoFromType(*m_pConnection->getTypeInfo(),eType,::rtl::OUString(),m_Precision,m_Scale,bForceTo); if ( pTypeInfo ) m_TypeName = pTypeInfo->aSimpleType.aTypeName; else if ( eType == adVarBinary && ADOS::isJetEngine(m_pConnection->getEngineType()) ) { ::comphelper::TStringMixEqualFunctor aCase(sal_False); OTypeInfoMap::const_iterator aFind = ::std::find_if(pTypeInfoMap->begin(), pTypeInfoMap->end(), ::std::compose1( ::std::bind2nd(aCase, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("VarBinary"))), ::std::compose1( ::std::mem_fun(&OExtendedTypeInfo::getDBName), ::std::select2nd<OTypeInfoMap::value_type>()) ) ); if ( aFind != pTypeInfoMap->end() ) // change column type if necessary { eType = aFind->first; pTypeInfo = aFind->second; } if ( !pTypeInfo ) { pTypeInfo = OConnection::getTypeInfoFromType(*m_pConnection->getTypeInfo(),adBinary,::rtl::OUString(),m_Precision,m_Scale,bForceTo); eType = adBinary; } if ( pTypeInfo ) { m_TypeName = pTypeInfo->aSimpleType.aTypeName; m_Type = ADOS::MapADOType2Jdbc(eType); } } // fill some specific props { WpADOProperties aProps( m_aColumn.get_Properties() ); if ( aProps.IsValid() ) { m_IsAutoIncrement = OTools::getValue( aProps, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Autoincrement")) ); m_Description = OTools::getValue( aProps, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Description")) ); m_DefaultValue = OTools::getValue( aProps, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Default")) ); #if OSL_DEBUG_LEVEL > 0 sal_Int32 nCount = aProps.GetItemCount(); for (sal_Int32 i = 0; i<nCount; ++i) { WpADOProperty aProp = aProps.GetItem(i); ::rtl::OUString sName = aProp.GetName(); ::rtl::OUString sVal = aProp.GetValue(); } #endif } } } } // ----------------------------------------------------------------------------- WpADOColumn OAdoColumn::getColumnImpl() const { return m_aColumn; } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void SAL_CALL OAdoColumn::acquire() throw(::com::sun::star::uno::RuntimeException) { OColumn_ADO::acquire(); } // ----------------------------------------------------------------------------- void SAL_CALL OAdoColumn::release() throw(::com::sun::star::uno::RuntimeException) { OColumn_ADO::release(); } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>// ======================================================================================== // ApproxMVBB // Copyright (C) 2014 by Gabriel Nützi <nuetzig (at) imes (d0t) mavt (d0t) ethz (døt) ch> // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // ======================================================================================== #ifndef TestFunctions_hpp #define TestFunctions_hpp #include <stdlib.h> #include <fstream> #include <functional> #include <gtest/gtest.h> #include "ApproxMVBB/Config/Config.hpp" #include "ApproxMVBB/Common/AssertionDebug.hpp" #include "ApproxMVBB/Common/SfinaeMacros.hpp" #include ApproxMVBB_TypeDefs_INCLUDE_FILE #include "ApproxMVBB/RandomGenerators.hpp" #include "ApproxMVBB/PointFunctions.hpp" #include "ApproxMVBB/OOBB.hpp" #define MY_TEST(name1 , name2 ) TEST(name1, name2) #define MY_TEST_RANDOM_STUFF(name) \ std::string testName = #name ; \ auto seed = hashString(#name); \ std::cout << "Seed for this test: " << seed << std::endl; \ ApproxMVBB::RandomGenerators::DefaultRandomGen rng(seed); \ std::uniform_real_distribution<PREC> uni(0.0,1.0); \ auto f = [&](PREC) { return uni(rng); }; namespace ApproxMVBB{ namespace TestFunctions{ ApproxMVBB_DEFINE_MATRIX_TYPES ApproxMVBB_DEFINE_POINTS_CONFIG_TYPES // TODO not std lib conform! std::size_t hashString(std::string name); template<typename A, typename B> ::testing::AssertionResult assertNearArrays( const A & a, const B & b, PREC absError = 1e-3) { if(a.size()!=b.size()){ return ::testing::AssertionFailure() << "not same size";} if(a.rows()!=b.rows()){ return ::testing::AssertionFailure() << "not same rows";} if( (( a - b ).array().abs() >= absError).any() ){ return ::testing::AssertionFailure() <<"not near: absTol:" << absError; } return ::testing::AssertionSuccess(); } template<bool matchCols , typename A, typename B, ApproxMVBB_SFINAE_ENABLE_IF( matchCols == true ) > ::testing::AssertionResult assertNearArrayColsRows_cr(const A & a, std::size_t i, const B & b, std::size_t j) { return assertNearArrays(a.col(i), b.col(j)); } template<bool matchCols , typename A, typename B, ApproxMVBB_SFINAE_ENABLE_IF( matchCols == false ) > ::testing::AssertionResult assertNearArrayColsRows_cr(const A & a, std::size_t i, const B & b, std::size_t j) { return assertNearArrays(a.row(i), b.row(j)); } template<bool matchCols = true, typename A, typename B> ::testing::AssertionResult assertNearArrayColsRows(const A & a, const B & b){ if(a.size()!=b.size()){ return ::testing::AssertionFailure() << "not same size";} if(a.rows()!=b.rows()){ return ::testing::AssertionFailure() << "not same rows";} // Check all points std::vector<bool> indexMatched; if(matchCols){ indexMatched.resize(a.cols(),false); }else{ indexMatched.resize(a.rows(),false); } auto s = indexMatched.size(); std::size_t nMatched = 0; std::size_t i = 0; std::size_t pointIdx = 0; while( pointIdx < s){ if( i < s){ if( indexMatched[i] ){ ++i; continue; } // check points[pointIdx] against i-th valid one if ( assertNearArrayColsRows_cr<matchCols>(a,pointIdx,b,i)){ indexMatched[i] = true; ++nMatched; } } // all indices i checked go to next point, reset check idx i = 0; ++pointIdx; } if(nMatched != s){ return ::testing::AssertionFailure() << "Matched only " << nMatched << "/" << s ; } return ::testing::AssertionSuccess(); } template<typename Derived> void dumpPointsMatrix(std::string filePath, const MatrixBase<Derived> & v) { std::ofstream l; l.open(filePath.c_str()); if(!l.good()){ ApproxMVBB_ERRORMSG("Could not open file: " << filePath << std::endl) } if(v.cols() != 0){ unsigned int i=0; for(; i<v.cols()-1; i++) { l << v.col(i).transpose().format(MyMatrixIOFormat::SpaceSep) << std::endl; } l << v.col(i).transpose().format(MyMatrixIOFormat::SpaceSep); } l.close(); } int isBigEndian(void); template <typename T> T swapEndian(T u) { ApproxMVBB_STATIC_ASSERTM(sizeof(char) == 1, "char != 8 bit"); union { T u; unsigned char u8[sizeof(T)]; } source, dest; source.u = u; for (size_t k = 0; k < sizeof(T); k++) dest.u8[k] = source.u8[sizeof(T) - k - 1]; return dest.u; } template<class Matrix> void dumpPointsMatrixBinary(std::string filename, const Matrix& matrix){ std::ofstream out(filename,std::ios::out | std::ios::binary | std::ios::trunc); typename Matrix::Index rows=matrix.rows(); typename Matrix::Index cols=matrix.cols(); ApproxMVBB_STATIC_ASSERT( sizeof(typename Matrix::Index) == 8 ) bool bigEndian = isBigEndian(); out.write((char*) (&bigEndian), sizeof(bool)); out.write((char*) (&rows), sizeof(typename Matrix::Index)); out.write((char*) (&cols), sizeof(typename Matrix::Index)); typename Matrix::Index bytes = sizeof(typename Matrix::Scalar); out.write((char*) (&bytes), sizeof(typename Matrix::Index )); out.write((char*) matrix.data(), rows*cols*sizeof(typename Matrix::Scalar) ); out.close(); } template<class Matrix> void readPointsMatrixBinary(std::string filename, Matrix& matrix, bool withHeader=true){ std::ifstream in(filename,std::ios::in | std::ios::binary); if(!in.is_open()){ ApproxMVBB_ERRORMSG("cannot open file: " << filename); } typename Matrix::Index rows=matrix.rows(); typename Matrix::Index cols=matrix.cols(); ApproxMVBB_STATIC_ASSERT( sizeof(typename Matrix::Index) == 8 ) bool bigEndian = false; // assume all input files with no headers are little endian! if(withHeader){ in.read((char*) (&bigEndian), sizeof(bool)); in.read((char*) (&rows),sizeof(typename Matrix::Index)); in.read((char*) (&cols),sizeof(typename Matrix::Index)); typename Matrix::Index bytes; in.read((char*) (&bytes), sizeof(typename Matrix::Index )); // swap endianness if file has other type if(isBigEndian() != bigEndian ){ rows = swapEndian(rows); cols = swapEndian(cols); bytes = swapEndian(bytes); } if(bytes != sizeof(typename Matrix::Scalar)){ ApproxMVBB_ERRORMSG("read binary with wrong data type: " << filename << "bigEndian: " << bigEndian << ", rows: " << rows << ", cols: " << cols <<", scalar bytes: " << bytes); } matrix.resize(rows, cols); } in.read( (char *) matrix.data() , rows*cols*sizeof(typename Matrix::Scalar) ); // swap endianness of whole matrix if file has other type if(isBigEndian() != bigEndian ){ auto f = [](const typename Matrix::Scalar & v){return swapEndian(v);}; matrix = matrix.unaryExpr( f ); } in.close(); } template<typename List, typename Derived> void convertMatrixToListRows(const MatrixBase<Derived> & M, List& points){ if (List::value_type::RowsAtCompileTime == M.cols()) { points.resize(M.rows()); for(std::size_t i = 0 ; i < M.rows(); ++i){ points[i] = M.row(i); } }else{ ApproxMVBB_ERRORMSG("points cannot be converted into list with vector size: " << List::value_type::RowsAtCompileTime) } } template<typename List, typename Derived> void convertMatrixToListCols(const MatrixBase<Derived> & M, List& points){ if (List::value_type::RowsAtCompileTime == M.rows()) { points.resize(M.cols()); for(std::size_t i = 0 ; i < M.cols(); ++i){ points[i] = M.col(i); } }else{ ApproxMVBB_ERRORMSG("points cannot be converted into list with vector size: " << List::value_type::RowsAtCompileTime) } } template<typename List, typename Derived> void convertMatrixToList_assCols(const MatrixBase<Derived> & M, List& points){ } template<typename Container> void dumpPoints(std::string filePath, Container & c) { std::ofstream l; l.open(filePath.c_str()); if(!l.good()){ ApproxMVBB_ERRORMSG("Could not open file: " << filePath << std::endl) } if(c.size()!=0){ auto e = c.begin() + (c.size() - 1); auto it = c.begin(); for(; it != e; ++it) { l << it->transpose().format(MyMatrixIOFormat::SpaceSep) << std::endl; } l << (it)->transpose().format(MyMatrixIOFormat::SpaceSep); } l.close(); } void readOOBB(std::string filePath, Vector3 & minP, Vector3 & maxP, Matrix33 & R_KI, Vector3List & pointList); void readOOBBAndCheck( OOBB & validOOBB, std::string filePath); void dumpOOBB(std::string filePath, const OOBB & oobb); Vector3List getPointsFromFile3D(std::string filePath); Vector2List getPointsFromFile2D(std::string filePath); // Vector2List generatePoints2D(unsigned int n=4); // // Vector3List generatePoints3D(unsigned int n=4); template<typename Derived, typename IndexSet> Derived filterPoints(MatrixBase<Derived> & v, IndexSet & s){ Derived ret; ret.resize(v.rows(),s.size()); auto size = v.cols(); decltype(size) k = 0; for(auto i : s){ if(i < size && i >=0){ ret.col(k++) = v.col(i); } }; return ret; } template<typename Derived> bool checkPointsInOOBB(const MatrixBase<Derived> & points, OOBB oobb){ Matrix33 A_KI = oobb.m_q_KI.matrix(); A_KI.transposeInPlace(); Vector3 p; bool allInside = true; auto size = points.cols(); decltype(size) i = 0; while(i<size && allInside){ p = A_KI * points.col(i); allInside &= ( p(0) >= oobb.m_minPoint(0) && p(0) <= oobb.m_maxPoint(0) && p(1) >= oobb.m_minPoint(1) && p(1) <= oobb.m_maxPoint(1) && p(2) >= oobb.m_minPoint(2) && p(2) <= oobb.m_maxPoint(2)); ++i; } return allInside; } } } #endif <commit_msg>assert bug fix<commit_after>// ======================================================================================== // ApproxMVBB // Copyright (C) 2014 by Gabriel Nützi <nuetzig (at) imes (d0t) mavt (d0t) ethz (døt) ch> // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // ======================================================================================== #ifndef TestFunctions_hpp #define TestFunctions_hpp #include <stdlib.h> #include <fstream> #include <functional> #include <gtest/gtest.h> #include "ApproxMVBB/Config/Config.hpp" #include "ApproxMVBB/Common/AssertionDebug.hpp" #include "ApproxMVBB/Common/SfinaeMacros.hpp" #include ApproxMVBB_TypeDefs_INCLUDE_FILE #include "ApproxMVBB/RandomGenerators.hpp" #include "ApproxMVBB/PointFunctions.hpp" #include "ApproxMVBB/OOBB.hpp" #define MY_TEST(name1 , name2 ) TEST(name1, name2) #define MY_TEST_RANDOM_STUFF(name) \ std::string testName = #name ; \ auto seed = hashString(#name); \ std::cout << "Seed for this test: " << seed << std::endl; \ ApproxMVBB::RandomGenerators::DefaultRandomGen rng(seed); \ std::uniform_real_distribution<PREC> uni(0.0,1.0); \ auto f = [&](PREC) { return uni(rng); }; namespace ApproxMVBB{ namespace TestFunctions{ ApproxMVBB_DEFINE_MATRIX_TYPES ApproxMVBB_DEFINE_POINTS_CONFIG_TYPES // TODO not std lib conform! std::size_t hashString(std::string name); template<typename A, typename B> ::testing::AssertionResult assertNearArrays( const A & a, const B & b, PREC absError = 1e-3) { if(a.size()!=b.size()){ return ::testing::AssertionFailure() << "not same size";} if(a.rows()!=b.rows()){ return ::testing::AssertionFailure() << "not same rows";} if( (( a - b ).array().abs() >= absError).any() ){ return ::testing::AssertionFailure() <<"not near: absTol:" << absError; } return ::testing::AssertionSuccess(); } template<bool matchCols , typename A, typename B, ApproxMVBB_SFINAE_ENABLE_IF( matchCols == true ) > ::testing::AssertionResult assertNearArrayColsRows_cr(const A & a, std::size_t i, const B & b, std::size_t j) { return assertNearArrays(a.col(i), b.col(j)); } template<bool matchCols , typename A, typename B, ApproxMVBB_SFINAE_ENABLE_IF( matchCols == false ) > ::testing::AssertionResult assertNearArrayColsRows_cr(const A & a, std::size_t i, const B & b, std::size_t j) { return assertNearArrays(a.row(i), b.row(j)); } template<bool matchCols = true, typename A, typename B> ::testing::AssertionResult assertNearArrayColsRows(const A & a, const B & b){ if(a.size()!=b.size()){ return ::testing::AssertionFailure() << "not same size";} if(a.rows()!=b.rows()){ return ::testing::AssertionFailure() << "not same rows";} // Check all points std::vector<bool> indexMatched; if(matchCols){ indexMatched.resize(a.cols(),false); }else{ indexMatched.resize(a.rows(),false); } auto s = indexMatched.size(); std::size_t nMatched = 0; std::size_t i = 0; std::size_t pointIdx = 0; while( pointIdx < s){ if( i < s){ // check points[pointIdx] against i-th valid one if ( !indexMatched[i] && assertNearArrayColsRows_cr<matchCols>(a,pointIdx,b,i)){ indexMatched[i] = true; ++nMatched; }else{ ++i; continue; } } // all indices i checked go to next point, reset check idx i = 0; ++pointIdx; } if(nMatched != s){ return ::testing::AssertionFailure() << "Matched only " << nMatched << "/" << s ; } return ::testing::AssertionSuccess(); } template<typename Derived> void dumpPointsMatrix(std::string filePath, const MatrixBase<Derived> & v) { std::ofstream l; l.open(filePath.c_str()); if(!l.good()){ ApproxMVBB_ERRORMSG("Could not open file: " << filePath << std::endl) } if(v.cols() != 0){ unsigned int i=0; for(; i<v.cols()-1; i++) { l << v.col(i).transpose().format(MyMatrixIOFormat::SpaceSep) << std::endl; } l << v.col(i).transpose().format(MyMatrixIOFormat::SpaceSep); } l.close(); } int isBigEndian(void); template <typename T> T swapEndian(T u) { ApproxMVBB_STATIC_ASSERTM(sizeof(char) == 1, "char != 8 bit"); union { T u; unsigned char u8[sizeof(T)]; } source, dest; source.u = u; for (size_t k = 0; k < sizeof(T); k++) dest.u8[k] = source.u8[sizeof(T) - k - 1]; return dest.u; } template<class Matrix> void dumpPointsMatrixBinary(std::string filename, const Matrix& matrix){ std::ofstream out(filename,std::ios::out | std::ios::binary | std::ios::trunc); typename Matrix::Index rows=matrix.rows(); typename Matrix::Index cols=matrix.cols(); ApproxMVBB_STATIC_ASSERT( sizeof(typename Matrix::Index) == 8 ) bool bigEndian = isBigEndian(); out.write((char*) (&bigEndian), sizeof(bool)); out.write((char*) (&rows), sizeof(typename Matrix::Index)); out.write((char*) (&cols), sizeof(typename Matrix::Index)); typename Matrix::Index bytes = sizeof(typename Matrix::Scalar); out.write((char*) (&bytes), sizeof(typename Matrix::Index )); out.write((char*) matrix.data(), rows*cols*sizeof(typename Matrix::Scalar) ); out.close(); } template<class Matrix> void readPointsMatrixBinary(std::string filename, Matrix& matrix, bool withHeader=true){ std::ifstream in(filename,std::ios::in | std::ios::binary); if(!in.is_open()){ ApproxMVBB_ERRORMSG("cannot open file: " << filename); } typename Matrix::Index rows=matrix.rows(); typename Matrix::Index cols=matrix.cols(); ApproxMVBB_STATIC_ASSERT( sizeof(typename Matrix::Index) == 8 ) bool bigEndian = false; // assume all input files with no headers are little endian! if(withHeader){ in.read((char*) (&bigEndian), sizeof(bool)); in.read((char*) (&rows),sizeof(typename Matrix::Index)); in.read((char*) (&cols),sizeof(typename Matrix::Index)); typename Matrix::Index bytes; in.read((char*) (&bytes), sizeof(typename Matrix::Index )); // swap endianness if file has other type if(isBigEndian() != bigEndian ){ rows = swapEndian(rows); cols = swapEndian(cols); bytes = swapEndian(bytes); } if(bytes != sizeof(typename Matrix::Scalar)){ ApproxMVBB_ERRORMSG("read binary with wrong data type: " << filename << "bigEndian: " << bigEndian << ", rows: " << rows << ", cols: " << cols <<", scalar bytes: " << bytes); } matrix.resize(rows, cols); } in.read( (char *) matrix.data() , rows*cols*sizeof(typename Matrix::Scalar) ); // swap endianness of whole matrix if file has other type if(isBigEndian() != bigEndian ){ auto f = [](const typename Matrix::Scalar & v){return swapEndian(v);}; matrix = matrix.unaryExpr( f ); } in.close(); } template<typename List, typename Derived> void convertMatrixToListRows(const MatrixBase<Derived> & M, List& points){ if (List::value_type::RowsAtCompileTime == M.cols()) { points.resize(M.rows()); for(std::size_t i = 0 ; i < M.rows(); ++i){ points[i] = M.row(i); } }else{ ApproxMVBB_ERRORMSG("points cannot be converted into list with vector size: " << List::value_type::RowsAtCompileTime) } } template<typename List, typename Derived> void convertMatrixToListCols(const MatrixBase<Derived> & M, List& points){ if (List::value_type::RowsAtCompileTime == M.rows()) { points.resize(M.cols()); for(std::size_t i = 0 ; i < M.cols(); ++i){ points[i] = M.col(i); } }else{ ApproxMVBB_ERRORMSG("points cannot be converted into list with vector size: " << List::value_type::RowsAtCompileTime) } } template<typename List, typename Derived> void convertMatrixToList_assCols(const MatrixBase<Derived> & M, List& points){ } template<typename Container> void dumpPoints(std::string filePath, Container & c) { std::ofstream l; l.open(filePath.c_str()); if(!l.good()){ ApproxMVBB_ERRORMSG("Could not open file: " << filePath << std::endl) } if(c.size()!=0){ auto e = c.begin() + (c.size() - 1); auto it = c.begin(); for(; it != e; ++it) { l << it->transpose().format(MyMatrixIOFormat::SpaceSep) << std::endl; } l << (it)->transpose().format(MyMatrixIOFormat::SpaceSep); } l.close(); } void readOOBB(std::string filePath, Vector3 & minP, Vector3 & maxP, Matrix33 & R_KI, Vector3List & pointList); void readOOBBAndCheck( OOBB & validOOBB, std::string filePath); void dumpOOBB(std::string filePath, const OOBB & oobb); Vector3List getPointsFromFile3D(std::string filePath); Vector2List getPointsFromFile2D(std::string filePath); // Vector2List generatePoints2D(unsigned int n=4); // // Vector3List generatePoints3D(unsigned int n=4); template<typename Derived, typename IndexSet> Derived filterPoints(MatrixBase<Derived> & v, IndexSet & s){ Derived ret; ret.resize(v.rows(),s.size()); auto size = v.cols(); decltype(size) k = 0; for(auto i : s){ if(i < size && i >=0){ ret.col(k++) = v.col(i); } }; return ret; } template<typename Derived> bool checkPointsInOOBB(const MatrixBase<Derived> & points, OOBB oobb){ Matrix33 A_KI = oobb.m_q_KI.matrix(); A_KI.transposeInPlace(); Vector3 p; bool allInside = true; auto size = points.cols(); decltype(size) i = 0; while(i<size && allInside){ p = A_KI * points.col(i); allInside &= ( p(0) >= oobb.m_minPoint(0) && p(0) <= oobb.m_maxPoint(0) && p(1) >= oobb.m_minPoint(1) && p(1) <= oobb.m_maxPoint(1) && p(2) >= oobb.m_minPoint(2) && p(2) <= oobb.m_maxPoint(2)); ++i; } return allInside; } } } #endif <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // PelotonDB // // logging_test.cpp // // Identification: tests/logging/logging_test.cpp // // Copyright (c) 2016, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <sys/stat.h> #include <sys/types.h> #include <sys/mman.h> #include <dirent.h> #include "harness.h" #include "backend/concurrency/transaction_manager_factory.h" #include "backend/executor/logical_tile_factory.h" #include "backend/storage/data_table.h" #include "backend/storage/tile.h" #include "backend/logging/loggers/wal_frontend_logger.h" #include "backend/storage/table_factory.h" #include "backend/logging/log_manager.h" #include "backend/index/index.h" #include "backend/logging/logging_util.h" #include "logging/logging_tests_util.h" #include "executor/mock_executor.h" #include "executor/executor_tests_util.h" #define DEFAULT_RECOVERY_CID 15 using ::testing::NotNull; using ::testing::Return; using ::testing::InSequence; namespace peloton { namespace test { //===--------------------------------------------------------------------===// // Recovery Tests //===--------------------------------------------------------------------===// class RecoveryTests : public PelotonTest {}; std::vector<storage::Tuple *> BuildLoggingTuples(storage::DataTable *table, int num_rows, bool mutate, bool random) { std::vector<storage::Tuple *> tuples; LOG_INFO("build a vector of %d tuples", num_rows); // Random values std::srand(std::time(nullptr)); const catalog::Schema *schema = table->GetSchema(); // Ensure that the tile group is as expected. assert(schema->GetColumnCount() == 4); // Insert tuples into tile_group. const bool allocate = true; auto testing_pool = TestingHarness::GetInstance().GetTestingPool(); for (int rowid = 0; rowid < num_rows; rowid++) { int populate_value = rowid; if (mutate) populate_value *= 3; storage::Tuple *tuple = new storage::Tuple(schema, allocate); // First column is unique in this case tuple->SetValue(0, ValueFactory::GetIntegerValue( ExecutorTestsUtil::PopulatedValue(populate_value, 0)), testing_pool); // In case of random, make sure this column has duplicated values tuple->SetValue( 1, ValueFactory::GetIntegerValue(ExecutorTestsUtil::PopulatedValue( random ? std::rand() % (num_rows / 3) : populate_value, 1)), testing_pool); tuple->SetValue( 2, ValueFactory::GetDoubleValue(ExecutorTestsUtil::PopulatedValue( random ? std::rand() : populate_value, 2)), testing_pool); // In case of random, make sure this column has duplicated values Value string_value = ValueFactory::GetStringValue( std::to_string(ExecutorTestsUtil::PopulatedValue( random ? std::rand() % (num_rows / 3) : populate_value, 3))); tuple->SetValue(3, string_value, testing_pool); tuples.push_back(tuple); } return tuples; } TEST_F(RecoveryTests, RestartTest) { auto recovery_table = ExecutorTestsUtil::CreateTable(1024); auto &manager = catalog::Manager::GetInstance(); size_t tile_group_size = 5; size_t table_tile_group_count = 3; int num_files = 3; auto mutate = true; auto random = false; cid_t default_commit_id = INVALID_CID; cid_t default_delimiter = INVALID_CID; std::string dir_name = "pl_log0"; storage::Database db(DEFAULT_DB_ID); manager.AddDatabase(&db); db.AddTable(recovery_table); int num_rows = tile_group_size * table_tile_group_count; std::vector<std::shared_ptr<storage::Tuple>> tuples = LoggingTestsUtil::BuildTuples(recovery_table, num_rows, mutate, random); std::vector<logging::TupleRecord> records = LoggingTestsUtil::BuildTupleRecordsForRestartTest(tuples, tile_group_size, table_tile_group_count); auto status = logging::LoggingUtil::CreateDirectory(dir_name.c_str(), 0700); EXPECT_EQ(status, true); for (int i = 0; i < num_files; i++) { std::string file_name = dir_name + "/" + std::string("peloton_log_") + std::to_string(i) + std::string(".log"); FILE *fp = fopen(file_name.c_str(), "wb"); // now set the first 8 bytes to 0 - this is for the max_log id in this file fwrite((void *)&default_commit_id, sizeof(default_commit_id), 1, fp); // now set the next 8 bytes to 0 - this is for the max delimiter in this // file fwrite((void *)&default_delimiter, sizeof(default_delimiter), 1, fp); // First write a begin record CopySerializeOutput output_buffer_begin; logging::TransactionRecord record_begin(LOGRECORD_TYPE_TRANSACTION_BEGIN, i + 2); record_begin.Serialize(output_buffer_begin); fwrite(record_begin.GetMessage(), sizeof(char), record_begin.GetMessageLength(), fp); // Now write 5 insert tuple records into this file for (int j = 0; j < (int)tile_group_size; j++) { int num_record = i * tile_group_size + j; CopySerializeOutput output_buffer; records[num_record].Serialize(output_buffer); fwrite(records[num_record].GetMessage(), sizeof(char), records[num_record].GetMessageLength(), fp); } // Now write commit logging::TransactionRecord record_commit(LOGRECORD_TYPE_TRANSACTION_COMMIT, i + 2); CopySerializeOutput output_buffer_commit; record_commit.Serialize(output_buffer_commit); fwrite(record_commit.GetMessage(), sizeof(char), record_commit.GetMessageLength(), fp); // Now write delimiter CopySerializeOutput output_buffer_delim; logging::TransactionRecord record_delim(LOGRECORD_TYPE_ITERATION_DELIMITER, i + 2); record_delim.Serialize(output_buffer_delim); fwrite(record_delim.GetMessage(), sizeof(char), record_delim.GetMessageLength(), fp); fclose(fp); } int index_count = recovery_table->GetIndexCount(); LOG_INFO("Number of indexes on this table: %d", (int)index_count); for (int index_itr = index_count - 1; index_itr >= 0; --index_itr) { auto index = recovery_table->GetIndex(index_itr); EXPECT_EQ(index->GetNumberOfTuples(), 0); } logging::WriteAheadFrontendLogger wal_fel(std::string("pl_log")); EXPECT_EQ(wal_fel.GetMaxDelimiterForRecovery(), num_files + 1); EXPECT_EQ(wal_fel.GetLogFileCounter(), num_files); EXPECT_EQ(recovery_table->GetNumberOfTuples(), 0); auto &log_manager = logging::LogManager::GetInstance(); log_manager.SetGlobalMaxFlushedIdForRecovery(num_files + 1); wal_fel.DoRecovery(); EXPECT_EQ(recovery_table->GetNumberOfTuples(), tile_group_size * table_tile_group_count); EXPECT_EQ(wal_fel.GetLogFileCursor(), num_files); wal_fel.RecoverIndex(); for (int index_itr = index_count - 1; index_itr >= 0; --index_itr) { auto index = recovery_table->GetIndex(index_itr); EXPECT_EQ(index->GetNumberOfTuples(), tile_group_size * table_tile_group_count); } for (int i = 0; i < num_files; i++) { int return_val = remove((dir_name + "/" + std::string("peloton_log_") + std::to_string(i) + (".log")).c_str()); EXPECT_EQ(return_val, 0); } status = logging::LoggingUtil::RemoveDirectory("pl_log0", false); EXPECT_EQ(status, true); } TEST_F(RecoveryTests, BasicInsertTest) { auto recovery_table = ExecutorTestsUtil::CreateTable(1024); auto &manager = catalog::Manager::GetInstance(); storage::Database db(DEFAULT_DB_ID); manager.AddDatabase(&db); db.AddTable(recovery_table); auto tuples = BuildLoggingTuples(recovery_table, 1, false, false); EXPECT_EQ(recovery_table->GetNumberOfTuples(), 0); EXPECT_EQ(recovery_table->GetTileGroupCount(), 1); EXPECT_EQ(tuples.size(), 1); logging::WriteAheadFrontendLogger fel(true); // auto bel = logging::WriteAheadBackendLogger::GetInstance(); cid_t test_commit_id = 10; Value val0 = tuples[0]->GetValue(0); Value val1 = tuples[0]->GetValue(1); Value val2 = tuples[0]->GetValue(2); Value val3 = tuples[0]->GetValue(3); auto curr_rec = new logging::TupleRecord( LOGRECORD_TYPE_TUPLE_INSERT, test_commit_id, recovery_table->GetOid(), ItemPointer(100, 5), INVALID_ITEMPOINTER, tuples[0], DEFAULT_DB_ID); curr_rec->SetTuple(tuples[0]); fel.InsertTuple(curr_rec); delete curr_rec; auto tg_header = recovery_table->GetTileGroupById(100)->GetHeader(); EXPECT_TRUE(tg_header->GetBeginCommitId(5) <= test_commit_id); EXPECT_EQ(tg_header->GetEndCommitId(5), MAX_CID); EXPECT_TRUE( val0.Compare(recovery_table->GetTileGroupById(100)->GetValue(5, 0)) == 0); EXPECT_TRUE( val1.Compare(recovery_table->GetTileGroupById(100)->GetValue(5, 1)) == 0); EXPECT_TRUE( val2.Compare(recovery_table->GetTileGroupById(100)->GetValue(5, 2)) == 0); EXPECT_TRUE( val3.Compare(recovery_table->GetTileGroupById(100)->GetValue(5, 3)) == 0); EXPECT_EQ(recovery_table->GetNumberOfTuples(), 1); EXPECT_EQ(recovery_table->GetTileGroupCount(), 2); } TEST_F(RecoveryTests, BasicUpdateTest) { auto recovery_table = ExecutorTestsUtil::CreateTable(1024); auto &manager = catalog::Manager::GetInstance(); storage::Database db(DEFAULT_DB_ID); manager.AddDatabase(&db); db.AddTable(recovery_table); auto tuples = BuildLoggingTuples(recovery_table, 1, false, false); EXPECT_EQ(recovery_table->GetNumberOfTuples(), 0); EXPECT_EQ(recovery_table->GetTileGroupCount(), 1); EXPECT_EQ(tuples.size(), 1); logging::WriteAheadFrontendLogger fel(true); // auto bel = logging::WriteAheadBackendLogger::GetInstance(); cid_t test_commit_id = 10; Value val0 = tuples[0]->GetValue(0); Value val1 = tuples[0]->GetValue(1); Value val2 = tuples[0]->GetValue(2); Value val3 = tuples[0]->GetValue(3); auto curr_rec = new logging::TupleRecord( LOGRECORD_TYPE_TUPLE_UPDATE, test_commit_id, recovery_table->GetOid(), ItemPointer(100, 5), ItemPointer(100, 4), tuples[0], DEFAULT_DB_ID); curr_rec->SetTuple(tuples[0]); fel.UpdateTuple(curr_rec); delete curr_rec; auto tg_header = recovery_table->GetTileGroupById(100)->GetHeader(); EXPECT_TRUE(tg_header->GetBeginCommitId(5) <= test_commit_id); EXPECT_EQ(tg_header->GetEndCommitId(5), MAX_CID); EXPECT_EQ(tg_header->GetEndCommitId(4), test_commit_id); EXPECT_TRUE( val0.Compare(recovery_table->GetTileGroupById(100)->GetValue(5, 0)) == 0); EXPECT_TRUE( val1.Compare(recovery_table->GetTileGroupById(100)->GetValue(5, 1)) == 0); EXPECT_TRUE( val2.Compare(recovery_table->GetTileGroupById(100)->GetValue(5, 2)) == 0); EXPECT_TRUE( val3.Compare(recovery_table->GetTileGroupById(100)->GetValue(5, 3)) == 0); EXPECT_EQ(recovery_table->GetNumberOfTuples(), 0); EXPECT_EQ(recovery_table->GetTileGroupCount(), 2); } /* (From Joy) TODO FIX this TEST_F(RecoveryTests, BasicDeleteTest) { auto recovery_table = ExecutorTestsUtil::CreateTable(1024); auto &manager = catalog::Manager::GetInstance(); storage::Database db(DEFAULT_DB_ID); manager.AddDatabase(&db); db.AddTable(recovery_table); EXPECT_EQ(recovery_table->GetNumberOfTuples(), 0); EXPECT_EQ(recovery_table->GetTileGroupCount(), 1); logging::WriteAheadFrontendLogger fel(true); cid_t test_commit_id = 10; auto curr_rec = new logging::TupleRecord( LOGRECORD_TYPE_TUPLE_UPDATE, test_commit_id, recovery_table->GetOid(), INVALID_ITEMPOINTER, ItemPointer(100, 4), nullptr, DEFAULT_DB_ID); fel.DeleteTuple(curr_rec); delete curr_rec; auto tg_header = recovery_table->GetTileGroupById(100)->GetHeader(); EXPECT_EQ(tg_header->GetEndCommitId(4), test_commit_id); // EXPECT_EQ(recovery_table->GetNumberOfTuples(), 1); EXPECT_EQ(recovery_table->GetTileGroupCount(), 2); }*/ TEST_F(RecoveryTests, OutOfOrderCommitTest) { auto recovery_table = ExecutorTestsUtil::CreateTable(1024); auto &manager = catalog::Manager::GetInstance(); storage::Database db(DEFAULT_DB_ID); manager.AddDatabase(&db); db.AddTable(recovery_table); auto tuples = BuildLoggingTuples(recovery_table, 1, false, false); EXPECT_EQ(recovery_table->GetNumberOfTuples(), 0); EXPECT_EQ(recovery_table->GetTileGroupCount(), 1); EXPECT_EQ(tuples.size(), 1); logging::WriteAheadFrontendLogger fel(true); // auto bel = logging::WriteAheadBackendLogger::GetInstance(); cid_t test_commit_id = 10; auto curr_rec = new logging::TupleRecord( LOGRECORD_TYPE_TUPLE_UPDATE, test_commit_id + 1, recovery_table->GetOid(), INVALID_ITEMPOINTER, ItemPointer(100, 5), nullptr, DEFAULT_DB_ID); fel.DeleteTuple(curr_rec); delete curr_rec; EXPECT_EQ(recovery_table->GetTileGroupCount(), 2); curr_rec = new logging::TupleRecord( LOGRECORD_TYPE_TUPLE_INSERT, test_commit_id, recovery_table->GetOid(), ItemPointer(100, 5), INVALID_ITEMPOINTER, tuples[0], DEFAULT_DB_ID); curr_rec->SetTuple(tuples[0]); fel.InsertTuple(curr_rec); delete curr_rec; auto tg_header = recovery_table->GetTileGroupById(100)->GetHeader(); EXPECT_EQ(tg_header->GetEndCommitId(5), test_commit_id + 1); EXPECT_EQ(recovery_table->GetNumberOfTuples(), 0); EXPECT_EQ(recovery_table->GetTileGroupCount(), 2); } } // End test namespace } // End peloton namespace <commit_msg>test CreateNewLogFile<commit_after>//===----------------------------------------------------------------------===// // // PelotonDB // // logging_test.cpp // // Identification: tests/logging/logging_test.cpp // // Copyright (c) 2016, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <sys/stat.h> #include <sys/types.h> #include <sys/mman.h> #include <dirent.h> #include "harness.h" #include "backend/concurrency/transaction_manager_factory.h" #include "backend/executor/logical_tile_factory.h" #include "backend/storage/data_table.h" #include "backend/storage/tile.h" #include "backend/logging/loggers/wal_frontend_logger.h" #include "backend/storage/table_factory.h" #include "backend/logging/log_manager.h" #include "backend/index/index.h" #include "backend/logging/logging_util.h" #include "logging/logging_tests_util.h" #include "executor/mock_executor.h" #include "executor/executor_tests_util.h" #define DEFAULT_RECOVERY_CID 15 using ::testing::NotNull; using ::testing::Return; using ::testing::InSequence; namespace peloton { namespace test { //===--------------------------------------------------------------------===// // Recovery Tests //===--------------------------------------------------------------------===// class RecoveryTests : public PelotonTest {}; std::vector<storage::Tuple *> BuildLoggingTuples(storage::DataTable *table, int num_rows, bool mutate, bool random) { std::vector<storage::Tuple *> tuples; LOG_INFO("build a vector of %d tuples", num_rows); // Random values std::srand(std::time(nullptr)); const catalog::Schema *schema = table->GetSchema(); // Ensure that the tile group is as expected. assert(schema->GetColumnCount() == 4); // Insert tuples into tile_group. const bool allocate = true; auto testing_pool = TestingHarness::GetInstance().GetTestingPool(); for (int rowid = 0; rowid < num_rows; rowid++) { int populate_value = rowid; if (mutate) populate_value *= 3; storage::Tuple *tuple = new storage::Tuple(schema, allocate); // First column is unique in this case tuple->SetValue(0, ValueFactory::GetIntegerValue( ExecutorTestsUtil::PopulatedValue(populate_value, 0)), testing_pool); // In case of random, make sure this column has duplicated values tuple->SetValue( 1, ValueFactory::GetIntegerValue(ExecutorTestsUtil::PopulatedValue( random ? std::rand() % (num_rows / 3) : populate_value, 1)), testing_pool); tuple->SetValue( 2, ValueFactory::GetDoubleValue(ExecutorTestsUtil::PopulatedValue( random ? std::rand() : populate_value, 2)), testing_pool); // In case of random, make sure this column has duplicated values Value string_value = ValueFactory::GetStringValue( std::to_string(ExecutorTestsUtil::PopulatedValue( random ? std::rand() % (num_rows / 3) : populate_value, 3))); tuple->SetValue(3, string_value, testing_pool); tuples.push_back(tuple); } return tuples; } TEST_F(RecoveryTests, RestartTest) { auto recovery_table = ExecutorTestsUtil::CreateTable(1024); auto &manager = catalog::Manager::GetInstance(); size_t tile_group_size = 5; size_t table_tile_group_count = 3; int num_files = 3; auto mutate = true; auto random = false; cid_t default_commit_id = INVALID_CID; cid_t default_delimiter = INVALID_CID; std::string dir_name = "pl_log0"; storage::Database db(DEFAULT_DB_ID); manager.AddDatabase(&db); db.AddTable(recovery_table); int num_rows = tile_group_size * table_tile_group_count; std::vector<std::shared_ptr<storage::Tuple>> tuples = LoggingTestsUtil::BuildTuples(recovery_table, num_rows, mutate, random); std::vector<logging::TupleRecord> records = LoggingTestsUtil::BuildTupleRecordsForRestartTest(tuples, tile_group_size, table_tile_group_count); auto status = logging::LoggingUtil::CreateDirectory(dir_name.c_str(), 0700); EXPECT_EQ(status, true); for (int i = 0; i < num_files; i++) { std::string file_name = dir_name + "/" + std::string("peloton_log_") + std::to_string(i) + std::string(".log"); FILE *fp = fopen(file_name.c_str(), "wb"); // now set the first 8 bytes to 0 - this is for the max_log id in this file fwrite((void *)&default_commit_id, sizeof(default_commit_id), 1, fp); // now set the next 8 bytes to 0 - this is for the max delimiter in this // file fwrite((void *)&default_delimiter, sizeof(default_delimiter), 1, fp); // First write a begin record CopySerializeOutput output_buffer_begin; logging::TransactionRecord record_begin(LOGRECORD_TYPE_TRANSACTION_BEGIN, i + 2); record_begin.Serialize(output_buffer_begin); fwrite(record_begin.GetMessage(), sizeof(char), record_begin.GetMessageLength(), fp); // Now write 5 insert tuple records into this file for (int j = 0; j < (int)tile_group_size; j++) { int num_record = i * tile_group_size + j; CopySerializeOutput output_buffer; records[num_record].Serialize(output_buffer); fwrite(records[num_record].GetMessage(), sizeof(char), records[num_record].GetMessageLength(), fp); } // Now write commit logging::TransactionRecord record_commit(LOGRECORD_TYPE_TRANSACTION_COMMIT, i + 2); CopySerializeOutput output_buffer_commit; record_commit.Serialize(output_buffer_commit); fwrite(record_commit.GetMessage(), sizeof(char), record_commit.GetMessageLength(), fp); // Now write delimiter CopySerializeOutput output_buffer_delim; logging::TransactionRecord record_delim(LOGRECORD_TYPE_ITERATION_DELIMITER, i + 2); record_delim.Serialize(output_buffer_delim); fwrite(record_delim.GetMessage(), sizeof(char), record_delim.GetMessageLength(), fp); fclose(fp); } int index_count = recovery_table->GetIndexCount(); LOG_INFO("Number of indexes on this table: %d", (int)index_count); for (int index_itr = index_count - 1; index_itr >= 0; --index_itr) { auto index = recovery_table->GetIndex(index_itr); EXPECT_EQ(index->GetNumberOfTuples(), 0); } logging::WriteAheadFrontendLogger wal_fel(std::string("pl_log")); EXPECT_EQ(wal_fel.GetMaxDelimiterForRecovery(), num_files + 1); EXPECT_EQ(wal_fel.GetLogFileCounter(), num_files); EXPECT_EQ(recovery_table->GetNumberOfTuples(), 0); auto &log_manager = logging::LogManager::GetInstance(); log_manager.SetGlobalMaxFlushedIdForRecovery(num_files + 1); wal_fel.DoRecovery(); EXPECT_EQ(recovery_table->GetNumberOfTuples(), tile_group_size * table_tile_group_count); EXPECT_EQ(wal_fel.GetLogFileCursor(), num_files); wal_fel.RecoverIndex(); for (int index_itr = index_count - 1; index_itr >= 0; --index_itr) { auto index = recovery_table->GetIndex(index_itr); EXPECT_EQ(index->GetNumberOfTuples(), tile_group_size * table_tile_group_count); } // TODO check a few more invariants here wal_fel.CreateNewLogFile(false); EXPECT_EQ(wal_fel.GetLogFileCounter(), num_files + 1); wal_fel.CreateNewLogFile(true); EXPECT_EQ(wal_fel.GetLogFileCounter(), num_files + 2); status = logging::LoggingUtil::RemoveDirectory("pl_log0", false); EXPECT_EQ(status, true); } TEST_F(RecoveryTests, BasicInsertTest) { auto recovery_table = ExecutorTestsUtil::CreateTable(1024); auto &manager = catalog::Manager::GetInstance(); storage::Database db(DEFAULT_DB_ID); manager.AddDatabase(&db); db.AddTable(recovery_table); auto tuples = BuildLoggingTuples(recovery_table, 1, false, false); EXPECT_EQ(recovery_table->GetNumberOfTuples(), 0); EXPECT_EQ(recovery_table->GetTileGroupCount(), 1); EXPECT_EQ(tuples.size(), 1); logging::WriteAheadFrontendLogger fel(true); // auto bel = logging::WriteAheadBackendLogger::GetInstance(); cid_t test_commit_id = 10; Value val0 = tuples[0]->GetValue(0); Value val1 = tuples[0]->GetValue(1); Value val2 = tuples[0]->GetValue(2); Value val3 = tuples[0]->GetValue(3); auto curr_rec = new logging::TupleRecord( LOGRECORD_TYPE_TUPLE_INSERT, test_commit_id, recovery_table->GetOid(), ItemPointer(100, 5), INVALID_ITEMPOINTER, tuples[0], DEFAULT_DB_ID); curr_rec->SetTuple(tuples[0]); fel.InsertTuple(curr_rec); delete curr_rec; auto tg_header = recovery_table->GetTileGroupById(100)->GetHeader(); EXPECT_TRUE(tg_header->GetBeginCommitId(5) <= test_commit_id); EXPECT_EQ(tg_header->GetEndCommitId(5), MAX_CID); EXPECT_TRUE( val0.Compare(recovery_table->GetTileGroupById(100)->GetValue(5, 0)) == 0); EXPECT_TRUE( val1.Compare(recovery_table->GetTileGroupById(100)->GetValue(5, 1)) == 0); EXPECT_TRUE( val2.Compare(recovery_table->GetTileGroupById(100)->GetValue(5, 2)) == 0); EXPECT_TRUE( val3.Compare(recovery_table->GetTileGroupById(100)->GetValue(5, 3)) == 0); EXPECT_EQ(recovery_table->GetNumberOfTuples(), 1); EXPECT_EQ(recovery_table->GetTileGroupCount(), 2); } TEST_F(RecoveryTests, BasicUpdateTest) { auto recovery_table = ExecutorTestsUtil::CreateTable(1024); auto &manager = catalog::Manager::GetInstance(); storage::Database db(DEFAULT_DB_ID); manager.AddDatabase(&db); db.AddTable(recovery_table); auto tuples = BuildLoggingTuples(recovery_table, 1, false, false); EXPECT_EQ(recovery_table->GetNumberOfTuples(), 0); EXPECT_EQ(recovery_table->GetTileGroupCount(), 1); EXPECT_EQ(tuples.size(), 1); logging::WriteAheadFrontendLogger fel(true); // auto bel = logging::WriteAheadBackendLogger::GetInstance(); cid_t test_commit_id = 10; Value val0 = tuples[0]->GetValue(0); Value val1 = tuples[0]->GetValue(1); Value val2 = tuples[0]->GetValue(2); Value val3 = tuples[0]->GetValue(3); auto curr_rec = new logging::TupleRecord( LOGRECORD_TYPE_TUPLE_UPDATE, test_commit_id, recovery_table->GetOid(), ItemPointer(100, 5), ItemPointer(100, 4), tuples[0], DEFAULT_DB_ID); curr_rec->SetTuple(tuples[0]); fel.UpdateTuple(curr_rec); delete curr_rec; auto tg_header = recovery_table->GetTileGroupById(100)->GetHeader(); EXPECT_TRUE(tg_header->GetBeginCommitId(5) <= test_commit_id); EXPECT_EQ(tg_header->GetEndCommitId(5), MAX_CID); EXPECT_EQ(tg_header->GetEndCommitId(4), test_commit_id); EXPECT_TRUE( val0.Compare(recovery_table->GetTileGroupById(100)->GetValue(5, 0)) == 0); EXPECT_TRUE( val1.Compare(recovery_table->GetTileGroupById(100)->GetValue(5, 1)) == 0); EXPECT_TRUE( val2.Compare(recovery_table->GetTileGroupById(100)->GetValue(5, 2)) == 0); EXPECT_TRUE( val3.Compare(recovery_table->GetTileGroupById(100)->GetValue(5, 3)) == 0); EXPECT_EQ(recovery_table->GetNumberOfTuples(), 0); EXPECT_EQ(recovery_table->GetTileGroupCount(), 2); } /* (From Joy) TODO FIX this TEST_F(RecoveryTests, BasicDeleteTest) { auto recovery_table = ExecutorTestsUtil::CreateTable(1024); auto &manager = catalog::Manager::GetInstance(); storage::Database db(DEFAULT_DB_ID); manager.AddDatabase(&db); db.AddTable(recovery_table); EXPECT_EQ(recovery_table->GetNumberOfTuples(), 0); EXPECT_EQ(recovery_table->GetTileGroupCount(), 1); logging::WriteAheadFrontendLogger fel(true); cid_t test_commit_id = 10; auto curr_rec = new logging::TupleRecord( LOGRECORD_TYPE_TUPLE_UPDATE, test_commit_id, recovery_table->GetOid(), INVALID_ITEMPOINTER, ItemPointer(100, 4), nullptr, DEFAULT_DB_ID); fel.DeleteTuple(curr_rec); delete curr_rec; auto tg_header = recovery_table->GetTileGroupById(100)->GetHeader(); EXPECT_EQ(tg_header->GetEndCommitId(4), test_commit_id); // EXPECT_EQ(recovery_table->GetNumberOfTuples(), 1); EXPECT_EQ(recovery_table->GetTileGroupCount(), 2); }*/ TEST_F(RecoveryTests, OutOfOrderCommitTest) { auto recovery_table = ExecutorTestsUtil::CreateTable(1024); auto &manager = catalog::Manager::GetInstance(); storage::Database db(DEFAULT_DB_ID); manager.AddDatabase(&db); db.AddTable(recovery_table); auto tuples = BuildLoggingTuples(recovery_table, 1, false, false); EXPECT_EQ(recovery_table->GetNumberOfTuples(), 0); EXPECT_EQ(recovery_table->GetTileGroupCount(), 1); EXPECT_EQ(tuples.size(), 1); logging::WriteAheadFrontendLogger fel(true); // auto bel = logging::WriteAheadBackendLogger::GetInstance(); cid_t test_commit_id = 10; auto curr_rec = new logging::TupleRecord( LOGRECORD_TYPE_TUPLE_UPDATE, test_commit_id + 1, recovery_table->GetOid(), INVALID_ITEMPOINTER, ItemPointer(100, 5), nullptr, DEFAULT_DB_ID); fel.DeleteTuple(curr_rec); delete curr_rec; EXPECT_EQ(recovery_table->GetTileGroupCount(), 2); curr_rec = new logging::TupleRecord( LOGRECORD_TYPE_TUPLE_INSERT, test_commit_id, recovery_table->GetOid(), ItemPointer(100, 5), INVALID_ITEMPOINTER, tuples[0], DEFAULT_DB_ID); curr_rec->SetTuple(tuples[0]); fel.InsertTuple(curr_rec); delete curr_rec; auto tg_header = recovery_table->GetTileGroupById(100)->GetHeader(); EXPECT_EQ(tg_header->GetEndCommitId(5), test_commit_id + 1); EXPECT_EQ(recovery_table->GetNumberOfTuples(), 0); EXPECT_EQ(recovery_table->GetTileGroupCount(), 2); } } // End test namespace } // End peloton namespace <|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <fstream> #include <vector> #include <string> #include <stdio.h> #include <stdlib.h> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/algorithm/string.hpp> #include "testdriverconfig.h" // SRC and BIN dir definitions #include "specification.h" // parsing spec files #include <zorba/zorba.h> #include <zorba/error_handler.h> #include <zorba/exception.h> namespace fs = boost::filesystem; void printFile(std::ostream& os, std::string aInFile) { std::ifstream lInFileStream(aInFile.c_str()); assert(lInFileStream); os << lInFileStream.rdbuf() << std::endl; } // print parts of a file // starting at aStartPos with the length of aLen void printPart(std::ostream& os, std::string aInFile, int aStartPos, int aLen) { char* buffer = new char [aLen]; try { std::ifstream lIn(aInFile.c_str()); lIn.seekg(aStartPos); int lCharsRead = lIn.readsome (buffer, aLen); os.write (buffer, lCharsRead); os.flush(); delete[] buffer; } catch (...) { delete[] buffer; } return; } bool isErrorExpected(zorba::ZorbaException& e, State* aState) { if ( aState->hasErrors) { std::vector<std::string>::const_iterator lIter = aState->theErrors.begin(); std::vector<std::string>::const_iterator lEnd = aState->theErrors.end(); zorba::String lError = zorba::ZorbaError::getErrorCode(e.getErrorCode()); for(;lIter!=lEnd;++lIter) { zorba::String lSpecError = *lIter; if (lError.compare(lSpecError) == 0) { return true; } } } return false; } zorba::XQuery::CompilerHints getCompilerHints() { zorba::XQuery::CompilerHints lHints; // ZORBA_OPTLEVEL=O0 | O1 char* lOptLevel = getenv("ZORBA_OPTLEVEL"); if ( lOptLevel != NULL && strcmp(lOptLevel, "O0") == 0 ) { lHints.opt_level = zorba::XQuery::CompilerHints::O0; std::cout << "testdriver is using optimization level O0" << std::endl; } else { lHints.opt_level = zorba::XQuery::CompilerHints::O1; std::cout << "testdriver is using optimization level O1" << std::endl; } return lHints; } // set a variable in the dynamic context // inlineFile specifies whether the given parameter is a file and it's value should // be inlined or not void set_var (bool inlineFile, std::string name, std::string val, zorba::DynamicContext_t dctx) { boost::replace_all(val, "$UPDATE_SRC_DIR", zorba::UPDATE_SRC_DIR); zorba::ItemFactory* lFactory = zorba::Zorba::getInstance()->getItemFactory(); if (!inlineFile) { zorba::Item lItem = lFactory->createString(val); if(name != ".") dctx->setVariable (name, lItem); else dctx->setContextItem (lItem); } else { std::ifstream is (val.c_str ()); assert (is); if(name != ".") dctx->setVariableAsDocument (name, val.c_str(), is); else dctx->setContextItemAsDocument (val.c_str(), is); } } // return false if the files are not equal // aLine contains the line number in which the first difference occurs // aCol contains the column number in which the first difference occurs // aPos is the character number off the first difference in the file // -1 is returned for aLine, aCol, and aPos if the files are equal bool isEqual(fs::path aRefFile, fs::path aResFile, int& aLine, int& aCol, int& aPos) { std::ifstream li(aRefFile.native_file_string().c_str()); std::ifstream ri(aResFile.native_file_string().c_str()); std::string lLine, rLine; aLine = 1; aCol = 0; aPos = -1; while (! li.eof() ) { if ( ri.eof() ) { std::getline(li, lLine); if (li.peek() == -1) // ignore end-of-line in the ref result return true; else return false; } std::getline(li, lLine); std::getline(ri, rLine); ++aLine; if ( (aCol = lLine.compare(rLine)) != 0) { return false; } } return true; } int #ifdef _WIN32_WCE _tmain(int argc, _TCHAR* argv[]) #else main(int argc, char** argv) #endif { fs::path lSpecFile, lResultFile; fs::path lSpecPath, lRefPath, lResultPath; Specification lSpec; if (argc != 2) { std::cerr << "\nusage: testdriver [testfile]" << std::endl; return 1; } // do initial stuff { std::string lSpecFileString = zorba::UPDATE_SRC_DIR +"/Queries/" + argv[1]; lSpecFile = fs::system_complete( fs::path( lSpecFileString, fs::native ) ); lSpecPath = fs::system_complete(fs::path(lSpecFile.branch_path().string(), fs::native )); std::string lSpecWithoutSuffix = std::string(argv[1]).substr( 0, std::string(argv[1]).size()-5 ); std::cout << "test " << lSpecWithoutSuffix << std::endl; lResultFile = fs::system_complete(fs::path( zorba::UPDATE_BINARY_DIR +"/QueryResults/" +lSpecWithoutSuffix + ".res", fs::native) ); lResultPath = fs::system_complete(fs::path(lResultFile.branch_path().string(), fs::native )); fs::path lRefFile = fs::system_complete(fs::path( zorba::UPDATE_SRC_DIR +"/ExpectedTestResults/" +lSpecWithoutSuffix +".xml.res", fs::native) ); lRefPath = fs::system_complete(fs::path(lRefFile.branch_path().string(), fs::native )); } // does the spec file exists if ( (! fs::exists( lSpecFile )) || fs::is_directory( lSpecFile) ) { std::cerr << "\n spec file " << lSpecFile.native_file_string() << " does not exist or is not a file" << std::endl; return 2; } // create the result directory if ( ! fs::exists( lResultPath ) ) fs::create_directories(lResultPath); // create deep directories // read the xargs and errors if the spec file exists lSpec.parseFile(lSpecFile.native_file_string()); zorba::Zorba *engine = zorba::Zorba::getInstance(); std::vector<zorba::XQuery_t> lQueries; zorba::XQuery::SerializerOptions lSerOptions; lSerOptions.omit_xml_declaration = zorba::XQuery::SerializerOptions::omit_xml_declaration::YES; // create and compile the query { std::vector<State*>::const_iterator lIter = lSpec.statesBegin(); std::vector<State*>::const_iterator lEnd = lSpec.statesEnd(); int lRun = 0; for(;lIter!=lEnd;++lIter) { State* lState = *lIter; std::string lQueryFile = lSpecPath.native_file_string() + "/" + (*lIter)->theName + ".xq"; std::cout << std::endl << "Query (Run " << ++lRun << "):" << std::endl; printFile(std::cout, lQueryFile); std::cout << std::endl; std::ifstream lQueryStream(lQueryFile.c_str()); try { lQueries.push_back(engine->compileQuery(lQueryStream, getCompilerHints())); } catch (zorba::ZorbaException &e) { if (isErrorExpected(e, lState)) { return 0; } else { std::cerr << e << std::endl; return 3; } } zorba::DynamicContext_t lDynCtx = lQueries.back()->getDynamicContext(); if (lState->hasDate) { std::string lDateTime = lState->theDate; if (lDateTime.find("T") == std::string::npos) { lDateTime += "T00:00:00"; } lDynCtx->setCurrentDateTime(engine->getItemFactory()->createDateTime(lDateTime)); } std::vector<Variable*>::const_iterator lVarIter = (*lIter)->varsBegin(); std::vector<Variable*>::const_iterator lVarEnd = (*lIter)->varsEnd(); for(;lVarIter!=lVarEnd;++lVarIter) { Variable* lVar = *lVarIter; set_var(lVar->theInline, lVar->theName, lVar->theValue, lDynCtx); } try { if (lQueries.back()->isUpdateQuery()) { std::stringstream lStream; lQueries.back()->applyUpdates(lStream); std::cout << "Updating Query -> no Result" << std::endl; } else { if ( fs::exists(lResultFile)) { fs::remove (lResultFile); } std::ofstream lResFileStream(lResultFile.native_file_string().c_str()); lQueries.back()->serialize(lResFileStream, lSerOptions); lResFileStream.flush(); std::cout << "Result:" << std::endl; printFile(std::cout, lResultFile.native_file_string()); if ( lState->hasCompare ) { fs::path lRefFile = fs::system_complete(fs::path( lRefPath.native_file_string() + "/" + lState->theCompare , fs::native) ); int lLine, lCol, lPos; bool lRes = isEqual(lRefFile, lResultFile, lLine, lCol, lPos); if (!lRes) { std::cerr << std::endl << "Result does not match expected result" << std::endl; printFile(std::cerr, lRefFile.native_file_string()); std::cerr << std::endl; std::cerr << "See line " << lLine << ", col " << lCol << " of expected result. " << std::endl; std::cerr << "Got "; printFile(std::cerr, lRefFile.native_file_string()); printPart(std::cerr, lResultFile.native_file_string(), lPos, 15); std::cerr << std::endl << "Expected "; printPart(std::cerr, lRefFile.native_file_string(), lPos, 15); std::cerr << std::endl; return 4; } } else if (lState->hasErrors) { std::cerr << "Query must throw an error!" << std::endl; return 5; } else { // if the queries is not an updating query, it must return a result or throw an error assert(false); } } } catch (zorba::ZorbaException &e) { if (isErrorExpected(e, lState)) { return 0; } else { std::cerr << e << std::endl; return 6; } } } } return 0; } <commit_msg>format fix in the test output<commit_after>#include <iostream> #include <sstream> #include <fstream> #include <vector> #include <string> #include <stdio.h> #include <stdlib.h> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/algorithm/string.hpp> #include "testdriverconfig.h" // SRC and BIN dir definitions #include "specification.h" // parsing spec files #include <zorba/zorba.h> #include <zorba/error_handler.h> #include <zorba/exception.h> namespace fs = boost::filesystem; void printFile(std::ostream& os, std::string aInFile) { std::ifstream lInFileStream(aInFile.c_str()); assert(lInFileStream); os << lInFileStream.rdbuf() << std::endl; } // print parts of a file // starting at aStartPos with the length of aLen void printPart(std::ostream& os, std::string aInFile, int aStartPos, int aLen) { char* buffer = new char [aLen]; try { std::ifstream lIn(aInFile.c_str()); lIn.seekg(aStartPos); int lCharsRead = lIn.readsome (buffer, aLen); os.write (buffer, lCharsRead); os.flush(); delete[] buffer; } catch (...) { delete[] buffer; } return; } bool isErrorExpected(zorba::ZorbaException& e, State* aState) { if ( aState->hasErrors) { std::vector<std::string>::const_iterator lIter = aState->theErrors.begin(); std::vector<std::string>::const_iterator lEnd = aState->theErrors.end(); zorba::String lError = zorba::ZorbaError::getErrorCode(e.getErrorCode()); for(;lIter!=lEnd;++lIter) { zorba::String lSpecError = *lIter; if (lError.compare(lSpecError) == 0) { return true; } } } return false; } zorba::XQuery::CompilerHints getCompilerHints() { zorba::XQuery::CompilerHints lHints; // ZORBA_OPTLEVEL=O0 | O1 char* lOptLevel = getenv("ZORBA_OPTLEVEL"); if ( lOptLevel != NULL && strcmp(lOptLevel, "O0") == 0 ) { lHints.opt_level = zorba::XQuery::CompilerHints::O0; std::cout << "testdriver is using optimization level O0" << std::endl; } else { lHints.opt_level = zorba::XQuery::CompilerHints::O1; std::cout << "testdriver is using optimization level O1" << std::endl; } return lHints; } // set a variable in the dynamic context // inlineFile specifies whether the given parameter is a file and it's value should // be inlined or not void set_var (bool inlineFile, std::string name, std::string val, zorba::DynamicContext_t dctx) { boost::replace_all(val, "$UPDATE_SRC_DIR", zorba::UPDATE_SRC_DIR); zorba::ItemFactory* lFactory = zorba::Zorba::getInstance()->getItemFactory(); if (!inlineFile) { zorba::Item lItem = lFactory->createString(val); if(name != ".") dctx->setVariable (name, lItem); else dctx->setContextItem (lItem); } else { std::ifstream is (val.c_str ()); assert (is); if(name != ".") dctx->setVariableAsDocument (name, val.c_str(), is); else dctx->setContextItemAsDocument (val.c_str(), is); } } // return false if the files are not equal // aLine contains the line number in which the first difference occurs // aCol contains the column number in which the first difference occurs // aPos is the character number off the first difference in the file // -1 is returned for aLine, aCol, and aPos if the files are equal bool isEqual(fs::path aRefFile, fs::path aResFile, int& aLine, int& aCol, int& aPos) { std::ifstream li(aRefFile.native_file_string().c_str()); std::ifstream ri(aResFile.native_file_string().c_str()); std::string lLine, rLine; aLine = 1; aCol = 0; aPos = -1; while (! li.eof() ) { if ( ri.eof() ) { std::getline(li, lLine); if (li.peek() == -1) // ignore end-of-line in the ref result return true; else return false; } std::getline(li, lLine); std::getline(ri, rLine); ++aLine; if ( (aCol = lLine.compare(rLine)) != 0) { return false; } } return true; } int #ifdef _WIN32_WCE _tmain(int argc, _TCHAR* argv[]) #else main(int argc, char** argv) #endif { fs::path lSpecFile, lResultFile; fs::path lSpecPath, lRefPath, lResultPath; Specification lSpec; if (argc != 2) { std::cerr << "\nusage: testdriver [testfile]" << std::endl; return 1; } // do initial stuff { std::string lSpecFileString = zorba::UPDATE_SRC_DIR +"/Queries/" + argv[1]; lSpecFile = fs::system_complete( fs::path( lSpecFileString, fs::native ) ); lSpecPath = fs::system_complete(fs::path(lSpecFile.branch_path().string(), fs::native )); std::string lSpecWithoutSuffix = std::string(argv[1]).substr( 0, std::string(argv[1]).size()-5 ); std::cout << "test " << lSpecWithoutSuffix << std::endl; lResultFile = fs::system_complete(fs::path( zorba::UPDATE_BINARY_DIR +"/QueryResults/" +lSpecWithoutSuffix + ".res", fs::native) ); lResultPath = fs::system_complete(fs::path(lResultFile.branch_path().string(), fs::native )); fs::path lRefFile = fs::system_complete(fs::path( zorba::UPDATE_SRC_DIR +"/ExpectedTestResults/" +lSpecWithoutSuffix +".xml.res", fs::native) ); lRefPath = fs::system_complete(fs::path(lRefFile.branch_path().string(), fs::native )); } // does the spec file exists if ( (! fs::exists( lSpecFile )) || fs::is_directory( lSpecFile) ) { std::cerr << "\n spec file " << lSpecFile.native_file_string() << " does not exist or is not a file" << std::endl; return 2; } // create the result directory if ( ! fs::exists( lResultPath ) ) fs::create_directories(lResultPath); // create deep directories // read the xargs and errors if the spec file exists lSpec.parseFile(lSpecFile.native_file_string()); zorba::Zorba *engine = zorba::Zorba::getInstance(); std::vector<zorba::XQuery_t> lQueries; zorba::XQuery::SerializerOptions lSerOptions; lSerOptions.omit_xml_declaration = zorba::XQuery::SerializerOptions::omit_xml_declaration::YES; // create and compile the query { std::vector<State*>::const_iterator lIter = lSpec.statesBegin(); std::vector<State*>::const_iterator lEnd = lSpec.statesEnd(); int lRun = 0; for(;lIter!=lEnd;++lIter) { State* lState = *lIter; std::string lQueryFile = lSpecPath.native_file_string() + "/" + (*lIter)->theName + ".xq"; std::cout << std::endl << "Query (Run " << ++lRun << "):" << std::endl; printFile(std::cout, lQueryFile); std::cout << std::endl; std::ifstream lQueryStream(lQueryFile.c_str()); try { lQueries.push_back(engine->compileQuery(lQueryStream, getCompilerHints())); } catch (zorba::ZorbaException &e) { if (isErrorExpected(e, lState)) { return 0; } else { std::cerr << e << std::endl; return 3; } } zorba::DynamicContext_t lDynCtx = lQueries.back()->getDynamicContext(); if (lState->hasDate) { std::string lDateTime = lState->theDate; if (lDateTime.find("T") == std::string::npos) { lDateTime += "T00:00:00"; } lDynCtx->setCurrentDateTime(engine->getItemFactory()->createDateTime(lDateTime)); } std::vector<Variable*>::const_iterator lVarIter = (*lIter)->varsBegin(); std::vector<Variable*>::const_iterator lVarEnd = (*lIter)->varsEnd(); for(;lVarIter!=lVarEnd;++lVarIter) { Variable* lVar = *lVarIter; set_var(lVar->theInline, lVar->theName, lVar->theValue, lDynCtx); } try { if (lQueries.back()->isUpdateQuery()) { std::stringstream lStream; lQueries.back()->applyUpdates(lStream); std::cout << "Updating Query -> no Result" << std::endl; } else { if ( fs::exists(lResultFile)) { fs::remove (lResultFile); } std::ofstream lResFileStream(lResultFile.native_file_string().c_str()); lQueries.back()->serialize(lResFileStream, lSerOptions); lResFileStream.flush(); std::cout << "Result:" << std::endl; printFile(std::cout, lResultFile.native_file_string()); if ( lState->hasCompare ) { fs::path lRefFile = fs::system_complete(fs::path( lRefPath.native_file_string() + "/" + lState->theCompare , fs::native) ); int lLine, lCol, lPos; bool lRes = isEqual(lRefFile, lResultFile, lLine, lCol, lPos); if (!lRes) { std::cerr << std::endl << "Result does not match expected result" << std::endl; printFile(std::cerr, lRefFile.native_file_string()); std::cerr << std::endl; std::cerr << "See line " << lLine << ", col " << lCol << " of expected result. " << std::endl; std::cerr << "Got: " << std::endl; printFile(std::cerr, lRefFile.native_file_string()); printPart(std::cerr, lResultFile.native_file_string(), lPos, 15); std::cerr << std::endl << "Expected "; printPart(std::cerr, lRefFile.native_file_string(), lPos, 15); std::cerr << std::endl; return 4; } } else if (lState->hasErrors) { std::cerr << "Query must throw an error!" << std::endl; return 5; } else { // if the queries is not an updating query, it must return a result or throw an error assert(false); } } } catch (zorba::ZorbaException &e) { if (isErrorExpected(e, lState)) { return 0; } else { std::cerr << e << std::endl; return 6; } } } } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: odbcconfig.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: jl $ $Date: 2001-03-23 13:29: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 EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _DBAUI_ODBC_CONFIG_HXX_ #include "odbcconfig.hxx" #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifdef HAVE_ODBC_SUPPORT #ifdef WIN #define ODBC_LIBRARY "ODBC.DLL" #define ODBC_UI_LIBRARY "ODBCINST.DLL" #endif #if defined WNT #define ODBC_LIBRARY "ODBC32.DLL" #define ODBC_UI_LIBRARY "ODBCCP32.DLL" #endif #ifdef UNX #define ODBC_LIBRARY "libodbc.so" #define ODBC_UI_LIBRARY "libodbc.so" #endif // just to go with calling convention of windows // so don't touch this #if defined(WIN) || defined(WNT) #define SQL_API __stdcall #endif // defined(WIN) || defined(WNT) #ifndef __SQLEXT_H #include <odbc/sqlext.h> #endif #if defined(WIN) || defined(WNT) #undef SQL_API #define SQL_API __stdcall #endif // defined(WIN) || defined(WNT) // from here on you can do what you want to #else #define ODBC_LIBRARY "" #define ODBC_UI_LIBRARY "" #endif // HAVE_ODBC_SUPPORT //......................................................................... namespace dbaui { //......................................................................... #ifdef HAVE_ODBC_SUPPORT typedef SQLRETURN (SQL_API* TSQLManageDataSource) (SQLHWND hwndParent); typedef SQLRETURN (SQL_API* TSQLAllocHandle) (SQLSMALLINT HandleType, SQLHANDLE InputHandle, SQLHANDLE* OutputHandlePtr); typedef SQLRETURN (SQL_API* TSQLFreeHandle) (SQLSMALLINT HandleType, SQLHANDLE Handle); typedef SQLRETURN (SQL_API* TSQLSetEnvAttr) (SQLHENV EnvironmentHandle, SQLINTEGER Attribute, SQLPOINTER ValuePtr, SQLINTEGER StringLength); typedef SQLRETURN (SQL_API* TSQLDataSources) (SQLHENV EnvironmentHandle, SQLUSMALLINT Direction, SQLCHAR* ServerName, SQLSMALLINT BufferLength1, SQLSMALLINT* NameLength1Ptr, SQLCHAR* Description, SQLSMALLINT BufferLength2, SQLSMALLINT* NameLength2Ptr); #define NSQLManageDataSource(a) (*(TSQLManageDataSource)(m_pSQLManageDataSource))(a) #define NSQLAllocHandle(a,b,c) (*(TSQLAllocHandle)(m_pAllocHandle))(a,b,c) #define NSQLFreeHandle(a,b) (*(TSQLFreeHandle)(m_pFreeHandle))(a,b) #define NSQLSetEnvAttr(a,b,c,d) (*(TSQLSetEnvAttr)(m_pSetEnvAttr))(a,b,c,d) #define NSQLDataSources(a,b,c,d,e,f,g,h) (*(TSQLDataSources)(m_pDataSources))(a,b,c,d,e,f,g,h) #endif //========================================================================= //= OOdbcLibWrapper //========================================================================= //------------------------------------------------------------------------- OOdbcLibWrapper::OOdbcLibWrapper(const sal_Char* _pLibPath) :m_sLibPath(::rtl::OUString::createFromAscii(_pLibPath)) ,m_pOdbcLib(NULL) { } //------------------------------------------------------------------------- sal_Bool OOdbcLibWrapper::load() { #ifdef HAVE_ODBC_SUPPORT // load the module m_pOdbcLib = osl_loadModule(m_sLibPath.pData, SAL_LOADMODULE_NOW); return (NULL != m_pOdbcLib); #endif } //------------------------------------------------------------------------- void OOdbcLibWrapper::unload() { #ifdef HAVE_ODBC_SUPPORT if (isLoaded()) { osl_unloadModule(m_pOdbcLib); m_pOdbcLib = NULL; } #endif } //------------------------------------------------------------------------- void* OOdbcLibWrapper::loadSymbol(const sal_Char* _pFunctionName) { return osl_getSymbol(m_pOdbcLib, ::rtl::OUString::createFromAscii(_pFunctionName).pData); } //------------------------------------------------------------------------- OOdbcLibWrapper::~OOdbcLibWrapper() { unload(); } //========================================================================= //= OOdbcEnumeration //========================================================================= struct OdbcTypesImpl { #ifdef HAVE_ODBC_SUPPORT SQLHANDLE hEnvironment; OdbcTypesImpl() : hEnvironment(NULL) { } #else void* pDummy; #endif }; //------------------------------------------------------------------------- OOdbcEnumeration::OOdbcEnumeration() #ifdef HAVE_ODBC_SUPPORT :OOdbcLibWrapper(ODBC_LIBRARY) ,m_pAllocHandle(NULL) ,m_pSetEnvAttr(NULL) ,m_pDataSources(NULL) ,m_pImpl(new OdbcTypesImpl) #endif { if (load()) { #ifdef HAVE_ODBC_SUPPORT // load the generic functions m_pAllocHandle = loadSymbol("SQLAllocHandle"); m_pFreeHandle = loadSymbol("SQLFreeHandle"); m_pSetEnvAttr = loadSymbol("SQLSetEnvAttr"); m_pDataSources = loadSymbol("SQLDataSources"); // all or nothing if (!m_pAllocHandle || !m_pSetEnvAttr || !m_pDataSources || !m_pFreeHandle) { unload(); m_pAllocHandle = m_pFreeHandle = m_pSetEnvAttr = m_pDataSources = NULL; } #endif } } //------------------------------------------------------------------------- OOdbcEnumeration::~OOdbcEnumeration() { freeEnv(); delete m_pImpl; } //------------------------------------------------------------------------- sal_Bool OOdbcEnumeration::allocEnv() { OSL_ENSURE(isLoaded(), "OOdbcEnumeration::allocEnv: not loaded!"); if (!isLoaded()) return sal_False; #ifdef HAVE_ODBC_SUPPORT if (m_pImpl->hEnvironment) // nothing to do return sal_True; SQLRETURN nResult = NSQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_pImpl->hEnvironment); if (SQL_SUCCESS != nResult) // can't do anything without environment return sal_False; NSQLSetEnvAttr(m_pImpl->hEnvironment, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER); return sal_True; #else return sal_False; #endif } //------------------------------------------------------------------------- void OOdbcEnumeration::freeEnv() { #ifdef HAVE_ODBC_SUPPORT if (m_pImpl->hEnvironment) NSQLFreeHandle(SQL_HANDLE_ENV, m_pImpl->hEnvironment); m_pImpl->hEnvironment =NULL; #endif } //------------------------------------------------------------------------- void OOdbcEnumeration::getDatasourceNames(StringBag& _rNames) { OSL_ENSURE(isLoaded(), "OOdbcManagement::getDatasourceNames: not loaded!"); if (!isLoaded()) return; if (!allocEnv()) { OSL_ENSURE(sal_False, "OOdbcManagement::getDatasourceNames: could not allocate an ODBC environment!"); return; } #ifdef HAVE_ODBC_SUPPORT // now that we have an environment collect the data source names UCHAR szDSN[SQL_MAX_DSN_LENGTH+1]; SWORD pcbDSN; UCHAR szDescription[1024+1]; SWORD pcbDescription; SQLRETURN nResult = SQL_SUCCESS; for ( nResult = NSQLDataSources(m_pImpl->hEnvironment, SQL_FETCH_FIRST, szDSN, sizeof(szDSN), &pcbDSN, szDescription, sizeof(szDescription), &pcbDescription); ; nResult = NSQLDataSources(m_pImpl->hEnvironment, SQL_FETCH_NEXT, szDSN, sizeof(szDSN), &pcbDSN, szDescription, sizeof(szDescription), &pcbDescription) ) { if (nResult != SQL_SUCCESS) // no further error handling break; else { ::rtl::OUStringBuffer aCurrentDsn; aCurrentDsn.appendAscii(reinterpret_cast<const char*>(szDSN)); _rNames.insert(aCurrentDsn.makeStringAndClear()); } } #endif } //========================================================================= //= OOdbcManagement //========================================================================= //------------------------------------------------------------------------- OOdbcManagement::OOdbcManagement() :OOdbcLibWrapper(ODBC_UI_LIBRARY) #ifdef HAVE_ODBC_SUPPORT ,m_pSQLManageDataSource(NULL) #endif { if (load()) { #ifdef HAVE_ODBC_SUPPORT m_pSQLManageDataSource = loadSymbol("SQLManageDataSources"); if (!m_pSQLManageDataSource) unload(); #endif // HAVE_ODBC_SUPPORT } } //------------------------------------------------------------------------- void OOdbcManagement::manageDataSources(void* _pParentSysWindowHandle) { OSL_ENSURE(isLoaded(), "OOdbcManagement::manageDataSources: not loaded!"); OSL_ENSURE(_pParentSysWindowHandle, "OOdbcManagement::manageDataSources: invalid parent window!"); if (!isLoaded()) return; #ifdef HAVE_ODBC_SUPPORT NSQLManageDataSource(_pParentSysWindowHandle); #endif // HAVE_ODBC_SUPPORT } //......................................................................... } // namespace dbaui //......................................................................... /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.5 2001/01/10 12:09:37 oj * #82620# calling convention of windows changed * * Revision 1.4 2000/10/30 15:36:51 fs * don't append the description of the ODBC data source to the DSN name * * Revision 1.3 2000/10/26 13:47:46 kz * chg. cast & ifdef WIN * * Revision 1.2 2000/10/26 13:11:36 obo * #65293# cant compile for linux * * Revision 1.1 2000/10/24 12:48:36 fs * initial checkin - wrapping (system) data source related ODBC functionality * * * Revision 1.0 24.10.00 10:14:13 fs ************************************************************************/ <commit_msg>#i1513# use libodbcinst.so as ui lib for odbc under unix<commit_after>/************************************************************************* * * $RCSfile: odbcconfig.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: oj $ $Date: 2002-10-15 13:09:39 $ * * 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 EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _DBAUI_ODBC_CONFIG_HXX_ #include "odbcconfig.hxx" #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifdef HAVE_ODBC_SUPPORT #ifdef WIN #define ODBC_LIBRARY "ODBC.DLL" #define ODBC_UI_LIBRARY "ODBCINST.DLL" #endif #if defined WNT #define ODBC_LIBRARY "ODBC32.DLL" #define ODBC_UI_LIBRARY "ODBCCP32.DLL" #endif #ifdef UNX #define ODBC_LIBRARY "libodbc.so" #define ODBC_UI_LIBRARY "libodbcinst.so" #endif // just to go with calling convention of windows // so don't touch this #if defined(WIN) || defined(WNT) #define SQL_API __stdcall #endif // defined(WIN) || defined(WNT) #ifndef __SQLEXT_H #include <odbc/sqlext.h> #endif #if defined(WIN) || defined(WNT) #undef SQL_API #define SQL_API __stdcall #endif // defined(WIN) || defined(WNT) // from here on you can do what you want to #else #define ODBC_LIBRARY "" #define ODBC_UI_LIBRARY "" #endif // HAVE_ODBC_SUPPORT //......................................................................... namespace dbaui { //......................................................................... #ifdef HAVE_ODBC_SUPPORT typedef SQLRETURN (SQL_API* TSQLManageDataSource) (SQLHWND hwndParent); typedef SQLRETURN (SQL_API* TSQLAllocHandle) (SQLSMALLINT HandleType, SQLHANDLE InputHandle, SQLHANDLE* OutputHandlePtr); typedef SQLRETURN (SQL_API* TSQLFreeHandle) (SQLSMALLINT HandleType, SQLHANDLE Handle); typedef SQLRETURN (SQL_API* TSQLSetEnvAttr) (SQLHENV EnvironmentHandle, SQLINTEGER Attribute, SQLPOINTER ValuePtr, SQLINTEGER StringLength); typedef SQLRETURN (SQL_API* TSQLDataSources) (SQLHENV EnvironmentHandle, SQLUSMALLINT Direction, SQLCHAR* ServerName, SQLSMALLINT BufferLength1, SQLSMALLINT* NameLength1Ptr, SQLCHAR* Description, SQLSMALLINT BufferLength2, SQLSMALLINT* NameLength2Ptr); #define NSQLManageDataSource(a) (*(TSQLManageDataSource)(m_pSQLManageDataSource))(a) #define NSQLAllocHandle(a,b,c) (*(TSQLAllocHandle)(m_pAllocHandle))(a,b,c) #define NSQLFreeHandle(a,b) (*(TSQLFreeHandle)(m_pFreeHandle))(a,b) #define NSQLSetEnvAttr(a,b,c,d) (*(TSQLSetEnvAttr)(m_pSetEnvAttr))(a,b,c,d) #define NSQLDataSources(a,b,c,d,e,f,g,h) (*(TSQLDataSources)(m_pDataSources))(a,b,c,d,e,f,g,h) #endif //========================================================================= //= OOdbcLibWrapper //========================================================================= //------------------------------------------------------------------------- OOdbcLibWrapper::OOdbcLibWrapper(const sal_Char* _pLibPath) :m_sLibPath(::rtl::OUString::createFromAscii(_pLibPath)) ,m_pOdbcLib(NULL) { } //------------------------------------------------------------------------- sal_Bool OOdbcLibWrapper::load() { #ifdef HAVE_ODBC_SUPPORT // load the module m_pOdbcLib = osl_loadModule(m_sLibPath.pData, SAL_LOADMODULE_NOW); return (NULL != m_pOdbcLib); #endif } //------------------------------------------------------------------------- void OOdbcLibWrapper::unload() { #ifdef HAVE_ODBC_SUPPORT if (isLoaded()) { osl_unloadModule(m_pOdbcLib); m_pOdbcLib = NULL; } #endif } //------------------------------------------------------------------------- void* OOdbcLibWrapper::loadSymbol(const sal_Char* _pFunctionName) { return osl_getSymbol(m_pOdbcLib, ::rtl::OUString::createFromAscii(_pFunctionName).pData); } //------------------------------------------------------------------------- OOdbcLibWrapper::~OOdbcLibWrapper() { unload(); } //========================================================================= //= OOdbcEnumeration //========================================================================= struct OdbcTypesImpl { #ifdef HAVE_ODBC_SUPPORT SQLHANDLE hEnvironment; OdbcTypesImpl() : hEnvironment(NULL) { } #else void* pDummy; #endif }; //------------------------------------------------------------------------- OOdbcEnumeration::OOdbcEnumeration() #ifdef HAVE_ODBC_SUPPORT :OOdbcLibWrapper(ODBC_LIBRARY) ,m_pAllocHandle(NULL) ,m_pSetEnvAttr(NULL) ,m_pDataSources(NULL) ,m_pImpl(new OdbcTypesImpl) #endif { if (load()) { #ifdef HAVE_ODBC_SUPPORT // load the generic functions m_pAllocHandle = loadSymbol("SQLAllocHandle"); m_pFreeHandle = loadSymbol("SQLFreeHandle"); m_pSetEnvAttr = loadSymbol("SQLSetEnvAttr"); m_pDataSources = loadSymbol("SQLDataSources"); // all or nothing if (!m_pAllocHandle || !m_pSetEnvAttr || !m_pDataSources || !m_pFreeHandle) { unload(); m_pAllocHandle = m_pFreeHandle = m_pSetEnvAttr = m_pDataSources = NULL; } #endif } } //------------------------------------------------------------------------- OOdbcEnumeration::~OOdbcEnumeration() { freeEnv(); delete m_pImpl; } //------------------------------------------------------------------------- sal_Bool OOdbcEnumeration::allocEnv() { OSL_ENSURE(isLoaded(), "OOdbcEnumeration::allocEnv: not loaded!"); if (!isLoaded()) return sal_False; #ifdef HAVE_ODBC_SUPPORT if (m_pImpl->hEnvironment) // nothing to do return sal_True; SQLRETURN nResult = NSQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_pImpl->hEnvironment); if (SQL_SUCCESS != nResult) // can't do anything without environment return sal_False; NSQLSetEnvAttr(m_pImpl->hEnvironment, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER); return sal_True; #else return sal_False; #endif } //------------------------------------------------------------------------- void OOdbcEnumeration::freeEnv() { #ifdef HAVE_ODBC_SUPPORT if (m_pImpl->hEnvironment) NSQLFreeHandle(SQL_HANDLE_ENV, m_pImpl->hEnvironment); m_pImpl->hEnvironment =NULL; #endif } //------------------------------------------------------------------------- void OOdbcEnumeration::getDatasourceNames(StringBag& _rNames) { OSL_ENSURE(isLoaded(), "OOdbcManagement::getDatasourceNames: not loaded!"); if (!isLoaded()) return; if (!allocEnv()) { OSL_ENSURE(sal_False, "OOdbcManagement::getDatasourceNames: could not allocate an ODBC environment!"); return; } #ifdef HAVE_ODBC_SUPPORT // now that we have an environment collect the data source names UCHAR szDSN[SQL_MAX_DSN_LENGTH+1]; SWORD pcbDSN; UCHAR szDescription[1024+1]; SWORD pcbDescription; SQLRETURN nResult = SQL_SUCCESS; for ( nResult = NSQLDataSources(m_pImpl->hEnvironment, SQL_FETCH_FIRST, szDSN, sizeof(szDSN), &pcbDSN, szDescription, sizeof(szDescription), &pcbDescription); ; nResult = NSQLDataSources(m_pImpl->hEnvironment, SQL_FETCH_NEXT, szDSN, sizeof(szDSN), &pcbDSN, szDescription, sizeof(szDescription), &pcbDescription) ) { if (nResult != SQL_SUCCESS) // no further error handling break; else { ::rtl::OUStringBuffer aCurrentDsn; aCurrentDsn.appendAscii(reinterpret_cast<const char*>(szDSN)); _rNames.insert(aCurrentDsn.makeStringAndClear()); } } #endif } //========================================================================= //= OOdbcManagement //========================================================================= //------------------------------------------------------------------------- OOdbcManagement::OOdbcManagement() :OOdbcLibWrapper(ODBC_UI_LIBRARY) #ifdef HAVE_ODBC_SUPPORT ,m_pSQLManageDataSource(NULL) #endif { if (load()) { #ifdef HAVE_ODBC_SUPPORT m_pSQLManageDataSource = loadSymbol("SQLManageDataSources"); if (!m_pSQLManageDataSource) unload(); #endif // HAVE_ODBC_SUPPORT } } //------------------------------------------------------------------------- void OOdbcManagement::manageDataSources(void* _pParentSysWindowHandle) { OSL_ENSURE(isLoaded(), "OOdbcManagement::manageDataSources: not loaded!"); OSL_ENSURE(_pParentSysWindowHandle, "OOdbcManagement::manageDataSources: invalid parent window!"); if (!isLoaded()) return; #ifdef HAVE_ODBC_SUPPORT NSQLManageDataSource(_pParentSysWindowHandle); #endif // HAVE_ODBC_SUPPORT } //......................................................................... } // namespace dbaui //......................................................................... /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.6 2001/03/23 13:29:31 jl * replaced: OSL_ENSHURE->OSL_ENSURE * * Revision 1.5 2001/01/10 12:09:37 oj * #82620# calling convention of windows changed * * Revision 1.4 2000/10/30 15:36:51 fs * don't append the description of the ODBC data source to the DSN name * * Revision 1.3 2000/10/26 13:47:46 kz * chg. cast & ifdef WIN * * Revision 1.2 2000/10/26 13:11:36 obo * #65293# cant compile for linux * * Revision 1.1 2000/10/24 12:48:36 fs * initial checkin - wrapping (system) data source related ODBC functionality * * * Revision 1.0 24.10.00 10:14:13 fs ************************************************************************/ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: queryorder.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2004-10-22 09:06:21 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef DBAUI_QUERYORDER_HXX #define DBAUI_QUERYORDER_HXX #ifndef _DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _EDIT_HXX //autogen #include <vcl/edit.hxx> #endif #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #define DOG_ROWS 3 namespace rtl { class OUString; } namespace com { namespace sun { namespace star { namespace sdb { class XSingleSelectQueryAnalyzer; class XSingleSelectQueryComposer; } namespace sdbc { class XConnection; } namespace container { class XNameAccess; } namespace beans { struct PropertyValue; class XPropertySet; } } } } //================================================================== // DlgOrderCrit //================================================================== namespace dbaui { class DlgOrderCrit : public ModalDialog { protected: ListBox aLB_ORDERFIELD1; ListBox aLB_ORDERVALUE1; ListBox aLB_ORDERFIELD2; ListBox aLB_ORDERVALUE2; ListBox aLB_ORDERFIELD3; ListBox aLB_ORDERVALUE3; FixedText aFT_ORDERFIELD; FixedText aFT_ORDERAFTER1; FixedText aFT_ORDERAFTER2; FixedText aFT_ORDEROPER; FixedText aFT_ORDERDIR; OKButton aBT_OK; CancelButton aBT_CANCEL; HelpButton aBT_HELP; FixedLine aFL_ORDER; String aSTR_NOENTRY; ::rtl::OUString m_sOrgOrder; ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSingleSelectQueryAnalyzer> m_xQueryAnalyzer; ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSingleSelectQueryComposer> m_xQueryComposer; ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> m_xColumns; ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> m_xConnection; ListBox* arrLbFields[DOG_ROWS]; ListBox* arrLbValues[DOG_ROWS]; DECL_LINK( FieldListSelectHdl, ListBox * ); void EnableLines(); public: DlgOrderCrit( Window * pParent, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _rxConnection, const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSingleSelectQueryAnalyzer>& _rxQueryComposer, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess>& _rxCols); ~DlgOrderCrit(); void BuildOrderPart(); ::rtl::OUString GetOrderList( ) const; void SetOrderList( const String& _rOrderList ); ::rtl::OUString GetOrignalOrder() const { return m_sOrgOrder; } }; } #endif // DBAUI_QUERYORDER_HXX <commit_msg>INTEGRATION: CWS dba20 (1.6.18); FILE MERGED 2004/11/17 15:13:13 fs 1.6.18.1: #i37185# XSingleSelectQueryComposer now derived from XSingleSelectQueryAnalyzer<commit_after>/************************************************************************* * * $RCSfile: queryorder.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2005-01-05 12:36:52 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef DBAUI_QUERYORDER_HXX #define DBAUI_QUERYORDER_HXX #ifndef _DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _EDIT_HXX //autogen #include <vcl/edit.hxx> #endif #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #define DOG_ROWS 3 namespace rtl { class OUString; } namespace com { namespace sun { namespace star { namespace sdb { class XSingleSelectQueryComposer; } namespace sdbc { class XConnection; } namespace container { class XNameAccess; } namespace beans { struct PropertyValue; class XPropertySet; } } } } //================================================================== // DlgOrderCrit //================================================================== namespace dbaui { class DlgOrderCrit : public ModalDialog { protected: ListBox aLB_ORDERFIELD1; ListBox aLB_ORDERVALUE1; ListBox aLB_ORDERFIELD2; ListBox aLB_ORDERVALUE2; ListBox aLB_ORDERFIELD3; ListBox aLB_ORDERVALUE3; FixedText aFT_ORDERFIELD; FixedText aFT_ORDERAFTER1; FixedText aFT_ORDERAFTER2; FixedText aFT_ORDEROPER; FixedText aFT_ORDERDIR; OKButton aBT_OK; CancelButton aBT_CANCEL; HelpButton aBT_HELP; FixedLine aFL_ORDER; String aSTR_NOENTRY; ::rtl::OUString m_sOrgOrder; ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSingleSelectQueryComposer> m_xQueryComposer; ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> m_xColumns; ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> m_xConnection; ListBox* arrLbFields[DOG_ROWS]; ListBox* arrLbValues[DOG_ROWS]; DECL_LINK( FieldListSelectHdl, ListBox * ); void EnableLines(); public: DlgOrderCrit( Window * pParent, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _rxConnection, const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSingleSelectQueryComposer>& _rxComposer, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess>& _rxCols); ~DlgOrderCrit(); void BuildOrderPart(); ::rtl::OUString GetOrderList( ) const; void SetOrderList( const String& _rOrderList ); ::rtl::OUString GetOrignalOrder() const { return m_sOrgOrder; } }; } #endif // DBAUI_QUERYORDER_HXX <|endoftext|>
<commit_before>#ifndef TEST_CLIENT_UTILS_HPP #define TEST_CLIENT_UTILS_HPP #include "TestAuthProvider.hpp" #include "TestUserData.hpp" #include "TestUtils.hpp" #include "test_server_data.hpp" #include "AccountStorage.hpp" #include "CAppInformation.hpp" #include "Client.hpp" #include "ClientSettings.hpp" #include "ConnectionApi.hpp" #include "DataStorage.hpp" #include "Operations/ClientAuthOperation.hpp" #include <QSignalSpy> namespace Telegram { namespace Test { void setupAppInfo(Client::AppInformation *appInfo) { appInfo->setAppId(14617); appInfo->setAppHash(QLatin1String("e17ac360fd072f83d5d08db45ce9a121")); appInfo->setAppVersion(QLatin1String("0.1")); appInfo->setDeviceInfo(QLatin1String("pc")); appInfo->setOsInfo(QLatin1String("GNU/Linux")); appInfo->setLanguageCode(QLatin1String("en")); } void setupClientHelper(Telegram::Client::Client *client, const UserData &userData, const Telegram::RsaKey &serverPublicKey, const Telegram::DcOption clientDcOption) { Telegram::Client::AccountStorage *accountStorage = new Telegram::Client::AccountStorage(client); accountStorage->setPhoneNumber(userData.phoneNumber); accountStorage->setDcInfo(clientDcOption); Telegram::Client::Settings *clientSettings = new Telegram::Client::Settings(client); Telegram::Client::InMemoryDataStorage *dataStorage = new Telegram::Client::InMemoryDataStorage(client); client->setAppInformation(new Client::AppInformation(client)); setupAppInfo(client->appInformation()); client->setSettings(clientSettings); client->setAccountStorage(accountStorage); client->setDataStorage(dataStorage); QVERIFY(clientSettings->setServerConfiguration({clientDcOption})); QVERIFY(clientSettings->setServerRsaKey(serverPublicKey)); } void setupClientHelper(Telegram::Client::Client *client, const UserData &userData, const Telegram::RsaKey &serverPublicKey, const Telegram::DcOption clientDcOption, const Telegram::Client::Settings::SessionType sessionType) { setupClientHelper(client, userData, serverPublicKey, clientDcOption); client->settings()->setPreferedSessionType(sessionType); } void signInHelper(Telegram::Client::Client *client, const UserData &userData, Telegram::Test::AuthProvider *authProvider, Telegram::Client::AuthOperation **output = nullptr); void signInHelper(Telegram::Client::Client *client, const UserData &userData, Telegram::Test::AuthProvider *authProvider, Telegram::Client::AuthOperation **output) { Telegram::Client::AuthOperation *signInOperation = client->connectionApi()->startAuthentication(); if (output) { *output = signInOperation; } QSignalSpy serverAuthCodeSpy(authProvider, &Telegram::Test::AuthProvider::codeSent); QSignalSpy authCodeSpy(signInOperation, &Telegram::Client::AuthOperation::authCodeRequired); signInOperation->setPhoneNumber(userData.phoneNumber); TRY_VERIFY(!authCodeSpy.isEmpty()); QCOMPARE(authCodeSpy.count(), 1); QCOMPARE(serverAuthCodeSpy.count(), 1); QList<QVariant> authCodeSentArguments = serverAuthCodeSpy.takeFirst(); QCOMPARE(authCodeSentArguments.count(), 2); const QString authCode = authCodeSentArguments.at(1).toString(); signInOperation->submitAuthCode(authCode); if (!userData.password.isEmpty()) { QSignalSpy authPasswordSpy(signInOperation, &Telegram::Client::AuthOperation::passwordRequired); QSignalSpy passwordCheckFailedSpy(signInOperation, &Telegram::Client::AuthOperation::passwordCheckFailed); TRY_VERIFY2(!authPasswordSpy.isEmpty(), "The user has a password-protection, " "but there are no passwordRequired signals on the client side"); QCOMPARE(authPasswordSpy.count(), 1); QVERIFY(passwordCheckFailedSpy.isEmpty()); signInOperation->submitPassword(userData.password + QStringLiteral("invalid")); TRY_VERIFY2(!passwordCheckFailedSpy.isEmpty(), "The submitted password is not valid, " "but there are not signals on the client side"); QVERIFY(!signInOperation->isFinished()); QCOMPARE(passwordCheckFailedSpy.count(), 1); signInOperation->submitPassword(userData.password); } } } // Test namespace } // Telegram namespace #endif // TEST_CLIENT_UTILS_HPP <commit_msg>Tests/Utils: Add Test::Client class<commit_after>#ifndef TEST_CLIENT_UTILS_HPP #define TEST_CLIENT_UTILS_HPP #include "TestAuthProvider.hpp" #include "TestUserData.hpp" #include "TestUtils.hpp" #include "test_server_data.hpp" #include "AccountStorage.hpp" #include "CAppInformation.hpp" #include "Client.hpp" #include "ClientSettings.hpp" #include "ConnectionApi.hpp" #include "DataStorage.hpp" #include "Operations/ClientAuthOperation.hpp" #include <QSignalSpy> namespace Telegram { namespace Test { void setupAppInfo(Client::AppInformation *appInfo) { appInfo->setAppId(14617); appInfo->setAppHash(QLatin1String("e17ac360fd072f83d5d08db45ce9a121")); appInfo->setAppVersion(QLatin1String("0.1")); appInfo->setDeviceInfo(QLatin1String("pc")); appInfo->setOsInfo(QLatin1String("GNU/Linux")); appInfo->setLanguageCode(QLatin1String("en")); } void setupClientHelper(Telegram::Client::Client *client, const UserData &userData, const Telegram::RsaKey &serverPublicKey, const Telegram::DcOption clientDcOption) { Telegram::Client::AccountStorage *accountStorage = new Telegram::Client::AccountStorage(client); accountStorage->setPhoneNumber(userData.phoneNumber); accountStorage->setDcInfo(clientDcOption); Telegram::Client::Settings *clientSettings = new Telegram::Client::Settings(client); Telegram::Client::InMemoryDataStorage *dataStorage = new Telegram::Client::InMemoryDataStorage(client); client->setAppInformation(new Client::AppInformation(client)); setupAppInfo(client->appInformation()); client->setSettings(clientSettings); client->setAccountStorage(accountStorage); client->setDataStorage(dataStorage); QVERIFY(clientSettings->setServerConfiguration({clientDcOption})); QVERIFY(clientSettings->setServerRsaKey(serverPublicKey)); } void setupClientHelper(Telegram::Client::Client *client, const UserData &userData, const Telegram::RsaKey &serverPublicKey, const Telegram::DcOption clientDcOption, const Telegram::Client::Settings::SessionType sessionType) { setupClientHelper(client, userData, serverPublicKey, clientDcOption); client->settings()->setPreferedSessionType(sessionType); } void signInHelper(Telegram::Client::Client *client, const UserData &userData, Telegram::Test::AuthProvider *authProvider, Telegram::Client::AuthOperation **output = nullptr); void signInHelper(Telegram::Client::Client *client, const UserData &userData, Telegram::Test::AuthProvider *authProvider, Telegram::Client::AuthOperation **output) { Telegram::Client::AuthOperation *signInOperation = client->connectionApi()->startAuthentication(); if (output) { *output = signInOperation; } QSignalSpy serverAuthCodeSpy(authProvider, &Telegram::Test::AuthProvider::codeSent); QSignalSpy authCodeSpy(signInOperation, &Telegram::Client::AuthOperation::authCodeRequired); signInOperation->setPhoneNumber(userData.phoneNumber); TRY_VERIFY(!authCodeSpy.isEmpty()); QCOMPARE(authCodeSpy.count(), 1); QCOMPARE(serverAuthCodeSpy.count(), 1); QList<QVariant> authCodeSentArguments = serverAuthCodeSpy.takeFirst(); QCOMPARE(authCodeSentArguments.count(), 2); const QString authCode = authCodeSentArguments.at(1).toString(); signInOperation->submitAuthCode(authCode); if (!userData.password.isEmpty()) { QSignalSpy authPasswordSpy(signInOperation, &Telegram::Client::AuthOperation::passwordRequired); QSignalSpy passwordCheckFailedSpy(signInOperation, &Telegram::Client::AuthOperation::passwordCheckFailed); TRY_VERIFY2(!authPasswordSpy.isEmpty(), "The user has a password-protection, " "but there are no passwordRequired signals on the client side"); QCOMPARE(authPasswordSpy.count(), 1); QVERIFY(passwordCheckFailedSpy.isEmpty()); signInOperation->submitPassword(userData.password + QStringLiteral("invalid")); TRY_VERIFY2(!passwordCheckFailedSpy.isEmpty(), "The submitted password is not valid, " "but there are not signals on the client side"); QVERIFY(!signInOperation->isFinished()); QCOMPARE(passwordCheckFailedSpy.count(), 1); signInOperation->submitPassword(userData.password); } } class Client : public Telegram::Client::Client { public: explicit Client(QObject *parent = nullptr) : Telegram::Client::Client(parent) { setSettings(new Telegram::Client::Settings(this)); setAccountStorage(new Telegram::Client::AccountStorage(this)); setDataStorage(new Telegram::Client::InMemoryDataStorage(this)); setAppInformation(new Telegram::Client::AppInformation(this)); setupAppInfo(appInformation()); } }; } // Test namespace } // Telegram namespace #endif // TEST_CLIENT_UTILS_HPP <|endoftext|>
<commit_before>#include "VideoSuite.hpp" #include <iostream> #include <Video/LowLevelRenderer/Interface/LowLevelRenderer.hpp> #ifdef OPENGL_SUPPORT #include <Video/LowLevelRenderer/OpenGL/OpenGLRenderer.hpp> #endif #ifdef VULKAN_SUPPORT #include <Video/LowLevelRenderer/Vulkan/VulkanRenderer.hpp> #endif #include <GLFW/glfw3.h> VideoSuite::VideoSuite(Video::Renderer::GraphicsAPI graphicsAPI) : TestSuite("Video") { this->graphicsAPI = graphicsAPI; AddTest("DrawTriangle", DrawTriangle, &lowLevelRenderer); AddTest("DrawVertexTriangle", DrawVertexTriangle, &lowLevelRenderer); AddTest("DrawTexturedTriangle", DrawTexturedTriangle, &lowLevelRenderer); AddTest("DrawQuad", DrawQuad, &lowLevelRenderer); AddTest("DrawTriangles", DrawTriangles, &lowLevelRenderer); AddTest("DrawPushTriangles", DrawPushTriangles, &lowLevelRenderer); AddTest("DrawStorageTriangle", DrawStorageTriangle, &lowLevelRenderer); AddTest("InvertColors", InvertColors, &lowLevelRenderer); AddTest("DrawMipmappedTriangle", DrawMipmappedTriangle, &lowLevelRenderer); AddTest("DepthPrePass", DepthPrePass, &lowLevelRenderer); AddTest("DrawLines", DrawLines, &lowLevelRenderer); AddTest("Attachmentless", Attachmentless, &lowLevelRenderer); AddTest("ConservativeRasterization", ConservativeRasterization, &lowLevelRenderer); AddTest("MultipleFrames", MultipleFrames, &lowLevelRenderer); AddTest("ComputeSetBuffer", ComputeSetBuffer, &lowLevelRenderer); AddTest("ComputeVertexBuffer", ComputeVertexBuffer, &lowLevelRenderer); AddTest("ComputeMultipleBuffers", ComputeMultipleBuffers, &lowLevelRenderer); } void VideoSuite::Init() { glfwInit(); switch (graphicsAPI) { #ifdef OPENGL_SUPPORT case Video::Renderer::GraphicsAPI::OPENGL: { // Create window. window = glfwCreateWindow(swapchainSize, swapchainSize, "Tests - OpenGL", nullptr, nullptr); lowLevelRenderer = new Video::OpenGLRenderer(window); break; } #endif #ifdef VULKAN_SUPPORT case Video::Renderer::GraphicsAPI::VULKAN: // Create window. glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); window = glfwCreateWindow(swapchainSize, swapchainSize, "Tests - Vulkan", nullptr, nullptr); lowLevelRenderer = new Video::VulkanRenderer(window); break; #endif } } void VideoSuite::Shutdown() { delete lowLevelRenderer; glfwDestroyWindow(window); glfwTerminate(); } <commit_msg>Wait before shutting down test suite<commit_after>#include "VideoSuite.hpp" #include <iostream> #include <Video/LowLevelRenderer/Interface/LowLevelRenderer.hpp> #ifdef OPENGL_SUPPORT #include <Video/LowLevelRenderer/OpenGL/OpenGLRenderer.hpp> #endif #ifdef VULKAN_SUPPORT #include <Video/LowLevelRenderer/Vulkan/VulkanRenderer.hpp> #endif #include <GLFW/glfw3.h> VideoSuite::VideoSuite(Video::Renderer::GraphicsAPI graphicsAPI) : TestSuite("Video") { this->graphicsAPI = graphicsAPI; AddTest("DrawTriangle", DrawTriangle, &lowLevelRenderer); AddTest("DrawVertexTriangle", DrawVertexTriangle, &lowLevelRenderer); AddTest("DrawTexturedTriangle", DrawTexturedTriangle, &lowLevelRenderer); AddTest("DrawQuad", DrawQuad, &lowLevelRenderer); AddTest("DrawTriangles", DrawTriangles, &lowLevelRenderer); AddTest("DrawPushTriangles", DrawPushTriangles, &lowLevelRenderer); AddTest("DrawStorageTriangle", DrawStorageTriangle, &lowLevelRenderer); AddTest("InvertColors", InvertColors, &lowLevelRenderer); AddTest("DrawMipmappedTriangle", DrawMipmappedTriangle, &lowLevelRenderer); AddTest("DepthPrePass", DepthPrePass, &lowLevelRenderer); AddTest("DrawLines", DrawLines, &lowLevelRenderer); AddTest("Attachmentless", Attachmentless, &lowLevelRenderer); AddTest("ConservativeRasterization", ConservativeRasterization, &lowLevelRenderer); AddTest("MultipleFrames", MultipleFrames, &lowLevelRenderer); AddTest("ComputeSetBuffer", ComputeSetBuffer, &lowLevelRenderer); AddTest("ComputeVertexBuffer", ComputeVertexBuffer, &lowLevelRenderer); AddTest("ComputeMultipleBuffers", ComputeMultipleBuffers, &lowLevelRenderer); } void VideoSuite::Init() { glfwInit(); switch (graphicsAPI) { #ifdef OPENGL_SUPPORT case Video::Renderer::GraphicsAPI::OPENGL: { // Create window. window = glfwCreateWindow(swapchainSize, swapchainSize, "Tests - OpenGL", nullptr, nullptr); lowLevelRenderer = new Video::OpenGLRenderer(window); break; } #endif #ifdef VULKAN_SUPPORT case Video::Renderer::GraphicsAPI::VULKAN: // Create window. glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); window = glfwCreateWindow(swapchainSize, swapchainSize, "Tests - Vulkan", nullptr, nullptr); lowLevelRenderer = new Video::VulkanRenderer(window); break; #endif } } void VideoSuite::Shutdown() { lowLevelRenderer->Wait(); delete lowLevelRenderer; glfwDestroyWindow(window); glfwTerminate(); } <|endoftext|>
<commit_before>#include "App.h" #include "ModuleWindow.h" #include "ModuleCamera3D.h" #include "Globals.h" #include "App.h" #include "ModuleRenderer3D.h" #include "Glew/include/glew.h" #include "SDL\include\SDL_opengl.h" #include <gl/GL.h> #include <gl/GLU.h> #pragma comment (lib, "glu32.lib") /* link OpenGL Utility lib */ #pragma comment (lib, "opengl32.lib") /* link Microsoft OpenGL lib */ #pragma comment (lib, "Glew/Lib/glew32.lib") /* link Microsoft OpenGL lib */ ModuleRenderer3D::ModuleRenderer3D(bool start_enabled) : Module(start_enabled) { SetName("Renderer3D"); } // Destructor ModuleRenderer3D::~ModuleRenderer3D() { } // Called before render is available bool ModuleRenderer3D::Awake() { bool ret = true; LOG_OUTPUT("Creating 3D Renderer context"); //Create context context = SDL_GL_CreateContext(App->window->window); if (context == NULL) { LOG_OUTPUT("OpenGL context could not be created! SDL_Error: %s\n", SDL_GetError()); ret = false; } GLenum err = glewInit(); if (err != GLEW_OK) { LOG_OUTPUT("Glew library could not init %s\n", glewGetErrorString(err)); ret = false; } else { LOG_OUTPUT("Glew library is being used correctly\n"); LOG_OUTPUT("Using Glew %s\n", glewGetString(GLEW_VERSION)); } if (ret == true) { // get version info LOG_OUTPUT("Vendor: %s", glGetString(GL_VENDOR)); LOG_OUTPUT("Renderer: %s", glGetString(GL_RENDERER)); LOG_OUTPUT("OpenGL version supported %s", glGetString(GL_VERSION)); LOG_OUTPUT("GLSL: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION)); //Use Vsync if (SDL_GL_SetSwapInterval(App->window->GetVsync()) < 0) LOG_OUTPUT("Warning: Unable to set VSync! SDL Error: %s\n", SDL_GetError()); //Initialize Projection Matrix glMatrixMode(GL_PROJECTION); glLoadIdentity(); //Check for error GLenum error = glGetError(); if (error != GL_NO_ERROR) { LOG_OUTPUT("Error initializing OpenGL! %s\n", gluErrorString(error)); ret = false; } //Initialize Modelview Matrix glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //Check for error error = glGetError(); if (error != GL_NO_ERROR) { LOG_OUTPUT("Error initializing OpenGL! %s\n", gluErrorString(error)); ret = false; } glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glClearDepth(1.0f); //Initialize clear color glClearColor(0.f, 0.f, 0.f, 1.f); //Check for error error = glGetError(); if (error != GL_NO_ERROR) { LOG_OUTPUT("Error initializing OpenGL! %s\n", gluErrorString(error)); ret = false; } GLfloat LightModelAmbient[] = { 0.6f, 0.6f, 0.6f, 1.0f }; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, LightModelAmbient); lights[0].ref = GL_LIGHT0; lights[0].ambient.Set(0.25f, 0.25f, 0.25f, 1.0f); lights[0].diffuse.Set(0.75f, 0.75f, 0.75f, 1.0f); lights[0].SetPos(0.0f, 0.0f, 2.5f); lights[0].Init(); GLfloat MaterialAmbient[] = { 1.0f, 1.0f, 1.0f, 1.0f }; glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, MaterialAmbient); GLfloat MaterialDiffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f }; glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialDiffuse); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); lights[0].Active(true); glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); } // Projection matrix for OnResize(App->window->GetWindowSize().x, App->window->GetWindowSize().y); return ret; } // PreUpdate: clear buffer bool ModuleRenderer3D::PreUpdate() { bool ret = true; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadMatrixf(App->camera->GetViewMatrix()); // light 0 on cam pos lights[0].SetPos(App->camera->Position.x, App->camera->Position.y, App->camera->Position.z); for (uint i = 0; i < MAX_LIGHTS; ++i) lights[i].Render(); return ret; } // PostUpdate present buffer to screen bool ModuleRenderer3D::PostUpdate() { SDL_GL_SwapWindow(App->window->window); return true; } // Called before quitting bool ModuleRenderer3D::CleanUp() { bool ret = true; LOG_OUTPUT("Destroying 3D Renderer"); SDL_GL_DeleteContext(context); return ret; } void ModuleRenderer3D::OnResize(int width, int height) { glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); ProjectionMatrix = perspective(60.0f, (float)width / (float)height, 0.125f, 512.0f); glLoadMatrixf(&ProjectionMatrix); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void ModuleRenderer3D::DrawGrid(int HALF_GRID_SIZE) { glBegin(GL_LINES); glColor3f(0.75f, 0.75f, 0.75f); for (int i = -HALF_GRID_SIZE; i <= HALF_GRID_SIZE; i++) { glVertex3f((float)i, 0, (float)-HALF_GRID_SIZE); glVertex3f((float)i, 0, (float)HALF_GRID_SIZE); glVertex3f((float)-HALF_GRID_SIZE, 0, (float)i); glVertex3f((float)HALF_GRID_SIZE, 0, (float)i); } glEnd(); }<commit_msg>Forgot to write that Glew was implemented in the last commit<commit_after>#include "App.h" #include "ModuleWindow.h" #include "ModuleCamera3D.h" #include "Globals.h" #include "App.h" #include "ModuleRenderer3D.h" #include "Glew/include/glew.h" #include "SDL\include\SDL_opengl.h" #include <gl/GL.h> #include <gl/GLU.h> #pragma comment (lib, "glu32.lib") /* link OpenGL Utility lib */ #pragma comment (lib, "opengl32.lib") /* link Microsoft OpenGL lib */ #pragma comment (lib, "Glew/Lib/glew32.lib") /* link Microsoft OpenGL lib */ ModuleRenderer3D::ModuleRenderer3D(bool start_enabled) : Module(start_enabled) { SetName("Renderer3D"); } // Destructor ModuleRenderer3D::~ModuleRenderer3D() { } // Called before render is available bool ModuleRenderer3D::Awake() { bool ret = true; LOG_OUTPUT("Creating 3D Renderer context"); //Create context context = SDL_GL_CreateContext(App->window->window); if (context == NULL) { LOG_OUTPUT("OpenGL context could not be created! SDL_Error: %s\n", SDL_GetError()); ret = false; } GLenum err = glewInit(); /* Glew Initialization */ if (err != GLEW_OK) { LOG_OUTPUT("Glew library could not init %s\n", glewGetErrorString(err)); ret = false; } else { LOG_OUTPUT("Glew library is being used correctly\n"); LOG_OUTPUT("Using Glew %s\n", glewGetString(GLEW_VERSION)); } if (ret == true) { // get version info LOG_OUTPUT("Vendor: %s", glGetString(GL_VENDOR)); LOG_OUTPUT("Renderer: %s", glGetString(GL_RENDERER)); LOG_OUTPUT("OpenGL version supported %s", glGetString(GL_VERSION)); LOG_OUTPUT("GLSL: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION)); //Use Vsync if (SDL_GL_SetSwapInterval(App->window->GetVsync()) < 0) LOG_OUTPUT("Warning: Unable to set VSync! SDL Error: %s\n", SDL_GetError()); //Initialize Projection Matrix glMatrixMode(GL_PROJECTION); glLoadIdentity(); //Check for error GLenum error = glGetError(); if (error != GL_NO_ERROR) { LOG_OUTPUT("Error initializing OpenGL! %s\n", gluErrorString(error)); ret = false; } //Initialize Modelview Matrix glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //Check for error error = glGetError(); if (error != GL_NO_ERROR) { LOG_OUTPUT("Error initializing OpenGL! %s\n", gluErrorString(error)); ret = false; } glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glClearDepth(1.0f); //Initialize clear color glClearColor(0.f, 0.f, 0.f, 1.f); //Check for error error = glGetError(); if (error != GL_NO_ERROR) { LOG_OUTPUT("Error initializing OpenGL! %s\n", gluErrorString(error)); ret = false; } GLfloat LightModelAmbient[] = { 0.6f, 0.6f, 0.6f, 1.0f }; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, LightModelAmbient); lights[0].ref = GL_LIGHT0; lights[0].ambient.Set(0.25f, 0.25f, 0.25f, 1.0f); lights[0].diffuse.Set(0.75f, 0.75f, 0.75f, 1.0f); lights[0].SetPos(0.0f, 0.0f, 2.5f); lights[0].Init(); GLfloat MaterialAmbient[] = { 1.0f, 1.0f, 1.0f, 1.0f }; glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, MaterialAmbient); GLfloat MaterialDiffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f }; glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialDiffuse); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); lights[0].Active(true); glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); } // Projection matrix for OnResize(App->window->GetWindowSize().x, App->window->GetWindowSize().y); return ret; } // PreUpdate: clear buffer bool ModuleRenderer3D::PreUpdate() { bool ret = true; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadMatrixf(App->camera->GetViewMatrix()); // light 0 on cam pos lights[0].SetPos(App->camera->Position.x, App->camera->Position.y, App->camera->Position.z); for (uint i = 0; i < MAX_LIGHTS; ++i) lights[i].Render(); return ret; } // PostUpdate present buffer to screen bool ModuleRenderer3D::PostUpdate() { SDL_GL_SwapWindow(App->window->window); return true; } // Called before quitting bool ModuleRenderer3D::CleanUp() { bool ret = true; LOG_OUTPUT("Destroying 3D Renderer"); SDL_GL_DeleteContext(context); return ret; } void ModuleRenderer3D::OnResize(int width, int height) { glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); ProjectionMatrix = perspective(60.0f, (float)width / (float)height, 0.125f, 512.0f); glLoadMatrixf(&ProjectionMatrix); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void ModuleRenderer3D::DrawGrid(int HALF_GRID_SIZE) { glBegin(GL_LINES); glColor3f(0.75f, 0.75f, 0.75f); for (int i = -HALF_GRID_SIZE; i <= HALF_GRID_SIZE; i++) { glVertex3f((float)i, 0, (float)-HALF_GRID_SIZE); glVertex3f((float)i, 0, (float)HALF_GRID_SIZE); glVertex3f((float)-HALF_GRID_SIZE, 0, (float)i); glVertex3f((float)HALF_GRID_SIZE, 0, (float)i); } glEnd(); }<|endoftext|>
<commit_before>/*Santiago Zubieta*/ #include <iostream> #include <numeric> #include <fstream> #include <climits> #include <cstring> #include <cstdio> #include <cmath> #include <queue> #include <list> #include <map> #include <set> #include <stack> #include <deque> #include <vector> #include <string> #include <cstdlib> #include <cassert> #include <sstream> #include <iterator> #include <algorithm> #define llu unsigned long long int using namespace std; struct Num { int n; bool operator < (const Num &that) const { // Overload < operator because this structure will be used in a priority // queue, and in such a structure, it will always maintain the 'biggest' // element on top of it, and we want the 'smallest' element instead. return n > that.n; } }; int main() { int T; // Number of test cases int N; // Placeholder for read numbers llu sum; // The sum of the 2 lowest numbers available llu total; // The total of the costs of each pair of numbers added int index; while(cin >> T) { priority_queue < Num > nums; if(!T) { break; } sum = 0; total = 0; index = 0; for(int k = 0; k < T; k++) { cin >> N; Num num; num.n = N; nums.push(num); } while(nums.size() > 1) { int n1 = nums.top().n; // Take the lowest element out of the priority queue nums.pop(); int n2 = nums.top().n; // Take the second lowest element out of it too nums.pop(); sum = n1 + n2; // Add the two lowest values that were in the queue total += sum; // Add this to the total as a cost of adding up Num num; num.n = sum; nums.push(num); // Put back the result back into the priority queue } cout << total << endl; } } <commit_msg>Added first batch of problems from Summer Training, 2014<commit_after>/*Santiago Zubieta*/ #include <iostream> #include <numeric> #include <fstream> #include <climits> #include <cstring> #include <cstdio> #include <cmath> #include <queue> #include <list> #include <map> #include <set> #include <stack> #include <deque> #include <vector> #include <string> #include <cstdlib> #include <cassert> #include <sstream> #include <iterator> #include <algorithm> #define llu unsigned long long int using namespace std; struct Num { int n; bool operator < (const Num &that) const { // Overload < operator because this structure will be used in a priority // queue, and in such a structure, it will always maintain the 'biggest' // element on top of it, and we want the 'smallest' element instead. return n > that.n; } }; int main() { int T; // Number of test cases int N; // Placeholder for read numbers llu sum; // The sum of the 2 lowest numbers available llu total; // The total of the costs of each pair of numbers added int index; while(cin >> T) { priority_queue < Num > nums; if(!T) { break; } sum = 0; total = 0; index = 0; for(int k = 0; k < T; k++) { cin >> N; Num num; num.n = N; nums.push(num); } while(nums.size() > 1) { int n1 = nums.top().n; // Take the lowest element out of the priority queue nums.pop(); int n2 = nums.top().n; // Take the second lowest element out of it too nums.pop(); sum = n1 + n2; // Add the two lowest values that were in the queue total += sum; // Add this to the total as a cost of adding up Num num; num.n = sum; nums.push(num); // Put back the result back into the priority queue } cout << total << endl; } }<|endoftext|>
<commit_before>/** * This file is part of TelepathyQt * * @copyright Copyright (C) 2012 Collabora Ltd. <http://www.collabora.co.uk/> * @license LGPL 2.1 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "pending-captchas.h" #include "captcha.h" #include "captcha-authentication.h" #include "captcha-authentication-internal.h" #include "cli-channel.h" namespace Tp { struct TP_QT_NO_EXPORT PendingCaptchas::Private { Private(PendingCaptchas *parent); ~Private(); CaptchaAuthentication::ChallengeType stringToChallengeType(const QString &string) const; void appendCaptchaResult(const QString &mimeType, const QString &label, const QByteArray &data, CaptchaAuthentication::ChallengeType type, uint id); // Public object PendingCaptchas *parent; CaptchaAuthentication::ChallengeTypes preferredTypes; QStringList preferredMimeTypes; bool multipleRequired; QList<Captcha> captchas; int captchasLeft; CaptchaAuthenticationPtr channel; }; PendingCaptchas::Private::Private(PendingCaptchas *parent) : parent(parent) { } PendingCaptchas::Private::~Private() { } CaptchaAuthentication::ChallengeType PendingCaptchas::Private::stringToChallengeType(const QString &string) const { if (string == "audio_recog") { return CaptchaAuthentication::AudioRecognitionChallenge; } else if (string == "ocr") { return CaptchaAuthentication::OCRChallenge; } else if (string == "picture_q") { return CaptchaAuthentication::PictureQuestionChallenge; } else if (string == "picture_recog") { return CaptchaAuthentication::PictureRecognitionChallenge; } else if (string == "qa") { return CaptchaAuthentication::TextQuestionChallenge; } else if (string == "speech_q") { return CaptchaAuthentication::SpeechQuestionChallenge; } else if (string == "speech_recog") { return CaptchaAuthentication::SpeechRecognitionChallenge; } else if (string == "video_q") { return CaptchaAuthentication::VideoQuestionChallenge; } else if (string == "video_recog") { return CaptchaAuthentication::VideoRecognitionChallenge; } // Not really making sense... return CaptchaAuthentication::UnknownChallenge; } void PendingCaptchas::Private::appendCaptchaResult(const QString &mimeType, const QString &label, const QByteArray &data, CaptchaAuthentication::ChallengeType type, uint id) { // Add to the list Captcha captchaItem(mimeType, label, data, type, id); captchas.append(captchaItem); --captchasLeft; if (!captchasLeft) { parent->setFinished(); } } /** * \class PendingCaptchas * \ingroup client * \headerfile TelepathyQt/pending-captchas.h <TelepathyQt/PendingCaptchas> * * \brief The PendingCaptchas class represents an asynchronous * operation for retrieving a captcha challenge from a connection manager. * * See \ref async_model */ PendingCaptchas::PendingCaptchas( const QDBusPendingCall &call, const QStringList &preferredMimeTypes, CaptchaAuthentication::ChallengeTypes preferredTypes, const CaptchaAuthenticationPtr &channel) : PendingOperation(channel), mPriv(new Private(this)) { mPriv->channel = channel; mPriv->preferredMimeTypes = preferredMimeTypes; mPriv->preferredTypes = preferredTypes; /* keep track of channel invalidation */ connect(channel.data()->mPriv->channel.data(), SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)), SLOT(onChannelInvalidated(Tp::DBusProxy*,QString,QString))); connect(new QDBusPendingCallWatcher(call), SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(onGetCaptchasWatcherFinished(QDBusPendingCallWatcher*))); } PendingCaptchas::PendingCaptchas( const QString& errorName, const QString& errorMessage, const CaptchaAuthenticationPtr &channel) : PendingOperation(channel), mPriv(new PendingCaptchas::Private(this)) { setFinishedWithError(errorName, errorMessage); } /** * Class destructor. */ PendingCaptchas::~PendingCaptchas() { delete mPriv; } void PendingCaptchas::onChannelInvalidated(Tp::DBusProxy *proxy, const QString &errorName, const QString &errorMessage) { Q_UNUSED(proxy); if (isFinished()) { return; } qWarning().nospace() << "StreamTube.Accept failed because channel was invalidated with " << errorName << ": " << errorMessage; setFinishedWithError(errorName, errorMessage); } void PendingCaptchas::onGetCaptchasWatcherFinished(QDBusPendingCallWatcher *watcher) { QDBusPendingReply<Tp::CaptchaInfoList, uint, QString> reply = *watcher; if (reply.isError()) { qDebug().nospace() << "PendingDBusCall failed: " << reply.error().name() << ": " << reply.error().message(); setFinishedWithError(reply.error()); watcher->deleteLater(); return; } qDebug() << "Got reply to PendingDBusCall"; Tp::CaptchaInfoList list = reply.argumentAt(0).value<Tp::CaptchaInfoList>(); int howManyRequired = reply.argumentAt(1).toUInt(); // Compute which captchas are required QList<QPair<Tp::CaptchaInfo,QString> > finalList; Q_FOREACH (const Tp::CaptchaInfo &info, list) { // First of all, mimetype check QString mimeType; if (info.availableMIMETypes.isEmpty()) { // If it's one of the types which might not have a payload, go for it CaptchaAuthentication::ChallengeTypes noPayloadChallenges = CaptchaAuthentication::TextQuestionChallenge & CaptchaAuthentication::UnknownChallenge; if (mPriv->stringToChallengeType(info.type) & noPayloadChallenges) { // Ok, move on } else { // In this case, there's something wrong qWarning() << "Got a captcha with type " << info.type << " which does not " "expose any available mimetype for its payload. Something might be " "wrong with the connection manager."; continue; } } else if (mPriv->preferredMimeTypes.isEmpty()) { // No preference, let's take the first of the list mimeType = info.availableMIMETypes.first(); } else { QSet<QString> supportedMimeTypes = info.availableMIMETypes.toSet().intersect( mPriv->preferredMimeTypes.toSet()); if (supportedMimeTypes.isEmpty()) { // Apparently our handler does not support any of this captcha's mimetypes, skip continue; } // Ok, use the first one mimeType = *supportedMimeTypes.constBegin(); } // If it's required, easy if (info.flags & CaptchaFlagRequired) { finalList.append(qMakePair(info, mimeType)); continue; } // Otherwise, let's see if the mimetype matches if (mPriv->preferredTypes & mPriv->stringToChallengeType(info.type)) { finalList.append(qMakePair(info, mimeType)); } if (finalList.size() == howManyRequired) { break; } } if (finalList.size() != howManyRequired) { // No captchas available with our preferences setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE, "No captchas matching the handler's request"); return; } // Now, get the infos for all the required captchas in our final list. mPriv->captchasLeft = finalList.size(); mPriv->multipleRequired = howManyRequired > 1 ? true : false; for (QList<QPair<Tp::CaptchaInfo,QString> >::const_iterator i = finalList.constBegin(); i != finalList.constEnd(); ++i) { // If the captcha does not have a mimetype, we can add it straight if ((*i).second.isEmpty()) { mPriv->appendCaptchaResult((*i).second, (*i).first.label, QByteArray(), mPriv->stringToChallengeType((*i).first.type), (*i).first.ID); continue; } QDBusPendingCall call = mPriv->channel->mPriv->channel->interface<Client::ChannelInterfaceCaptchaAuthenticationInterface>()->GetCaptchaData( (*i).first.ID, (*i).second); QDBusPendingCallWatcher *dataWatcher = new QDBusPendingCallWatcher(call); dataWatcher->setProperty("__Tp_Qt_CaptchaID", (*i).first.ID); dataWatcher->setProperty("__Tp_Qt_CaptchaMimeType", (*i).second); dataWatcher->setProperty("__Tp_Qt_CaptchaLabel", (*i).first.label); dataWatcher->setProperty("__Tp_Qt_CaptchaType", mPriv->stringToChallengeType((*i).first.type)); connect(dataWatcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(onGetCaptchaDataWatcherFinished(QDBusPendingCallWatcher*))); } watcher->deleteLater(); } void PendingCaptchas::onGetCaptchaDataWatcherFinished(QDBusPendingCallWatcher *watcher) { QDBusPendingReply<QByteArray> reply = *watcher; if (reply.isError()) { qDebug().nospace() << "PendingDBusCall failed: " << reply.error().name() << ": " << reply.error().message(); setFinishedWithError(reply.error()); watcher->deleteLater(); return; } qDebug() << "Got reply to PendingDBusCall"; // Add to the list mPriv->appendCaptchaResult(watcher->property("__Tp_Qt_CaptchaMimeType").toString(), watcher->property("__Tp_Qt_CaptchaLabel").toString(), reply.value(), (CaptchaAuthentication::ChallengeType) watcher->property("__Tp_Qt_CaptchaType").toUInt(), watcher->property("__Tp_Qt_CaptchaID").toUInt()); watcher->deleteLater(); } /** * Return the main captcha of the request. This captcha is guaranteed to be compatible * with any constraint specified in CaptchaAuthentication::requestCaptchas(). * * This is a convenience method which should be used when requiresMultipleCaptchas() * is false - otherwise, you should use captchaList. * * The returned Captcha can be answered through CaptchaAuthentication::answer() by * using its id. * * This method will return a meaningful value only if the operation was completed * successfully. * * \return The main captcha for the pending request. * * \sa captchaList() * CaptchaAuthentication::requestCaptchas() * requiresMultipleCaptchas() * CaptchaAuthentication::answer() */ Captcha PendingCaptchas::captcha() const { if (!isFinished()) { return Captcha(); } return mPriv->captchas.first(); } /** * Return all the captchas of the request. These captchas are guaranteed to be compatible * with any constraint specified in CaptchaAuthentication::requestCaptchas(). * * If requiresMultipleCaptchas() is false, you probably want to use the convenience method * captcha() instead. * * The returned Captchas can be answered through CaptchaAuthentication::answer() by * using their ids. * * This method will return a meaningful value only if the operation was completed * successfully. * * \return All the captchas for the pending request. * * \sa captcha() * CaptchaAuthentication::requestCaptchas() * requiresMultipleCaptchas() * CaptchaAuthentication::answer() */ QList<Captcha> PendingCaptchas::captchaList() const { if (!isFinished()) { return QList<Captcha>(); } return mPriv->captchas; } /** * Return whether this request requires more than one captcha to be answered or not. * * This method should always be checked before answering to find out what the * connection manager expects. Depending on the result, you might want to use the * result from captcha() if just a single answer is required, or from captchaList() * otherwise. * * This method will return a meaningful value only if the operation was completed * successfully. * * \return The main captcha for the pending request. * \sa captcha() * captchaList() */ bool PendingCaptchas::requiresMultipleCaptchas() const { return mPriv->multipleRequired; } } <commit_msg>captcha-authentication: Use a qdbus_cast for custom types to prevent the QVariant conversion from failing<commit_after>/** * This file is part of TelepathyQt * * @copyright Copyright (C) 2012 Collabora Ltd. <http://www.collabora.co.uk/> * @license LGPL 2.1 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "pending-captchas.h" #include "captcha.h" #include "captcha-authentication.h" #include "captcha-authentication-internal.h" #include "cli-channel.h" namespace Tp { struct TP_QT_NO_EXPORT PendingCaptchas::Private { Private(PendingCaptchas *parent); ~Private(); CaptchaAuthentication::ChallengeType stringToChallengeType(const QString &string) const; void appendCaptchaResult(const QString &mimeType, const QString &label, const QByteArray &data, CaptchaAuthentication::ChallengeType type, uint id); // Public object PendingCaptchas *parent; CaptchaAuthentication::ChallengeTypes preferredTypes; QStringList preferredMimeTypes; bool multipleRequired; QList<Captcha> captchas; int captchasLeft; CaptchaAuthenticationPtr channel; }; PendingCaptchas::Private::Private(PendingCaptchas *parent) : parent(parent) { } PendingCaptchas::Private::~Private() { } CaptchaAuthentication::ChallengeType PendingCaptchas::Private::stringToChallengeType(const QString &string) const { if (string == "audio_recog") { return CaptchaAuthentication::AudioRecognitionChallenge; } else if (string == "ocr") { return CaptchaAuthentication::OCRChallenge; } else if (string == "picture_q") { return CaptchaAuthentication::PictureQuestionChallenge; } else if (string == "picture_recog") { return CaptchaAuthentication::PictureRecognitionChallenge; } else if (string == "qa") { return CaptchaAuthentication::TextQuestionChallenge; } else if (string == "speech_q") { return CaptchaAuthentication::SpeechQuestionChallenge; } else if (string == "speech_recog") { return CaptchaAuthentication::SpeechRecognitionChallenge; } else if (string == "video_q") { return CaptchaAuthentication::VideoQuestionChallenge; } else if (string == "video_recog") { return CaptchaAuthentication::VideoRecognitionChallenge; } // Not really making sense... return CaptchaAuthentication::UnknownChallenge; } void PendingCaptchas::Private::appendCaptchaResult(const QString &mimeType, const QString &label, const QByteArray &data, CaptchaAuthentication::ChallengeType type, uint id) { // Add to the list Captcha captchaItem(mimeType, label, data, type, id); captchas.append(captchaItem); --captchasLeft; if (!captchasLeft) { parent->setFinished(); } } /** * \class PendingCaptchas * \ingroup client * \headerfile TelepathyQt/pending-captchas.h <TelepathyQt/PendingCaptchas> * * \brief The PendingCaptchas class represents an asynchronous * operation for retrieving a captcha challenge from a connection manager. * * See \ref async_model */ PendingCaptchas::PendingCaptchas( const QDBusPendingCall &call, const QStringList &preferredMimeTypes, CaptchaAuthentication::ChallengeTypes preferredTypes, const CaptchaAuthenticationPtr &channel) : PendingOperation(channel), mPriv(new Private(this)) { mPriv->channel = channel; mPriv->preferredMimeTypes = preferredMimeTypes; mPriv->preferredTypes = preferredTypes; /* keep track of channel invalidation */ connect(channel.data()->mPriv->channel.data(), SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)), SLOT(onChannelInvalidated(Tp::DBusProxy*,QString,QString))); connect(new QDBusPendingCallWatcher(call), SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(onGetCaptchasWatcherFinished(QDBusPendingCallWatcher*))); } PendingCaptchas::PendingCaptchas( const QString& errorName, const QString& errorMessage, const CaptchaAuthenticationPtr &channel) : PendingOperation(channel), mPriv(new PendingCaptchas::Private(this)) { setFinishedWithError(errorName, errorMessage); } /** * Class destructor. */ PendingCaptchas::~PendingCaptchas() { delete mPriv; } void PendingCaptchas::onChannelInvalidated(Tp::DBusProxy *proxy, const QString &errorName, const QString &errorMessage) { Q_UNUSED(proxy); if (isFinished()) { return; } qWarning().nospace() << "StreamTube.Accept failed because channel was invalidated with " << errorName << ": " << errorMessage; setFinishedWithError(errorName, errorMessage); } void PendingCaptchas::onGetCaptchasWatcherFinished(QDBusPendingCallWatcher *watcher) { QDBusPendingReply<Tp::CaptchaInfoList, uint, QString> reply = *watcher; if (reply.isError()) { qDebug().nospace() << "PendingDBusCall failed: " << reply.error().name() << ": " << reply.error().message(); setFinishedWithError(reply.error()); watcher->deleteLater(); return; } qDebug() << "Got reply to PendingDBusCall"; Tp::CaptchaInfoList list = qdbus_cast<Tp::CaptchaInfoList>(reply.argumentAt(0)); int howManyRequired = reply.argumentAt(1).toUInt(); // Compute which captchas are required QList<QPair<Tp::CaptchaInfo,QString> > finalList; Q_FOREACH (const Tp::CaptchaInfo &info, list) { // First of all, mimetype check QString mimeType; if (info.availableMIMETypes.isEmpty()) { // If it's one of the types which might not have a payload, go for it CaptchaAuthentication::ChallengeTypes noPayloadChallenges = CaptchaAuthentication::TextQuestionChallenge & CaptchaAuthentication::UnknownChallenge; if (mPriv->stringToChallengeType(info.type) & noPayloadChallenges) { // Ok, move on } else { // In this case, there's something wrong qWarning() << "Got a captcha with type " << info.type << " which does not " "expose any available mimetype for its payload. Something might be " "wrong with the connection manager."; continue; } } else if (mPriv->preferredMimeTypes.isEmpty()) { // No preference, let's take the first of the list mimeType = info.availableMIMETypes.first(); } else { QSet<QString> supportedMimeTypes = info.availableMIMETypes.toSet().intersect( mPriv->preferredMimeTypes.toSet()); if (supportedMimeTypes.isEmpty()) { // Apparently our handler does not support any of this captcha's mimetypes, skip continue; } // Ok, use the first one mimeType = *supportedMimeTypes.constBegin(); } // If it's required, easy if (info.flags & CaptchaFlagRequired) { finalList.append(qMakePair(info, mimeType)); continue; } // Otherwise, let's see if the mimetype matches if (mPriv->preferredTypes & mPriv->stringToChallengeType(info.type)) { finalList.append(qMakePair(info, mimeType)); } if (finalList.size() == howManyRequired) { break; } } if (finalList.size() != howManyRequired) { // No captchas available with our preferences setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE, "No captchas matching the handler's request"); return; } // Now, get the infos for all the required captchas in our final list. mPriv->captchasLeft = finalList.size(); mPriv->multipleRequired = howManyRequired > 1 ? true : false; for (QList<QPair<Tp::CaptchaInfo,QString> >::const_iterator i = finalList.constBegin(); i != finalList.constEnd(); ++i) { // If the captcha does not have a mimetype, we can add it straight if ((*i).second.isEmpty()) { mPriv->appendCaptchaResult((*i).second, (*i).first.label, QByteArray(), mPriv->stringToChallengeType((*i).first.type), (*i).first.ID); continue; } QDBusPendingCall call = mPriv->channel->mPriv->channel->interface<Client::ChannelInterfaceCaptchaAuthenticationInterface>()->GetCaptchaData( (*i).first.ID, (*i).second); QDBusPendingCallWatcher *dataWatcher = new QDBusPendingCallWatcher(call); dataWatcher->setProperty("__Tp_Qt_CaptchaID", (*i).first.ID); dataWatcher->setProperty("__Tp_Qt_CaptchaMimeType", (*i).second); dataWatcher->setProperty("__Tp_Qt_CaptchaLabel", (*i).first.label); dataWatcher->setProperty("__Tp_Qt_CaptchaType", mPriv->stringToChallengeType((*i).first.type)); connect(dataWatcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(onGetCaptchaDataWatcherFinished(QDBusPendingCallWatcher*))); } watcher->deleteLater(); } void PendingCaptchas::onGetCaptchaDataWatcherFinished(QDBusPendingCallWatcher *watcher) { QDBusPendingReply<QByteArray> reply = *watcher; if (reply.isError()) { qDebug().nospace() << "PendingDBusCall failed: " << reply.error().name() << ": " << reply.error().message(); setFinishedWithError(reply.error()); watcher->deleteLater(); return; } qDebug() << "Got reply to PendingDBusCall"; // Add to the list mPriv->appendCaptchaResult(watcher->property("__Tp_Qt_CaptchaMimeType").toString(), watcher->property("__Tp_Qt_CaptchaLabel").toString(), reply.value(), (CaptchaAuthentication::ChallengeType) watcher->property("__Tp_Qt_CaptchaType").toUInt(), watcher->property("__Tp_Qt_CaptchaID").toUInt()); watcher->deleteLater(); } /** * Return the main captcha of the request. This captcha is guaranteed to be compatible * with any constraint specified in CaptchaAuthentication::requestCaptchas(). * * This is a convenience method which should be used when requiresMultipleCaptchas() * is false - otherwise, you should use captchaList. * * The returned Captcha can be answered through CaptchaAuthentication::answer() by * using its id. * * This method will return a meaningful value only if the operation was completed * successfully. * * \return The main captcha for the pending request. * * \sa captchaList() * CaptchaAuthentication::requestCaptchas() * requiresMultipleCaptchas() * CaptchaAuthentication::answer() */ Captcha PendingCaptchas::captcha() const { if (!isFinished()) { return Captcha(); } return mPriv->captchas.first(); } /** * Return all the captchas of the request. These captchas are guaranteed to be compatible * with any constraint specified in CaptchaAuthentication::requestCaptchas(). * * If requiresMultipleCaptchas() is false, you probably want to use the convenience method * captcha() instead. * * The returned Captchas can be answered through CaptchaAuthentication::answer() by * using their ids. * * This method will return a meaningful value only if the operation was completed * successfully. * * \return All the captchas for the pending request. * * \sa captcha() * CaptchaAuthentication::requestCaptchas() * requiresMultipleCaptchas() * CaptchaAuthentication::answer() */ QList<Captcha> PendingCaptchas::captchaList() const { if (!isFinished()) { return QList<Captcha>(); } return mPriv->captchas; } /** * Return whether this request requires more than one captcha to be answered or not. * * This method should always be checked before answering to find out what the * connection manager expects. Depending on the result, you might want to use the * result from captcha() if just a single answer is required, or from captchaList() * otherwise. * * This method will return a meaningful value only if the operation was completed * successfully. * * \return The main captcha for the pending request. * \sa captcha() * captchaList() */ bool PendingCaptchas::requiresMultipleCaptchas() const { return mPriv->multipleRequired; } } <|endoftext|>
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/util/sequencedtaskexecutor.h> #include <vespa/vespalib/util/adaptive_sequenced_executor.h> #include <vespa/vespalib/testkit/testapp.h> #include <vespa/vespalib/test/insertion_operators.h> #include <condition_variable> #include <unistd.h> #include <vespa/log/log.h> LOG_SETUP("sequencedtaskexecutor_test"); VESPA_THREAD_STACK_TAG(sequenced_executor) namespace vespalib { class Fixture { public: std::unique_ptr<ISequencedTaskExecutor> _threads; Fixture() : _threads(SequencedTaskExecutor::create(sequenced_executor, 2)) { } }; class TestObj { public: std::mutex _m; std::condition_variable _cv; int _done; int _fail; int _val; TestObj() noexcept : _m(), _cv(), _done(0), _fail(0), _val(0) { } void modify(int oldValue, int newValue) { { std::lock_guard<std::mutex> guard(_m); if (_val == oldValue) { _val = newValue; } else { ++_fail; } ++_done; } _cv.notify_all(); } void wait(int wantDone) { std::unique_lock<std::mutex> guard(_m); _cv.wait(guard, [this, wantDone] { return this->_done >= wantDone; }); } }; vespalib::stringref ZERO("0"); TEST_F("testExecute", Fixture) { std::shared_ptr<TestObj> tv(std::make_shared<TestObj>()); EXPECT_EQUAL(0, tv->_val); f._threads->execute(1, [=]() { tv->modify(0, 42); }); tv->wait(1); EXPECT_EQUAL(0, tv->_fail); EXPECT_EQUAL(42, tv->_val); f._threads->sync_all(); EXPECT_EQUAL(0, tv->_fail); EXPECT_EQUAL(42, tv->_val); } TEST_F("require that task with same component id are serialized", Fixture) { std::shared_ptr<TestObj> tv(std::make_shared<TestObj>()); EXPECT_EQUAL(0, tv->_val); f._threads->execute(0, [=]() { usleep(2000); tv->modify(0, 14); }); f._threads->execute(0, [=]() { tv->modify(14, 42); }); tv->wait(2); EXPECT_EQUAL(0, tv->_fail); EXPECT_EQUAL(42, tv->_val); f._threads->sync_all(); EXPECT_EQUAL(0, tv->_fail); EXPECT_EQUAL(42, tv->_val); } TEST_F("require that task with different component ids are not serialized", Fixture) { int tryCnt = 0; for (tryCnt = 0; tryCnt < 100; ++tryCnt) { std::shared_ptr<TestObj> tv(std::make_shared<TestObj>()); EXPECT_EQUAL(0, tv->_val); f._threads->execute(0, [=]() { usleep(2000); tv->modify(0, 14); }); f._threads->execute(2, [=]() { tv->modify(14, 42); }); tv->wait(2); if (tv->_fail != 1) { continue; } EXPECT_EQUAL(1, tv->_fail); EXPECT_EQUAL(14, tv->_val); f._threads->sync_all(); EXPECT_EQUAL(1, tv->_fail); EXPECT_EQUAL(14, tv->_val); break; } EXPECT_TRUE(tryCnt < 100); } TEST_F("require that task with same string component id are serialized", Fixture) { std::shared_ptr<TestObj> tv(std::make_shared<TestObj>()); EXPECT_EQUAL(0, tv->_val); auto test2 = [=]() { tv->modify(14, 42); }; f._threads->execute(f._threads->getExecutorIdFromName(ZERO), [=]() { usleep(2000); tv->modify(0, 14); }); f._threads->execute(f._threads->getExecutorIdFromName(ZERO), test2); tv->wait(2); EXPECT_EQUAL(0, tv->_fail); EXPECT_EQUAL(42, tv->_val); f._threads->sync_all(); EXPECT_EQUAL(0, tv->_fail); EXPECT_EQUAL(42, tv->_val); } namespace { int detectSerializeFailure(Fixture &f, vespalib::stringref altComponentId, int tryLimit) { int tryCnt = 0; for (tryCnt = 0; tryCnt < tryLimit; ++tryCnt) { std::shared_ptr<TestObj> tv(std::make_shared<TestObj>()); EXPECT_EQUAL(0, tv->_val); f._threads->execute(f._threads->getExecutorIdFromName(ZERO), [=]() { usleep(2000); tv->modify(0, 14); }); f._threads->execute(f._threads->getExecutorIdFromName(altComponentId), [=]() { tv->modify(14, 42); }); tv->wait(2); if (tv->_fail != 1) { continue; } EXPECT_EQUAL(1, tv->_fail); EXPECT_EQUAL(14, tv->_val); f._threads->sync_all(); EXPECT_EQUAL(1, tv->_fail); EXPECT_EQUAL(14, tv->_val); break; } return tryCnt; } vespalib::string makeAltComponentId(Fixture &f) { int tryCnt = 0; char altComponentId[20]; ISequencedTaskExecutor::ExecutorId executorId0 = f._threads->getExecutorIdFromName(ZERO); for (tryCnt = 1; tryCnt < 100; ++tryCnt) { sprintf(altComponentId, "%d", tryCnt); if (f._threads->getExecutorIdFromName(altComponentId) == executorId0) { break; } } EXPECT_TRUE(tryCnt < 100); return altComponentId; } } TEST_F("require that task with different string component ids are not serialized", Fixture) { int tryCnt = detectSerializeFailure(f, "2", 100); EXPECT_TRUE(tryCnt < 100); } TEST_F("require that task with different string component ids mapping to the same executor id are serialized", Fixture) { vespalib::string altComponentId = makeAltComponentId(f); LOG(info, "second string component id is \"%s\"", altComponentId.c_str()); int tryCnt = detectSerializeFailure(f, altComponentId, 100); EXPECT_TRUE(tryCnt == 100); } TEST_F("require that execute works with const lambda", Fixture) { int i = 5; std::vector<int> res; const auto lambda = [i, &res]() mutable { res.push_back(i--); res.push_back(i--); }; f._threads->execute(0, lambda); f._threads->execute(0, lambda); f._threads->sync_all(); std::vector<int> exp({5, 4, 5, 4}); EXPECT_EQUAL(exp, res); EXPECT_EQUAL(5, i); } TEST_F("require that execute works with reference to lambda", Fixture) { int i = 5; std::vector<int> res; auto lambda = [i, &res]() mutable { res.push_back(i--); res.push_back(i--); }; auto &lambdaref = lambda; f._threads->execute(0, lambdaref); f._threads->execute(0, lambdaref); f._threads->sync_all(); std::vector<int> exp({5, 4, 5, 4}); EXPECT_EQUAL(exp, res); EXPECT_EQUAL(5, i); } TEST_F("require that executeLambda works", Fixture) { int i = 5; std::vector<int> res; const auto lambda = [i, &res]() mutable { res.push_back(i--); res.push_back(i--); }; f._threads->executeLambda(ISequencedTaskExecutor::ExecutorId(0), lambda); f._threads->sync_all(); std::vector<int> exp({5, 4}); EXPECT_EQUAL(exp, res); EXPECT_EQUAL(5, i); } TEST("require that you get correct number of executors") { auto seven = SequencedTaskExecutor::create(sequenced_executor, 7); EXPECT_EQUAL(7u, seven->getNumExecutors()); } TEST("require that you distribute well") { auto seven = SequencedTaskExecutor::create(sequenced_executor, 7); const SequencedTaskExecutor & seq = dynamic_cast<const SequencedTaskExecutor &>(*seven); EXPECT_EQUAL(7u, seven->getNumExecutors()); EXPECT_EQUAL(97u, seq.getComponentHashSize()); EXPECT_EQUAL(0u, seq.getComponentEffectiveHashSize()); for (uint32_t id=0; id < 1000; id++) { EXPECT_EQUAL((id%97)%7, seven->getExecutorId(id).getId()); } EXPECT_EQUAL(97u, seq.getComponentHashSize()); EXPECT_EQUAL(97u, seq.getComponentEffectiveHashSize()); } TEST("Test creation of different types") { auto iseq = SequencedTaskExecutor::create(sequenced_executor, 1); EXPECT_EQUAL(1u, iseq->getNumExecutors()); auto * seq = dynamic_cast<SequencedTaskExecutor *>(iseq.get()); ASSERT_TRUE(seq != nullptr); iseq = SequencedTaskExecutor::create(sequenced_executor, 1, 1000, Executor::OptimizeFor::LATENCY); seq = dynamic_cast<SequencedTaskExecutor *>(iseq.get()); ASSERT_TRUE(seq != nullptr); iseq = SequencedTaskExecutor::create(sequenced_executor, 1, 1000, Executor::OptimizeFor::THROUGHPUT); seq = dynamic_cast<SequencedTaskExecutor *>(iseq.get()); ASSERT_TRUE(seq != nullptr); iseq = SequencedTaskExecutor::create(sequenced_executor, 1, 1000, Executor::OptimizeFor::ADAPTIVE, 17); auto aseq = dynamic_cast<AdaptiveSequencedExecutor *>(iseq.get()); ASSERT_TRUE(aseq != nullptr); } } TEST_MAIN() { TEST_RUN_ALL(); } <commit_msg>Test the distribution we get with 8 attributes and 4/8 threads.<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/util/sequencedtaskexecutor.h> #include <vespa/vespalib/util/adaptive_sequenced_executor.h> #include <vespa/vespalib/testkit/testapp.h> #include <vespa/vespalib/test/insertion_operators.h> #include <condition_variable> #include <unistd.h> #include <vespa/log/log.h> LOG_SETUP("sequencedtaskexecutor_test"); VESPA_THREAD_STACK_TAG(sequenced_executor) namespace vespalib { class Fixture { public: std::unique_ptr<ISequencedTaskExecutor> _threads; Fixture() : _threads(SequencedTaskExecutor::create(sequenced_executor, 2)) { } }; class TestObj { public: std::mutex _m; std::condition_variable _cv; int _done; int _fail; int _val; TestObj() noexcept : _m(), _cv(), _done(0), _fail(0), _val(0) { } void modify(int oldValue, int newValue) { { std::lock_guard<std::mutex> guard(_m); if (_val == oldValue) { _val = newValue; } else { ++_fail; } ++_done; } _cv.notify_all(); } void wait(int wantDone) { std::unique_lock<std::mutex> guard(_m); _cv.wait(guard, [this, wantDone] { return this->_done >= wantDone; }); } }; vespalib::stringref ZERO("0"); TEST_F("testExecute", Fixture) { std::shared_ptr<TestObj> tv(std::make_shared<TestObj>()); EXPECT_EQUAL(0, tv->_val); f._threads->execute(1, [=]() { tv->modify(0, 42); }); tv->wait(1); EXPECT_EQUAL(0, tv->_fail); EXPECT_EQUAL(42, tv->_val); f._threads->sync_all(); EXPECT_EQUAL(0, tv->_fail); EXPECT_EQUAL(42, tv->_val); } TEST_F("require that task with same component id are serialized", Fixture) { std::shared_ptr<TestObj> tv(std::make_shared<TestObj>()); EXPECT_EQUAL(0, tv->_val); f._threads->execute(0, [=]() { usleep(2000); tv->modify(0, 14); }); f._threads->execute(0, [=]() { tv->modify(14, 42); }); tv->wait(2); EXPECT_EQUAL(0, tv->_fail); EXPECT_EQUAL(42, tv->_val); f._threads->sync_all(); EXPECT_EQUAL(0, tv->_fail); EXPECT_EQUAL(42, tv->_val); } TEST_F("require that task with different component ids are not serialized", Fixture) { int tryCnt = 0; for (tryCnt = 0; tryCnt < 100; ++tryCnt) { std::shared_ptr<TestObj> tv(std::make_shared<TestObj>()); EXPECT_EQUAL(0, tv->_val); f._threads->execute(0, [=]() { usleep(2000); tv->modify(0, 14); }); f._threads->execute(2, [=]() { tv->modify(14, 42); }); tv->wait(2); if (tv->_fail != 1) { continue; } EXPECT_EQUAL(1, tv->_fail); EXPECT_EQUAL(14, tv->_val); f._threads->sync_all(); EXPECT_EQUAL(1, tv->_fail); EXPECT_EQUAL(14, tv->_val); break; } EXPECT_TRUE(tryCnt < 100); } TEST_F("require that task with same string component id are serialized", Fixture) { std::shared_ptr<TestObj> tv(std::make_shared<TestObj>()); EXPECT_EQUAL(0, tv->_val); auto test2 = [=]() { tv->modify(14, 42); }; f._threads->execute(f._threads->getExecutorIdFromName(ZERO), [=]() { usleep(2000); tv->modify(0, 14); }); f._threads->execute(f._threads->getExecutorIdFromName(ZERO), test2); tv->wait(2); EXPECT_EQUAL(0, tv->_fail); EXPECT_EQUAL(42, tv->_val); f._threads->sync_all(); EXPECT_EQUAL(0, tv->_fail); EXPECT_EQUAL(42, tv->_val); } namespace { int detectSerializeFailure(Fixture &f, vespalib::stringref altComponentId, int tryLimit) { int tryCnt = 0; for (tryCnt = 0; tryCnt < tryLimit; ++tryCnt) { std::shared_ptr<TestObj> tv(std::make_shared<TestObj>()); EXPECT_EQUAL(0, tv->_val); f._threads->execute(f._threads->getExecutorIdFromName(ZERO), [=]() { usleep(2000); tv->modify(0, 14); }); f._threads->execute(f._threads->getExecutorIdFromName(altComponentId), [=]() { tv->modify(14, 42); }); tv->wait(2); if (tv->_fail != 1) { continue; } EXPECT_EQUAL(1, tv->_fail); EXPECT_EQUAL(14, tv->_val); f._threads->sync_all(); EXPECT_EQUAL(1, tv->_fail); EXPECT_EQUAL(14, tv->_val); break; } return tryCnt; } vespalib::string makeAltComponentId(Fixture &f) { int tryCnt = 0; char altComponentId[20]; ISequencedTaskExecutor::ExecutorId executorId0 = f._threads->getExecutorIdFromName(ZERO); for (tryCnt = 1; tryCnt < 100; ++tryCnt) { sprintf(altComponentId, "%d", tryCnt); if (f._threads->getExecutorIdFromName(altComponentId) == executorId0) { break; } } EXPECT_TRUE(tryCnt < 100); return altComponentId; } } TEST_F("require that task with different string component ids are not serialized", Fixture) { int tryCnt = detectSerializeFailure(f, "2", 100); EXPECT_TRUE(tryCnt < 100); } TEST_F("require that task with different string component ids mapping to the same executor id are serialized", Fixture) { vespalib::string altComponentId = makeAltComponentId(f); LOG(info, "second string component id is \"%s\"", altComponentId.c_str()); int tryCnt = detectSerializeFailure(f, altComponentId, 100); EXPECT_TRUE(tryCnt == 100); } TEST_F("require that execute works with const lambda", Fixture) { int i = 5; std::vector<int> res; const auto lambda = [i, &res]() mutable { res.push_back(i--); res.push_back(i--); }; f._threads->execute(0, lambda); f._threads->execute(0, lambda); f._threads->sync_all(); std::vector<int> exp({5, 4, 5, 4}); EXPECT_EQUAL(exp, res); EXPECT_EQUAL(5, i); } TEST_F("require that execute works with reference to lambda", Fixture) { int i = 5; std::vector<int> res; auto lambda = [i, &res]() mutable { res.push_back(i--); res.push_back(i--); }; auto &lambdaref = lambda; f._threads->execute(0, lambdaref); f._threads->execute(0, lambdaref); f._threads->sync_all(); std::vector<int> exp({5, 4, 5, 4}); EXPECT_EQUAL(exp, res); EXPECT_EQUAL(5, i); } TEST_F("require that executeLambda works", Fixture) { int i = 5; std::vector<int> res; const auto lambda = [i, &res]() mutable { res.push_back(i--); res.push_back(i--); }; f._threads->executeLambda(ISequencedTaskExecutor::ExecutorId(0), lambda); f._threads->sync_all(); std::vector<int> exp({5, 4}); EXPECT_EQUAL(exp, res); EXPECT_EQUAL(5, i); } TEST("require that you get correct number of executors") { auto seven = SequencedTaskExecutor::create(sequenced_executor, 7); EXPECT_EQUAL(7u, seven->getNumExecutors()); } TEST("require that you distribute well") { auto seven = SequencedTaskExecutor::create(sequenced_executor, 7); const SequencedTaskExecutor & seq = dynamic_cast<const SequencedTaskExecutor &>(*seven); EXPECT_EQUAL(7u, seven->getNumExecutors()); EXPECT_EQUAL(97u, seq.getComponentHashSize()); EXPECT_EQUAL(0u, seq.getComponentEffectiveHashSize()); for (uint32_t id=0; id < 1000; id++) { EXPECT_EQUAL((id%97)%7, seven->getExecutorId(id).getId()); } EXPECT_EQUAL(97u, seq.getComponentHashSize()); EXPECT_EQUAL(97u, seq.getComponentEffectiveHashSize()); } TEST("require that similar names get perfect distribution with 4 executors") { auto four = SequencedTaskExecutor::create(sequenced_executor, 4); EXPECT_EQUAL(0u, four->getExecutorIdFromName("f1").getId()); EXPECT_EQUAL(1u, four->getExecutorIdFromName("f2").getId()); EXPECT_EQUAL(2u, four->getExecutorIdFromName("f3").getId()); EXPECT_EQUAL(3u, four->getExecutorIdFromName("f4").getId()); EXPECT_EQUAL(0u, four->getExecutorIdFromName("f5").getId()); EXPECT_EQUAL(1u, four->getExecutorIdFromName("f6").getId()); EXPECT_EQUAL(2u, four->getExecutorIdFromName("f7").getId()); EXPECT_EQUAL(3u, four->getExecutorIdFromName("f8").getId()); } TEST("require that similar names gets 7/8 unique ids with 8 executors") { auto four = SequencedTaskExecutor::create(sequenced_executor, 8); EXPECT_EQUAL(0u, four->getExecutorIdFromName("f1").getId()); EXPECT_EQUAL(1u, four->getExecutorIdFromName("f2").getId()); EXPECT_EQUAL(2u, four->getExecutorIdFromName("f3").getId()); EXPECT_EQUAL(3u, four->getExecutorIdFromName("f4").getId()); EXPECT_EQUAL(4u, four->getExecutorIdFromName("f5").getId()); EXPECT_EQUAL(5u, four->getExecutorIdFromName("f6").getId()); EXPECT_EQUAL(2u, four->getExecutorIdFromName("f7").getId()); EXPECT_EQUAL(6u, four->getExecutorIdFromName("f8").getId()); } TEST("Test creation of different types") { auto iseq = SequencedTaskExecutor::create(sequenced_executor, 1); EXPECT_EQUAL(1u, iseq->getNumExecutors()); auto * seq = dynamic_cast<SequencedTaskExecutor *>(iseq.get()); ASSERT_TRUE(seq != nullptr); iseq = SequencedTaskExecutor::create(sequenced_executor, 1, 1000, Executor::OptimizeFor::LATENCY); seq = dynamic_cast<SequencedTaskExecutor *>(iseq.get()); ASSERT_TRUE(seq != nullptr); iseq = SequencedTaskExecutor::create(sequenced_executor, 1, 1000, Executor::OptimizeFor::THROUGHPUT); seq = dynamic_cast<SequencedTaskExecutor *>(iseq.get()); ASSERT_TRUE(seq != nullptr); iseq = SequencedTaskExecutor::create(sequenced_executor, 1, 1000, Executor::OptimizeFor::ADAPTIVE, 17); auto aseq = dynamic_cast<AdaptiveSequencedExecutor *>(iseq.get()); ASSERT_TRUE(aseq != nullptr); } } TEST_MAIN() { TEST_RUN_ALL(); } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2019 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file FlightManualAltitude.cpp */ #include "FlightTaskManualAltitudeSmoothVel.hpp" #include <float.h> using namespace matrix; bool FlightTaskManualAltitudeSmoothVel::activate(vehicle_local_position_setpoint_s last_setpoint) { bool ret = FlightTaskManualAltitude::activate(last_setpoint); // Check if the previous FlightTask provided setpoints checkSetpoints(last_setpoint); _smoothing.reset(last_setpoint.acc_z, last_setpoint.vz, last_setpoint.z); _initEkfResetCounters(); _resetPositionLock(); return ret; } void FlightTaskManualAltitudeSmoothVel::reActivate() { // The task is reacivated while the vehicle is on the ground. To detect takeoff in mc_pos_control_main properly // using the generated jerk, reset the z derivatives to zero _smoothing.reset(0.f, 0.f, _position(2)); _initEkfResetCounters(); _resetPositionLock(); } void FlightTaskManualAltitudeSmoothVel::checkSetpoints(vehicle_local_position_setpoint_s &setpoints) { // If the position setpoint is unknown, set to the current postion if (!PX4_ISFINITE(setpoints.z)) { setpoints.z = _position(2); } // If the velocity setpoint is unknown, set to the current velocity if (!PX4_ISFINITE(setpoints.vz)) { setpoints.vz = _velocity(2); } // No acceleration estimate available, set to zero if the setpoint is NAN if (!PX4_ISFINITE(setpoints.acc_z)) { setpoints.acc_z = 0.f; } } void FlightTaskManualAltitudeSmoothVel::_resetPositionLock() { // Always start unlocked _position_lock_z_active = false; _position_setpoint_z_locked = NAN; } void FlightTaskManualAltitudeSmoothVel::_initEkfResetCounters() { _reset_counters.z = _sub_vehicle_local_position->get().z_reset_counter; _reset_counters.vz = _sub_vehicle_local_position->get().vz_reset_counter; } void FlightTaskManualAltitudeSmoothVel::_checkEkfResetCounters() { if (_sub_vehicle_local_position->get().z_reset_counter != _reset_counters.z) { _smoothing.setCurrentPosition(_position(2)); _reset_counters.z = _sub_vehicle_local_position->get().z_reset_counter; } if (_sub_vehicle_local_position->get().vz_reset_counter != _reset_counters.vz) { _smoothing.setCurrentVelocity(_velocity(2)); _reset_counters.vz = _sub_vehicle_local_position->get().vz_reset_counter; } } void FlightTaskManualAltitudeSmoothVel::_updateSetpoints() { /* Get yaw setpont, un-smoothed position setpoints.*/ FlightTaskManualAltitude::_updateSetpoints(); /* Update constraints */ if (_velocity_setpoint(2) < 0.f) { // up _smoothing.setMaxAccel(_param_mpc_acc_up_max.get()); _smoothing.setMaxVel(_constraints.speed_up); } else { // down _smoothing.setMaxAccel(_param_mpc_acc_down_max.get()); _smoothing.setMaxVel(_constraints.speed_down); } float jerk = _param_mpc_jerk_max.get(); _checkEkfResetCounters(); /* Check for position unlock * During a position lock -> position unlock transition, we have to make sure that the velocity setpoint * is continuous. We know that the output of the position loop (part of the velocity setpoint) will suddenly become null * and only the feedforward (generated by this flight task) will remain. This is why the previous input of the velocity controller * is used to set current velocity of the trajectory. */ if (fabsf(_sticks_expo(2)) > FLT_EPSILON) { if (_position_lock_z_active) { _smoothing.setCurrentVelocity(_velocity_setpoint_feedback( 2)); // Start the trajectory at the current velocity setpoint _position_setpoint_z_locked = NAN; } _position_lock_z_active = false; } // During position lock, lower jerk to help the optimizer // to converge to 0 acceleration and velocity jerk = _position_lock_z_active ? 1.f : _param_mpc_jerk_max.get(); _smoothing.setMaxJerk(jerk); _smoothing.updateDurations(_deltatime, _velocity_setpoint(2)); if (!_position_lock_z_active) { _smoothing.setCurrentPosition(_position(2)); } float pos_sp_smooth; _smoothing.integrate(_acceleration_setpoint(2), _vel_sp_smooth, pos_sp_smooth); _velocity_setpoint(2) = _vel_sp_smooth; // Feedforward _jerk_setpoint(2) = _smoothing.getCurrentJerk(); if (fabsf(_vel_sp_smooth) < 0.1f && fabsf(_acceleration_setpoint(2)) < .2f && fabsf(_sticks_expo(2)) <= FLT_EPSILON) { _position_lock_z_active = true; } // Set valid position setpoint while in position lock. // When the position lock condition above is false, it does not // mean that the unlock condition is true. This is why // we are checking the lock flag here. if (_position_lock_z_active) { _position_setpoint_z_locked = pos_sp_smooth; // If the velocity setpoint is smaller than 1mm/s and that the acceleration is 0, force the setpoints // to zero. This is required because the generated velocity is never exactly zero and if the drone hovers // for a long period of time, thr drift of the position setpoint will be noticeable. if (fabsf(_velocity_setpoint(2)) < 1e-3f && fabsf(_acceleration_setpoint(2)) < FLT_EPSILON) { _velocity_setpoint(2) = 0.f; _acceleration_setpoint(2) = 0.f; _smoothing.setCurrentVelocity(0.f); _smoothing.setCurrentAcceleration(0.f); } } _position_setpoint(2) = _position_setpoint_z_locked; } <commit_msg>check velocity_setpoint instead of sticks in altitude mode<commit_after>/**************************************************************************** * * Copyright (c) 2019 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file FlightManualAltitude.cpp */ #include "FlightTaskManualAltitudeSmoothVel.hpp" #include <float.h> using namespace matrix; bool FlightTaskManualAltitudeSmoothVel::activate(vehicle_local_position_setpoint_s last_setpoint) { bool ret = FlightTaskManualAltitude::activate(last_setpoint); // Check if the previous FlightTask provided setpoints checkSetpoints(last_setpoint); _smoothing.reset(last_setpoint.acc_z, last_setpoint.vz, last_setpoint.z); _initEkfResetCounters(); _resetPositionLock(); return ret; } void FlightTaskManualAltitudeSmoothVel::reActivate() { // The task is reacivated while the vehicle is on the ground. To detect takeoff in mc_pos_control_main properly // using the generated jerk, reset the z derivatives to zero _smoothing.reset(0.f, 0.f, _position(2)); _initEkfResetCounters(); _resetPositionLock(); } void FlightTaskManualAltitudeSmoothVel::checkSetpoints(vehicle_local_position_setpoint_s &setpoints) { // If the position setpoint is unknown, set to the current postion if (!PX4_ISFINITE(setpoints.z)) { setpoints.z = _position(2); } // If the velocity setpoint is unknown, set to the current velocity if (!PX4_ISFINITE(setpoints.vz)) { setpoints.vz = _velocity(2); } // No acceleration estimate available, set to zero if the setpoint is NAN if (!PX4_ISFINITE(setpoints.acc_z)) { setpoints.acc_z = 0.f; } } void FlightTaskManualAltitudeSmoothVel::_resetPositionLock() { // Always start unlocked _position_lock_z_active = false; _position_setpoint_z_locked = NAN; } void FlightTaskManualAltitudeSmoothVel::_initEkfResetCounters() { _reset_counters.z = _sub_vehicle_local_position->get().z_reset_counter; _reset_counters.vz = _sub_vehicle_local_position->get().vz_reset_counter; } void FlightTaskManualAltitudeSmoothVel::_checkEkfResetCounters() { if (_sub_vehicle_local_position->get().z_reset_counter != _reset_counters.z) { _smoothing.setCurrentPosition(_position(2)); _reset_counters.z = _sub_vehicle_local_position->get().z_reset_counter; } if (_sub_vehicle_local_position->get().vz_reset_counter != _reset_counters.vz) { _smoothing.setCurrentVelocity(_velocity(2)); _reset_counters.vz = _sub_vehicle_local_position->get().vz_reset_counter; } } void FlightTaskManualAltitudeSmoothVel::_updateSetpoints() { /* Get yaw setpont, un-smoothed position setpoints.*/ FlightTaskManualAltitude::_updateSetpoints(); /* Update constraints */ if (_velocity_setpoint(2) < 0.f) { // up _smoothing.setMaxAccel(_param_mpc_acc_up_max.get()); _smoothing.setMaxVel(_constraints.speed_up); } else { // down _smoothing.setMaxAccel(_param_mpc_acc_down_max.get()); _smoothing.setMaxVel(_constraints.speed_down); } float jerk = _param_mpc_jerk_max.get(); _checkEkfResetCounters(); /* Check for position unlock * During a position lock -> position unlock transition, we have to make sure that the velocity setpoint * is continuous. We know that the output of the position loop (part of the velocity setpoint) will suddenly become null * and only the feedforward (generated by this flight task) will remain. This is why the previous input of the velocity controller * is used to set current velocity of the trajectory. */ if (fabsf(_velocity_setpoint(2)) > FLT_EPSILON) { if (_position_lock_z_active) { _smoothing.setCurrentVelocity(_velocity_setpoint_feedback( 2)); // Start the trajectory at the current velocity setpoint _position_setpoint_z_locked = NAN; } _position_lock_z_active = false; } // During position lock, lower jerk to help the optimizer // to converge to 0 acceleration and velocity jerk = _position_lock_z_active ? 1.f : _param_mpc_jerk_max.get(); _smoothing.setMaxJerk(jerk); _smoothing.updateDurations(_deltatime, _velocity_setpoint(2)); if (!_position_lock_z_active) { _smoothing.setCurrentPosition(_position(2)); } float pos_sp_smooth; _smoothing.integrate(_acceleration_setpoint(2), _vel_sp_smooth, pos_sp_smooth); _velocity_setpoint(2) = _vel_sp_smooth; // Feedforward _jerk_setpoint(2) = _smoothing.getCurrentJerk(); if (fabsf(_vel_sp_smooth) < 0.1f && fabsf(_acceleration_setpoint(2)) < .2f && fabsf(_velocity_setpoint(2)) <= FLT_EPSILON) { _position_lock_z_active = true; } // Set valid position setpoint while in position lock. // When the position lock condition above is false, it does not // mean that the unlock condition is true. This is why // we are checking the lock flag here. if (_position_lock_z_active) { _position_setpoint_z_locked = pos_sp_smooth; // If the velocity setpoint is smaller than 1mm/s and that the acceleration is 0, force the setpoints // to zero. This is required because the generated velocity is never exactly zero and if the drone hovers // for a long period of time, thr drift of the position setpoint will be noticeable. if (fabsf(_velocity_setpoint(2)) < 1e-3f && fabsf(_acceleration_setpoint(2)) < FLT_EPSILON) { _velocity_setpoint(2) = 0.f; _acceleration_setpoint(2) = 0.f; _smoothing.setCurrentVelocity(0.f); _smoothing.setCurrentAcceleration(0.f); } } _position_setpoint(2) = _position_setpoint_z_locked; } <|endoftext|>
<commit_before>#include <tests/lib/test.h> #include <tests/lib/glib-helpers/test-conn-helper.h> #include <tests/lib/glib/echo2/conn.h> #define TP_QT4_ENABLE_LOWLEVEL_API #include <TelepathyQt4/Channel> #include <TelepathyQt4/Connection> #include <TelepathyQt4/ConnectionLowlevel> #include <TelepathyQt4/PendingChannel> #include <TelepathyQt4/PendingHandles> #include <TelepathyQt4/PendingReady> #include <TelepathyQt4/ReferencedHandles> #include <telepathy-glib/debug.h> using namespace Tp; class TestChanBasics : public Test { Q_OBJECT public: TestChanBasics(QObject *parent = 0) : Test(parent), mConn(0), mHandle(0) { } protected Q_SLOTS: void expectInvalidated(); void expectPendingHandleFinished(Tp::PendingOperation *); void expectCreateChannelFinished(Tp::PendingOperation *); void expectEnsureChannelFinished(Tp::PendingOperation *); private Q_SLOTS: void initTestCase(); void init(); void testRequestHandle(); void testCreateChannel(); void testEnsureChannel(); void cleanup(); void cleanupTestCase(); private: TestConnHelper *mConn; ChannelPtr mChan; QString mChanObjectPath; uint mHandle; }; void TestChanBasics::expectInvalidated() { mLoop->exit(0); } void TestChanBasics::expectPendingHandleFinished(PendingOperation *op) { if (!op->isFinished()) { qWarning() << "unfinished"; mLoop->exit(1); return; } if (op->isError()) { qWarning().nospace() << op->errorName() << ": " << op->errorMessage(); mLoop->exit(2); return; } if (!op->isValid()) { qWarning() << "inconsistent results"; mLoop->exit(3); return; } qDebug() << "finished"; PendingHandles *pending = qobject_cast<PendingHandles*>(op); mHandle = pending->handles().at(0); mLoop->exit(0); } void TestChanBasics::expectCreateChannelFinished(PendingOperation* op) { if (!op->isFinished()) { qWarning() << "unfinished"; mLoop->exit(1); return; } if (op->isError()) { qWarning().nospace() << op->errorName() << ": " << op->errorMessage(); mLoop->exit(2); return; } if (!op->isValid()) { qWarning() << "inconsistent results"; mLoop->exit(3); return; } PendingChannel *pc = qobject_cast<PendingChannel*>(op); mChan = pc->channel(); mChanObjectPath = mChan->objectPath(); mLoop->exit(0); } void TestChanBasics::expectEnsureChannelFinished(PendingOperation* op) { if (!op->isFinished()) { qWarning() << "unfinished"; mLoop->exit(1); return; } if (op->isError()) { qWarning().nospace() << op->errorName() << ": " << op->errorMessage(); mLoop->exit(2); return; } if (!op->isValid()) { qWarning() << "inconsistent results"; mLoop->exit(3); return; } PendingChannel *pc = qobject_cast<PendingChannel*>(op); mChan = pc->channel(); QCOMPARE(pc->yours(), false); QCOMPARE(mChan->objectPath(), mChanObjectPath); mLoop->exit(0); } void TestChanBasics::initTestCase() { initTestCaseImpl(); g_type_init(); g_set_prgname("chan-basics"); tp_debug_set_flags("all"); dbus_g_bus_get(DBUS_BUS_STARTER, 0); mConn = new TestConnHelper(this, EXAMPLE_TYPE_ECHO_2_CONNECTION, "account", "me@example.com", "protocol", "contacts", NULL); QCOMPARE(mConn->connect(), true); QCOMPARE(mConn->enableFeatures(Connection::FeatureSelfContact), true); } void TestChanBasics::init() { initImpl(); mChan.reset(); } void TestChanBasics::testRequestHandle() { // Test identifiers QStringList ids = QStringList() << QLatin1String("alice"); // Request handles for the identifiers and wait for the request to process PendingHandles *pending = mConn->client()->lowlevel()->requestHandles(Tp::HandleTypeContact, ids); QVERIFY(connect(pending, SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectPendingHandleFinished(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QVERIFY(disconnect(pending, SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(expectPendingHandleFinished(Tp::PendingOperation*)))); QVERIFY(mHandle != 0); } void TestChanBasics::testCreateChannel() { QVariantMap request; request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"), QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_TEXT)); request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"), (uint) Tp::HandleTypeContact); request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle"), mHandle); QVERIFY(connect(mConn->client()->lowlevel()->createChannel(request), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectCreateChannelFinished(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); Q_ASSERT(!mChan.isNull()); QVERIFY(connect(mChan->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mChan->isReady(), true); QCOMPARE(mChan->isRequested(), true); QCOMPARE(mChan->groupCanAddContacts(), false); QCOMPARE(mChan->groupCanRemoveContacts(), false); QCOMPARE(mChan->initiatorContact()->id(), QString(QLatin1String("me@example.com"))); QCOMPARE(mChan->groupSelfContact()->id(), QString(QLatin1String("me@example.com"))); QCOMPARE(mChan->groupSelfContact(), mConn->client()->selfContact()); QCOMPARE(mChan->targetId(), QString::fromLatin1("alice")); QVERIFY(!mChan->targetContact().isNull()); QCOMPARE(mChan->targetContact()->id(), QString::fromLatin1("alice")); QStringList ids; Q_FOREACH (const ContactPtr &contact, mChan->groupContacts()) { ids << contact->id(); QVERIFY(contact == mChan->groupSelfContact() || contact == mChan->targetContact()); } ids.sort(); QStringList toCheck = QStringList() << QLatin1String("me@example.com") << QLatin1String("alice"); toCheck.sort(); QCOMPARE(ids, toCheck); } void TestChanBasics::testEnsureChannel() { QVariantMap request; request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"), QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_TEXT)); request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"), (uint) Tp::HandleTypeContact); request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle"), mHandle); QVERIFY(connect(mConn->client()->lowlevel()->ensureChannel(request), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectEnsureChannelFinished(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QVERIFY(!mChan.isNull()); QVERIFY(connect(mChan->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mChan->isReady(), true); QCOMPARE(mChan->isRequested(), true); QCOMPARE(mChan->groupCanAddContacts(), false); QCOMPARE(mChan->groupCanRemoveContacts(), false); QCOMPARE(mChan->initiatorContact()->id(), QString(QLatin1String("me@example.com"))); QCOMPARE(mChan->groupSelfContact()->id(), QString(QLatin1String("me@example.com"))); QCOMPARE(mChan->groupSelfContact(), mConn->client()->selfContact()); QStringList ids; Q_FOREACH (const ContactPtr &contact, mChan->groupContacts()) { ids << contact->id(); } ids.sort(); QStringList toCheck = QStringList() << QLatin1String("me@example.com") << QLatin1String("alice"); toCheck.sort(); QCOMPARE(ids, toCheck); QVERIFY(connect(mChan->requestClose(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mChan->isValid(), false); } void TestChanBasics::cleanup() { cleanupImpl(); } void TestChanBasics::cleanupTestCase() { QCOMPARE(mConn->disconnect(), true); delete mConn; if (mChan) { QVERIFY(!mChan->isValid()); QVERIFY(mChan->invalidationReason() == TP_QT4_ERROR_CANCELLED || mChan->invalidationReason() == TP_QT4_ERROR_ORPHANED); } cleanupTestCaseImpl(); } QTEST_MAIN(TestChanBasics) #include "_gen/chan-basics.cpp.moc.hpp" <commit_msg>chan-basics test: Use TestConnHelper::create/ensureChannel()<commit_after>#include <tests/lib/test.h> #include <tests/lib/glib-helpers/test-conn-helper.h> #include <tests/lib/glib/echo2/conn.h> #define TP_QT4_ENABLE_LOWLEVEL_API #include <TelepathyQt4/Channel> #include <TelepathyQt4/Connection> #include <TelepathyQt4/ConnectionLowlevel> #include <TelepathyQt4/PendingChannel> #include <TelepathyQt4/PendingHandles> #include <TelepathyQt4/PendingReady> #include <TelepathyQt4/ReferencedHandles> #include <telepathy-glib/debug.h> using namespace Tp; class TestChanBasics : public Test { Q_OBJECT public: TestChanBasics(QObject *parent = 0) : Test(parent), mConn(0), mHandle(0) { } protected Q_SLOTS: void expectInvalidated(); void expectPendingHandleFinished(Tp::PendingOperation *); private Q_SLOTS: void initTestCase(); void init(); void testRequestHandle(); void testCreateChannel(); void testEnsureChannel(); void cleanup(); void cleanupTestCase(); private: TestConnHelper *mConn; ChannelPtr mChan; QString mChanObjectPath; uint mHandle; }; void TestChanBasics::expectInvalidated() { mLoop->exit(0); } void TestChanBasics::expectPendingHandleFinished(PendingOperation *op) { if (!op->isFinished()) { qWarning() << "unfinished"; mLoop->exit(1); return; } if (op->isError()) { qWarning().nospace() << op->errorName() << ": " << op->errorMessage(); mLoop->exit(2); return; } if (!op->isValid()) { qWarning() << "inconsistent results"; mLoop->exit(3); return; } qDebug() << "finished"; PendingHandles *pending = qobject_cast<PendingHandles*>(op); mHandle = pending->handles().at(0); mLoop->exit(0); } void TestChanBasics::initTestCase() { initTestCaseImpl(); g_type_init(); g_set_prgname("chan-basics"); tp_debug_set_flags("all"); dbus_g_bus_get(DBUS_BUS_STARTER, 0); mConn = new TestConnHelper(this, EXAMPLE_TYPE_ECHO_2_CONNECTION, "account", "me@example.com", "protocol", "contacts", NULL); QCOMPARE(mConn->connect(), true); QCOMPARE(mConn->enableFeatures(Connection::FeatureSelfContact), true); } void TestChanBasics::init() { initImpl(); mChan.reset(); } void TestChanBasics::testRequestHandle() { // Test identifiers QStringList ids = QStringList() << QLatin1String("alice"); // Request handles for the identifiers and wait for the request to process PendingHandles *pending = mConn->client()->lowlevel()->requestHandles(Tp::HandleTypeContact, ids); QVERIFY(connect(pending, SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectPendingHandleFinished(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QVERIFY(disconnect(pending, SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(expectPendingHandleFinished(Tp::PendingOperation*)))); QVERIFY(mHandle != 0); } void TestChanBasics::testCreateChannel() { mChan = mConn->createChannel(TP_QT4_IFACE_CHANNEL_TYPE_TEXT, Tp::HandleTypeContact, mHandle); QVERIFY(mChan); mChanObjectPath = mChan->objectPath(); QVERIFY(connect(mChan->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mChan->isReady(), true); QCOMPARE(mChan->isRequested(), true); QCOMPARE(mChan->groupCanAddContacts(), false); QCOMPARE(mChan->groupCanRemoveContacts(), false); QCOMPARE(mChan->initiatorContact()->id(), QString(QLatin1String("me@example.com"))); QCOMPARE(mChan->groupSelfContact()->id(), QString(QLatin1String("me@example.com"))); QCOMPARE(mChan->groupSelfContact(), mConn->client()->selfContact()); QCOMPARE(mChan->targetId(), QString::fromLatin1("alice")); QVERIFY(!mChan->targetContact().isNull()); QCOMPARE(mChan->targetContact()->id(), QString::fromLatin1("alice")); QStringList ids; Q_FOREACH (const ContactPtr &contact, mChan->groupContacts()) { ids << contact->id(); QVERIFY(contact == mChan->groupSelfContact() || contact == mChan->targetContact()); } ids.sort(); QStringList toCheck = QStringList() << QLatin1String("me@example.com") << QLatin1String("alice"); toCheck.sort(); QCOMPARE(ids, toCheck); } void TestChanBasics::testEnsureChannel() { ChannelPtr chan = mConn->ensureChannel(TP_QT4_IFACE_CHANNEL_TYPE_TEXT, Tp::HandleTypeContact, mHandle); QVERIFY(chan); QCOMPARE(chan->objectPath(), mChanObjectPath); mChan = chan; QVERIFY(connect(mChan->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mChan->isReady(), true); QCOMPARE(mChan->isRequested(), true); QCOMPARE(mChan->groupCanAddContacts(), false); QCOMPARE(mChan->groupCanRemoveContacts(), false); QCOMPARE(mChan->initiatorContact()->id(), QString(QLatin1String("me@example.com"))); QCOMPARE(mChan->groupSelfContact()->id(), QString(QLatin1String("me@example.com"))); QCOMPARE(mChan->groupSelfContact(), mConn->client()->selfContact()); QStringList ids; Q_FOREACH (const ContactPtr &contact, mChan->groupContacts()) { ids << contact->id(); } ids.sort(); QStringList toCheck = QStringList() << QLatin1String("me@example.com") << QLatin1String("alice"); toCheck.sort(); QCOMPARE(ids, toCheck); QVERIFY(connect(mChan->requestClose(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mChan->isValid(), false); } void TestChanBasics::cleanup() { cleanupImpl(); } void TestChanBasics::cleanupTestCase() { QCOMPARE(mConn->disconnect(), true); delete mConn; if (mChan) { QVERIFY(!mChan->isValid()); QVERIFY(mChan->invalidationReason() == TP_QT4_ERROR_CANCELLED || mChan->invalidationReason() == TP_QT4_ERROR_ORPHANED); } cleanupTestCaseImpl(); } QTEST_MAIN(TestChanBasics) #include "_gen/chan-basics.cpp.moc.hpp" <|endoftext|>
<commit_before>#include "Halide.h" #include "wrapper_test_120.h" #include <tiramisu/utils.h> #define NN 10 #define MM 10 int main(int, char **) { Halide::Buffer<uint8_t> reference_buf(NN, MM); init_buffer(reference_buf, (uint8_t)7); Halide::Buffer<uint8_t> output_buf(NN, MM); init_buffer(output_buf, (uint8_t)13); func(output_buf.raw_buffer()); compare_buffers("store_in", output_buf, reference_buf); return 0; } <commit_msg>Fix test 125<commit_after>#include "Halide.h" #include "wrapper_test_125.h" #include <tiramisu/utils.h> #define NN 10 #define MM 10 int main(int, char **) { Halide::Buffer<uint8_t> reference_buf(NN, MM); init_buffer(reference_buf, (uint8_t)7); Halide::Buffer<uint8_t> output_buf(NN, MM); init_buffer(output_buf, (uint8_t)13); func(output_buf.raw_buffer()); compare_buffers("store_in", output_buf, reference_buf); return 0; } <|endoftext|>
<commit_before>#include "src/thread.h" #include "JobLoggingDecorator.h" using namespace ThreadWeaver; JobLoggingDecorator::JobLoggingDecorator(const JobPointer &job, JobLoggingDecoratorCollector* collector) : IdDecorator(job.data(), false) , collector_(collector) { Q_ASSERT(collector); } void JobLoggingDecorator::run(JobPointer self, Thread *thread) { data_.start = collector_->time(); if (thread) { data_.threadId = thread->id(); } else { data_.threadId = -1; } IdDecorator::run(self, thread); data_.end = collector_->time(); collector_->storeJobData(data_); } JobLoggingDecoratorCollector::JobLoggingDecoratorCollector() { elapsed_.start(); start_ = QDateTime::currentDateTime(); } void JobLoggingDecoratorCollector::storeJobData(const JobLoggingDecorator::JobData &data) { QMutexLocker m(&mutex_); jobData_.append(data); } qint64 JobLoggingDecoratorCollector::time() { return elapsed_.elapsed(); } <commit_msg>Use nanoseconds elapsed time.<commit_after>#include "src/thread.h" #include "JobLoggingDecorator.h" using namespace ThreadWeaver; JobLoggingDecorator::JobLoggingDecorator(const JobPointer &job, JobLoggingDecoratorCollector* collector) : IdDecorator(job.data(), false) , collector_(collector) { Q_ASSERT(collector); } void JobLoggingDecorator::run(JobPointer self, Thread *thread) { data_.start = collector_->time(); if (thread) { data_.threadId = thread->id(); } else { data_.threadId = -1; } IdDecorator::run(self, thread); data_.end = collector_->time(); collector_->storeJobData(data_); } JobLoggingDecoratorCollector::JobLoggingDecoratorCollector() { elapsed_.start(); start_ = QDateTime::currentDateTime(); } void JobLoggingDecoratorCollector::storeJobData(const JobLoggingDecorator::JobData &data) { QMutexLocker m(&mutex_); jobData_.append(data); } qint64 JobLoggingDecoratorCollector::time() { return elapsed_.nsecsElapsed(); } <|endoftext|>
<commit_before>#include <thrill/data/byte_block.hpp> #include <thrill/data/block_pool.hpp> namespace thrill { namespace data{ void ByteBlock::deleter(ByteBlock* bb) { assert(bb->head.pin_count_ == 0); //some blocks are created in 'detached' state (tests etc) if(bb->head.block_pool_ && bb->reference_count() == bb->die_limit_) { bb->head.block_pool_->FreeBlockMemory(bb->size()); bb->head.block_pool_->DestroyBlock(bb); } operator delete (bb); } void ByteBlock::deleter(const ByteBlock* bb) { return deleter(const_cast<ByteBlock*>(bb)); } ByteBlock::ByteBlock(size_t size, BlockPool* block_pool) : head({ size, block_pool }) { } //! Construct a block of given size. ByteBlockPtr ByteBlock::Allocate( size_t block_size, BlockPool* block_pool) { // this counts only the bytes and excludes the header. why? -tb block_pool->ClaimBlockMemory(block_size); // allocate a new block of uninitialized memory ByteBlock* block = static_cast<ByteBlock*>( operator new ( sizeof(common::ReferenceCount) + sizeof(head) + block_size)); // initialize block using constructor new (block)ByteBlock(block_size, block_pool); // wrap allocated ByteBlock in a shared_ptr. TODO(tb) figure out how to do // this whole procedure with std::make_shared. return ByteBlockPtr(block); } using ByteBlockPtr = ByteBlock::ByteBlockPtr; } } <commit_msg>fix compile error - I should be more carefull with 'git add -p'<commit_after>#include <thrill/data/byte_block.hpp> #include <thrill/data/block_pool.hpp> namespace thrill { namespace data{ void ByteBlock::deleter(ByteBlock* bb) { assert(bb->head.pin_count_ == 0); //some blocks are created in 'detached' state (tests etc) if(bb->head.block_pool_ && bb->reference_count() == 0) { bb->head.block_pool_->FreeBlockMemory(bb->size()); bb->head.block_pool_->DestroyBlock(bb); } operator delete (bb); } void ByteBlock::deleter(const ByteBlock* bb) { return deleter(const_cast<ByteBlock*>(bb)); } ByteBlock::ByteBlock(size_t size, BlockPool* block_pool) : head({ size, block_pool }) { } //! Construct a block of given size. ByteBlockPtr ByteBlock::Allocate( size_t block_size, BlockPool* block_pool) { // this counts only the bytes and excludes the header. why? -tb block_pool->ClaimBlockMemory(block_size); // allocate a new block of uninitialized memory ByteBlock* block = static_cast<ByteBlock*>( operator new ( sizeof(common::ReferenceCount) + sizeof(head) + block_size)); // initialize block using constructor new (block)ByteBlock(block_size, block_pool); // wrap allocated ByteBlock in a shared_ptr. TODO(tb) figure out how to do // this whole procedure with std::make_shared. return ByteBlockPtr(block); } using ByteBlockPtr = ByteBlock::ByteBlockPtr; } } <|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 "base/threading/thread.h" #include <vector> #include "base/message_loop.h" #include "base/third_party/dynamic_annotations/dynamic_annotations.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" using base::Thread; typedef PlatformTest ThreadTest; namespace { class ToggleValue : public Task { public: explicit ToggleValue(bool* value) : value_(value) { ANNOTATE_BENIGN_RACE(value, "Test-only data race on boolean " "in base/thread_unittest"); } virtual void Run() { *value_ = !*value_; } private: bool* value_; }; class SleepSome : public Task { public: explicit SleepSome(int msec) : msec_(msec) { } virtual void Run() { base::PlatformThread::Sleep(msec_); } private: int msec_; }; class SleepInsideInitThread : public Thread { public: SleepInsideInitThread() : Thread("none") { init_called_ = false; } virtual ~SleepInsideInitThread() { } virtual void Init() { base::PlatformThread::Sleep(500); init_called_ = true; } bool InitCalled() { return init_called_; } private: bool init_called_; }; enum ThreadEvent { // Thread::Init() was called. THREAD_EVENT_INIT = 0, // The MessageLoop for the thread was deleted. THREAD_EVENT_MESSAGE_LOOP_DESTROYED, // Thread::CleanUp() was called. THREAD_EVENT_CLEANUP, // Keep at end of list. THREAD_NUM_EVENTS }; typedef std::vector<ThreadEvent> EventList; class CaptureToEventList : public Thread { public: // This Thread pushes events into the vector |event_list| to show // the order they occured in. |event_list| must remain valid for the // lifetime of this thread. explicit CaptureToEventList(EventList* event_list) : Thread("none"), event_list_(event_list) { } virtual ~CaptureToEventList() { // Must call Stop() manually to have our CleanUp() function called. Stop(); } virtual void Init() { event_list_->push_back(THREAD_EVENT_INIT); } virtual void CleanUp() { event_list_->push_back(THREAD_EVENT_CLEANUP); } private: EventList* event_list_; }; // Observer that writes a value into |event_list| when a message loop has been // destroyed. class CapturingDestructionObserver : public MessageLoop::DestructionObserver { public: // |event_list| must remain valid throughout the observer's lifetime. explicit CapturingDestructionObserver(EventList* event_list) : event_list_(event_list) { } // DestructionObserver implementation: virtual void WillDestroyCurrentMessageLoop() { event_list_->push_back(THREAD_EVENT_MESSAGE_LOOP_DESTROYED); event_list_ = NULL; } private: EventList* event_list_; }; // Task that adds a destruction observer to the current message loop. class RegisterDestructionObserver : public Task { public: explicit RegisterDestructionObserver( MessageLoop::DestructionObserver* observer) : observer_(observer) { } virtual void Run() { MessageLoop::current()->AddDestructionObserver(observer_); observer_ = NULL; } private: MessageLoop::DestructionObserver* observer_; }; } // namespace TEST_F(ThreadTest, Restart) { Thread a("Restart"); a.Stop(); EXPECT_FALSE(a.message_loop()); EXPECT_FALSE(a.IsRunning()); EXPECT_TRUE(a.Start()); EXPECT_TRUE(a.message_loop()); EXPECT_TRUE(a.IsRunning()); a.Stop(); EXPECT_FALSE(a.message_loop()); EXPECT_FALSE(a.IsRunning()); EXPECT_TRUE(a.Start()); EXPECT_TRUE(a.message_loop()); EXPECT_TRUE(a.IsRunning()); a.Stop(); EXPECT_FALSE(a.message_loop()); EXPECT_FALSE(a.IsRunning()); a.Stop(); EXPECT_FALSE(a.message_loop()); EXPECT_FALSE(a.IsRunning()); } TEST_F(ThreadTest, StartWithOptions_StackSize) { Thread a("StartWithStackSize"); // Ensure that the thread can work with only 12 kb and still process a // message. Thread::Options options; options.stack_size = 12*1024; EXPECT_TRUE(a.StartWithOptions(options)); EXPECT_TRUE(a.message_loop()); EXPECT_TRUE(a.IsRunning()); bool was_invoked = false; a.message_loop()->PostTask(FROM_HERE, new ToggleValue(&was_invoked)); // wait for the task to run (we could use a kernel event here // instead to avoid busy waiting, but this is sufficient for // testing purposes). for (int i = 100; i >= 0 && !was_invoked; --i) { base::PlatformThread::Sleep(10); } EXPECT_TRUE(was_invoked); } TEST_F(ThreadTest, TwoTasks) { bool was_invoked = false; { Thread a("TwoTasks"); EXPECT_TRUE(a.Start()); EXPECT_TRUE(a.message_loop()); // Test that all events are dispatched before the Thread object is // destroyed. We do this by dispatching a sleep event before the // event that will toggle our sentinel value. a.message_loop()->PostTask(FROM_HERE, new SleepSome(20)); a.message_loop()->PostTask(FROM_HERE, new ToggleValue(&was_invoked)); } EXPECT_TRUE(was_invoked); } TEST_F(ThreadTest, StopSoon) { Thread a("StopSoon"); EXPECT_TRUE(a.Start()); EXPECT_TRUE(a.message_loop()); EXPECT_TRUE(a.IsRunning()); a.StopSoon(); a.StopSoon(); a.Stop(); EXPECT_FALSE(a.message_loop()); EXPECT_FALSE(a.IsRunning()); } TEST_F(ThreadTest, ThreadName) { Thread a("ThreadName"); EXPECT_TRUE(a.Start()); EXPECT_EQ("ThreadName", a.thread_name()); } // Make sure we can't use a thread between Start() and Init(). TEST_F(ThreadTest, SleepInsideInit) { SleepInsideInitThread t; EXPECT_FALSE(t.InitCalled()); t.Start(); EXPECT_TRUE(t.InitCalled()); } // Make sure that the destruction sequence is: // // (1) Thread::CleanUp() // (2) MessageLoop::~MessageLoop() // MessageLoop::DestructionObservers called. TEST_F(ThreadTest, CleanUp) { EventList captured_events; CapturingDestructionObserver loop_destruction_observer(&captured_events); { // Start a thread which writes its event into |captured_events|. CaptureToEventList t(&captured_events); EXPECT_TRUE(t.Start()); EXPECT_TRUE(t.message_loop()); EXPECT_TRUE(t.IsRunning()); // Register an observer that writes into |captured_events| once the // thread's message loop is destroyed. t.message_loop()->PostTask( FROM_HERE, new RegisterDestructionObserver(&loop_destruction_observer)); // Upon leaving this scope, the thread is deleted. } // Check the order of events during shutdown. ASSERT_EQ(static_cast<size_t>(THREAD_NUM_EVENTS), captured_events.size()); EXPECT_EQ(THREAD_EVENT_INIT, captured_events[0]); EXPECT_EQ(THREAD_EVENT_CLEANUP, captured_events[1]); EXPECT_EQ(THREAD_EVENT_MESSAGE_LOOP_DESTROYED, captured_events[2]); } <commit_msg>Suppress benign race in ThreadTest.SleepInsideInit<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 "base/threading/thread.h" #include <vector> #include "base/message_loop.h" #include "base/third_party/dynamic_annotations/dynamic_annotations.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" using base::Thread; typedef PlatformTest ThreadTest; namespace { class ToggleValue : public Task { public: explicit ToggleValue(bool* value) : value_(value) { ANNOTATE_BENIGN_RACE(value, "Test-only data race on boolean " "in base/thread_unittest"); } virtual void Run() { *value_ = !*value_; } private: bool* value_; }; class SleepSome : public Task { public: explicit SleepSome(int msec) : msec_(msec) { } virtual void Run() { base::PlatformThread::Sleep(msec_); } private: int msec_; }; class SleepInsideInitThread : public Thread { public: SleepInsideInitThread() : Thread("none") { init_called_ = false; ANNOTATE_BENIGN_RACE( this, "Benign test-only data race on vptr - http://crbug.com/98219"); } virtual ~SleepInsideInitThread() { } virtual void Init() { base::PlatformThread::Sleep(500); init_called_ = true; } bool InitCalled() { return init_called_; } private: bool init_called_; }; enum ThreadEvent { // Thread::Init() was called. THREAD_EVENT_INIT = 0, // The MessageLoop for the thread was deleted. THREAD_EVENT_MESSAGE_LOOP_DESTROYED, // Thread::CleanUp() was called. THREAD_EVENT_CLEANUP, // Keep at end of list. THREAD_NUM_EVENTS }; typedef std::vector<ThreadEvent> EventList; class CaptureToEventList : public Thread { public: // This Thread pushes events into the vector |event_list| to show // the order they occured in. |event_list| must remain valid for the // lifetime of this thread. explicit CaptureToEventList(EventList* event_list) : Thread("none"), event_list_(event_list) { } virtual ~CaptureToEventList() { // Must call Stop() manually to have our CleanUp() function called. Stop(); } virtual void Init() { event_list_->push_back(THREAD_EVENT_INIT); } virtual void CleanUp() { event_list_->push_back(THREAD_EVENT_CLEANUP); } private: EventList* event_list_; }; // Observer that writes a value into |event_list| when a message loop has been // destroyed. class CapturingDestructionObserver : public MessageLoop::DestructionObserver { public: // |event_list| must remain valid throughout the observer's lifetime. explicit CapturingDestructionObserver(EventList* event_list) : event_list_(event_list) { } // DestructionObserver implementation: virtual void WillDestroyCurrentMessageLoop() { event_list_->push_back(THREAD_EVENT_MESSAGE_LOOP_DESTROYED); event_list_ = NULL; } private: EventList* event_list_; }; // Task that adds a destruction observer to the current message loop. class RegisterDestructionObserver : public Task { public: explicit RegisterDestructionObserver( MessageLoop::DestructionObserver* observer) : observer_(observer) { } virtual void Run() { MessageLoop::current()->AddDestructionObserver(observer_); observer_ = NULL; } private: MessageLoop::DestructionObserver* observer_; }; } // namespace TEST_F(ThreadTest, Restart) { Thread a("Restart"); a.Stop(); EXPECT_FALSE(a.message_loop()); EXPECT_FALSE(a.IsRunning()); EXPECT_TRUE(a.Start()); EXPECT_TRUE(a.message_loop()); EXPECT_TRUE(a.IsRunning()); a.Stop(); EXPECT_FALSE(a.message_loop()); EXPECT_FALSE(a.IsRunning()); EXPECT_TRUE(a.Start()); EXPECT_TRUE(a.message_loop()); EXPECT_TRUE(a.IsRunning()); a.Stop(); EXPECT_FALSE(a.message_loop()); EXPECT_FALSE(a.IsRunning()); a.Stop(); EXPECT_FALSE(a.message_loop()); EXPECT_FALSE(a.IsRunning()); } TEST_F(ThreadTest, StartWithOptions_StackSize) { Thread a("StartWithStackSize"); // Ensure that the thread can work with only 12 kb and still process a // message. Thread::Options options; options.stack_size = 12*1024; EXPECT_TRUE(a.StartWithOptions(options)); EXPECT_TRUE(a.message_loop()); EXPECT_TRUE(a.IsRunning()); bool was_invoked = false; a.message_loop()->PostTask(FROM_HERE, new ToggleValue(&was_invoked)); // wait for the task to run (we could use a kernel event here // instead to avoid busy waiting, but this is sufficient for // testing purposes). for (int i = 100; i >= 0 && !was_invoked; --i) { base::PlatformThread::Sleep(10); } EXPECT_TRUE(was_invoked); } TEST_F(ThreadTest, TwoTasks) { bool was_invoked = false; { Thread a("TwoTasks"); EXPECT_TRUE(a.Start()); EXPECT_TRUE(a.message_loop()); // Test that all events are dispatched before the Thread object is // destroyed. We do this by dispatching a sleep event before the // event that will toggle our sentinel value. a.message_loop()->PostTask(FROM_HERE, new SleepSome(20)); a.message_loop()->PostTask(FROM_HERE, new ToggleValue(&was_invoked)); } EXPECT_TRUE(was_invoked); } TEST_F(ThreadTest, StopSoon) { Thread a("StopSoon"); EXPECT_TRUE(a.Start()); EXPECT_TRUE(a.message_loop()); EXPECT_TRUE(a.IsRunning()); a.StopSoon(); a.StopSoon(); a.Stop(); EXPECT_FALSE(a.message_loop()); EXPECT_FALSE(a.IsRunning()); } TEST_F(ThreadTest, ThreadName) { Thread a("ThreadName"); EXPECT_TRUE(a.Start()); EXPECT_EQ("ThreadName", a.thread_name()); } // Make sure we can't use a thread between Start() and Init(). TEST_F(ThreadTest, SleepInsideInit) { SleepInsideInitThread t; EXPECT_FALSE(t.InitCalled()); t.Start(); EXPECT_TRUE(t.InitCalled()); } // Make sure that the destruction sequence is: // // (1) Thread::CleanUp() // (2) MessageLoop::~MessageLoop() // MessageLoop::DestructionObservers called. TEST_F(ThreadTest, CleanUp) { EventList captured_events; CapturingDestructionObserver loop_destruction_observer(&captured_events); { // Start a thread which writes its event into |captured_events|. CaptureToEventList t(&captured_events); EXPECT_TRUE(t.Start()); EXPECT_TRUE(t.message_loop()); EXPECT_TRUE(t.IsRunning()); // Register an observer that writes into |captured_events| once the // thread's message loop is destroyed. t.message_loop()->PostTask( FROM_HERE, new RegisterDestructionObserver(&loop_destruction_observer)); // Upon leaving this scope, the thread is deleted. } // Check the order of events during shutdown. ASSERT_EQ(static_cast<size_t>(THREAD_NUM_EVENTS), captured_events.size()); EXPECT_EQ(THREAD_EVENT_INIT, captured_events[0]); EXPECT_EQ(THREAD_EVENT_CLEANUP, captured_events[1]); EXPECT_EQ(THREAD_EVENT_MESSAGE_LOOP_DESTROYED, captured_events[2]); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: b3dtuple.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: pjunck $ $Date: 2004-11-03 08:39:47 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _BGFX_TUPLE_B3DTUPLE_HXX #include <basegfx/tuple/b3dtuple.hxx> #endif #ifndef INCLUDED_RTL_INSTANCE_HXX #include <rtl/instance.hxx> #endif namespace { struct EmptyTuple : public rtl::Static<basegfx::B3DTuple, EmptyTuple> {}; } #ifndef _BGFX_TUPLE_B3ITUPLE_HXX #include <basegfx/tuple/b3ituple.hxx> #endif namespace basegfx { B3DTuple::B3DTuple(const B3ITuple& rTup) : mfX( rTup.getX() ), mfY( rTup.getY() ), mfZ( rTup.getZ() ) {} B3ITuple fround(const B3DTuple& rTup) { return B3ITuple(fround(rTup.getX()), fround(rTup.getY()), fround(rTup.getZ())); } static const B3DTuple& getEmptyTuple() { return EmptyTuple::get(); } } // end of namespace basegfx // eof <commit_msg>INTEGRATION: CWS ooo19126 (1.6.28); FILE MERGED 2005/09/05 17:38:46 rt 1.6.28.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: b3dtuple.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-07 20:53:01 $ * * 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 _BGFX_TUPLE_B3DTUPLE_HXX #include <basegfx/tuple/b3dtuple.hxx> #endif #ifndef INCLUDED_RTL_INSTANCE_HXX #include <rtl/instance.hxx> #endif namespace { struct EmptyTuple : public rtl::Static<basegfx::B3DTuple, EmptyTuple> {}; } #ifndef _BGFX_TUPLE_B3ITUPLE_HXX #include <basegfx/tuple/b3ituple.hxx> #endif namespace basegfx { B3DTuple::B3DTuple(const B3ITuple& rTup) : mfX( rTup.getX() ), mfY( rTup.getY() ), mfZ( rTup.getZ() ) {} B3ITuple fround(const B3DTuple& rTup) { return B3ITuple(fround(rTup.getX()), fround(rTup.getY()), fround(rTup.getZ())); } static const B3DTuple& getEmptyTuple() { return EmptyTuple::get(); } } // end of namespace basegfx // eof <|endoftext|>
<commit_before>#include <QString> #include <QStringList> #include <functional> #include <future> #include <memory> #include "kernel.h" #include "coverage.h" #include "columndefinition.h" #include "table.h" #include "attributerecord.h" #include "feature.h" #include "featurecoverage.h" #include "symboltable.h" #include "operationExpression.h" #include "operationmetadata.h" #include "operation.h" #include "operationhelper.h" #include "operationhelperfeatures.h" #include "commandhandler.h" #include "featureiterator.h" #include "ifoperation.h" #include "iffeature.h" using namespace Ilwis; using namespace BaseOperations; REGISTER_OPERATION(IfFeature) Ilwis::BaseOperations::IfFeature::IfFeature() { } IfFeature::IfFeature(quint64 metaid, const Ilwis::OperationExpression &expr) : IfOperation(metaid, expr) { } bool IfFeature::execute(ExecutionContext *ctx, SymbolTable &symTable) { if (_prepState == sNOTPREPARED) if((_prepState = prepare(ctx, symTable)) != sPREPARED) return false; SubSetAsyncFunc iffunc = [&](const std::vector<quint32>& subset) -> bool { FeatureIterator iterOut(_outputFC); FeatureIterator iterIn(_inputFC,subset); FeatureIterator iterEnd = iterOut.end(); while(iterIn != iterEnd) { _outputFC->newFeatureFrom(*iterIn); ++iterOut; ++iterIn; } return true; }; bool resource = OperationHelperFeatures::execute(ctx, iffunc, _inputFC, _outputFC); if ( resource && ctx != 0) { QVariant value; value.setValue<IFeatureCoverage>(_outputFC); ctx->setOutput(symTable,value,_outputFC->name(),itFEATURE,_outputFC->source()); } return true; } Ilwis::OperationImplementation *IfFeature::create(quint64 metaid, const Ilwis::OperationExpression &expr) { return new IfFeature(metaid, expr); } Ilwis::OperationImplementation::State IfFeature::prepare(ExecutionContext *ctx, const SymbolTable &) { QString fc = _expression.parm(0).value(); if (!_inputFC.prepare(fc)) { ERROR2(ERR_COULD_NOT_LOAD_2,fc,""); return sPREPAREFAILED; } OperationHelperFeatures helper; IIlwisObject obj = helper.initialize(_inputFC.as<IlwisObject>(), itFEATURE, itENVELOPE | itCOORDSYSTEM) ; if ( !obj.isValid()) { ERROR2(ERR_INVALID_INIT_FOR_2,"FeatureCoverage",fc); return sPREPAREFAILED; } _outputFC = obj.as<FeatureCoverage>(); // DataDefinition outputDataDef = findOutputDataDef(_expression); // _outputFC->datadef() = outputDataDef; return sPREPARED; } quint64 IfFeature::createMetadata() { QString url = QString("ilwis://operations/iff"); Resource resource(QUrl(url), itOPERATIONMETADATA); resource.addProperty("namespace","ilwis"); resource.addProperty("longname","iff"); resource.addProperty("syntax","iffraster(featurecoverage,outputchoicetrue, outputchoicefalse)"); resource.addProperty("description","constructs a new coverage based on a boolean selection described by the boolean map. The true pixels are taken from the first input map, the false pixels from the second map"); resource.addProperty("inparameters","3"); resource.addProperty("pin_1_type", itFEATURE); resource.addProperty("pin_1_name", TR("input featurecoverage")); resource.addProperty("pin_1_desc",TR("input featurecoverage with boolean domain")); resource.addProperty("pin_2_type", itNUMBER | itSTRING | itBOOL | itFEATURE); resource.addProperty("pin_2_name", TR("true choice")); resource.addProperty("pin_2_desc",TR("value returned when the boolean input feature is true")); resource.addProperty("pin_3_type", itNUMBER | itSTRING | itBOOL | itFEATURE); resource.addProperty("pin_3_name", TR("false choice")); resource.addProperty("pin_3_desc",TR("value returned when the boolean input feature is false")); resource.addProperty("outparameters",1); resource.addProperty("pout_1_type", itFEATURE); resource.addProperty("pout_1_name", TR("featurecoverage")); resource.addProperty("pout_1_desc",TR("featurecoverage with all features that correspond to the true value in the input having a value")); resource.prepare(); url += "=" + QString::number(resource.id()); resource.setUrl(url); mastercatalog()->addItems({resource}); return resource.id(); } <commit_msg>removed unneeded comment<commit_after>#include <QString> #include <QStringList> #include <functional> #include <future> #include <memory> #include "kernel.h" #include "coverage.h" #include "columndefinition.h" #include "table.h" #include "attributerecord.h" #include "feature.h" #include "featurecoverage.h" #include "symboltable.h" #include "operationExpression.h" #include "operationmetadata.h" #include "operation.h" #include "operationhelper.h" #include "operationhelperfeatures.h" #include "commandhandler.h" #include "featureiterator.h" #include "ifoperation.h" #include "iffeature.h" using namespace Ilwis; using namespace BaseOperations; REGISTER_OPERATION(IfFeature) Ilwis::BaseOperations::IfFeature::IfFeature() { } IfFeature::IfFeature(quint64 metaid, const Ilwis::OperationExpression &expr) : IfOperation(metaid, expr) { } bool IfFeature::execute(ExecutionContext *ctx, SymbolTable &symTable) { if (_prepState == sNOTPREPARED) if((_prepState = prepare(ctx, symTable)) != sPREPARED) return false; SubSetAsyncFunc iffunc = [&](const std::vector<quint32>& subset) -> bool { FeatureIterator iterOut(_outputFC); FeatureIterator iterIn(_inputFC,subset); FeatureIterator iterEnd = iterOut.end(); while(iterIn != iterEnd) { _outputFC->newFeatureFrom(*iterIn); ++iterOut; ++iterIn; } return true; }; bool resource = OperationHelperFeatures::execute(ctx, iffunc, _inputFC, _outputFC); if ( resource && ctx != 0) { QVariant value; value.setValue<IFeatureCoverage>(_outputFC); ctx->setOutput(symTable,value,_outputFC->name(),itFEATURE,_outputFC->source()); } return true; } Ilwis::OperationImplementation *IfFeature::create(quint64 metaid, const Ilwis::OperationExpression &expr) { return new IfFeature(metaid, expr); } Ilwis::OperationImplementation::State IfFeature::prepare(ExecutionContext *ctx, const SymbolTable &) { QString fc = _expression.parm(0).value(); if (!_inputFC.prepare(fc)) { ERROR2(ERR_COULD_NOT_LOAD_2,fc,""); return sPREPAREFAILED; } OperationHelperFeatures helper; IIlwisObject obj = helper.initialize(_inputFC.as<IlwisObject>(), itFEATURE, itENVELOPE | itCOORDSYSTEM) ; if ( !obj.isValid()) { ERROR2(ERR_INVALID_INIT_FOR_2,"FeatureCoverage",fc); return sPREPAREFAILED; } _outputFC = obj.as<FeatureCoverage>(); return sPREPARED; } quint64 IfFeature::createMetadata() { QString url = QString("ilwis://operations/iff"); Resource resource(QUrl(url), itOPERATIONMETADATA); resource.addProperty("namespace","ilwis"); resource.addProperty("longname","iff"); resource.addProperty("syntax","iffraster(featurecoverage,outputchoicetrue, outputchoicefalse)"); resource.addProperty("description","constructs a new coverage based on a boolean selection described by the boolean map. The true pixels are taken from the first input map, the false pixels from the second map"); resource.addProperty("inparameters","3"); resource.addProperty("pin_1_type", itFEATURE); resource.addProperty("pin_1_name", TR("input featurecoverage")); resource.addProperty("pin_1_desc",TR("input featurecoverage with boolean domain")); resource.addProperty("pin_2_type", itNUMBER | itSTRING | itBOOL | itFEATURE); resource.addProperty("pin_2_name", TR("true choice")); resource.addProperty("pin_2_desc",TR("value returned when the boolean input feature is true")); resource.addProperty("pin_3_type", itNUMBER | itSTRING | itBOOL | itFEATURE); resource.addProperty("pin_3_name", TR("false choice")); resource.addProperty("pin_3_desc",TR("value returned when the boolean input feature is false")); resource.addProperty("outparameters",1); resource.addProperty("pout_1_type", itFEATURE); resource.addProperty("pout_1_name", TR("featurecoverage")); resource.addProperty("pout_1_desc",TR("featurecoverage with all features that correspond to the true value in the input having a value")); resource.prepare(); url += "=" + QString::number(resource.id()); resource.setUrl(url); mastercatalog()->addItems({resource}); return resource.id(); } <|endoftext|>
<commit_before>/** * @file * exercise_03_05_part_2.cpp * @author * Henrik Samuelsson, henrik.somuelsson(at)gmail.com */ #include <iostream> #include <string> using std::cin; using std::cout; using std::string; int main() { string temp, result; string spacer = " "; while(cin >> temp) { result.append(temp); result.append(spacer); } cout << result; return 0; } <commit_msg>Update exercise_03_05_part_2.cpp<commit_after>/** * @file * exercise_03_05_part_2.cpp * @author * Henrik Samuelsson, henrik.samuelsson(at)gmail.com */ #include <iostream> #include <string> using std::cin; using std::cout; using std::string; int main() { string temp, result; string spacer = " "; while(cin >> temp) { result.append(temp); result.append(spacer); } cout << result; return 0; } <|endoftext|>
<commit_before>#define QT_NO_CAST_ASCII // configuredialog_p.cpp: classes internal to ConfigureDialog // see configuredialog.cpp for details. // This must be first #ifdef HAVE_CONFIG_H #include <config.h> #endif // my header: #include "configuredialog_p.h" // other KMail headers: #include "kmidentity.h" // for IdentityList::{export,import}Data // other kdenetwork headers: (none) // other KDE headers: #include <kemailsettings.h> // for IdentityEntry::fromControlCenter() #include <kmtransport.h> #include <ksimpleconfig.h> #include <kstandarddirs.h> // Qt headers: #include <qheader.h> #include <qtabwidget.h> #include <qradiobutton.h> #include <qbuttongroup.h> #include <qlabel.h> #include <qlayout.h> // Other headers: #include <assert.h> #include <signal.h> #include <stdlib.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif // used in IdentityList::{import,export}Data static QString pipeSymbol = QString::fromLatin1("|"); //******************************************************** // Identity handling //******************************************************** IdentityEntry IdentityEntry::fromControlCenter() { KEMailSettings emailSettings; emailSettings.setProfile( emailSettings.defaultProfileName() ); return // use return optimization (saves a copy) IdentityEntry( emailSettings.getSetting( KEMailSettings::RealName ), emailSettings.getSetting( KEMailSettings::EmailAddress ), emailSettings.getSetting( KEMailSettings::Organization ), emailSettings.getSetting( KEMailSettings::ReplyToAddress ) ); } QStringList IdentityList::names() const { QStringList list; QValueListConstIterator<IdentityEntry> it = begin(); for( ; it != end() ; ++it ) list << (*it).identityName(); return list; } IdentityEntry & IdentityList::getByName( const QString & i ) { QValueListIterator<IdentityEntry> it = begin(); for( ; it != end() ; ++it ) if( i == (*it).identityName() ) return (*it); assert( 0 ); // one should throw an exception instead, but well... } void IdentityList::importData() { clear(); bool defaultIdentity = true; QStringList identities = KMIdentity::identities(); QStringList::Iterator it = identities.begin(); for( ; it != identities.end(); ++it ) { KMIdentity ident( *it ); ident.readConfig(); IdentityEntry entry; entry.setIsDefault( defaultIdentity ); // only the first entry is the default one: defaultIdentity = false; entry.setIdentityName( ident.identity() ); entry.setFullName( ident.fullName() ); entry.setOrganization( ident.organization() ); entry.setPgpIdentity( ident.pgpIdentity() ); entry.setEmailAddress( ident.emailAddr() ); entry.setReplyToAddress( ident.replyToAddr() ); // We encode the "use output of command" case with a trailing pipe // symbol to distinguish it from the case of a normal data file. QString signatureFileName = ident.signatureFile(); if( signatureFileName.endsWith( pipeSymbol ) ) { // it's a command: chop off the "|". entry.setSignatureFileName( signatureFileName .left( signatureFileName.length() - 1 ) ); entry.setSignatureFileIsAProgram( true ); } else { // it's an ordinary file: entry.setSignatureFileName( signatureFileName ); entry.setSignatureFileIsAProgram( false ); } entry.setSignatureInlineText( ident.signatureInlineText() ); entry.setUseSignatureFile( ident.useSignatureFile() ); entry.setTransport( ident.transport() ); entry.setFcc( ident.fcc() ); entry.setDrafts( ident.drafts() ); append( entry ); } } void IdentityList::exportData() const { QStringList identityNames; QValueListConstIterator<IdentityEntry> it = begin(); for( ; it != end() ; ++it ) { KMIdentity ident( (*it).identityName() ); ident.setFullName( (*it).fullName() ); ident.setOrganization( (*it).organization() ); ident.setPgpIdentity( (*it).pgpIdentity().local8Bit() ); ident.setEmailAddr( (*it).emailAddress() ); ident.setReplyToAddr( (*it).replyToAddress() ); ident.setUseSignatureFile( (*it).useSignatureFile() ); // We encode the "use output of command" case with a trailing pipe // symbol to distinguish it from the case of a normal data file. QString signatureFileName = (*it).signatureFileName(); if ( (*it).signatureFileIsAProgram() ) signatureFileName += pipeSymbol; ident.setSignatureFile( signatureFileName ); ident.setSignatureInlineText( (*it).signatureInlineText() ); ident.setTransport( (*it).transport() ); ident.setFcc( (*it).fcc() ); ident.setDrafts( (*it).drafts() ); ident.writeConfig( false ); // saves the identity data identityNames << (*it).identityName(); } KMIdentity::saveIdentities( identityNames, false ); // writes a list of names } NewIdentityDialog::NewIdentityDialog( const QStringList & identities, QWidget *parent, const char *name, bool modal ) : KDialogBase( parent, name, modal, i18n("New Identity"), Ok|Cancel|Help, Ok, true ) { setHelp( QString::fromLatin1("configure-identity-newidentitydialog") ); QWidget * page = makeMainWidget(); QVBoxLayout * vlay = new QVBoxLayout( page, 0, spacingHint() ); // row 0: line edit with label QHBoxLayout * hlay = new QHBoxLayout( vlay ); // inherits spacing mLineEdit = new QLineEdit( page ); mLineEdit->setFocus(); hlay->addWidget( new QLabel( mLineEdit, i18n("&New Identity:"), page ) ); hlay->addWidget( mLineEdit, 1 ); connect( mLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(slotEnableOK(const QString&)) ); mButtonGroup = new QButtonGroup( page ); mButtonGroup->hide(); // row 1: radio button QRadioButton *radio = new QRadioButton( i18n("&With empty fields"), page ); radio->setChecked( true ); mButtonGroup->insert( radio, Empty ); vlay->addWidget( radio ); // row 2: radio button radio = new QRadioButton( i18n("&Use Control Center settings"), page ); mButtonGroup->insert( radio, ControlCenter ); vlay->addWidget( radio ); // row 3: radio button radio = new QRadioButton( i18n("&Duplicate existing identity"), page ); mButtonGroup->insert( radio, ExistingEntry ); vlay->addWidget( radio ); // row 4: combobox with existing identities and label hlay = new QHBoxLayout( vlay ); // inherits spacing mComboBox = new QComboBox( false, page ); mComboBox->insertStringList( identities ); mComboBox->setEnabled( false ); QLabel *label = new QLabel( mComboBox, i18n("&Existing identities:"), page ); label->setEnabled( false ); hlay->addWidget( label ); hlay->addWidget( mComboBox, 1 ); vlay->addStretch( 1 ); // spacer // enable/disable combobox and label depending on the third radio // button's state: connect( radio, SIGNAL(toggled(bool)), label, SLOT(setEnabled(bool)) ); connect( radio, SIGNAL(toggled(bool)), mComboBox, SLOT(setEnabled(bool)) ); enableButtonOK( false ); // since line edit is empty } NewIdentityDialog::DuplicateMode NewIdentityDialog::duplicateMode() const { int id = mButtonGroup->id( mButtonGroup->selected() ); assert( id == (int)Empty || id == (int)ControlCenter || id == (int)ExistingEntry ); return static_cast<DuplicateMode>( id ); } void NewIdentityDialog::slotEnableOK( const QString & proposedIdentityName ) { // OK button is disabled if QString name = proposedIdentityName.stripWhiteSpace(); // name isn't empty if ( name.isEmpty() ) { enableButtonOK( false ); return; } // or name doesn't yet exist. for ( int i = 0 ; i < mComboBox->count() ; i++ ) if ( mComboBox->text(i) == name ) { enableButtonOK( false ); return; } enableButtonOK( true ); } void ApplicationLaunch::doIt() { // This isn't used anywhere else so // it should be safe to do this here. // I dont' see how we can cleanly wait // on all possible childs in this app so // I use this hack instead. Another // alternative is to fork() twice, recursively, // but that is slower. signal(SIGCHLD, SIG_IGN); // FIXME use KShellProcess instead system(mCmdLine.latin1()); } void ApplicationLaunch::run() { signal(SIGCHLD, SIG_IGN); // see comment above. if( fork() == 0 ) { doIt(); exit(0); } } ListView::ListView( QWidget *parent, const char *name, int visibleItem ) : KListView( parent, name ) { setVisibleItem(visibleItem); } void ListView::resizeEvent( QResizeEvent *e ) { KListView::resizeEvent(e); resizeColums(); } void ListView::showEvent( QShowEvent *e ) { KListView::showEvent(e); resizeColums(); } void ListView::resizeColums() { int c = columns(); if( c == 0 ) { return; } int w1 = viewport()->width(); int w2 = w1 / c; int w3 = w1 - (c-1)*w2; for( int i=0; i<c-1; i++ ) { setColumnWidth( i, w2 ); } setColumnWidth( c-1, w3 ); } void ListView::setVisibleItem( int visibleItem, bool updateSize ) { mVisibleItem = QMAX( 1, visibleItem ); if( updateSize == true ) { QSize s = sizeHint(); setMinimumSize( s.width() + verticalScrollBar()->sizeHint().width() + lineWidth() * 2, s.height() ); } } QSize ListView::sizeHint() const { QSize s = QListView::sizeHint(); int h = fontMetrics().height() + 2*itemMargin(); if( h % 2 > 0 ) { h++; } s.setHeight( h*mVisibleItem + lineWidth()*2 + header()->sizeHint().height()); return( s ); } static QString flagPng = QString::fromLatin1("/flag.png"); NewLanguageDialog::NewLanguageDialog( LanguageItemList & suppressedLangs, QWidget *parent, const char *name, bool modal ) : KDialogBase( parent, name, modal, i18n("New Language"), Ok|Cancel, Ok, true ) { // layout the page (a combobox with label): QWidget *page = makeMainWidget(); QHBoxLayout *hlay = new QHBoxLayout( page, 0, spacingHint() ); mComboBox = new QComboBox( false, page ); hlay->addWidget( new QLabel( mComboBox, i18n("Choose &language:"), page ) ); hlay->addWidget( mComboBox, 1 ); QStringList pathList = KGlobal::dirs()->findAllResources( "locale", QString::fromLatin1("*/entry.desktop") ); // extract a list of language tags that should not be included: QStringList suppressedAcronyms; for ( LanguageItemList::Iterator lit = suppressedLangs.begin(); lit != suppressedLangs.end(); ++lit ) suppressedAcronyms << (*lit).mLanguage; // populate the combo box: for ( QStringList::ConstIterator it = pathList.begin(); it != pathList.end(); ++it ) { KSimpleConfig entry( *it ); entry.setGroup( "KCM Locale" ); // full name: QString name = entry.readEntry( "Name" ); // {2,3}-letter abbreviation: // we extract it from the path: "/prefix/de/entry.desktop" -> "de" QString acronym = (*it).section( '/', -2, -2 ); if ( suppressedAcronyms.find( acronym ) == suppressedAcronyms.end() ) { // not found: QString displayname = QString::fromLatin1("%1 (%2)") .arg( name ).arg( acronym ); QPixmap flag( locate("locale", acronym + flagPng ) ); mComboBox->insertItem( flag, displayname ); } } if ( !mComboBox->count() ) { mComboBox->insertItem( i18n("No more languages available") ); enableButtonOK( false ); } else mComboBox->listBox()->sort(); } QString NewLanguageDialog::language() const { QString s = mComboBox->currentText(); int i = s.findRev( '(' ); return s.mid( i + 1, s.length() - i - 2 ); } LanguageComboBox::LanguageComboBox( bool rw, QWidget *parent, const char *name ) : QComboBox( rw, parent, name ) { } int LanguageComboBox::insertLanguage( const QString & language ) { static QString entryDesktop = QString::fromLatin1("/entry.desktop"); KSimpleConfig entry( locate("locale", language + entryDesktop) ); entry.setGroup( "KCM Locale" ); QString name = entry.readEntry( "Name" ); QString output = QString::fromLatin1("%1 (%2)").arg( name ).arg( language ); insertItem( QPixmap( locate("locale", language + flagPng ) ), output ); return listBox()->index( listBox()->findItem(output) ); } QString LanguageComboBox::language() const { QString s = currentText(); int i = s.findRev( '(' ); return( s.mid( i + 1, s.length() - i - 2 ) ); } void LanguageComboBox::setLanguage( const QString & language ) { QString parenthizedLanguage = QString::fromLatin1("(%1)").arg( language ); for (int i = 0; i < count(); i++) if ( text(i).find( parenthizedLanguage ) >= 0 ) { setCurrentItem(i); return; } } /******************************************************************** * * *ConfigurationPage classes * ********************************************************************/ TabbedConfigurationPage::TabbedConfigurationPage( QWidget * parent, const char * name ) : ConfigurationPage( parent, name ) { QVBoxLayout *vlay = new QVBoxLayout( this, 0, KDialog::spacingHint() ); mTabWidget = new QTabWidget( this ); vlay->addWidget( mTabWidget ); } void TabbedConfigurationPage::addTab( QWidget * tab, const QString & title ) { mTabWidget->addTab( tab, title ); } #include "configuredialog_p.moc" <commit_msg>#define QT_NO_CAST_ASCII only if not compiling with --enable-final; plus: return is no function ;-)<commit_after>#ifndef KDE_USE_FINAL #define QT_NO_CAST_ASCII #endif // configuredialog_p.cpp: classes internal to ConfigureDialog // see configuredialog.cpp for details. // This must be first #ifdef HAVE_CONFIG_H #include <config.h> #endif // my header: #include "configuredialog_p.h" // other KMail headers: #include "kmidentity.h" // for IdentityList::{export,import}Data // other kdenetwork headers: (none) // other KDE headers: #include <kemailsettings.h> // for IdentityEntry::fromControlCenter() #include <kmtransport.h> #include <ksimpleconfig.h> #include <kstandarddirs.h> // Qt headers: #include <qheader.h> #include <qtabwidget.h> #include <qradiobutton.h> #include <qbuttongroup.h> #include <qlabel.h> #include <qlayout.h> // Other headers: #include <assert.h> #include <signal.h> #include <stdlib.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif // used in IdentityList::{import,export}Data static QString pipeSymbol = QString::fromLatin1("|"); //******************************************************** // Identity handling //******************************************************** IdentityEntry IdentityEntry::fromControlCenter() { KEMailSettings emailSettings; emailSettings.setProfile( emailSettings.defaultProfileName() ); return // use return optimization (saves a copy) IdentityEntry( emailSettings.getSetting( KEMailSettings::RealName ), emailSettings.getSetting( KEMailSettings::EmailAddress ), emailSettings.getSetting( KEMailSettings::Organization ), emailSettings.getSetting( KEMailSettings::ReplyToAddress ) ); } QStringList IdentityList::names() const { QStringList list; QValueListConstIterator<IdentityEntry> it = begin(); for( ; it != end() ; ++it ) list << (*it).identityName(); return list; } IdentityEntry & IdentityList::getByName( const QString & i ) { QValueListIterator<IdentityEntry> it = begin(); for( ; it != end() ; ++it ) if( i == (*it).identityName() ) return (*it); assert( 0 ); // one should throw an exception instead, but well... } void IdentityList::importData() { clear(); bool defaultIdentity = true; QStringList identities = KMIdentity::identities(); QStringList::Iterator it = identities.begin(); for( ; it != identities.end(); ++it ) { KMIdentity ident( *it ); ident.readConfig(); IdentityEntry entry; entry.setIsDefault( defaultIdentity ); // only the first entry is the default one: defaultIdentity = false; entry.setIdentityName( ident.identity() ); entry.setFullName( ident.fullName() ); entry.setOrganization( ident.organization() ); entry.setPgpIdentity( ident.pgpIdentity() ); entry.setEmailAddress( ident.emailAddr() ); entry.setReplyToAddress( ident.replyToAddr() ); // We encode the "use output of command" case with a trailing pipe // symbol to distinguish it from the case of a normal data file. QString signatureFileName = ident.signatureFile(); if( signatureFileName.endsWith( pipeSymbol ) ) { // it's a command: chop off the "|". entry.setSignatureFileName( signatureFileName .left( signatureFileName.length() - 1 ) ); entry.setSignatureFileIsAProgram( true ); } else { // it's an ordinary file: entry.setSignatureFileName( signatureFileName ); entry.setSignatureFileIsAProgram( false ); } entry.setSignatureInlineText( ident.signatureInlineText() ); entry.setUseSignatureFile( ident.useSignatureFile() ); entry.setTransport( ident.transport() ); entry.setFcc( ident.fcc() ); entry.setDrafts( ident.drafts() ); append( entry ); } } void IdentityList::exportData() const { QStringList identityNames; QValueListConstIterator<IdentityEntry> it = begin(); for( ; it != end() ; ++it ) { KMIdentity ident( (*it).identityName() ); ident.setFullName( (*it).fullName() ); ident.setOrganization( (*it).organization() ); ident.setPgpIdentity( (*it).pgpIdentity().local8Bit() ); ident.setEmailAddr( (*it).emailAddress() ); ident.setReplyToAddr( (*it).replyToAddress() ); ident.setUseSignatureFile( (*it).useSignatureFile() ); // We encode the "use output of command" case with a trailing pipe // symbol to distinguish it from the case of a normal data file. QString signatureFileName = (*it).signatureFileName(); if ( (*it).signatureFileIsAProgram() ) signatureFileName += pipeSymbol; ident.setSignatureFile( signatureFileName ); ident.setSignatureInlineText( (*it).signatureInlineText() ); ident.setTransport( (*it).transport() ); ident.setFcc( (*it).fcc() ); ident.setDrafts( (*it).drafts() ); ident.writeConfig( false ); // saves the identity data identityNames << (*it).identityName(); } KMIdentity::saveIdentities( identityNames, false ); // writes a list of names } NewIdentityDialog::NewIdentityDialog( const QStringList & identities, QWidget *parent, const char *name, bool modal ) : KDialogBase( parent, name, modal, i18n("New Identity"), Ok|Cancel|Help, Ok, true ) { setHelp( QString::fromLatin1("configure-identity-newidentitydialog") ); QWidget * page = makeMainWidget(); QVBoxLayout * vlay = new QVBoxLayout( page, 0, spacingHint() ); // row 0: line edit with label QHBoxLayout * hlay = new QHBoxLayout( vlay ); // inherits spacing mLineEdit = new QLineEdit( page ); mLineEdit->setFocus(); hlay->addWidget( new QLabel( mLineEdit, i18n("&New Identity:"), page ) ); hlay->addWidget( mLineEdit, 1 ); connect( mLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(slotEnableOK(const QString&)) ); mButtonGroup = new QButtonGroup( page ); mButtonGroup->hide(); // row 1: radio button QRadioButton *radio = new QRadioButton( i18n("&With empty fields"), page ); radio->setChecked( true ); mButtonGroup->insert( radio, Empty ); vlay->addWidget( radio ); // row 2: radio button radio = new QRadioButton( i18n("&Use Control Center settings"), page ); mButtonGroup->insert( radio, ControlCenter ); vlay->addWidget( radio ); // row 3: radio button radio = new QRadioButton( i18n("&Duplicate existing identity"), page ); mButtonGroup->insert( radio, ExistingEntry ); vlay->addWidget( radio ); // row 4: combobox with existing identities and label hlay = new QHBoxLayout( vlay ); // inherits spacing mComboBox = new QComboBox( false, page ); mComboBox->insertStringList( identities ); mComboBox->setEnabled( false ); QLabel *label = new QLabel( mComboBox, i18n("&Existing identities:"), page ); label->setEnabled( false ); hlay->addWidget( label ); hlay->addWidget( mComboBox, 1 ); vlay->addStretch( 1 ); // spacer // enable/disable combobox and label depending on the third radio // button's state: connect( radio, SIGNAL(toggled(bool)), label, SLOT(setEnabled(bool)) ); connect( radio, SIGNAL(toggled(bool)), mComboBox, SLOT(setEnabled(bool)) ); enableButtonOK( false ); // since line edit is empty } NewIdentityDialog::DuplicateMode NewIdentityDialog::duplicateMode() const { int id = mButtonGroup->id( mButtonGroup->selected() ); assert( id == (int)Empty || id == (int)ControlCenter || id == (int)ExistingEntry ); return static_cast<DuplicateMode>( id ); } void NewIdentityDialog::slotEnableOK( const QString & proposedIdentityName ) { // OK button is disabled if QString name = proposedIdentityName.stripWhiteSpace(); // name isn't empty if ( name.isEmpty() ) { enableButtonOK( false ); return; } // or name doesn't yet exist. for ( int i = 0 ; i < mComboBox->count() ; i++ ) if ( mComboBox->text(i) == name ) { enableButtonOK( false ); return; } enableButtonOK( true ); } void ApplicationLaunch::doIt() { // This isn't used anywhere else so // it should be safe to do this here. // I dont' see how we can cleanly wait // on all possible childs in this app so // I use this hack instead. Another // alternative is to fork() twice, recursively, // but that is slower. signal(SIGCHLD, SIG_IGN); // FIXME use KShellProcess instead system(mCmdLine.latin1()); } void ApplicationLaunch::run() { signal(SIGCHLD, SIG_IGN); // see comment above. if( fork() == 0 ) { doIt(); exit(0); } } ListView::ListView( QWidget *parent, const char *name, int visibleItem ) : KListView( parent, name ) { setVisibleItem(visibleItem); } void ListView::resizeEvent( QResizeEvent *e ) { KListView::resizeEvent(e); resizeColums(); } void ListView::showEvent( QShowEvent *e ) { KListView::showEvent(e); resizeColums(); } void ListView::resizeColums() { int c = columns(); if( c == 0 ) { return; } int w1 = viewport()->width(); int w2 = w1 / c; int w3 = w1 - (c-1)*w2; for( int i=0; i<c-1; i++ ) { setColumnWidth( i, w2 ); } setColumnWidth( c-1, w3 ); } void ListView::setVisibleItem( int visibleItem, bool updateSize ) { mVisibleItem = QMAX( 1, visibleItem ); if( updateSize == true ) { QSize s = sizeHint(); setMinimumSize( s.width() + verticalScrollBar()->sizeHint().width() + lineWidth() * 2, s.height() ); } } QSize ListView::sizeHint() const { QSize s = QListView::sizeHint(); int h = fontMetrics().height() + 2*itemMargin(); if( h % 2 > 0 ) { h++; } s.setHeight( h*mVisibleItem + lineWidth()*2 + header()->sizeHint().height()); return s; } static QString flagPng = QString::fromLatin1("/flag.png"); NewLanguageDialog::NewLanguageDialog( LanguageItemList & suppressedLangs, QWidget *parent, const char *name, bool modal ) : KDialogBase( parent, name, modal, i18n("New Language"), Ok|Cancel, Ok, true ) { // layout the page (a combobox with label): QWidget *page = makeMainWidget(); QHBoxLayout *hlay = new QHBoxLayout( page, 0, spacingHint() ); mComboBox = new QComboBox( false, page ); hlay->addWidget( new QLabel( mComboBox, i18n("Choose &language:"), page ) ); hlay->addWidget( mComboBox, 1 ); QStringList pathList = KGlobal::dirs()->findAllResources( "locale", QString::fromLatin1("*/entry.desktop") ); // extract a list of language tags that should not be included: QStringList suppressedAcronyms; for ( LanguageItemList::Iterator lit = suppressedLangs.begin(); lit != suppressedLangs.end(); ++lit ) suppressedAcronyms << (*lit).mLanguage; // populate the combo box: for ( QStringList::ConstIterator it = pathList.begin(); it != pathList.end(); ++it ) { KSimpleConfig entry( *it ); entry.setGroup( "KCM Locale" ); // full name: QString name = entry.readEntry( "Name" ); // {2,3}-letter abbreviation: // we extract it from the path: "/prefix/de/entry.desktop" -> "de" QString acronym = (*it).section( '/', -2, -2 ); if ( suppressedAcronyms.find( acronym ) == suppressedAcronyms.end() ) { // not found: QString displayname = QString::fromLatin1("%1 (%2)") .arg( name ).arg( acronym ); QPixmap flag( locate("locale", acronym + flagPng ) ); mComboBox->insertItem( flag, displayname ); } } if ( !mComboBox->count() ) { mComboBox->insertItem( i18n("No more languages available") ); enableButtonOK( false ); } else mComboBox->listBox()->sort(); } QString NewLanguageDialog::language() const { QString s = mComboBox->currentText(); int i = s.findRev( '(' ); return s.mid( i + 1, s.length() - i - 2 ); } LanguageComboBox::LanguageComboBox( bool rw, QWidget *parent, const char *name ) : QComboBox( rw, parent, name ) { } int LanguageComboBox::insertLanguage( const QString & language ) { static QString entryDesktop = QString::fromLatin1("/entry.desktop"); KSimpleConfig entry( locate("locale", language + entryDesktop) ); entry.setGroup( "KCM Locale" ); QString name = entry.readEntry( "Name" ); QString output = QString::fromLatin1("%1 (%2)").arg( name ).arg( language ); insertItem( QPixmap( locate("locale", language + flagPng ) ), output ); return listBox()->index( listBox()->findItem(output) ); } QString LanguageComboBox::language() const { QString s = currentText(); int i = s.findRev( '(' ); return s.mid( i + 1, s.length() - i - 2 ); } void LanguageComboBox::setLanguage( const QString & language ) { QString parenthizedLanguage = QString::fromLatin1("(%1)").arg( language ); for (int i = 0; i < count(); i++) // ### FIXME: use .endWith(): if ( text(i).find( parenthizedLanguage ) >= 0 ) { setCurrentItem(i); return; } } /******************************************************************** * * *ConfigurationPage classes * ********************************************************************/ TabbedConfigurationPage::TabbedConfigurationPage( QWidget * parent, const char * name ) : ConfigurationPage( parent, name ) { QVBoxLayout *vlay = new QVBoxLayout( this, 0, KDialog::spacingHint() ); mTabWidget = new QTabWidget( this ); vlay->addWidget( mTabWidget ); } void TabbedConfigurationPage::addTab( QWidget * tab, const QString & title ) { mTabWidget->addTab( tab, title ); } #include "configuredialog_p.moc" <|endoftext|>
<commit_before>#include "kontsevich_graph_series.hpp" #include "util/cartesian_product.hpp" #include <sstream> template <class T> size_t KontsevichGraphSeries<T>::precision() const { return d_precision; } template <class T> size_t KontsevichGraphSeries<T>::precision(size_t new_precision) { return d_precision = new_precision; } template <class T> void KontsevichGraphSeries<T>::reduce_mod_skew() { auto current_term = this->begin(); while (current_term != this->end()) { current_term->second.reduce_mod_skew(); if (current_term->second.size() == 0) current_term = this->erase(current_term); else ++current_term; } } template <class T> KontsevichGraphSeries<T> KontsevichGraphSeries<T>::operator()(std::vector< KontsevichGraphSeries<T> > arguments) const { KontsevichGraphSeries<T> result; // Theoretical precision of the result (may be the theoretical maximum): size_t new_precision = precision(); for (auto& argument : arguments) new_precision = std::min(new_precision, argument.precision()); result.precision(new_precision); // Return zero if the series itself or any of its arguments are zero: if (this->empty()) return result; for (auto& argument : arguments) if (argument.empty()) return result; // Practical precision (actually considering the data available): size_t practical_precision = std::min(this->rbegin()->first, new_precision); std::vector<size_t> argument_sizes(arguments.size()); for (size_t i = 0; i != arguments.size(); ++i) { argument_sizes[i] = arguments[i].rbegin()->first + 1; } // Actual composition: for (size_t n = 0; n <= practical_precision; ++n) { auto entry = this->find(n); if (entry == this->end()) continue; CartesianProduct multilinearity_indices(argument_sizes); for (auto arg_indices = multilinearity_indices.begin(); arg_indices != multilinearity_indices.end(); ++arg_indices) // Multi-linearity { size_t total_order = n; for (size_t i = 0; i != arguments.size(); ++i) total_order += (*arg_indices)[i]; if (total_order > practical_precision) continue; std::vector< KontsevichGraphSum<T> > args(arguments.size()); for (size_t i = 0; i != arguments.size(); ++i) args[i] = arguments[i][(*arg_indices)[i]]; result[total_order] += entry->second(args); } } return result; } template <class T> KontsevichGraphSeries<T> KontsevichGraphSeries<T>::skew_symmetrization() const { KontsevichGraphSeries<T> total; total.precision(this->precision()); for (auto current_term = this->begin(); current_term != this->end(); ++current_term) total[current_term->first] = current_term->second.skew_symmetrization(); return total; } template <class T> KontsevichGraphSeries<T> KontsevichGraphSeries<T>::inverse() const { // TODO: only defined if series has one ground vertex KontsevichGraphSeries<T> result; result.precision(this->precision()); result[0] = this->at(0); // TODO: properly test whether invertible for (size_t n = 1; n != precision() + 1; ++n) { for (size_t k = 0; k != n; ++k) { try { result[n] -= result[k]({ this->at(n-k) }); } catch (std::out_of_range) {} } } return result; } template <class T> KontsevichGraphSeries<T> KontsevichGraphSeries<T>::gauge_transform(const KontsevichGraphSeries<T>& gauge) { // TODO: only defined if series has two ground vertices KontsevichGraphSeries<T> gauge_inverse = gauge.inverse(); return gauge_inverse({ (*this)({ gauge, gauge }) }); } template <class T> KontsevichGraphSeries<T>& KontsevichGraphSeries<T>::operator+=(const KontsevichGraphSeries<T>& rhs) { size_t practical_precision = this->rbegin()->first; for (size_t n = 0; n <= practical_precision; ++n) { try { (*this)[n] += rhs.at(n); } catch (std::out_of_range) {} } return *this; } template <class T> KontsevichGraphSeries<T> operator+(KontsevichGraphSeries<T> lhs, const KontsevichGraphSeries<T> &rhs) { lhs += rhs; return lhs; } template <class T> KontsevichGraphSeries<T>& KontsevichGraphSeries<T>::operator-=(const KontsevichGraphSeries<T>& rhs) { size_t practical_precision = this->rbegin()->first; for (size_t n = 0; n <= practical_precision; ++n) { try { (*this)[n] -= rhs.at(n); } catch (std::out_of_range) { } } return *this; } template <class T> KontsevichGraphSeries<T> operator-(KontsevichGraphSeries<T> lhs, const KontsevichGraphSeries<T>& rhs) { lhs -= rhs; return lhs; } template <class T> bool KontsevichGraphSeries<T>::operator==(int other) const { if (other != 0) return false; KontsevichGraphSeries<T> difference = *this; difference.reduce_mod_skew(); return difference.size() == 0; } template <class T> bool KontsevichGraphSeries<T>::operator!=(int other) const { return !(*this == other); } template <class T> KontsevichGraphSeries<T> KontsevichGraphSeries<T>::from_istream(std::istream& is, std::function<T(std::string)> const& parser, std::function<bool(KontsevichGraph, size_t)> const& filter) { KontsevichGraphSeries<T> graph_series; KontsevichGraphSum<T> term; size_t order = 0; for (std::string line; getline(is, line); ) { if (line.length() == 0 || line[0] == '#') // also skip comments continue; if (line[0] == 'h') { graph_series[order] = term; term = KontsevichGraphSum<T>({ }); order = stoi(line.substr(2)); } else { KontsevichGraph graph; std::stringstream ss(line); ss >> graph; graph.normalize(); if (filter && !filter(graph, order)) continue; std::string coefficient_str; ss >> coefficient_str; T coefficient = parser(coefficient_str); term += KontsevichGraphSum<T>({ { coefficient, graph } }); } } graph_series[order] = term; // the last one graph_series.precision(order); return graph_series; } template <class T> std::ostream& operator<<(std::ostream& os, const KontsevichGraphSeries<T>& series) { if (series.size() == 0) return os << "0"; auto final_term = series.end(); --final_term; for (auto term = series.begin(); term != series.end(); term++) { if (term->first == 0) os << term->second; else os << "(" << term->second << ")*h^" << term->first; if (term != final_term) os << " + "; } return os; } template <class T> KontsevichGraphSeries<T> schouten_bracket(const KontsevichGraphSeries<T>& left, const KontsevichGraphSeries<T>& right) { KontsevichGraphSeries<T> result; size_t new_precision = std::min(left.precision(), right.precision()); result.precision(new_precision); if (left.empty() || right.empty()) return result; size_t practical_precision = std::min(left.rbegin()->first, new_precision); for (size_t n = 0; n <= practical_precision; ++n) { for (size_t k = 0; k <= n; ++k) { try { result[n] += schouten_bracket(left.at(n), right.at(n-k)); if (n != n - k) result[n] += schouten_bracket(left.at(n-k), right.at(n)); } catch (std::out_of_range) {} } } return result; } <commit_msg>KontsevichGraphSeries<T>::reduce_mod_skew(): don't lose precision information<commit_after>#include "kontsevich_graph_series.hpp" #include "util/cartesian_product.hpp" #include <sstream> template <class T> size_t KontsevichGraphSeries<T>::precision() const { return d_precision; } template <class T> size_t KontsevichGraphSeries<T>::precision(size_t new_precision) { return d_precision = new_precision; } template <class T> void KontsevichGraphSeries<T>::reduce_mod_skew() { auto current_term = this->begin(); while (current_term != this->end()) { current_term->second.reduce_mod_skew(); ++current_term; } } template <class T> KontsevichGraphSeries<T> KontsevichGraphSeries<T>::operator()(std::vector< KontsevichGraphSeries<T> > arguments) const { KontsevichGraphSeries<T> result; // Theoretical precision of the result (may be the theoretical maximum): size_t new_precision = precision(); for (auto& argument : arguments) new_precision = std::min(new_precision, argument.precision()); result.precision(new_precision); // Return zero if the series itself or any of its arguments are zero: if (this->empty()) return result; for (auto& argument : arguments) if (argument.empty()) return result; // Practical precision (actually considering the data available): size_t practical_precision = std::min(this->rbegin()->first, new_precision); std::vector<size_t> argument_sizes(arguments.size()); for (size_t i = 0; i != arguments.size(); ++i) { argument_sizes[i] = arguments[i].rbegin()->first + 1; } // Actual composition: for (size_t n = 0; n <= practical_precision; ++n) { auto entry = this->find(n); if (entry == this->end()) continue; CartesianProduct multilinearity_indices(argument_sizes); for (auto arg_indices = multilinearity_indices.begin(); arg_indices != multilinearity_indices.end(); ++arg_indices) // Multi-linearity { size_t total_order = n; for (size_t i = 0; i != arguments.size(); ++i) total_order += (*arg_indices)[i]; if (total_order > practical_precision) continue; std::vector< KontsevichGraphSum<T> > args(arguments.size()); for (size_t i = 0; i != arguments.size(); ++i) args[i] = arguments[i][(*arg_indices)[i]]; result[total_order] += entry->second(args); } } return result; } template <class T> KontsevichGraphSeries<T> KontsevichGraphSeries<T>::skew_symmetrization() const { KontsevichGraphSeries<T> total; total.precision(this->precision()); for (auto current_term = this->begin(); current_term != this->end(); ++current_term) total[current_term->first] = current_term->second.skew_symmetrization(); return total; } template <class T> KontsevichGraphSeries<T> KontsevichGraphSeries<T>::inverse() const { // TODO: only defined if series has one ground vertex KontsevichGraphSeries<T> result; result.precision(this->precision()); result[0] = this->at(0); // TODO: properly test whether invertible for (size_t n = 1; n != precision() + 1; ++n) { for (size_t k = 0; k != n; ++k) { try { result[n] -= result[k]({ this->at(n-k) }); } catch (std::out_of_range) {} } } return result; } template <class T> KontsevichGraphSeries<T> KontsevichGraphSeries<T>::gauge_transform(const KontsevichGraphSeries<T>& gauge) { // TODO: only defined if series has two ground vertices KontsevichGraphSeries<T> gauge_inverse = gauge.inverse(); return gauge_inverse({ (*this)({ gauge, gauge }) }); } template <class T> KontsevichGraphSeries<T>& KontsevichGraphSeries<T>::operator+=(const KontsevichGraphSeries<T>& rhs) { size_t practical_precision = this->rbegin()->first; for (size_t n = 0; n <= practical_precision; ++n) { try { (*this)[n] += rhs.at(n); } catch (std::out_of_range) {} } return *this; } template <class T> KontsevichGraphSeries<T> operator+(KontsevichGraphSeries<T> lhs, const KontsevichGraphSeries<T> &rhs) { lhs += rhs; return lhs; } template <class T> KontsevichGraphSeries<T>& KontsevichGraphSeries<T>::operator-=(const KontsevichGraphSeries<T>& rhs) { size_t practical_precision = this->rbegin()->first; for (size_t n = 0; n <= practical_precision; ++n) { try { (*this)[n] -= rhs.at(n); } catch (std::out_of_range) { } } return *this; } template <class T> KontsevichGraphSeries<T> operator-(KontsevichGraphSeries<T> lhs, const KontsevichGraphSeries<T>& rhs) { lhs -= rhs; return lhs; } template <class T> bool KontsevichGraphSeries<T>::operator==(int other) const { if (other != 0) return false; KontsevichGraphSeries<T> difference = *this; difference.reduce_mod_skew(); for (auto term = this->begin(); term != this->end(); term++) { if (term->second.size() != 0) return false; } return true; } template <class T> bool KontsevichGraphSeries<T>::operator!=(int other) const { return !(*this == other); } template <class T> KontsevichGraphSeries<T> KontsevichGraphSeries<T>::from_istream(std::istream& is, std::function<T(std::string)> const& parser, std::function<bool(KontsevichGraph, size_t)> const& filter) { KontsevichGraphSeries<T> graph_series; KontsevichGraphSum<T> term; size_t order = 0; for (std::string line; getline(is, line); ) { if (line.length() == 0 || line[0] == '#') // also skip comments continue; if (line[0] == 'h') { graph_series[order] = term; term = KontsevichGraphSum<T>({ }); order = stoi(line.substr(2)); } else { KontsevichGraph graph; std::stringstream ss(line); ss >> graph; graph.normalize(); if (filter && !filter(graph, order)) continue; std::string coefficient_str; ss >> coefficient_str; T coefficient = parser(coefficient_str); term += KontsevichGraphSum<T>({ { coefficient, graph } }); } } graph_series[order] = term; // the last one graph_series.precision(order); return graph_series; } template <class T> std::ostream& operator<<(std::ostream& os, const KontsevichGraphSeries<T>& series) { if (series.size() == 0) return os << "0"; auto final_term = series.end(); --final_term; for (auto term = series.begin(); term != series.end(); term++) { if (term->first == 0) os << term->second; else os << "(" << term->second << ")*h^" << term->first; if (term != final_term) os << " + "; } return os; } template <class T> KontsevichGraphSeries<T> schouten_bracket(const KontsevichGraphSeries<T>& left, const KontsevichGraphSeries<T>& right) { KontsevichGraphSeries<T> result; size_t new_precision = std::min(left.precision(), right.precision()); result.precision(new_precision); if (left.empty() || right.empty()) return result; size_t practical_precision = std::min(left.rbegin()->first, new_precision); for (size_t n = 0; n <= practical_precision; ++n) { for (size_t k = 0; k <= n; ++k) { try { result[n] += schouten_bracket(left.at(n), right.at(n-k)); if (n != n - k) result[n] += schouten_bracket(left.at(n-k), right.at(n)); } catch (std::out_of_range) {} } } return result; } <|endoftext|>
<commit_before>//! //! @file Hydraulic43ValveNeutralSupplyToTank.hpp //! @author Karl Pettersson <karl.pettersson@liu.se> //! @date 2010-01-12 //! //! @brief Contains a hydraulic 4/3-valve of Q-type #ifndef HYDRAULIC43VALVENEUTRALSUPPLYTOTANK_HPP_INCLUDED #define HYDRAULIC43VALVENEUTRALSUPPLYTOTANK_HPP_INCLUDED #define pi 3.14159 #include <iostream> #include "../../ComponentEssentials.h" #include "../../ComponentUtilities.h" namespace hopsan { //! //! @brief Hydraulic 4/3-valve (closed centre) of Q-type. //! @ingroup HydraulicComponents //! class Hydraulic43ValveNeutralSupplyToTank : public ComponentQ { private: double Cq; double d; double f_pa, f_pb, f_at, f_bt, f_pt; double xvmax; double rho; double overlap_pa; double overlap_pb; double overlap_at; double overlap_bt; double omegah; double deltah; double *mpND_pp, *mpND_qp, *mpND_pt, *mpND_qt, *mpND_pa, *mpND_qa, *mpND_pb, *mpND_qb; double *mpND_cp, *mpND_Zcp, *mpND_ct, *ZmpND_ct, *mpND_ca, *mpND_Zca, *mpND_cb, *mpND_Zcb; double *mpND_xvin, *mpND_xvout; SecondOrderFilter filter; TurbulentFlowFunction qTurb_pa; TurbulentFlowFunction qTurb_pb; TurbulentFlowFunction qTurb_at; TurbulentFlowFunction qTurb_bt; TurbulentFlowFunction qTurb_pt; Port *mpPP, *mpPT, *mpPA, *mpPB, *mpIn, *mpOut; public: static Component *Creator() { return new Hydraulic43ValveNeutralSupplyToTank("Hydraulic 4/3 Valve Open To Tank In Neutral Position"); } Hydraulic43ValveNeutralSupplyToTank(const std::string name) : ComponentQ(name) { Cq = 0.67; d = 0.01; f_pa = 1.0; f_pb = 1.0; f_at = 1.0; f_bt = 1.0; f_pt = 0.1; xvmax = 0.01; rho = 890; overlap_pa = -1e-6; overlap_pb = -1e-6; overlap_at = -1e-6; overlap_bt = -1e-6; omegah = 100.0; deltah = 1.0; mpPP = addPowerPort("PP", "NodeHydraulic"); mpPT = addPowerPort("PT", "NodeHydraulic"); mpPA = addPowerPort("PA", "NodeHydraulic"); mpPB = addPowerPort("PB", "NodeHydraulic"); mpIn = addReadPort("in", "NodeSignal"); mpOut = addWritePort("xv", "NodeSignal", Port::NOTREQUIRED); registerParameter("C_q", "Flow Coefficient", "[-]", Cq); registerParameter("rho", "Oil Density", "[kg/m^3]", rho); registerParameter("d", "Diameter", "[m]", d); registerParameter("x_v,max", "Maximum Spool Displacement", "[m]", xvmax); registerParameter("f_pa", "Spool Fraction of the Diameter", "[-]", f_pa); registerParameter("f_pb", "Spool Fraction of the Diameter", "[-]", f_pb); registerParameter("f_at", "Spool Fraction of the Diameter", "[-]", f_at); registerParameter("f_bt", "Spool Fraction of the Diameter", "[-]", f_bt); registerParameter("f_pt", "Spool Fraction of the Diameter", "[-]", f_pt); registerParameter("x_pa", "Spool Overlap From Port P To A", "[m]", overlap_pa); registerParameter("x_pb", "Spool Overlap From Port P To B", "[m]", overlap_pb); registerParameter("x_at", "Spool Overlap From Port A To T", "[m]", overlap_at); registerParameter("x_bt", "Spool Overlap From Port B To T", "[m]", overlap_bt); registerParameter("omega_h", "Resonance Frequency", "[rad/s]", omegah); registerParameter("delta_h", "Damping Factor", "[-]", deltah); } void initialize() { mpND_pp = getSafeNodeDataPtr(mpPP, NodeHydraulic::PRESSURE); mpND_qp = getSafeNodeDataPtr(mpPP, NodeHydraulic::FLOW); mpND_cp = getSafeNodeDataPtr(mpPP, NodeHydraulic::WAVEVARIABLE); mpND_Zcp = getSafeNodeDataPtr(mpPP, NodeHydraulic::CHARIMP); mpND_pt = getSafeNodeDataPtr(mpPT, NodeHydraulic::PRESSURE); mpND_qt = getSafeNodeDataPtr(mpPT, NodeHydraulic::FLOW); mpND_ct = getSafeNodeDataPtr(mpPT, NodeHydraulic::WAVEVARIABLE); ZmpND_ct = getSafeNodeDataPtr(mpPT, NodeHydraulic::CHARIMP); mpND_pa = getSafeNodeDataPtr(mpPA, NodeHydraulic::PRESSURE); mpND_qa = getSafeNodeDataPtr(mpPA, NodeHydraulic::FLOW); mpND_ca = getSafeNodeDataPtr(mpPA, NodeHydraulic::WAVEVARIABLE); mpND_Zca = getSafeNodeDataPtr(mpPA, NodeHydraulic::CHARIMP); mpND_pb = getSafeNodeDataPtr(mpPB, NodeHydraulic::PRESSURE); mpND_qb = getSafeNodeDataPtr(mpPB, NodeHydraulic::FLOW); mpND_cb = getSafeNodeDataPtr(mpPB, NodeHydraulic::WAVEVARIABLE); mpND_Zcb = getSafeNodeDataPtr(mpPB, NodeHydraulic::CHARIMP); mpND_xvin = getSafeNodeDataPtr(mpIn, NodeSignal::VALUE); mpND_xvout = getSafeNodeDataPtr(mpOut, NodeSignal::VALUE); double num[3] = {0.0, 0.0, 1.0}; double den[3] = {1.0/(omegah*omegah), 2.0*deltah/omegah, 1.0}; filter.initialize(mTimestep, num, den, 0, 0, -xvmax, xvmax); } void simulateOneTimestep() { //Declare local variables double cp, Zcp, ct, Zct, ca, Zca, cb, Zcb, xvin, xv, xpanom, xpbnom, xatnom, xbtnom, xptnom, Kcpa, Kcpb, Kcat, Kcbt, Kcpt, qpa, qpb, qat, qbt, qpt, qp, qa, qb, qt, pa, pb, pt, pp; bool cav = false; //Get variable values from nodes cp = (*mpND_cp); Zcp = (*mpND_Zcp); ct = (*mpND_ct); Zct = (*ZmpND_ct); ca = (*mpND_ca); Zca = (*mpND_Zca); cb = (*mpND_cb); Zcb = (*mpND_Zcb); xvin = (*mpND_xvin); filter.update(xvin); xv = filter.value(); //Valve equations xpanom = std::max(xv-overlap_pa,0.0); xpbnom = std::max(-xv-overlap_pb,0.0); xatnom = std::max(-xv-overlap_at,0.0); xbtnom = std::max(xv-overlap_bt,0.0); xptnom = xvmax-fabs(xv); Kcpa = Cq*f_pa*pi*d*xpanom*sqrt(2.0/rho); Kcpb = Cq*f_pb*pi*d*xpbnom*sqrt(2.0/rho); Kcat = Cq*f_at*pi*d*xatnom*sqrt(2.0/rho); Kcbt = Cq*f_bt*pi*d*xbtnom*sqrt(2.0/rho); Kcpt = Cq*f_pt*pi*d*xptnom*sqrt(2.0/rho); //With TurbulentFlowFunction: qTurb_pa.setFlowCoefficient(Kcpa); qTurb_pb.setFlowCoefficient(Kcpb); qTurb_at.setFlowCoefficient(Kcat); qTurb_bt.setFlowCoefficient(Kcbt); qTurb_pt.setFlowCoefficient(Kcpt); qpa = qTurb_pa.getFlow(cp, ca, Zcp, Zca); qpb = qTurb_pb.getFlow(cp, cb, Zcp, Zcb); qat = qTurb_at.getFlow(ca, ct, Zca, Zct); qbt = qTurb_bt.getFlow(cb, ct, Zcb, Zct); qpt = qTurb_pt.getFlow(cp, ct, Zcp, Zct); if(mTime>8 && mTime<8.1) { std::stringstream ss; ss << "qpa = " << qpa << ", qpb = " << qpb << ", qat = " << qat << ", qbt = " << qbt << ", qpt = " << qpt; addDebugMessage(ss.str()); } qp = -qpa-qpb-qpt; qa = qpa-qat; qb = -qbt+qpb; qt = qbt+qat+qpt; pp = cp + qp*Zcp; pt = ct + qt*Zct; pa = ca + qa*Zca; pb = cb + qb*Zcb; //Cavitation check if(pa < 0.0) { ca = 0.0; Zca = 0; cav = true; } if(pb < 0.0) { cb = 0.0; Zcb = 0; cav = true; } if(pp < 0.0) { cp = 0.0; Zcp = 0; cav = true; } if(pt < 0.0) { ct = 0.0; Zct = 0; cav = true; } if(cav) { qpa = qTurb_pa.getFlow(cp, ca, Zcp, Zca); qpb = qTurb_pb.getFlow(cp, cb, Zcp, Zcb); qat = qTurb_at.getFlow(ca, ct, Zca, Zct); qbt = qTurb_bt.getFlow(cb, ct, Zcb, Zct); qpt = qTurb_pt.getFlow(cp, ct, Zcp, Zct); qp = -qpa-qpb-qpt; qa = qpa-qat; qb = -qbt+qpb; qt = qbt+qat+qpt; pp = cp + qp*Zcp; pt = ct + qt*Zct; pa = ca + qa*Zca; pb = cb + qb*Zcb; } //Write new values to nodes (*mpND_pp) = cp + qp*Zcp; (*mpND_qp) = qp; (*mpND_pt) = ct + qt*Zct; (*mpND_qt) = qt; (*mpND_pa) = ca + qa*Zca; (*mpND_qa) = qa; (*mpND_pb) = cb + qb*Zcb; (*mpND_qb) = qb; (*mpND_xvout) = xv; } }; } #endif // HYDRAULIC43VALVENEUTRALSUPPLYTOTANK_HPP_INCLUDED <commit_msg>Corrected parameter in another valve component<commit_after>//! //! @file Hydraulic43ValveNeutralSupplyToTank.hpp //! @author Karl Pettersson <karl.pettersson@liu.se> //! @date 2010-01-12 //! //! @brief Contains a hydraulic 4/3-valve of Q-type #ifndef HYDRAULIC43VALVENEUTRALSUPPLYTOTANK_HPP_INCLUDED #define HYDRAULIC43VALVENEUTRALSUPPLYTOTANK_HPP_INCLUDED #define pi 3.14159 #include <iostream> #include "../../ComponentEssentials.h" #include "../../ComponentUtilities.h" namespace hopsan { //! //! @brief Hydraulic 4/3-valve (closed centre) of Q-type. //! @ingroup HydraulicComponents //! class Hydraulic43ValveNeutralSupplyToTank : public ComponentQ { private: double Cq; double d; double p_c; double f_pa, f_pb, f_at, f_bt, f_c; double xvmax; double rho; double overlap_pa; double overlap_pb; double overlap_at; double overlap_bt; double omegah; double deltah; double *mpND_pp, *mpND_qp, *mpND_pt, *mpND_qt, *mpND_pa, *mpND_qa, *mpND_pb, *mpND_qb; double *mpND_cp, *mpND_Zcp, *mpND_ct, *ZmpND_ct, *mpND_ca, *mpND_Zca, *mpND_cb, *mpND_Zcb; double *mpND_xvin, *mpND_xvout; SecondOrderFilter filter; TurbulentFlowFunction qTurb_pa; TurbulentFlowFunction qTurb_pb; TurbulentFlowFunction qTurb_at; TurbulentFlowFunction qTurb_bt; TurbulentFlowFunction qTurb_pt; Port *mpPP, *mpPT, *mpPA, *mpPB, *mpIn, *mpOut; public: static Component *Creator() { return new Hydraulic43ValveNeutralSupplyToTank("Hydraulic 4/3 Valve Open To Tank In Neutral Position"); } Hydraulic43ValveNeutralSupplyToTank(const std::string name) : ComponentQ(name) { Cq = 0.67; d = 0.01; p_c = 0.02; f_pa = 1.0; f_pb = 1.0; f_at = 1.0; f_bt = 1.0; f_c = 0.1; xvmax = 0.01; rho = 890; overlap_pa = -1e-6; overlap_pb = -1e-6; overlap_at = -1e-6; overlap_bt = -1e-6; omegah = 100.0; deltah = 1.0; mpPP = addPowerPort("PP", "NodeHydraulic"); mpPT = addPowerPort("PT", "NodeHydraulic"); mpPA = addPowerPort("PA", "NodeHydraulic"); mpPB = addPowerPort("PB", "NodeHydraulic"); mpIn = addReadPort("in", "NodeSignal"); mpOut = addWritePort("xv", "NodeSignal", Port::NOTREQUIRED); registerParameter("C_q", "Flow Coefficient", "[-]", Cq); registerParameter("rho", "Oil Density", "[kg/m^3]", rho); registerParameter("d", "Diameter", "[m]", d); registerParameter("x_v,max", "Maximum Spool Displacement", "[m]", xvmax); registerParameter("p_c", "Fraction of displacement when central position is open", "[-]", p_c); registerParameter("f_pa", "Fraction of spool circumference opening P-A", "[-]", f_pa); registerParameter("f_pb", "Fraction of spool circumference opening P-B", "[-]", f_pb); registerParameter("f_at", "Fraction of spool circumference opening A-T", "[-]", f_at); registerParameter("f_bt", "Fraction of spool circumference opening B-T", "[-]", f_bt); registerParameter("f_c", "Fraction of spool circumference opening at neutral position", "-", f_c); registerParameter("x_pa", "Spool Overlap From Port P To A", "[m]", overlap_pa); registerParameter("x_pb", "Spool Overlap From Port P To B", "[m]", overlap_pb); registerParameter("x_at", "Spool Overlap From Port A To T", "[m]", overlap_at); registerParameter("x_bt", "Spool Overlap From Port B To T", "[m]", overlap_bt); registerParameter("omega_h", "Resonance Frequency", "[rad/s]", omegah); registerParameter("delta_h", "Damping Factor", "[-]", deltah); } void initialize() { mpND_pp = getSafeNodeDataPtr(mpPP, NodeHydraulic::PRESSURE); mpND_qp = getSafeNodeDataPtr(mpPP, NodeHydraulic::FLOW); mpND_cp = getSafeNodeDataPtr(mpPP, NodeHydraulic::WAVEVARIABLE); mpND_Zcp = getSafeNodeDataPtr(mpPP, NodeHydraulic::CHARIMP); mpND_pt = getSafeNodeDataPtr(mpPT, NodeHydraulic::PRESSURE); mpND_qt = getSafeNodeDataPtr(mpPT, NodeHydraulic::FLOW); mpND_ct = getSafeNodeDataPtr(mpPT, NodeHydraulic::WAVEVARIABLE); ZmpND_ct = getSafeNodeDataPtr(mpPT, NodeHydraulic::CHARIMP); mpND_pa = getSafeNodeDataPtr(mpPA, NodeHydraulic::PRESSURE); mpND_qa = getSafeNodeDataPtr(mpPA, NodeHydraulic::FLOW); mpND_ca = getSafeNodeDataPtr(mpPA, NodeHydraulic::WAVEVARIABLE); mpND_Zca = getSafeNodeDataPtr(mpPA, NodeHydraulic::CHARIMP); mpND_pb = getSafeNodeDataPtr(mpPB, NodeHydraulic::PRESSURE); mpND_qb = getSafeNodeDataPtr(mpPB, NodeHydraulic::FLOW); mpND_cb = getSafeNodeDataPtr(mpPB, NodeHydraulic::WAVEVARIABLE); mpND_Zcb = getSafeNodeDataPtr(mpPB, NodeHydraulic::CHARIMP); mpND_xvin = getSafeNodeDataPtr(mpIn, NodeSignal::VALUE); mpND_xvout = getSafeNodeDataPtr(mpOut, NodeSignal::VALUE); double num[3] = {0.0, 0.0, 1.0}; double den[3] = {1.0/(omegah*omegah), 2.0*deltah/omegah, 1.0}; filter.initialize(mTimestep, num, den, 0, 0, -xvmax, xvmax); } void simulateOneTimestep() { //Declare local variables double cp, Zcp, ct, Zct, ca, Zca, cb, Zcb, xvin, xv, xpanom, xpbnom, xatnom, xbtnom, xcnom, Kcpa, Kcpb, Kcat, Kcbt, Kcc, qpa, qpb, qat, qbt, qpt, qp, qa, qb, qt, pa, pb, pt, pp; bool cav = false; //Get variable values from nodes cp = (*mpND_cp); Zcp = (*mpND_Zcp); ct = (*mpND_ct); Zct = (*ZmpND_ct); ca = (*mpND_ca); Zca = (*mpND_Zca); cb = (*mpND_cb); Zcb = (*mpND_Zcb); xvin = (*mpND_xvin); filter.update(xvin); xv = filter.value(); //Valve equations xpanom = std::max(xv-overlap_pa,0.0); xpbnom = std::max(-xv-overlap_pb,0.0); xatnom = std::max(-xv-overlap_at,0.0); xbtnom = std::max(xv-overlap_bt,0.0); xcnom = std::max(xvmax - fabs(xv)/p_c, 0.0); Kcpa = Cq*f_pa*pi*d*xpanom*sqrt(2.0/rho); Kcpb = Cq*f_pb*pi*d*xpbnom*sqrt(2.0/rho); Kcat = Cq*f_at*pi*d*xatnom*sqrt(2.0/rho); Kcbt = Cq*f_bt*pi*d*xbtnom*sqrt(2.0/rho); Kcc = Cq*f_c*pi*d*xcnom*sqrt(2.0/rho); //With TurbulentFlowFunction: qTurb_pa.setFlowCoefficient(Kcpa); qTurb_pb.setFlowCoefficient(Kcpb); qTurb_at.setFlowCoefficient(Kcat); qTurb_bt.setFlowCoefficient(Kcbt); qTurb_pt.setFlowCoefficient(Kcc); qpa = qTurb_pa.getFlow(cp, ca, Zcp, Zca); qpb = qTurb_pb.getFlow(cp, cb, Zcp, Zcb); qat = qTurb_at.getFlow(ca, ct, Zca, Zct); qbt = qTurb_bt.getFlow(cb, ct, Zcb, Zct); qpt = qTurb_pt.getFlow(cp, ct, Zcp, Zct); qp = -qpa-qpb-qpt; qa = qpa-qat; qb = -qbt+qpb; qt = qbt+qat+qpt; pp = cp + qp*Zcp; pt = ct + qt*Zct; pa = ca + qa*Zca; pb = cb + qb*Zcb; //Cavitation check if(pa < 0.0) { ca = 0.0; Zca = 0; cav = true; } if(pb < 0.0) { cb = 0.0; Zcb = 0; cav = true; } if(pp < 0.0) { cp = 0.0; Zcp = 0; cav = true; } if(pt < 0.0) { ct = 0.0; Zct = 0; cav = true; } if(cav) { qpa = qTurb_pa.getFlow(cp, ca, Zcp, Zca); qpb = qTurb_pb.getFlow(cp, cb, Zcp, Zcb); qat = qTurb_at.getFlow(ca, ct, Zca, Zct); qbt = qTurb_bt.getFlow(cb, ct, Zcb, Zct); qpt = qTurb_pt.getFlow(cp, ct, Zcp, Zct); qp = -qpa-qpb-qpt; qa = qpa-qat; qb = -qbt+qpb; qt = qbt+qat+qpt; pp = cp + qp*Zcp; pt = ct + qt*Zct; pa = ca + qa*Zca; pb = cb + qb*Zcb; } //Write new values to nodes (*mpND_pp) = cp + qp*Zcp; (*mpND_qp) = qp; (*mpND_pt) = ct + qt*Zct; (*mpND_qt) = qt; (*mpND_pa) = ca + qa*Zca; (*mpND_qa) = qa; (*mpND_pb) = cb + qb*Zcb; (*mpND_qb) = qb; (*mpND_xvout) = xv; } }; } #endif // HYDRAULIC43VALVENEUTRALSUPPLYTOTANK_HPP_INCLUDED <|endoftext|>