text
stringlengths
54
60.6k
<commit_before>MAIN_ENV //======================================================================== // Global definitions //======================================================================== typedef struct { int n; int total; LOCKDEC(totalLock) int maxProfit; LOCKDEC(profitLock) int* maxBoard; LOCKDEC(boardLock) int p; } GM; GM *gm; //======================================================================== // Helper methods //======================================================================== void printBoard(int* board) { register int i, j; int row, bit; int n = gm->n; for (i = 0; i < n; i++) { bit = board[i]; row = bit ^ (bit & (bit - 1)); for (j = 0; j < n; j++) { if ((row >> j) & 1) printf("Q "); else printf("_ "); } printf("\n"); } } void printResults() { printf("Maximum profit board\n"); printf("Max profit: %d\n", gm->maxProfit); printf("Total solutions: %d\n", gm->total); printf("Maximum profit board\n"); printBoard(gm->maxBoard); } int bitsToValue(int bits){ if (!bits) return 0; int counter = -1; while (bits > 0) { bits = bits >> 1; counter++; } return counter; } //======================================================================== // Parallel N-Queens Algorithm //======================================================================== // // The sequential algorithm that the following code was derived from is // based heavily on optimizations published online by Jeff Somers, and // can be found at jsomers.com/nqueen_demo/nqueens.html // //======================================================================== void pnqueens(int bits, int n, char middle) { int localTotal = 0; int localMaxProfit = 0; int localMaxBoard[n]; int results[n]; int stack[n+2]; register int* stackPointer; int columns[n]; int updiags[n]; int dndiags[n]; register int row=1; register int lsb; int mask = (1 << n) - 1; stack[0] = -1; stackPointer = stack; *stackPointer = 0; stackPointer++; row = 1; results[0] = bits; columns[0] = 0; columns[1] = bits; updiags[0] = 0; updiags[1] = bits << 1; dndiags[0] = 0; dndiags[1] = bits >> 1; bits = mask & ~(columns[1] | updiags[1] | dndiags[1]); while(1) { if (!bits) { stackPointer--; if (stackPointer == stack) { break; } bits = *stackPointer; row--; } else { lsb = bits ^ (bits & (bits - 1)); bits &= ~lsb; results[row] = lsb; if (row < n-1) { int rowLast = row; row++; columns[row] = columns[rowLast] | lsb; updiags[row] = ( updiags[rowLast] | lsb ) << 1; dndiags[row] = ( dndiags[rowLast] | lsb ) >> 1; *stackPointer = bits; stackPointer++; bits = mask & ~(columns[row] | updiags[row] | dndiags[row]); } else { if (!middle) { localTotal += 2; register int k; register int profit0 = 0; register int profit1 = 0; for (k = 0; k < n; k++) { profit0 += abs(k - bitsToValue(results[k])); profit1 += abs((n - 1 - k) - bitsToValue(results[k])); } if ((profit0 > localMaxProfit) && (profit0 >= profit1)) { localMaxProfit = profit0; for (k = 0; k < n; k++) { localMaxBoard[k] = results[k]; } } else if (profit1 > localMaxProfit) { localMaxProfit = profit1; for (k = 0; k < n; k++) { localMaxBoard[k] = results[k]; } } } else { localTotal++; register int k; register int profit = 0; for (k = 0; k < n; k++) { profit += abs(k - bitsToValue(results[k])); } if (profit > localMaxProfit) { localMaxProfit = profit; for (k = 0; k < n; k++) { localMaxBoard[k] = results[k]; } } } stackPointer--; bits = *stackPointer; row--; } } } // All solutions for this initial position found LOCK(gm->totalLock) gm->total += localTotal; UNLOCK(gm->totalLock) LOCK(gm->profitLock) if (localMaxProfit > gm->maxProfit) { register int k; gm->maxProfit = localMaxProfit; LOCK(gm->boardLock) for (k = 0; k < n; k++) { gm->maxBoard[k] = localMaxBoard[k]; } UNLOCK(gm->boardLock) } UNLOCK(gm->profitLock) } void wrapper(void) { int pid; int n, p, i; GET_PID(pid); n = gm->n; p = gm->p; for (i = 0+pid; i < (n + 1)/2; i+=p) { char middle = (i == (n+1)/2 -1); int bits = (1 << i); pnqueens(bits, n, middle); } } //======================================================================== // Main //======================================================================== int main (int argc, char **argv) { int i, n, p, total, maxProfit; int* maxBoard; unsigned int t1, t2, t3; MAIN_INITENV //Enforce arguments if (argc != 3) { printf("Usage: nqueens-seq <P> <N>\nAborting.\n"); exit(0); } gm = (GM*)G_MALLOC(sizeof(GM)); p = gm->p = atoi(argv[1]); n = gm->n = atoi(argv[2]); assert(p > 0); assert(p <= 8); gm->total = 0; gm->maxProfit = 0; gm->maxBoard = (int*)G_MALLOC(n*sizeof(int)); LOCKINIT(gm->totalLock); LOCKINIT(gm->profitLock); LOCKINIT(gm->boardLock); for (i = 0; i < p-1; i++) CREATE(wrapper) CLOCK(t1) wrapper(); WAIT_FOR_END(p-1) CLOCK(t2) printResults(); CLOCK(t3) printf("Computation time: %u microseconds\n", t2-t1); printf("Printing time: %u microseconds\n", t3-t2); G_FREE(maxBoard,n*sizeof(int)) MAIN_END return 0; } <commit_msg>oops, bug fixed<commit_after>MAIN_ENV //======================================================================== // Global definitions //======================================================================== typedef struct { int n; int total; LOCKDEC(totalLock) int maxProfit; LOCKDEC(profitLock) int* maxBoard; LOCKDEC(boardLock) int p; } GM; GM *gm; //======================================================================== // Helper methods //======================================================================== void printBoard(int* board) { register int i, j; int row, bit; int n = gm->n; for (i = 0; i < n; i++) { bit = board[i]; row = bit ^ (bit & (bit - 1)); for (j = 0; j < n; j++) { if ((row >> j) & 1) printf("Q "); else printf("_ "); } printf("\n"); } } void printResults() { printf("Maximum profit board\n"); printf("Max profit: %d\n", gm->maxProfit); printf("Total solutions: %d\n", gm->total); printf("Maximum profit board\n"); printBoard(gm->maxBoard); } int bitsToValue(int bits){ if (!bits) return 0; int counter = -1; while (bits > 0) { bits = bits >> 1; counter++; } return counter; } //======================================================================== // Parallel N-Queens Algorithm //======================================================================== // // The sequential algorithm that the following code was derived from is // based heavily on optimizations published online by Jeff Somers, and // can be found at jsomers.com/nqueen_demo/nqueens.html // //======================================================================== void pnqueens(int bits, int n, char middle) { int localTotal = 0; int localMaxProfit = 0; int localMaxBoard[n]; int results[n]; int stack[n+2]; register int* stackPointer; int columns[n]; int updiags[n]; int dndiags[n]; register int row=1; register int lsb; int mask = (1 << n) - 1; stack[0] = -1; stackPointer = stack; *stackPointer = 0; stackPointer++; row = 1; results[0] = bits; columns[0] = 0; columns[1] = bits; updiags[0] = 0; updiags[1] = bits << 1; dndiags[0] = 0; dndiags[1] = bits >> 1; bits = mask & ~(columns[1] | updiags[1] | dndiags[1]); while(1) { if (!bits) { stackPointer--; if (stackPointer == stack) { break; } bits = *stackPointer; row--; } else { lsb = bits ^ (bits & (bits - 1)); bits &= ~lsb; results[row] = lsb; if (row < n-1) { int rowLast = row; row++; columns[row] = columns[rowLast] | lsb; updiags[row] = ( updiags[rowLast] | lsb ) << 1; dndiags[row] = ( dndiags[rowLast] | lsb ) >> 1; *stackPointer = bits; stackPointer++; bits = mask & ~(columns[row] | updiags[row] | dndiags[row]); } else { if (!middle) { localTotal += 2; register int k; register int profit0 = 0; register int profit1 = 0; for (k = 0; k < n; k++) { profit0 += abs(k - bitsToValue(results[k])); profit1 += abs((n - 1 - k) - bitsToValue(results[k])); } if ((profit0 > localMaxProfit) && (profit0 >= profit1)) { localMaxProfit = profit0; for (k = 0; k < n; k++) { localMaxBoard[k] = results[k]; } } else if (profit1 > localMaxProfit) { localMaxProfit = profit1; for (k = 0; k < n; k++) { localMaxBoard[k] = results[k]; } } } else { localTotal++; register int k; register int profit = 0; for (k = 0; k < n; k++) { profit += abs(k - bitsToValue(results[k])); } if (profit > localMaxProfit) { localMaxProfit = profit; for (k = 0; k < n; k++) { localMaxBoard[k] = results[k]; } } } stackPointer--; bits = *stackPointer; row--; } } } // All solutions for this initial position found LOCK(gm->totalLock) gm->total += localTotal; UNLOCK(gm->totalLock) LOCK(gm->profitLock) if (localMaxProfit > gm->maxProfit) { register int k; gm->maxProfit = localMaxProfit; LOCK(gm->boardLock) for (k = 0; k < n; k++) { gm->maxBoard[k] = localMaxBoard[k]; } UNLOCK(gm->boardLock) } UNLOCK(gm->profitLock) } void wrapper(void) { int pid; int n, p, i; GET_PID(pid); n = gm->n; p = gm->p; for (i = 0+pid; i < (n + 1)/2; i+=p) { char middle = ((i == (n+1)/2 -1) & (n & 1)); int bits = (1 << i); pnqueens(bits, n, middle); } } //======================================================================== // Main //======================================================================== int main (int argc, char **argv) { int i, n, p, total, maxProfit; int* maxBoard; unsigned int t1, t2, t3; MAIN_INITENV //Enforce arguments if (argc != 3) { printf("Usage: nqueens-seq <P> <N>\nAborting.\n"); exit(0); } gm = (GM*)G_MALLOC(sizeof(GM)); p = gm->p = atoi(argv[1]); n = gm->n = atoi(argv[2]); assert(p > 0); assert(p <= 8); gm->total = 0; gm->maxProfit = 0; gm->maxBoard = (int*)G_MALLOC(n*sizeof(int)); LOCKINIT(gm->totalLock); LOCKINIT(gm->profitLock); LOCKINIT(gm->boardLock); for (i = 0; i < p-1; i++) CREATE(wrapper) CLOCK(t1) wrapper(); WAIT_FOR_END(p-1) CLOCK(t2) printResults(); CLOCK(t3) printf("Computation time: %u microseconds\n", t2-t1); printf("Printing time: %u microseconds\n", t3-t2); G_FREE(maxBoard,n*sizeof(int)) MAIN_END return 0; } <|endoftext|>
<commit_before>/*===================================================================== QGroundControl Open Source Ground Control Station (c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> This file is part of the QGROUNDCONTROL project QGROUNDCONTROL is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QGROUNDCONTROL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ #include "PX4AutoPilotPlugin.h" #include "AutoPilotPluginManager.h" #include "PX4AirframeLoader.h" #include "FlightModesComponentController.h" #include "AirframeComponentController.h" #include "UAS.h" #include "FirmwarePlugin/PX4/PX4ParameterMetaData.h" // FIXME: Hack #include "FirmwarePlugin/PX4/PX4FirmwarePlugin.h" // FIXME: Hack #include "QGCApplication.h" /// @file /// @brief This is the AutoPilotPlugin implementatin for the MAV_AUTOPILOT_PX4 type. /// @author Don Gagne <[email protected]> enum PX4_CUSTOM_MAIN_MODE { PX4_CUSTOM_MAIN_MODE_MANUAL = 1, PX4_CUSTOM_MAIN_MODE_ALTCTL, PX4_CUSTOM_MAIN_MODE_POSCTL, PX4_CUSTOM_MAIN_MODE_AUTO, PX4_CUSTOM_MAIN_MODE_ACRO, PX4_CUSTOM_MAIN_MODE_OFFBOARD, PX4_CUSTOM_MAIN_MODE_STABILIZED, }; enum PX4_CUSTOM_SUB_MODE_AUTO { PX4_CUSTOM_SUB_MODE_AUTO_READY = 1, PX4_CUSTOM_SUB_MODE_AUTO_TAKEOFF, PX4_CUSTOM_SUB_MODE_AUTO_LOITER, PX4_CUSTOM_SUB_MODE_AUTO_MISSION, PX4_CUSTOM_SUB_MODE_AUTO_RTL, PX4_CUSTOM_SUB_MODE_AUTO_LAND, PX4_CUSTOM_SUB_MODE_AUTO_RTGS }; union px4_custom_mode { struct { uint16_t reserved; uint8_t main_mode; uint8_t sub_mode; }; uint32_t data; float data_float; }; PX4AutoPilotPlugin::PX4AutoPilotPlugin(Vehicle* vehicle, QObject* parent) : AutoPilotPlugin(vehicle, parent), _airframeComponent(NULL), _radioComponent(NULL), _esp8266Component(NULL), _flightModesComponent(NULL), _sensorsComponent(NULL), _safetyComponent(NULL), _powerComponent(NULL), _incorrectParameterVersion(false) { Q_ASSERT(vehicle); _airframeFacts = new PX4AirframeLoader(this, _vehicle->uas(), this); Q_CHECK_PTR(_airframeFacts); PX4AirframeLoader::loadAirframeFactMetaData(); } PX4AutoPilotPlugin::~PX4AutoPilotPlugin() { delete _airframeFacts; } const QVariantList& PX4AutoPilotPlugin::vehicleComponents(void) { if (_components.count() == 0 && !_incorrectParameterVersion) { Q_ASSERT(_vehicle); if (parametersReady()) { _airframeComponent = new AirframeComponent(_vehicle, this); _airframeComponent->setupTriggerSignals(); _components.append(QVariant::fromValue((VehicleComponent*)_airframeComponent)); _radioComponent = new PX4RadioComponent(_vehicle, this); _radioComponent->setupTriggerSignals(); _components.append(QVariant::fromValue((VehicleComponent*)_radioComponent)); //-- Is there an ESP8266 Connected? #ifdef QT_DEBUG #ifndef __mobile__ //-- Unit test barfs if I ask for a parameter that does not exists. The whole poing of the // test below is to behave differently if ESP8266 is present or not. if (!qgcApp()->runningUnitTests()) { #endif #endif Fact* espVersion = getFact(FactSystem::ParameterProvider, MAV_COMP_ID_UDP_BRIDGE, "SW_VER"); if(espVersion && espVersion->componentId() == MAV_COMP_ID_UDP_BRIDGE) { _esp8266Component = new PX4ESP8266Component(_vehicle, this); _esp8266Component->setupTriggerSignals(); _components.append(QVariant::fromValue((VehicleComponent*)_esp8266Component)); } #ifdef QT_DEBUG #ifndef __mobile__ } #endif #endif _flightModesComponent = new FlightModesComponent(_vehicle, this); _flightModesComponent->setupTriggerSignals(); _components.append(QVariant::fromValue((VehicleComponent*)_flightModesComponent)); _sensorsComponent = new SensorsComponent(_vehicle, this); _sensorsComponent->setupTriggerSignals(); _components.append(QVariant::fromValue((VehicleComponent*)_sensorsComponent)); _powerComponent = new PowerComponent(_vehicle, this); _powerComponent->setupTriggerSignals(); _components.append(QVariant::fromValue((VehicleComponent*)_powerComponent)); _safetyComponent = new SafetyComponent(_vehicle, this); _safetyComponent->setupTriggerSignals(); _components.append(QVariant::fromValue((VehicleComponent*)_safetyComponent)); _tuningComponent = new PX4TuningComponent(_vehicle, this); _tuningComponent->setupTriggerSignals(); _components.append(QVariant::fromValue((VehicleComponent*)_tuningComponent)); } else { qWarning() << "Call to vehicleCompenents prior to parametersReady"; } } return _components; } /// This will perform various checks prior to signalling that the plug in ready void PX4AutoPilotPlugin::_parametersReadyPreChecks(bool missingParameters) { // Check for older parameter version set // FIXME: Firmware is moving to version stamp parameter set. Once that is complete the version stamp // should be used instead. if (parameterExists(FactSystem::defaultComponentId, "SENS_GYRO_XOFF")) { _incorrectParameterVersion = true; qgcApp()->showMessage("This version of GroundControl can only perform vehicle setup on a newer version of firmware. " "Please perform a Firmware Upgrade if you wish to use Vehicle Setup."); } _parametersReady = true; _missingParameters = missingParameters; emit missingParametersChanged(_missingParameters); emit parametersReadyChanged(_parametersReady); } <commit_msg>Using proper Fact testing to test if the WiFi Bridge is present.<commit_after>/*===================================================================== QGroundControl Open Source Ground Control Station (c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> This file is part of the QGROUNDCONTROL project QGROUNDCONTROL is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QGROUNDCONTROL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ #include "PX4AutoPilotPlugin.h" #include "AutoPilotPluginManager.h" #include "PX4AirframeLoader.h" #include "FlightModesComponentController.h" #include "AirframeComponentController.h" #include "UAS.h" #include "FirmwarePlugin/PX4/PX4ParameterMetaData.h" // FIXME: Hack #include "FirmwarePlugin/PX4/PX4FirmwarePlugin.h" // FIXME: Hack #include "QGCApplication.h" /// @file /// @brief This is the AutoPilotPlugin implementatin for the MAV_AUTOPILOT_PX4 type. /// @author Don Gagne <[email protected]> enum PX4_CUSTOM_MAIN_MODE { PX4_CUSTOM_MAIN_MODE_MANUAL = 1, PX4_CUSTOM_MAIN_MODE_ALTCTL, PX4_CUSTOM_MAIN_MODE_POSCTL, PX4_CUSTOM_MAIN_MODE_AUTO, PX4_CUSTOM_MAIN_MODE_ACRO, PX4_CUSTOM_MAIN_MODE_OFFBOARD, PX4_CUSTOM_MAIN_MODE_STABILIZED, }; enum PX4_CUSTOM_SUB_MODE_AUTO { PX4_CUSTOM_SUB_MODE_AUTO_READY = 1, PX4_CUSTOM_SUB_MODE_AUTO_TAKEOFF, PX4_CUSTOM_SUB_MODE_AUTO_LOITER, PX4_CUSTOM_SUB_MODE_AUTO_MISSION, PX4_CUSTOM_SUB_MODE_AUTO_RTL, PX4_CUSTOM_SUB_MODE_AUTO_LAND, PX4_CUSTOM_SUB_MODE_AUTO_RTGS }; union px4_custom_mode { struct { uint16_t reserved; uint8_t main_mode; uint8_t sub_mode; }; uint32_t data; float data_float; }; PX4AutoPilotPlugin::PX4AutoPilotPlugin(Vehicle* vehicle, QObject* parent) : AutoPilotPlugin(vehicle, parent), _airframeComponent(NULL), _radioComponent(NULL), _esp8266Component(NULL), _flightModesComponent(NULL), _sensorsComponent(NULL), _safetyComponent(NULL), _powerComponent(NULL), _incorrectParameterVersion(false) { Q_ASSERT(vehicle); _airframeFacts = new PX4AirframeLoader(this, _vehicle->uas(), this); Q_CHECK_PTR(_airframeFacts); PX4AirframeLoader::loadAirframeFactMetaData(); } PX4AutoPilotPlugin::~PX4AutoPilotPlugin() { delete _airframeFacts; } const QVariantList& PX4AutoPilotPlugin::vehicleComponents(void) { if (_components.count() == 0 && !_incorrectParameterVersion) { Q_ASSERT(_vehicle); if (parametersReady()) { _airframeComponent = new AirframeComponent(_vehicle, this); _airframeComponent->setupTriggerSignals(); _components.append(QVariant::fromValue((VehicleComponent*)_airframeComponent)); _radioComponent = new PX4RadioComponent(_vehicle, this); _radioComponent->setupTriggerSignals(); _components.append(QVariant::fromValue((VehicleComponent*)_radioComponent)); //-- Is there an ESP8266 Connected? if(factExists(FactSystem::ParameterProvider, MAV_COMP_ID_UDP_BRIDGE, "SW_VER")) { _esp8266Component = new PX4ESP8266Component(_vehicle, this); _esp8266Component->setupTriggerSignals(); _components.append(QVariant::fromValue((VehicleComponent*)_esp8266Component)); } _flightModesComponent = new FlightModesComponent(_vehicle, this); _flightModesComponent->setupTriggerSignals(); _components.append(QVariant::fromValue((VehicleComponent*)_flightModesComponent)); _sensorsComponent = new SensorsComponent(_vehicle, this); _sensorsComponent->setupTriggerSignals(); _components.append(QVariant::fromValue((VehicleComponent*)_sensorsComponent)); _powerComponent = new PowerComponent(_vehicle, this); _powerComponent->setupTriggerSignals(); _components.append(QVariant::fromValue((VehicleComponent*)_powerComponent)); _safetyComponent = new SafetyComponent(_vehicle, this); _safetyComponent->setupTriggerSignals(); _components.append(QVariant::fromValue((VehicleComponent*)_safetyComponent)); _tuningComponent = new PX4TuningComponent(_vehicle, this); _tuningComponent->setupTriggerSignals(); _components.append(QVariant::fromValue((VehicleComponent*)_tuningComponent)); } else { qWarning() << "Call to vehicleCompenents prior to parametersReady"; } } return _components; } /// This will perform various checks prior to signalling that the plug in ready void PX4AutoPilotPlugin::_parametersReadyPreChecks(bool missingParameters) { // Check for older parameter version set // FIXME: Firmware is moving to version stamp parameter set. Once that is complete the version stamp // should be used instead. if (parameterExists(FactSystem::defaultComponentId, "SENS_GYRO_XOFF")) { _incorrectParameterVersion = true; qgcApp()->showMessage("This version of GroundControl can only perform vehicle setup on a newer version of firmware. " "Please perform a Firmware Upgrade if you wish to use Vehicle Setup."); } _parametersReady = true; _missingParameters = missingParameters; emit missingParametersChanged(_missingParameters); emit parametersReadyChanged(_parametersReady); } <|endoftext|>
<commit_before>// // Created by Silt on 23.04.2017. // #include <stdint.h> #include <stdlib.h> #include <chrono> #include <thread> #include "MachineOne.h" #include "logger.h" #include "ISR.h" #include "Control.h" #include "PulseMessageReceiverService.h" #include "PulseMessageSenderService.h" #include "Calibration.h" #include "LightSystemService.h" #include "LightSystemHal.h" #include "LightSystemController.h" #include "BLightSystem.h" #include "PuckManager.h" #include "PuckSignal.h" #include "LightSystemEnum.h" #include "HeightMeasurementController.h" #include "HeightService.h" #include "ActorHandler.h" #include "SignalDistributer.h" #include "SortingSwichtControl.h" SETUP(MachineOne){ REG_TEST(programm_m1, 1, "Just Create some distance trackers an let them run (no changes on the way)"); }; BEFORE_TC(MachineOne){return 1;} AFTER_TC(MachineOne){return 1;} BEFORE(MachineOne){return 1;} AFTER(MachineOne){return 1;} TEST_IMPL(MachineOne, programm_m1){ //----------INIT------------ //INIT MAIN CHANNEL PulseMessageReceiverService mainChannel; ///Main communication channel int mainChid = mainChannel.newChannel(); ///Chid of main com //INIT ISR Control isrCntrl(mainChid); ISR isr(&isrCntrl); std::thread isr_th(ref(isr)); //INIT Serial //Init PMR rcv::PulseMessageReceiverService pmrSer1; int pmrSer1Chid = pmrSer1.newChannel(); //Init PMS rcv::PulseMessageReceiverService pmsChannelCreatorSer1; int pmsSer1Chid = pmsChannelCreatorSer1.newChannel(); PulseMessageSenderService pmsSer1(pmsSer1Chid); //Init Sender & Receiver char ser1_path[] = "/dev/ser1"; SerialSender senderSer1(ser1_path); SerialReceiver receiverSer1(ser1_path); //Init Protocol SerialProtocoll protoSer1(SENDER); //Init Serial Serial ser1(receiverSer1, senderSer1, protoSer1, pmsSer1Chid, pmrSer1Chid); //Init SerialService SerialService serialService(pmsSer1Chid); //INIT CBS ConveyorBeltService cbs; //INIT CALIBRATION AND CALIBRATE Calibration& calibration = Calibration::getInstance(); std::cout << "start Hightcal" << "\n"; cout.flush(); //calibration.calibrateHeighMeasurement(); std::cout << "start distancecal" << "\n"; cout.flush(); calibration.loadFromDisk("/Calibration.dat"); //INIT LIGHTSYSTEM /*PulseMessageReceiverService lightsystemChannel; ///Lightsystem cntrl channel int lightsystemChid = ChannelCreate_r(0); //lightsystemChannel.newChannel(); std::cout << "LightSystemChid" <<lightsystemChid << "\n"; cout.flush(); BLightSystem *lsHal = new LightSystemHal(); LightSystemController *lightSystemCntrl = new LightSystemController(lightsystemChid, lsHal); LightSystemService *lightSystem = new LightSystemService(lightsystemChid); lightSystem->setWarningLevel(WARNING_OCCURED);*/ //INIT HEIGHTMEASUREMENT PulseMessageReceiverService heightMChannelCreator; ///Create channel for heightm int heightMChid = heightMChannelCreator.newChannel(); HeightMeasurementController::CalibrationData calData = calibration.getHmCalibration(); HeightMeasurementController hmController(heightMChid, mainChid, &calData); HeightService heightService(heightMChid); //INIT SWITCH CONTROL SortingSwichtControl ssCntrl(mainChid); //Init actor handler ActorHandler actorHandler(cbs, heightService, ssCntrl, serialService); //INIT PUCK MNG PuckManager puckManager(mainChid); //INIT SIGNAL DISTRIBUTER SignalDistributer signalDistributer(&puckManager, &ssCntrl, &actorHandler); //TESTLOOP rcv::msg_t event; while(1){ event = mainChannel.receivePulseMessage(); std::cout << "Got something \n"; switch(event.code){ case 0: std::cout << "\n\n Height \n"; break; //Height case 2: std::cout << "\n\n Serial \n";break; //Serial case 4: std::cout << "\n\n Serial \n";break; //Serial case 5: std::cout << "\n\n ISR \n";break; //ISR } cout.flush(); if(event.value == interrupts::BUTTON_RESET){ cbs.changeState(ConveyorBeltState::STOP); std::cout << "\n\n RESET \n"; puckManager = PuckManager(mainChid); } signalDistributer.process(event); } } <commit_msg>start serial<commit_after>// // Created by Silt on 23.04.2017. // #include <stdint.h> #include <stdlib.h> #include <chrono> #include <thread> #include "MachineOne.h" #include "logger.h" #include "ISR.h" #include "Control.h" #include "PulseMessageReceiverService.h" #include "PulseMessageSenderService.h" #include "Calibration.h" #include "LightSystemService.h" #include "LightSystemHal.h" #include "LightSystemController.h" #include "BLightSystem.h" #include "PuckManager.h" #include "PuckSignal.h" #include "LightSystemEnum.h" #include "HeightMeasurementController.h" #include "HeightService.h" #include "ActorHandler.h" #include "SignalDistributer.h" #include "SortingSwichtControl.h" #include <thread> SETUP(MachineOne){ REG_TEST(programm_m1, 1, "Just Create some distance trackers an let them run (no changes on the way)"); }; BEFORE_TC(MachineOne){return 1;} AFTER_TC(MachineOne){return 1;} BEFORE(MachineOne){return 1;} AFTER(MachineOne){return 1;} TEST_IMPL(MachineOne, programm_m1){ //----------INIT------------ //INIT MAIN CHANNEL PulseMessageReceiverService mainChannel; ///Main communication channel int mainChid = mainChannel.newChannel(); ///Chid of main com //INIT ISR Control isrCntrl(mainChid); ISR isr(&isrCntrl); std::thread isr_th(ref(isr)); //INIT Serial //Init PMR rcv::PulseMessageReceiverService pmrSer1; int pmrSer1Chid = pmrSer1.newChannel(); //Init PMS rcv::PulseMessageReceiverService pmsChannelCreatorSer1; int pmsSer1Chid = pmsChannelCreatorSer1.newChannel(); PulseMessageSenderService pmsSer1(pmsSer1Chid); //Init Sender & Receiver char ser1_path[] = "/dev/ser1"; SerialSender senderSer1(ser1_path); SerialReceiver receiverSer1(ser1_path); //Init Protocol SerialProtocoll protoSer1(SENDER); //Init Serial Serial ser1(receiverSer1, senderSer1, protoSer1, pmsSer1Chid, pmrSer1Chid); //Init SerialService SerialService serialService(pmsSer1Chid); std::thread ser1_thread(ref(ser1)); //INIT CBS ConveyorBeltService cbs; //INIT CALIBRATION AND CALIBRATE Calibration& calibration = Calibration::getInstance(); std::cout << "start Hightcal" << "\n"; cout.flush(); //calibration.calibrateHeighMeasurement(); std::cout << "start distancecal" << "\n"; cout.flush(); calibration.loadFromDisk("/Calibration.dat"); //INIT LIGHTSYSTEM /*PulseMessageReceiverService lightsystemChannel; ///Lightsystem cntrl channel int lightsystemChid = ChannelCreate_r(0); //lightsystemChannel.newChannel(); std::cout << "LightSystemChid" <<lightsystemChid << "\n"; cout.flush(); BLightSystem *lsHal = new LightSystemHal(); LightSystemController *lightSystemCntrl = new LightSystemController(lightsystemChid, lsHal); LightSystemService *lightSystem = new LightSystemService(lightsystemChid); lightSystem->setWarningLevel(WARNING_OCCURED);*/ //INIT HEIGHTMEASUREMENT PulseMessageReceiverService heightMChannelCreator; ///Create channel for heightm int heightMChid = heightMChannelCreator.newChannel(); HeightMeasurementController::CalibrationData calData = calibration.getHmCalibration(); HeightMeasurementController hmController(heightMChid, mainChid, &calData); HeightService heightService(heightMChid); //INIT SWITCH CONTROL SortingSwichtControl ssCntrl(mainChid); //Init actor handler ActorHandler actorHandler(cbs, heightService, ssCntrl, serialService); //INIT PUCK MNG PuckManager puckManager(mainChid); //INIT SIGNAL DISTRIBUTER SignalDistributer signalDistributer(&puckManager, &ssCntrl, &actorHandler); //TESTLOOP rcv::msg_t event; while(1){ event = mainChannel.receivePulseMessage(); std::cout << "Got something \n"; switch(event.code){ case 0: std::cout << "\n\n Height \n"; break; //Height case 2: std::cout << "\n\n Serial \n";break; //Serial case 4: std::cout << "\n\n Serial \n";break; //Serial case 5: std::cout << "\n\n ISR \n";break; //ISR } cout.flush(); if(event.value == interrupts::BUTTON_RESET){ cbs.changeState(ConveyorBeltState::STOP); std::cout << "\n\n RESET \n"; puckManager = PuckManager(mainChid); } signalDistributer.process(event); } } <|endoftext|>
<commit_before>/** * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS) * Copyright (c) 2016-2017 metaverse core developers (see MVS-AUTHORS) * * This file is part of metaverse. * * metaverse is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 <metaverse/node/protocols/protocol_transaction_out.hpp> #include <cstddef> #include <functional> #include <memory> #include <metaverse/network.hpp> namespace libbitcoin { namespace node { #define NAME "transaction" #define CLASS protocol_transaction_out using namespace bc::blockchain; using namespace bc::message; using namespace bc::network; using namespace std::placeholders; protocol_transaction_out::protocol_transaction_out(p2p& network, channel::ptr channel, block_chain& blockchain, transaction_pool& pool) : protocol_events(network, channel, NAME), blockchain_(blockchain), pool_(pool), // TODO: move fee filter to a derived class protocol_transaction_out_70013. minimum_fee_(0), // TODO: move relay to a derived class protocol_transaction_out_70001. relay_to_peer_(peer_version().relay), CONSTRUCT_TRACK(protocol_transaction_out) { } protocol_transaction_out::ptr protocol_transaction_out::do_subscribe() { SUBSCRIBE2(memory_pool, handle_receive_memory_pool, _1, _2); SUBSCRIBE2(fee_filter, handle_receive_fee_filter, _1, _2); SUBSCRIBE2(get_data, handle_receive_get_data, _1, _2); return std::dynamic_pointer_cast<protocol_transaction_out>(protocol::shared_from_this()); } // TODO: move not_found to derived class protocol_transaction_out_70001. // Start. //----------------------------------------------------------------------------- void protocol_transaction_out::start() { protocol_events::start(BIND1(handle_stop, _1)); // TODO: move relay to a derived class protocol_transaction_out_70001. // Prior to this level transaction relay is not configurable. if (relay_to_peer_) { // Subscribe to transaction pool notifications and relay txs. pool_.subscribe_transaction(BIND3(handle_floated, _1, _2, _3)); } // TODO: move fee filter to a derived class protocol_transaction_out_70013. // Filter announcements by fee if set. } // Receive send_headers. //----------------------------------------------------------------------------- // TODO: move fee_filters to a derived class protocol_transaction_out_70013. bool protocol_transaction_out::handle_receive_fee_filter(const code& ec, fee_filter_ptr message) { if (stopped()) return false; if (ec) { log::trace(LOG_NODE) << "Failure getting " << message->command << " from [" << authority() << "] " << ec.message(); stop(ec); return false; } // TODO: move fee filter to a derived class protocol_transaction_out_70013. // Transaction annoucements will be filtered by fee amount. minimum_fee_.store(message->minimum_fee); // The fee filter may be adjusted. return true; } // Receive mempool sequence. //----------------------------------------------------------------------------- bool protocol_transaction_out::handle_receive_memory_pool(const code& ec, memory_pool_ptr) { if (stopped()) { return false; } if (ec) { return false; } log::debug(LOG_NODE) << "protocol_transaction_out::handle_receive_memory_pool"; pool_.fetch([this](const code& ec, const std::vector<transaction_ptr>& txs){ if (stopped() || ec) { log::debug(LOG_NODE) << "pool fetch transaction failed," << ec.message(); return; } if (txs.empty()) { return; } std::vector<hash_digest> hashes; hashes.reserve(txs.size()); for(auto& t:txs) { hashes.push_back(t->hash()); } log::debug(LOG_NODE) << "memory pool size," << txs.size(); send<protocol_transaction_out>(inventory{hashes, inventory::type_id::transaction}, &protocol_transaction_out::handle_send, _1, inventory::command); }); return false; } // Receive get_data sequence. //----------------------------------------------------------------------------- bool protocol_transaction_out::handle_receive_get_data(const code& ec, get_data_ptr message) { if (stopped()) return false; if (ec) { log::trace(LOG_NODE) << "Failure getting inventory from [" << authority() << "] " << ec.message(); stop(ec); return false; } // if (message->inventories.size() > 50000) // { // return ! misbehaving(20); // } // TODO: these must return message objects or be copied! // Ignore non-transaction inventory requests in this protocol. for (const auto& inv: message->inventories) if (inv.type == inventory::type_id::transaction) { auto pThis = shared_from_this(); pool_.fetch(inv.hash, [this, &inv, pThis](const code& ec, transaction_ptr tx){ auto t = tx ? *tx : chain::transaction{}; send_transaction(ec, t, inv.hash); if(ec) { blockchain_.fetch_transaction(inv.hash, BIND3(send_transaction, _1, _2, inv.hash)); } }); } return true; } void protocol_transaction_out::send_transaction(const code& ec, const chain::transaction& transaction, const hash_digest& hash) { if (stopped() || ec == (code)error::service_stopped) return; if (ec == (code)error::not_found) { log::trace(LOG_NODE) << "Transaction requested by [" << authority() << "] not found."; const not_found reply{ { inventory::type_id::transaction, hash } }; SEND2(reply, handle_send, _1, reply.command); return; } if (ec) { log::error(LOG_NODE) << "Internal failure locating trnsaction requested by [" << authority() << "] " << ec.message(); stop(ec); return; } log::trace(LOG_NODE) << "send transaction " << encode_hash(transaction.hash()) << ", to " << authority(); // TODO: eliminate copy. SEND2(transaction_message(transaction), handle_send, _1, transaction_message::command); } // Subscription. //----------------------------------------------------------------------------- bool protocol_transaction_out::handle_floated(const code& ec, const index_list& unconfirmed, transaction_ptr message) { if (stopped() || ec == (code)error::service_stopped) return false; if (ec == (code)error::mock) { return true; } if (ec) { log::error(LOG_NODE) << "Failure handling transaction float: " << ec.message(); stop(ec); return false; } // TODO: move fee filter to a derived class protocol_transaction_out_70013. // TODO: implement fee computation. const uint64_t fee = 0; // Transactions are discovered and announced individually. if (message->originator() != nonce() && fee >= minimum_fee_.load()) { static const auto id = inventory::type_id::transaction; const inventory announcement{ { id, message->hash() } }; log::trace(LOG_NODE) << "handle floated send transaction hash," << encode_hash(message->hash()) ; SEND2(announcement, handle_send, _1, announcement.command); } return true; } void protocol_transaction_out::handle_stop(const code&) { log::trace(LOG_NETWORK) << "Stopped transaction_out protocol"; pool_.fired(); } } // namespace node } // namespace libbitcoin <commit_msg>pass shared ptr to callback<commit_after>/** * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS) * Copyright (c) 2016-2017 metaverse core developers (see MVS-AUTHORS) * * This file is part of metaverse. * * metaverse is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 <metaverse/node/protocols/protocol_transaction_out.hpp> #include <cstddef> #include <functional> #include <memory> #include <metaverse/network.hpp> namespace libbitcoin { namespace node { #define NAME "transaction" #define CLASS protocol_transaction_out using namespace bc::blockchain; using namespace bc::message; using namespace bc::network; using namespace std::placeholders; protocol_transaction_out::protocol_transaction_out(p2p& network, channel::ptr channel, block_chain& blockchain, transaction_pool& pool) : protocol_events(network, channel, NAME), blockchain_(blockchain), pool_(pool), // TODO: move fee filter to a derived class protocol_transaction_out_70013. minimum_fee_(0), // TODO: move relay to a derived class protocol_transaction_out_70001. relay_to_peer_(peer_version().relay), CONSTRUCT_TRACK(protocol_transaction_out) { } protocol_transaction_out::ptr protocol_transaction_out::do_subscribe() { SUBSCRIBE2(memory_pool, handle_receive_memory_pool, _1, _2); SUBSCRIBE2(fee_filter, handle_receive_fee_filter, _1, _2); SUBSCRIBE2(get_data, handle_receive_get_data, _1, _2); return std::dynamic_pointer_cast<protocol_transaction_out>(protocol::shared_from_this()); } // TODO: move not_found to derived class protocol_transaction_out_70001. // Start. //----------------------------------------------------------------------------- void protocol_transaction_out::start() { protocol_events::start(BIND1(handle_stop, _1)); // TODO: move relay to a derived class protocol_transaction_out_70001. // Prior to this level transaction relay is not configurable. if (relay_to_peer_) { // Subscribe to transaction pool notifications and relay txs. pool_.subscribe_transaction(BIND3(handle_floated, _1, _2, _3)); } // TODO: move fee filter to a derived class protocol_transaction_out_70013. // Filter announcements by fee if set. } // Receive send_headers. //----------------------------------------------------------------------------- // TODO: move fee_filters to a derived class protocol_transaction_out_70013. bool protocol_transaction_out::handle_receive_fee_filter(const code& ec, fee_filter_ptr message) { if (stopped()) return false; if (ec) { log::trace(LOG_NODE) << "Failure getting " << message->command << " from [" << authority() << "] " << ec.message(); stop(ec); return false; } // TODO: move fee filter to a derived class protocol_transaction_out_70013. // Transaction annoucements will be filtered by fee amount. minimum_fee_.store(message->minimum_fee); // The fee filter may be adjusted. return true; } // Receive mempool sequence. //----------------------------------------------------------------------------- bool protocol_transaction_out::handle_receive_memory_pool(const code& ec, memory_pool_ptr) { if (stopped()) { return false; } if (ec) { return false; } log::debug(LOG_NODE) << "protocol_transaction_out::handle_receive_memory_pool"; auto self = shared_from_this(); pool_.fetch([this, self](const code& ec, const std::vector<transaction_ptr>& txs){ if (stopped() || ec) { log::debug(LOG_NODE) << "pool fetch transaction failed," << ec.message(); return; } if (txs.empty()) { return; } std::vector<hash_digest> hashes; hashes.reserve(txs.size()); for(auto& t:txs) { hashes.push_back(t->hash()); } log::debug(LOG_NODE) << "memory pool size," << txs.size(); send<protocol_transaction_out>(inventory{hashes, inventory::type_id::transaction}, &protocol_transaction_out::handle_send, _1, inventory::command); }); return false; } // Receive get_data sequence. //----------------------------------------------------------------------------- bool protocol_transaction_out::handle_receive_get_data(const code& ec, get_data_ptr message) { if (stopped()) return false; if (ec) { log::trace(LOG_NODE) << "Failure getting inventory from [" << authority() << "] " << ec.message(); stop(ec); return false; } // if (message->inventories.size() > 50000) // { // return ! misbehaving(20); // } // TODO: these must return message objects or be copied! // Ignore non-transaction inventory requests in this protocol. for (const auto& inv: message->inventories) if (inv.type == inventory::type_id::transaction) { auto pThis = shared_from_this(); pool_.fetch(inv.hash, [this, &inv, pThis](const code& ec, transaction_ptr tx){ auto t = tx ? *tx : chain::transaction{}; send_transaction(ec, t, inv.hash); if(ec) { blockchain_.fetch_transaction(inv.hash, BIND3(send_transaction, _1, _2, inv.hash)); } }); } return true; } void protocol_transaction_out::send_transaction(const code& ec, const chain::transaction& transaction, const hash_digest& hash) { if (stopped() || ec == (code)error::service_stopped) return; if (ec == (code)error::not_found) { log::trace(LOG_NODE) << "Transaction requested by [" << authority() << "] not found."; const not_found reply{ { inventory::type_id::transaction, hash } }; SEND2(reply, handle_send, _1, reply.command); return; } if (ec) { log::error(LOG_NODE) << "Internal failure locating trnsaction requested by [" << authority() << "] " << ec.message(); stop(ec); return; } log::trace(LOG_NODE) << "send transaction " << encode_hash(transaction.hash()) << ", to " << authority(); // TODO: eliminate copy. SEND2(transaction_message(transaction), handle_send, _1, transaction_message::command); } // Subscription. //----------------------------------------------------------------------------- bool protocol_transaction_out::handle_floated(const code& ec, const index_list& unconfirmed, transaction_ptr message) { if (stopped() || ec == (code)error::service_stopped) return false; if (ec == (code)error::mock) { return true; } if (ec) { log::error(LOG_NODE) << "Failure handling transaction float: " << ec.message(); stop(ec); return false; } // TODO: move fee filter to a derived class protocol_transaction_out_70013. // TODO: implement fee computation. const uint64_t fee = 0; // Transactions are discovered and announced individually. if (message->originator() != nonce() && fee >= minimum_fee_.load()) { static const auto id = inventory::type_id::transaction; const inventory announcement{ { id, message->hash() } }; log::trace(LOG_NODE) << "handle floated send transaction hash," << encode_hash(message->hash()) ; SEND2(announcement, handle_send, _1, announcement.command); } return true; } void protocol_transaction_out::handle_stop(const code&) { log::trace(LOG_NETWORK) << "Stopped transaction_out protocol"; pool_.fired(); } } // namespace node } // namespace libbitcoin <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> #include <regex> #include <vector> #include <list> #include <stdexcept> #include <algorithm> #include <functional> #include <cctype> #include <locale> using namespace std; // trim from start (in place) static inline void ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); } // trim from end (in place) static inline void rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); } // trim from both ends (in place) static inline void trim(std::string &s) { ltrim(s); rtrim(s); } // trim from start (copying) static inline std::string ltrimmed(std::string s) { ltrim(s); return s; } // trim from end (copying) static inline std::string rtrimmed(std::string s) { rtrim(s); return s; } // trim from both ends (copying) static inline std::string trimmed(std::string s) { trim(s); return s; } std::list<std::string> readFile(std::string fileName) { /* Function which takes a file name as a parameter and * read all its content line per line * * INPUT - filename , std::std::string * OUTPUT - list of filecontent, std::list<std::std::string> * throws File not found exception error when file is not present */ std::list<std::string> myFileContent; std::ifstream myFile (fileName); if(!myFile) { cout<<"File hi nahi hai beta"; throw "File does not exist!"; } //myFile.exceptions (ifstream::failbit | ifstream::badbit ); try { for(std::string line; std::getline( myFile, line ); ) { myFileContent.push_back(line); cout<<line<<endl; } } catch(std::exception const& e) { cout << "There was an error: " << e.what() << endl; } myFile.close(); return myFileContent; } void writeFile(std::string filename, std::list<std::string> myFileContent) { std::ofstream myFile (filename); if(!myFile) { cout<<"File hi nahi hai beta"; throw "File not found"; } for( auto iterator = myFileContent.begin() ; iterator != myFileContent.end() ; ++iterator ) { myFile << *iterator << '\n' ; } std::cout<< "Hey, it's done'"; myFile.close(); } bool StringMatcher(std::string stringOne, std::string stringTwo) { cout<<stringOne<<endl; cout<<trimmed(stringOne); std::string regexString = "(\\s*)("+ trimmed(stringOne) + ")(\\s*)"; std::regex e (regexString); std::cout<<"this - "<<regexString<<endl; //std::regex e (stringOne); if (regex_match(stringTwo, e)) { cout << " matches" << endl; return true; } else { cout << " doesn’t match" << endl; return false; } } std::list<std::string> deleteMatching(std::list<std::string> myList, std::list<std::string> myNewList) { std::list<std::string>::iterator it1,it2; for(it1=myList.begin(); it1!=myList.end(); ++it1) { for(it2=myNewList.begin(); it2!=myNewList.end(); ++it2) { if(StringMatcher(*it1, *it2)==true) { cout<<"Yeh gaya - " <<*it2<<endl; it2 = myNewList.erase(it2); } } } for(it1=myNewList.begin(); it1!=myNewList.end(); ++it1) { cout<<*it1<<endl; } cout<< "\nKhatam"; return myNewList; } int main() { std::list<std::string> referenceList, targetList; std::string targetFileName = "files/patchinfo", referenceFileName = "files/reference"; try { referenceList = readFile(referenceFileName); targetList = readFile(targetFileName); targetList = deleteMatching(referenceList, targetList); writeFile(targetFileName, targetList); cout<< StringMatcher("hi", "hi "); } catch (std::exception const& errr) { std::cerr << errr.what()<<endl; } catch(const char *e) { std::cerr << e; } } <commit_msg>added comments and removed output statements<commit_after>#include <iostream> #include <fstream> #include <string> #include <regex> #include <vector> #include <list> #include <stdexcept> #include <algorithm> #include <functional> #include <cctype> #include <locale> using namespace std; // trim from start (in place) static inline void ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); } // trim from end (in place) static inline void rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); } // trim from both ends (in place) static inline void trim(std::string &s) { ltrim(s); rtrim(s); } // trim from start (copying) static inline std::string ltrimmed(std::string s) { ltrim(s); return s; } // trim from end (copying) static inline std::string rtrimmed(std::string s) { rtrim(s); return s; } // trim from both ends (copying) static inline std::string trimmed(std::string s) { trim(s); return s; } std::list<std::string> readFile(std::string fileName) { /* Function which takes a file name as a parameter and * read all its content line per line * * INPUT - filename , std::std::string * OUTPUT - list of filecontent, std::list<std::std::string> * throws File not found exception error when file is not present */ std::list<std::string> myFileContent; std::ifstream myFile (fileName); if(!myFile) { throw "File does not exist!"; } //myFile.exceptions (ifstream::failbit | ifstream::badbit ); try { for(std::string line; std::getline( myFile, line ); ) { myFileContent.push_back(line); } } catch(std::exception const& e) { cout << "There was an error: " << e.what() << endl; } myFile.close(); return myFileContent; } void writeFile(std::string filename, std::list<std::string> myFileContent) { /* Function which takes a file name and FileContent as string list a parameter and * writes all its content element per element * * INPUT - filename , std::std::string * OUTPUT - list of filecontent, std::list<std::std::string> * throws File not found exception error when file is not present */ std::ofstream myFile (filename); if(!myFile) { throw "File not found"; } for( auto iterator = myFileContent.begin() ; iterator != myFileContent.end() ; ++iterator ) { myFile << *iterator << '\n' ; } myFile.close(); } bool StringMatcher(std::string stringOne, std::string stringTwo) { /* Matches two strings by trimming the forward and trailing spaces * and returns true if matched else returns false */ std::string regexString = "(\\s*)("+ trimmed(stringOne) + ")(\\s*)"; std::regex e (regexString); //std::regex e (stringOne); if (regex_match(stringTwo, e)) { return true; else return false; } std::list<std::string> deleteMatching(std::list<std::string> myList, std::list<std::string> myNewList) { std::list<std::string>::iterator it1,it2; for(it1=myList.begin(); it1!=myList.end(); ++it1) { for(it2=myNewList.begin(); it2!=myNewList.end(); ++it2) { if(StringMatcher(*it1, *it2)==true) { cout<<"Yeh gaya - " <<*it2<<endl; it2 = myNewList.erase(it2); } } } return myNewList; } int main() { std::list<std::string> referenceList, targetList; std::string targetFileName = "files/patchinfo", referenceFileName = "files/reference"; try { referenceList = readFile(referenceFileName); targetList = readFile(targetFileName); targetList = deleteMatching(referenceList, targetList); writeFile(targetFileName, targetList); } catch (std::exception const& errr) { std::cerr << errr.what()<<endl; } catch(const char *e) { std::cerr << e; } } <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/framework/executor.h" #include <set> #include "gflags/gflags.h" #include "paddle/fluid/framework/feed_fetch_method.h" #include "paddle/fluid/framework/feed_fetch_type.h" #include "paddle/fluid/framework/lod_rank_table.h" #include "paddle/fluid/framework/lod_tensor_array.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/framework/reader.h" #include "paddle/fluid/platform/place.h" #include "paddle/fluid/platform/profiler.h" DECLARE_bool(benchmark); DEFINE_bool(check_nan_inf, false, "Checking whether operator produce NAN/INF or not. It will be " "extremely slow so please use this flag wisely."); namespace paddle { namespace framework { Executor::Executor(const platform::Place& place) : place_(place) {} static void CreateTensor(Variable* var, proto::VarDesc::VarType var_type) { if (var_type == proto::VarDesc::LOD_TENSOR) { var->GetMutable<LoDTensor>(); } else if (var_type == proto::VarDesc::SELECTED_ROWS) { var->GetMutable<SelectedRows>(); } else if (var_type == proto::VarDesc::FEED_MINIBATCH) { var->GetMutable<FeedFetchList>(); } else if (var_type == proto::VarDesc::FETCH_LIST) { var->GetMutable<FeedFetchList>(); } else if (var_type == proto::VarDesc::STEP_SCOPES) { var->GetMutable<std::vector<framework::Scope>>(); } else if (var_type == proto::VarDesc::LOD_RANK_TABLE) { var->GetMutable<LoDRankTable>(); } else if (var_type == proto::VarDesc::LOD_TENSOR_ARRAY) { var->GetMutable<LoDTensorArray>(); } else if (var_type == proto::VarDesc::PLACE_LIST) { var->GetMutable<platform::PlaceList>(); } else if (var_type == proto::VarDesc::READER) { var->GetMutable<ReaderHolder>(); } else if (var_type == proto::VarDesc::NCCL_COM) { // GetMutable will be called in ncclInit } else { PADDLE_THROW( "Variable type %d is not in " "[LOD_TENSOR, SELECTED_ROWS, FEED_MINIBATCH, FETCH_LIST, " "LOD_RANK_TABLE, PLACE_LIST, READER, NCCL_COM]", var_type); } } static void CheckTensorNANOrInf(const std::string& name, const framework::Tensor& tensor) { if (tensor.memory_size() == 0) { return; } if (tensor.type().hash_code() != typeid(float).hash_code() && tensor.type().hash_code() != typeid(double).hash_code()) { return; } PADDLE_ENFORCE(!framework::HasInf(tensor), "Tensor %s has Inf", name); PADDLE_ENFORCE(!framework::HasNAN(tensor), "Tensor %s has NAN", name); } void Executor::Run(const ProgramDesc& pdesc, Scope* scope, int block_id, bool create_local_scope, bool create_vars) { // TODO(tonyyang-svail): // - only runs on the first device (i.e. no interdevice communication) // - will change to use multiple blocks for RNN op and Cond Op PADDLE_ENFORCE_LT(static_cast<size_t>(block_id), pdesc.Size()); auto& block = pdesc.Block(block_id); Scope* local_scope = scope; if (create_vars) { if (create_local_scope) { local_scope = &scope->NewScope(); for (auto& var : block.AllVars()) { if (var->Name() == framework::kEmptyVarName) { continue; } if (var->Persistable()) { auto* ptr = scope->Var(var->Name()); CreateTensor(ptr, var->GetType()); VLOG(3) << "Create Variable " << var->Name() << " global, which pointer is " << ptr; } else { auto* ptr = local_scope->Var(var->Name()); CreateTensor(ptr, var->GetType()); VLOG(3) << "Create Variable " << var->Name() << " locally, which pointer is " << ptr; } } } else { for (auto& var : block.AllVars()) { auto* ptr = local_scope->Var(var->Name()); CreateTensor(ptr, var->GetType()); VLOG(3) << "Create variable " << var->Name() << ", which pointer is " << ptr; } } // if (create_local_scope) } // if (create_vars) for (auto& op_desc : block.AllOps()) { auto op = paddle::framework::OpRegistry::CreateOp(*op_desc); VLOG(3) << op->DebugStringEx(local_scope); platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance(); platform::RecordEvent record_event(op->Type(), pool.Get(place_)); op->Run(*local_scope, place_); if (FLAGS_benchmark) { VLOG(2) << "Memory used after operator " + op->Type() + " running: " << memory::memory_usage(place_); } if (FLAGS_check_nan_inf) { for (auto& vname : op->OutputVars(true)) { auto* var = local_scope->FindVar(vname); if (var == nullptr) continue; if (var->IsType<framework::LoDTensor>()) { CheckTensorNANOrInf(vname, var->Get<framework::LoDTensor>()); } } } } if (create_vars && create_local_scope) { scope->DeleteScope(local_scope); } if (FLAGS_benchmark) { VLOG(2) << "-------------------------------------------------------"; VLOG(2) << "Memory used after deleting local scope: " << memory::memory_usage(place_); VLOG(2) << "-------------------------------------------------------"; } } // Check whether the block already has feed operators and feed_holder. // Return false if the block does not have any feed operators. // If some feed operators have been prepended to the block, check that // the info contained in these feed operators matches the feed_targets // and feed_holder_name. Raise exception when any mismatch is found. // Return true if the block has feed operators and holder of matching info. static bool has_feed_operators( BlockDesc* block, std::map<std::string, const LoDTensor*>& feed_targets, const std::string& feed_holder_name) { size_t feed_count = 0; for (auto* op : block->AllOps()) { if (op->Type() == kFeedOpType) { feed_count++; PADDLE_ENFORCE_EQ(op->Input("X")[0], feed_holder_name, "Input to feed op should be '%s'", feed_holder_name); std::string feed_target_name = op->Output("Out")[0]; PADDLE_ENFORCE( feed_targets.find(feed_target_name) != feed_targets.end(), "Feed operator output name '%s' cannot be found in 'feed_targets'", feed_target_name); } } if (feed_count > 0) { PADDLE_ENFORCE_EQ( feed_count, feed_targets.size(), "The number of feed operators should match 'feed_targets'"); // When feed operator are present, so should be feed_holder auto var = block->FindVar(feed_holder_name); PADDLE_ENFORCE_NOT_NULL(var, "Block should already have a '%s' variable", feed_holder_name); PADDLE_ENFORCE_EQ(var->GetType(), proto::VarDesc::FEED_MINIBATCH, "'%s' variable should be 'FEED_MINIBATCH' type", feed_holder_name); } return feed_count > 0; } // Check whether the block already has fetch operators and fetch_holder. // Return false if the block does not have any fetch operators. // If some fetch operators have been appended to the block, check that // the info contained in these fetch operators matches the fetch_targets // and fetch_holder_name. Raise exception when any mismatch is found. // Return true if the block has fetch operators and holder of matching info. static bool has_fetch_operators( BlockDesc* block, std::map<std::string, LoDTensor*>& fetch_targets, const std::string& fetch_holder_name) { size_t fetch_count = 0; for (auto* op : block->AllOps()) { if (op->Type() == kFetchOpType) { fetch_count++; PADDLE_ENFORCE_EQ(op->Output("Out")[0], fetch_holder_name, "Output of fetch op should be '%s'", fetch_holder_name); std::string fetch_target_name = op->Input("X")[0]; PADDLE_ENFORCE( fetch_targets.find(fetch_target_name) != fetch_targets.end(), "Fetch operator input name '%s' cannot be found in 'fetch_targets'", fetch_target_name); } } if (fetch_count > 0) { PADDLE_ENFORCE_EQ( fetch_count, fetch_targets.size(), "The number of fetch operators should match 'fetch_targets'"); // When fetch operator are present, so should be fetch_holder auto var = block->FindVar(fetch_holder_name); PADDLE_ENFORCE_NOT_NULL(var, "Block should already have a '%s' variable", fetch_holder_name); PADDLE_ENFORCE_EQ(var->GetType(), proto::VarDesc::FETCH_LIST, "'%s' variable should be 'FETCH_LIST' type", fetch_holder_name); } return fetch_count > 0; } void Executor::Run(const ProgramDesc& program, Scope* scope, std::map<std::string, const LoDTensor*>& feed_targets, std::map<std::string, LoDTensor*>& fetch_targets, const std::string& feed_holder_name, const std::string& fetch_holder_name) { auto* copy_program = new ProgramDesc(program); auto* global_block = copy_program->MutableBlock(0); if (!has_feed_operators(global_block, feed_targets, feed_holder_name)) { // create feed_holder variable auto* feed_holder = global_block->Var(feed_holder_name); feed_holder->SetType(proto::VarDesc::FEED_MINIBATCH); feed_holder->SetPersistable(true); int i = 0; for (auto& feed_target : feed_targets) { std::string var_name = feed_target.first; VLOG(3) << "feed target's name: " << var_name; // prepend feed op auto* op = global_block->PrependOp(); op->SetType(kFeedOpType); op->SetInput("X", {feed_holder_name}); op->SetOutput("Out", {var_name}); op->SetAttr("col", {static_cast<int>(i)}); op->CheckAttrs(); i++; } } // map the data of feed_targets to feed_holder for (auto* op : global_block->AllOps()) { if (op->Type() == kFeedOpType) { std::string feed_target_name = op->Output("Out")[0]; int idx = boost::get<int>(op->GetAttr("col")); SetFeedVariable(scope, *feed_targets[feed_target_name], feed_holder_name, idx); } } if (!has_fetch_operators(global_block, fetch_targets, fetch_holder_name)) { // create fetch_holder variable auto* fetch_holder = global_block->Var(fetch_holder_name); fetch_holder->SetType(proto::VarDesc::FETCH_LIST); fetch_holder->SetPersistable(true); int i = 0; for (auto& fetch_target : fetch_targets) { std::string var_name = fetch_target.first; VLOG(3) << "fetch target's name: " << var_name; // append fetch op auto* op = global_block->AppendOp(); op->SetType(kFetchOpType); op->SetInput("X", {var_name}); op->SetOutput("Out", {fetch_holder_name}); op->SetAttr("col", {static_cast<int>(i)}); op->CheckAttrs(); i++; } } Run(*copy_program, scope, 0, true, true); // obtain the data of fetch_targets from fetch_holder for (auto* op : global_block->AllOps()) { if (op->Type() == kFetchOpType) { std::string fetch_target_name = op->Input("X")[0]; int idx = boost::get<int>(op->GetAttr("col")); *fetch_targets[fetch_target_name] = GetFetchVariable(*scope, fetch_holder_name, idx); } } delete copy_program; } } // namespace framework } // namespace paddle <commit_msg>diable debug string due to vector bug<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/framework/executor.h" #include <set> #include "gflags/gflags.h" #include "paddle/fluid/framework/feed_fetch_method.h" #include "paddle/fluid/framework/feed_fetch_type.h" #include "paddle/fluid/framework/lod_rank_table.h" #include "paddle/fluid/framework/lod_tensor_array.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/framework/reader.h" #include "paddle/fluid/platform/place.h" #include "paddle/fluid/platform/profiler.h" DECLARE_bool(benchmark); DEFINE_bool(check_nan_inf, false, "Checking whether operator produce NAN/INF or not. It will be " "extremely slow so please use this flag wisely."); namespace paddle { namespace framework { Executor::Executor(const platform::Place& place) : place_(place) {} static void CreateTensor(Variable* var, proto::VarDesc::VarType var_type) { if (var_type == proto::VarDesc::LOD_TENSOR) { var->GetMutable<LoDTensor>(); } else if (var_type == proto::VarDesc::SELECTED_ROWS) { var->GetMutable<SelectedRows>(); } else if (var_type == proto::VarDesc::FEED_MINIBATCH) { var->GetMutable<FeedFetchList>(); } else if (var_type == proto::VarDesc::FETCH_LIST) { var->GetMutable<FeedFetchList>(); } else if (var_type == proto::VarDesc::STEP_SCOPES) { var->GetMutable<std::vector<framework::Scope>>(); } else if (var_type == proto::VarDesc::LOD_RANK_TABLE) { var->GetMutable<LoDRankTable>(); } else if (var_type == proto::VarDesc::LOD_TENSOR_ARRAY) { var->GetMutable<LoDTensorArray>(); } else if (var_type == proto::VarDesc::PLACE_LIST) { var->GetMutable<platform::PlaceList>(); } else if (var_type == proto::VarDesc::READER) { var->GetMutable<ReaderHolder>(); } else if (var_type == proto::VarDesc::NCCL_COM) { // GetMutable will be called in ncclInit } else { PADDLE_THROW( "Variable type %d is not in " "[LOD_TENSOR, SELECTED_ROWS, FEED_MINIBATCH, FETCH_LIST, " "LOD_RANK_TABLE, PLACE_LIST, READER, NCCL_COM]", var_type); } } static void CheckTensorNANOrInf(const std::string& name, const framework::Tensor& tensor) { if (tensor.memory_size() == 0) { return; } if (tensor.type().hash_code() != typeid(float).hash_code() && tensor.type().hash_code() != typeid(double).hash_code()) { return; } PADDLE_ENFORCE(!framework::HasInf(tensor), "Tensor %s has Inf", name); PADDLE_ENFORCE(!framework::HasNAN(tensor), "Tensor %s has NAN", name); } void Executor::Run(const ProgramDesc& pdesc, Scope* scope, int block_id, bool create_local_scope, bool create_vars) { // TODO(tonyyang-svail): // - only runs on the first device (i.e. no interdevice communication) // - will change to use multiple blocks for RNN op and Cond Op PADDLE_ENFORCE_LT(static_cast<size_t>(block_id), pdesc.Size()); auto& block = pdesc.Block(block_id); Scope* local_scope = scope; if (create_vars) { if (create_local_scope) { local_scope = &scope->NewScope(); for (auto& var : block.AllVars()) { if (var->Name() == framework::kEmptyVarName) { continue; } if (var->Persistable()) { auto* ptr = scope->Var(var->Name()); CreateTensor(ptr, var->GetType()); VLOG(3) << "Create Variable " << var->Name() << " global, which pointer is " << ptr; } else { auto* ptr = local_scope->Var(var->Name()); CreateTensor(ptr, var->GetType()); VLOG(3) << "Create Variable " << var->Name() << " locally, which pointer is " << ptr; } } } else { for (auto& var : block.AllVars()) { auto* ptr = local_scope->Var(var->Name()); CreateTensor(ptr, var->GetType()); VLOG(3) << "Create variable " << var->Name() << ", which pointer is " << ptr; } } // if (create_local_scope) } // if (create_vars) for (auto& op_desc : block.AllOps()) { auto op = paddle::framework::OpRegistry::CreateOp(*op_desc); // VLOG(3) << op->DebugStringEx(local_scope); platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance(); platform::RecordEvent record_event(op->Type(), pool.Get(place_)); VLOG(3) << op->Type(); op->Run(*local_scope, place_); if (FLAGS_benchmark) { VLOG(2) << "Memory used after operator " + op->Type() + " running: " << memory::memory_usage(place_); } if (FLAGS_check_nan_inf) { for (auto& vname : op->OutputVars(true)) { auto* var = local_scope->FindVar(vname); if (var == nullptr) continue; if (var->IsType<framework::LoDTensor>()) { CheckTensorNANOrInf(vname, var->Get<framework::LoDTensor>()); } } } } if (create_vars && create_local_scope) { scope->DeleteScope(local_scope); } if (FLAGS_benchmark) { VLOG(2) << "-------------------------------------------------------"; VLOG(2) << "Memory used after deleting local scope: " << memory::memory_usage(place_); VLOG(2) << "-------------------------------------------------------"; } } // Check whether the block already has feed operators and feed_holder. // Return false if the block does not have any feed operators. // If some feed operators have been prepended to the block, check that // the info contained in these feed operators matches the feed_targets // and feed_holder_name. Raise exception when any mismatch is found. // Return true if the block has feed operators and holder of matching info. static bool has_feed_operators( BlockDesc* block, std::map<std::string, const LoDTensor*>& feed_targets, const std::string& feed_holder_name) { size_t feed_count = 0; for (auto* op : block->AllOps()) { if (op->Type() == kFeedOpType) { feed_count++; PADDLE_ENFORCE_EQ(op->Input("X")[0], feed_holder_name, "Input to feed op should be '%s'", feed_holder_name); std::string feed_target_name = op->Output("Out")[0]; PADDLE_ENFORCE( feed_targets.find(feed_target_name) != feed_targets.end(), "Feed operator output name '%s' cannot be found in 'feed_targets'", feed_target_name); } } if (feed_count > 0) { PADDLE_ENFORCE_EQ( feed_count, feed_targets.size(), "The number of feed operators should match 'feed_targets'"); // When feed operator are present, so should be feed_holder auto var = block->FindVar(feed_holder_name); PADDLE_ENFORCE_NOT_NULL(var, "Block should already have a '%s' variable", feed_holder_name); PADDLE_ENFORCE_EQ(var->GetType(), proto::VarDesc::FEED_MINIBATCH, "'%s' variable should be 'FEED_MINIBATCH' type", feed_holder_name); } return feed_count > 0; } // Check whether the block already has fetch operators and fetch_holder. // Return false if the block does not have any fetch operators. // If some fetch operators have been appended to the block, check that // the info contained in these fetch operators matches the fetch_targets // and fetch_holder_name. Raise exception when any mismatch is found. // Return true if the block has fetch operators and holder of matching info. static bool has_fetch_operators( BlockDesc* block, std::map<std::string, LoDTensor*>& fetch_targets, const std::string& fetch_holder_name) { size_t fetch_count = 0; for (auto* op : block->AllOps()) { if (op->Type() == kFetchOpType) { fetch_count++; PADDLE_ENFORCE_EQ(op->Output("Out")[0], fetch_holder_name, "Output of fetch op should be '%s'", fetch_holder_name); std::string fetch_target_name = op->Input("X")[0]; PADDLE_ENFORCE( fetch_targets.find(fetch_target_name) != fetch_targets.end(), "Fetch operator input name '%s' cannot be found in 'fetch_targets'", fetch_target_name); } } if (fetch_count > 0) { PADDLE_ENFORCE_EQ( fetch_count, fetch_targets.size(), "The number of fetch operators should match 'fetch_targets'"); // When fetch operator are present, so should be fetch_holder auto var = block->FindVar(fetch_holder_name); PADDLE_ENFORCE_NOT_NULL(var, "Block should already have a '%s' variable", fetch_holder_name); PADDLE_ENFORCE_EQ(var->GetType(), proto::VarDesc::FETCH_LIST, "'%s' variable should be 'FETCH_LIST' type", fetch_holder_name); } return fetch_count > 0; } void Executor::Run(const ProgramDesc& program, Scope* scope, std::map<std::string, const LoDTensor*>& feed_targets, std::map<std::string, LoDTensor*>& fetch_targets, const std::string& feed_holder_name, const std::string& fetch_holder_name) { auto* copy_program = new ProgramDesc(program); auto* global_block = copy_program->MutableBlock(0); if (!has_feed_operators(global_block, feed_targets, feed_holder_name)) { // create feed_holder variable auto* feed_holder = global_block->Var(feed_holder_name); feed_holder->SetType(proto::VarDesc::FEED_MINIBATCH); feed_holder->SetPersistable(true); int i = 0; for (auto& feed_target : feed_targets) { std::string var_name = feed_target.first; VLOG(3) << "feed target's name: " << var_name; // prepend feed op auto* op = global_block->PrependOp(); op->SetType(kFeedOpType); op->SetInput("X", {feed_holder_name}); op->SetOutput("Out", {var_name}); op->SetAttr("col", {static_cast<int>(i)}); op->CheckAttrs(); i++; } } // map the data of feed_targets to feed_holder for (auto* op : global_block->AllOps()) { if (op->Type() == kFeedOpType) { std::string feed_target_name = op->Output("Out")[0]; int idx = boost::get<int>(op->GetAttr("col")); SetFeedVariable(scope, *feed_targets[feed_target_name], feed_holder_name, idx); } } if (!has_fetch_operators(global_block, fetch_targets, fetch_holder_name)) { // create fetch_holder variable auto* fetch_holder = global_block->Var(fetch_holder_name); fetch_holder->SetType(proto::VarDesc::FETCH_LIST); fetch_holder->SetPersistable(true); int i = 0; for (auto& fetch_target : fetch_targets) { std::string var_name = fetch_target.first; VLOG(3) << "fetch target's name: " << var_name; // append fetch op auto* op = global_block->AppendOp(); op->SetType(kFetchOpType); op->SetInput("X", {var_name}); op->SetOutput("Out", {fetch_holder_name}); op->SetAttr("col", {static_cast<int>(i)}); op->CheckAttrs(); i++; } } Run(*copy_program, scope, 0, true, true); // obtain the data of fetch_targets from fetch_holder for (auto* op : global_block->AllOps()) { if (op->Type() == kFetchOpType) { std::string fetch_target_name = op->Input("X")[0]; int idx = boost::get<int>(op->GetAttr("col")); *fetch_targets[fetch_target_name] = GetFetchVariable(*scope, fetch_holder_name, idx); } } delete copy_program; } } // namespace framework } // namespace paddle <|endoftext|>
<commit_before>/* Copyright (c) 2013, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "test.hpp" #include "setup_transfer.hpp" #include "dht_server.hpp" #include "peer_server.hpp" #include "libtorrent/alert.hpp" #include "libtorrent/alert_types.hpp" #include <fstream> using namespace libtorrent; char const* proxy_name[] = { "none", "socks4", "socks5", "socks5_pw", "http", "http_pw", "i2p_proxy" }; std::vector<std::string> rejected_trackers; bool alert_predicate(libtorrent::alert* a) { anonymous_mode_alert* am = alert_cast<anonymous_mode_alert>(a); if (am == NULL) return false; if (am->kind == anonymous_mode_alert::tracker_not_anonymous) rejected_trackers.push_back(am->str); return false; } enum flags_t { anonymous_mode = 1, expect_http_connection = 2, expect_udp_connection = 4, expect_http_reject = 8, expect_udp_reject = 16, expect_dht_msg = 32, expect_peer_connection = 64, }; void test_proxy(proxy_settings::proxy_type proxy_type, int flags) { #ifdef TORRENT_DISABLE_DHT // if DHT is disabled, we won't get any requests to it flags &= ~expect_dht_msg; #endif fprintf(stderr, "\n=== TEST == proxy: %s anonymous-mode: %s\n\n", proxy_name[proxy_type], (flags & anonymous_mode) ? "yes" : "no"); int http_port = start_web_server(); int udp_port = start_tracker(); int dht_port = start_dht(); int peer_port = start_peer(); int prev_udp_announces = g_udp_tracker_requests; int prev_http_announces = g_http_tracker_requests; int const alert_mask = alert::all_categories & ~alert::progress_notification & ~alert::stats_notification; session* s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48875, 49800), "0.0.0.0", 0, alert_mask); session_settings sett; sett.stop_tracker_timeout = 1; sett.tracker_completion_timeout = 1; sett.tracker_receive_timeout = 1; sett.half_open_limit = 1; sett.announce_to_all_trackers = true; sett.announce_to_all_tiers = true; sett.anonymous_mode = flags & anonymous_mode; sett.force_proxy = flags & anonymous_mode; // if we don't do this, the peer connection test // will be delayed by several seconds, by first // trying uTP sett.enable_outgoing_utp = false; s->set_settings(sett); proxy_settings ps; ps.hostname = "non-existing.com"; ps.port = 4444; ps.type = proxy_type; s->set_proxy(ps); s->start_dht(); error_code ec; create_directory("tmp1_privacy", ec); std::ofstream file(combine_path("tmp1_privacy", "temporary").c_str()); boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024, 13, false); file.close(); char http_tracker_url[200]; snprintf(http_tracker_url, sizeof(http_tracker_url), "http://127.0.0.1:%d/announce", http_port); t->add_tracker(http_tracker_url, 0); char udp_tracker_url[200]; snprintf(udp_tracker_url, sizeof(udp_tracker_url), "udp://127.0.0.1:%d/announce", udp_port); t->add_tracker(udp_tracker_url, 1); add_torrent_params addp; addp.flags &= ~add_torrent_params::flag_paused; addp.flags &= ~add_torrent_params::flag_auto_managed; addp.ti = t; addp.save_path = "tmp1_privacy"; addp.dht_nodes.push_back(std::pair<std::string, int>("127.0.0.1", dht_port)); torrent_handle h = s->add_torrent(addp); printf("connect_peer: 127.0.0.1:%d\n", peer_port); h.connect_peer(tcp::endpoint(address_v4::from_string("127.0.0.1"), peer_port)); rejected_trackers.clear(); for (int i = 0; i < 15; ++i) { print_alerts(*s, "s", false, false, false, &alert_predicate); test_sleep(100); if (g_udp_tracker_requests >= prev_udp_announces + 1 && g_http_tracker_requests >= prev_http_announces + 1 && num_peer_hits() > 0) break; } // we should have announced to the tracker by now TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + bool(flags & expect_udp_connection)); TEST_EQUAL(g_http_tracker_requests, prev_http_announces + bool(flags & expect_http_connection)); if (flags & expect_dht_msg) { TEST_CHECK(num_dht_hits() > 0); } else { TEST_EQUAL(num_dht_hits(), 0); } if (flags & expect_peer_connection) { TEST_CHECK(num_peer_hits() > 0); } else { TEST_EQUAL(num_peer_hits(), 0); } if (flags & expect_udp_reject) TEST_CHECK(std::find(rejected_trackers.begin(), rejected_trackers.end(), udp_tracker_url) != rejected_trackers.end()); if (flags & expect_http_reject) TEST_CHECK(std::find(rejected_trackers.begin(), rejected_trackers.end(), http_tracker_url) != rejected_trackers.end()); fprintf(stderr, "%s: ~session\n", time_now_string()); delete s; fprintf(stderr, "%s: ~session done\n", time_now_string()); stop_peer(); stop_dht(); stop_tracker(); stop_web_server(); } int test_main() { // not using anonymous mode // UDP fails open if we can't connect to the proxy // or if the proxy doesn't support UDP test_proxy(proxy_settings::none, expect_udp_connection | expect_http_connection | expect_dht_msg | expect_peer_connection); test_proxy(proxy_settings::socks4, expect_udp_connection | expect_dht_msg); test_proxy(proxy_settings::socks5, expect_udp_connection | expect_dht_msg); test_proxy(proxy_settings::socks5_pw, expect_udp_connection | expect_dht_msg); test_proxy(proxy_settings::http, expect_udp_connection | expect_dht_msg); test_proxy(proxy_settings::http_pw, expect_udp_connection | expect_dht_msg); test_proxy(proxy_settings::i2p_proxy, expect_udp_connection | expect_dht_msg); // using anonymous mode // anonymous mode doesn't require a proxy when one isn't configured. It could be // used with a VPN for instance. This will all changed in 1.0, where anonymous // mode is separated from force_proxy test_proxy(proxy_settings::none, anonymous_mode | expect_peer_connection); test_proxy(proxy_settings::socks4, anonymous_mode | expect_udp_reject); test_proxy(proxy_settings::socks5, anonymous_mode); test_proxy(proxy_settings::socks5_pw, anonymous_mode); test_proxy(proxy_settings::http, anonymous_mode | expect_udp_reject); test_proxy(proxy_settings::http_pw, anonymous_mode | expect_udp_reject); test_proxy(proxy_settings::i2p_proxy, anonymous_mode); return 0; } <commit_msg>increase tracker timeouts for test_privacy<commit_after>/* Copyright (c) 2013, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "test.hpp" #include "setup_transfer.hpp" #include "dht_server.hpp" #include "peer_server.hpp" #include "libtorrent/alert.hpp" #include "libtorrent/alert_types.hpp" #include <fstream> using namespace libtorrent; char const* proxy_name[] = { "none", "socks4", "socks5", "socks5_pw", "http", "http_pw", "i2p_proxy" }; std::vector<std::string> rejected_trackers; bool alert_predicate(libtorrent::alert* a) { anonymous_mode_alert* am = alert_cast<anonymous_mode_alert>(a); if (am == NULL) return false; if (am->kind == anonymous_mode_alert::tracker_not_anonymous) rejected_trackers.push_back(am->str); return false; } enum flags_t { anonymous_mode = 1, expect_http_connection = 2, expect_udp_connection = 4, expect_http_reject = 8, expect_udp_reject = 16, expect_dht_msg = 32, expect_peer_connection = 64, }; void test_proxy(proxy_settings::proxy_type proxy_type, int flags) { #ifdef TORRENT_DISABLE_DHT // if DHT is disabled, we won't get any requests to it flags &= ~expect_dht_msg; #endif fprintf(stderr, "\n=== TEST == proxy: %s anonymous-mode: %s\n\n", proxy_name[proxy_type], (flags & anonymous_mode) ? "yes" : "no"); int http_port = start_web_server(); int udp_port = start_tracker(); int dht_port = start_dht(); int peer_port = start_peer(); int prev_udp_announces = g_udp_tracker_requests; int prev_http_announces = g_http_tracker_requests; int const alert_mask = alert::all_categories & ~alert::progress_notification & ~alert::stats_notification; session* s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48875, 49800), "0.0.0.0", 0, alert_mask); session_settings sett; sett.stop_tracker_timeout = 2; sett.tracker_completion_timeout = 2; sett.tracker_receive_timeout = 2; sett.half_open_limit = 1; sett.announce_to_all_trackers = true; sett.announce_to_all_tiers = true; sett.anonymous_mode = flags & anonymous_mode; sett.force_proxy = flags & anonymous_mode; // if we don't do this, the peer connection test // will be delayed by several seconds, by first // trying uTP sett.enable_outgoing_utp = false; s->set_settings(sett); proxy_settings ps; ps.hostname = "non-existing.com"; ps.port = 4444; ps.type = proxy_type; s->set_proxy(ps); s->start_dht(); error_code ec; create_directory("tmp1_privacy", ec); std::ofstream file(combine_path("tmp1_privacy", "temporary").c_str()); boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024, 13, false); file.close(); char http_tracker_url[200]; snprintf(http_tracker_url, sizeof(http_tracker_url), "http://127.0.0.1:%d/announce", http_port); t->add_tracker(http_tracker_url, 0); char udp_tracker_url[200]; snprintf(udp_tracker_url, sizeof(udp_tracker_url), "udp://127.0.0.1:%d/announce", udp_port); t->add_tracker(udp_tracker_url, 1); add_torrent_params addp; addp.flags &= ~add_torrent_params::flag_paused; addp.flags &= ~add_torrent_params::flag_auto_managed; addp.ti = t; addp.save_path = "tmp1_privacy"; addp.dht_nodes.push_back(std::pair<std::string, int>("127.0.0.1", dht_port)); torrent_handle h = s->add_torrent(addp); printf("connect_peer: 127.0.0.1:%d\n", peer_port); h.connect_peer(tcp::endpoint(address_v4::from_string("127.0.0.1"), peer_port)); rejected_trackers.clear(); for (int i = 0; i < 15; ++i) { print_alerts(*s, "s", false, false, false, &alert_predicate); test_sleep(100); if (g_udp_tracker_requests >= prev_udp_announces + 1 && g_http_tracker_requests >= prev_http_announces + 1 && num_peer_hits() > 0) break; } // we should have announced to the tracker by now TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + bool(flags & expect_udp_connection)); TEST_EQUAL(g_http_tracker_requests, prev_http_announces + bool(flags & expect_http_connection)); if (flags & expect_dht_msg) { TEST_CHECK(num_dht_hits() > 0); } else { TEST_EQUAL(num_dht_hits(), 0); } if (flags & expect_peer_connection) { TEST_CHECK(num_peer_hits() > 0); } else { TEST_EQUAL(num_peer_hits(), 0); } if (flags & expect_udp_reject) TEST_CHECK(std::find(rejected_trackers.begin(), rejected_trackers.end(), udp_tracker_url) != rejected_trackers.end()); if (flags & expect_http_reject) TEST_CHECK(std::find(rejected_trackers.begin(), rejected_trackers.end(), http_tracker_url) != rejected_trackers.end()); fprintf(stderr, "%s: ~session\n", time_now_string()); delete s; fprintf(stderr, "%s: ~session done\n", time_now_string()); stop_peer(); stop_dht(); stop_tracker(); stop_web_server(); } int test_main() { // not using anonymous mode // UDP fails open if we can't connect to the proxy // or if the proxy doesn't support UDP test_proxy(proxy_settings::none, expect_udp_connection | expect_http_connection | expect_dht_msg | expect_peer_connection); test_proxy(proxy_settings::socks4, expect_udp_connection | expect_dht_msg); test_proxy(proxy_settings::socks5, expect_udp_connection | expect_dht_msg); test_proxy(proxy_settings::socks5_pw, expect_udp_connection | expect_dht_msg); test_proxy(proxy_settings::http, expect_udp_connection | expect_dht_msg); test_proxy(proxy_settings::http_pw, expect_udp_connection | expect_dht_msg); test_proxy(proxy_settings::i2p_proxy, expect_udp_connection | expect_dht_msg); // using anonymous mode // anonymous mode doesn't require a proxy when one isn't configured. It could be // used with a VPN for instance. This will all changed in 1.0, where anonymous // mode is separated from force_proxy test_proxy(proxy_settings::none, anonymous_mode | expect_peer_connection); test_proxy(proxy_settings::socks4, anonymous_mode | expect_udp_reject); test_proxy(proxy_settings::socks5, anonymous_mode); test_proxy(proxy_settings::socks5_pw, anonymous_mode); test_proxy(proxy_settings::http, anonymous_mode | expect_udp_reject); test_proxy(proxy_settings::http_pw, anonymous_mode | expect_udp_reject); test_proxy(proxy_settings::i2p_proxy, anonymous_mode); return 0; } <|endoftext|>
<commit_before>#include <sstream> #include "Module/Decoder/BCH/Standard/Decoder_BCH_std.hpp" #include "Module/Decoder/BCH/Genius/Decoder_BCH_genius.hpp" #include "Tools/Exception/exception.hpp" #include "Decoder_BCH.hpp" using namespace aff3ct; using namespace aff3ct::factory; const std::string aff3ct::factory::Decoder_BCH_name = "Decoder BCH"; const std::string aff3ct::factory::Decoder_BCH_prefix = "dec"; Decoder_BCH::parameters ::parameters(const std::string &prefix) : Decoder::parameters(Decoder_BCH_name, prefix) { this->type = "ALGEBRAIC"; this->implem = "STD"; } Decoder_BCH::parameters ::~parameters() { } Decoder_BCH::parameters* Decoder_BCH::parameters ::clone() const { return new Decoder_BCH::parameters(*this); } void Decoder_BCH::parameters ::get_description(tools::Argument_map_info &args) const { Decoder::parameters::get_description(args); auto p = this->get_prefix(); args.add( {p+"-corr-pow", "T"}, tools::Integer(tools::Positive(), tools::Non_zero()), "correction power of the BCH code."); args.add_link({p+"-corr-pow", "T"}, {p+"-info-bits", "K"}); tools::add_options(args.at({p+"-type", "D"}), 0, "ALGEBRAIC"); tools::add_options(args.at({p+"-implem" }), 0, "GENIUS"); } void Decoder_BCH::parameters ::store(const tools::Argument_map_value &vals) { Decoder::parameters::store(vals); auto p = this->get_prefix(); this->m = (int)std::ceil(std::log2(this->N_cw)); if (this->m == 0) { std::stringstream message; message << "The Gallois Field order is null (because N_cw = " << this->N_cw << ")."; throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str()); } if (vals.exist({p+"-corr-pow", "T"})) { this->t = vals.to_int({p + "-corr-pow", "T"}); if (K == 0) { this->K = this->N_cw - tools::BCH_polynomial_generator(this->N_cw, this->t).get_n_rdncy(); this->R = (float) this->K / (float) this->N_cw; } } else this->t = (this->N_cw - this->K) / this->m; } void Decoder_BCH::parameters ::get_headers(std::map<std::string,header_list>& headers, const bool full) const { Decoder::parameters::get_headers(headers, full); if (this->type != "ML" && this->type != "CHASE") { auto p = this->get_prefix(); headers[p].push_back(std::make_pair("Galois field order (m)", std::to_string(this->m))); headers[p].push_back(std::make_pair("Correction power (T)", std::to_string(this->t))); } } template <typename B, typename Q> module::Decoder_SIHO<B,Q>* Decoder_BCH::parameters ::build(const tools::BCH_polynomial_generator &GF, module::Encoder<B> *encoder) const { try { return Decoder::parameters::build<B,Q>(encoder); } catch (tools::cannot_allocate const&) { return build_hiho<B,Q>(GF, encoder); } } template <typename B, typename Q> module::Decoder_SIHO<B,Q>* Decoder_BCH ::build(const parameters &params, const tools::BCH_polynomial_generator &GF, module::Encoder<B> *encoder) { return params.template build<B,Q>(GF, encoder); } template <typename B, typename Q> module::Decoder_SIHO_HIHO<B,Q>* Decoder_BCH::parameters ::build_hiho(const tools::BCH_polynomial_generator &GF, module::Encoder<B> *encoder) const { if (this->type == "ALGEBRAIC") { if (this->implem == "STD") return new module::Decoder_BCH_std<B,Q>(this->K, this->N_cw, GF, this->n_frames); if (encoder) { if (this->implem == "GENIUS") return new module::Decoder_BCH_genius<B,Q>(this->K, this->N_cw, this->t, *encoder, this->n_frames); } } throw tools::cannot_allocate(__FILE__, __LINE__, __func__); } template <typename B, typename Q> module::Decoder_SIHO_HIHO<B,Q>* Decoder_BCH ::build_hiho(const parameters &params, const tools::BCH_polynomial_generator &GF, module::Encoder<B> *encoder) { return params.template build_hiho<B,Q>(GF, encoder); } // ==================================================================================== explicit template instantiation #include "Tools/types.h" #ifdef MULTI_PREC template aff3ct::module::Decoder_SIHO<B_8 ,Q_8 >* aff3ct::factory::Decoder_BCH::parameters::build<B_8 ,Q_8 >(const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_8 >*) const; template aff3ct::module::Decoder_SIHO<B_16,Q_16>* aff3ct::factory::Decoder_BCH::parameters::build<B_16,Q_16>(const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_16>*) const; template aff3ct::module::Decoder_SIHO<B_32,Q_32>* aff3ct::factory::Decoder_BCH::parameters::build<B_32,Q_32>(const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_32>*) const; template aff3ct::module::Decoder_SIHO<B_64,Q_64>* aff3ct::factory::Decoder_BCH::parameters::build<B_64,Q_64>(const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_64>*) const; template aff3ct::module::Decoder_SIHO<B_8 ,Q_8 >* aff3ct::factory::Decoder_BCH::build<B_8 ,Q_8 >(const aff3ct::factory::Decoder_BCH::parameters&, const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_8 >*); template aff3ct::module::Decoder_SIHO<B_16,Q_16>* aff3ct::factory::Decoder_BCH::build<B_16,Q_16>(const aff3ct::factory::Decoder_BCH::parameters&, const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_16>*); template aff3ct::module::Decoder_SIHO<B_32,Q_32>* aff3ct::factory::Decoder_BCH::build<B_32,Q_32>(const aff3ct::factory::Decoder_BCH::parameters&, const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_32>*); template aff3ct::module::Decoder_SIHO<B_64,Q_64>* aff3ct::factory::Decoder_BCH::build<B_64,Q_64>(const aff3ct::factory::Decoder_BCH::parameters&, const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_64>*); #else template aff3ct::module::Decoder_SIHO<B,Q>* aff3ct::factory::Decoder_BCH::parameters::build<B,Q>(const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B>*) const; template aff3ct::module::Decoder_SIHO<B,Q>* aff3ct::factory::Decoder_BCH::build<B,Q>(const aff3ct::factory::Decoder_BCH::parameters&, const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B>*); #endif // ==================================================================================== explicit template instantiation // ==================================================================================== explicit template instantiation #include "Tools/types.h" #ifdef MULTI_PREC template aff3ct::module::Decoder_SIHO_HIHO<B_8 ,Q_8 >* aff3ct::factory::Decoder_BCH::parameters::build_hiho<B_8 ,Q_8 >(const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_8 >*) const; template aff3ct::module::Decoder_SIHO_HIHO<B_16,Q_16>* aff3ct::factory::Decoder_BCH::parameters::build_hiho<B_16,Q_16>(const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_16>*) const; template aff3ct::module::Decoder_SIHO_HIHO<B_32,Q_32>* aff3ct::factory::Decoder_BCH::parameters::build_hiho<B_32,Q_32>(const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_32>*) const; template aff3ct::module::Decoder_SIHO_HIHO<B_64,Q_64>* aff3ct::factory::Decoder_BCH::parameters::build_hiho<B_64,Q_64>(const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_64>*) const; template aff3ct::module::Decoder_SIHO_HIHO<B_8 ,Q_8 >* aff3ct::factory::Decoder_BCH::build_hiho<B_8 ,Q_8 >(const aff3ct::factory::Decoder_BCH::parameters&, const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_8 >*); template aff3ct::module::Decoder_SIHO_HIHO<B_16,Q_16>* aff3ct::factory::Decoder_BCH::build_hiho<B_16,Q_16>(const aff3ct::factory::Decoder_BCH::parameters&, const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_16>*); template aff3ct::module::Decoder_SIHO_HIHO<B_32,Q_32>* aff3ct::factory::Decoder_BCH::build_hiho<B_32,Q_32>(const aff3ct::factory::Decoder_BCH::parameters&, const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_32>*); template aff3ct::module::Decoder_SIHO_HIHO<B_64,Q_64>* aff3ct::factory::Decoder_BCH::build_hiho<B_64,Q_64>(const aff3ct::factory::Decoder_BCH::parameters&, const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_64>*); #else template aff3ct::module::Decoder_SIHO_HIHO<B,Q>* aff3ct::factory::Decoder_BCH::parameters::build_hiho<B>(const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B>*) const; template aff3ct::module::Decoder_SIHO_HIHO<B,Q>* aff3ct::factory::Decoder_BCH::build_hiho<B>(const aff3ct::factory::Decoder_BCH::parameters&, const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B>*); #endif // ==================================================================================== explicit template instantiation <commit_msg> Spelling correction<commit_after>#include <sstream> #include "Module/Decoder/BCH/Standard/Decoder_BCH_std.hpp" #include "Module/Decoder/BCH/Genius/Decoder_BCH_genius.hpp" #include "Tools/Exception/exception.hpp" #include "Decoder_BCH.hpp" using namespace aff3ct; using namespace aff3ct::factory; const std::string aff3ct::factory::Decoder_BCH_name = "Decoder BCH"; const std::string aff3ct::factory::Decoder_BCH_prefix = "dec"; Decoder_BCH::parameters ::parameters(const std::string &prefix) : Decoder::parameters(Decoder_BCH_name, prefix) { this->type = "ALGEBRAIC"; this->implem = "STD"; } Decoder_BCH::parameters ::~parameters() { } Decoder_BCH::parameters* Decoder_BCH::parameters ::clone() const { return new Decoder_BCH::parameters(*this); } void Decoder_BCH::parameters ::get_description(tools::Argument_map_info &args) const { Decoder::parameters::get_description(args); auto p = this->get_prefix(); args.add( {p+"-corr-pow", "T"}, tools::Integer(tools::Positive(), tools::Non_zero()), "correction power of the BCH code."); args.add_link({p+"-corr-pow", "T"}, {p+"-info-bits", "K"}); tools::add_options(args.at({p+"-type", "D"}), 0, "ALGEBRAIC"); tools::add_options(args.at({p+"-implem" }), 0, "GENIUS"); } void Decoder_BCH::parameters ::store(const tools::Argument_map_value &vals) { Decoder::parameters::store(vals); auto p = this->get_prefix(); this->m = (int)std::ceil(std::log2(this->N_cw)); if (this->m == 0) { std::stringstream message; message << "The Galois Field order is null (because N_cw = " << this->N_cw << ")."; throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str()); } if (vals.exist({p+"-corr-pow", "T"})) { this->t = vals.to_int({p + "-corr-pow", "T"}); if (K == 0) { this->K = this->N_cw - tools::BCH_polynomial_generator(this->N_cw, this->t).get_n_rdncy(); this->R = (float) this->K / (float) this->N_cw; } } else this->t = (this->N_cw - this->K) / this->m; } void Decoder_BCH::parameters ::get_headers(std::map<std::string,header_list>& headers, const bool full) const { Decoder::parameters::get_headers(headers, full); if (this->type != "ML" && this->type != "CHASE") { auto p = this->get_prefix(); headers[p].push_back(std::make_pair("Galois field order (m)", std::to_string(this->m))); headers[p].push_back(std::make_pair("Correction power (T)", std::to_string(this->t))); } } template <typename B, typename Q> module::Decoder_SIHO<B,Q>* Decoder_BCH::parameters ::build(const tools::BCH_polynomial_generator &GF, module::Encoder<B> *encoder) const { try { return Decoder::parameters::build<B,Q>(encoder); } catch (tools::cannot_allocate const&) { return build_hiho<B,Q>(GF, encoder); } } template <typename B, typename Q> module::Decoder_SIHO<B,Q>* Decoder_BCH ::build(const parameters &params, const tools::BCH_polynomial_generator &GF, module::Encoder<B> *encoder) { return params.template build<B,Q>(GF, encoder); } template <typename B, typename Q> module::Decoder_SIHO_HIHO<B,Q>* Decoder_BCH::parameters ::build_hiho(const tools::BCH_polynomial_generator &GF, module::Encoder<B> *encoder) const { if (this->type == "ALGEBRAIC") { if (this->implem == "STD") return new module::Decoder_BCH_std<B,Q>(this->K, this->N_cw, GF, this->n_frames); if (encoder) { if (this->implem == "GENIUS") return new module::Decoder_BCH_genius<B,Q>(this->K, this->N_cw, this->t, *encoder, this->n_frames); } } throw tools::cannot_allocate(__FILE__, __LINE__, __func__); } template <typename B, typename Q> module::Decoder_SIHO_HIHO<B,Q>* Decoder_BCH ::build_hiho(const parameters &params, const tools::BCH_polynomial_generator &GF, module::Encoder<B> *encoder) { return params.template build_hiho<B,Q>(GF, encoder); } // ==================================================================================== explicit template instantiation #include "Tools/types.h" #ifdef MULTI_PREC template aff3ct::module::Decoder_SIHO<B_8 ,Q_8 >* aff3ct::factory::Decoder_BCH::parameters::build<B_8 ,Q_8 >(const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_8 >*) const; template aff3ct::module::Decoder_SIHO<B_16,Q_16>* aff3ct::factory::Decoder_BCH::parameters::build<B_16,Q_16>(const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_16>*) const; template aff3ct::module::Decoder_SIHO<B_32,Q_32>* aff3ct::factory::Decoder_BCH::parameters::build<B_32,Q_32>(const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_32>*) const; template aff3ct::module::Decoder_SIHO<B_64,Q_64>* aff3ct::factory::Decoder_BCH::parameters::build<B_64,Q_64>(const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_64>*) const; template aff3ct::module::Decoder_SIHO<B_8 ,Q_8 >* aff3ct::factory::Decoder_BCH::build<B_8 ,Q_8 >(const aff3ct::factory::Decoder_BCH::parameters&, const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_8 >*); template aff3ct::module::Decoder_SIHO<B_16,Q_16>* aff3ct::factory::Decoder_BCH::build<B_16,Q_16>(const aff3ct::factory::Decoder_BCH::parameters&, const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_16>*); template aff3ct::module::Decoder_SIHO<B_32,Q_32>* aff3ct::factory::Decoder_BCH::build<B_32,Q_32>(const aff3ct::factory::Decoder_BCH::parameters&, const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_32>*); template aff3ct::module::Decoder_SIHO<B_64,Q_64>* aff3ct::factory::Decoder_BCH::build<B_64,Q_64>(const aff3ct::factory::Decoder_BCH::parameters&, const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_64>*); #else template aff3ct::module::Decoder_SIHO<B,Q>* aff3ct::factory::Decoder_BCH::parameters::build<B,Q>(const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B>*) const; template aff3ct::module::Decoder_SIHO<B,Q>* aff3ct::factory::Decoder_BCH::build<B,Q>(const aff3ct::factory::Decoder_BCH::parameters&, const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B>*); #endif // ==================================================================================== explicit template instantiation // ==================================================================================== explicit template instantiation #include "Tools/types.h" #ifdef MULTI_PREC template aff3ct::module::Decoder_SIHO_HIHO<B_8 ,Q_8 >* aff3ct::factory::Decoder_BCH::parameters::build_hiho<B_8 ,Q_8 >(const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_8 >*) const; template aff3ct::module::Decoder_SIHO_HIHO<B_16,Q_16>* aff3ct::factory::Decoder_BCH::parameters::build_hiho<B_16,Q_16>(const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_16>*) const; template aff3ct::module::Decoder_SIHO_HIHO<B_32,Q_32>* aff3ct::factory::Decoder_BCH::parameters::build_hiho<B_32,Q_32>(const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_32>*) const; template aff3ct::module::Decoder_SIHO_HIHO<B_64,Q_64>* aff3ct::factory::Decoder_BCH::parameters::build_hiho<B_64,Q_64>(const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_64>*) const; template aff3ct::module::Decoder_SIHO_HIHO<B_8 ,Q_8 >* aff3ct::factory::Decoder_BCH::build_hiho<B_8 ,Q_8 >(const aff3ct::factory::Decoder_BCH::parameters&, const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_8 >*); template aff3ct::module::Decoder_SIHO_HIHO<B_16,Q_16>* aff3ct::factory::Decoder_BCH::build_hiho<B_16,Q_16>(const aff3ct::factory::Decoder_BCH::parameters&, const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_16>*); template aff3ct::module::Decoder_SIHO_HIHO<B_32,Q_32>* aff3ct::factory::Decoder_BCH::build_hiho<B_32,Q_32>(const aff3ct::factory::Decoder_BCH::parameters&, const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_32>*); template aff3ct::module::Decoder_SIHO_HIHO<B_64,Q_64>* aff3ct::factory::Decoder_BCH::build_hiho<B_64,Q_64>(const aff3ct::factory::Decoder_BCH::parameters&, const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B_64>*); #else template aff3ct::module::Decoder_SIHO_HIHO<B,Q>* aff3ct::factory::Decoder_BCH::parameters::build_hiho<B>(const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B>*) const; template aff3ct::module::Decoder_SIHO_HIHO<B,Q>* aff3ct::factory::Decoder_BCH::build_hiho<B>(const aff3ct::factory::Decoder_BCH::parameters&, const aff3ct::tools::BCH_polynomial_generator&, module::Encoder<B>*); #endif // ==================================================================================== explicit template instantiation <|endoftext|>
<commit_before>#include <errno.h> #include <netdb.h> #include <poll.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <linux/errqueue.h> #include <linux/icmp.h> #include <sys/socket.h> #include <sys/time.h> #include "udpping.h" namespace { bool getAddress(const QString &address, sockaddr_any *addr) { struct addrinfo hints; struct addrinfo *rp = NULL, *result = NULL; memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; if (getaddrinfo(address.toStdString().c_str(), NULL, &hints, &result)) { return false; } for (rp = result; rp && rp->ai_family != AF_INET && rp->ai_family != AF_INET6; rp = rp->ai_next) { } if (!rp) { rp = result; } memcpy(addr, rp->ai_addr, rp->ai_addrlen); freeaddrinfo(result); return true; } void randomizePayload(char *payload, const quint32 size) { char chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; for (quint32 i = 0; i < size; i++) { payload[i] = chars[qrand() % strlen(chars)]; } if (size > 15) { // ignore terminating null character strncpy(&payload[size - 15], " measure-it.net", 15); } } } UdpPing::UdpPing(QObject *parent) : Measurement(parent) , currentStatus(Unknown) , m_device(NULL) , m_capture(NULL) , m_destAddress() , m_payload(NULL) { } UdpPing::~UdpPing() { } Measurement::Status UdpPing::status() const { return currentStatus; } void UdpPing::setStatus(Status status) { if (currentStatus != status) { currentStatus = status; emit statusChanged(status); } } bool UdpPing::prepare(NetworkManager *networkManager, const MeasurementDefinitionPtr &measurementDefinition) { Q_UNUSED(networkManager); definition = measurementDefinition.dynamicCast<UdpPingDefinition>(); if (definition->payload > 65536) { emit error("payload is too large (> 65536)"); return false; } memset(&m_destAddress, 0, sizeof(m_destAddress)); // resolve if (!getAddress(definition->url, &m_destAddress)) { return false; } if (m_destAddress.sa.sa_family == AF_INET) { m_destAddress.sin.sin_port = htons(definition->destinationPort ? definition->destinationPort : 33434); } else if (m_destAddress.sa.sa_family == AF_INET6) { m_destAddress.sin6.sin6_port = htons(definition->destinationPort ? definition->destinationPort : 33434); } else { // unreachable return false; } return true; } bool UdpPing::start() { PingProbe probe; // include null-character m_payload = new char[definition->payload + 1]; if (m_payload == NULL) { return false; } memset(m_payload, 0, definition->payload + 1); setStartDateTime(QDateTime::currentDateTime()); setStatus(UdpPing::Running); memset(&probe, 0, sizeof(probe)); probe.sock = initSocket(); if (probe.sock < 0) { emit error("socket: " + QString(strerror(errno))); delete[] m_payload; return false; } for (quint32 i = 0; i < definition->count; i++) { ping(&probe); m_pingProbes.append(probe); } close(probe.sock); setStatus(UdpPing::Finished); delete[] m_payload; emit finished(); return true; } bool UdpPing::stop() { return true; } ResultPtr UdpPing::result() const { QVariantList res; foreach (const PingProbe &probe, m_pingProbes) { if (probe.sendTime > 0 && probe.recvTime > 0) { res << probe.recvTime - probe.sendTime; } } return ResultPtr(new Result(startDateTime(), QDateTime::currentDateTime(), res, QVariant())); } int UdpPing::initSocket() { int n = 0; int sock = 0; int ttl = definition->ttl ? definition->ttl : 64; sockaddr_any src_addr; memset(&src_addr, 0, sizeof(src_addr)); sock = socket(m_destAddress.sa.sa_family, SOCK_DGRAM, IPPROTO_UDP); if (sock < 0) { emit error("socket: " + QString(strerror(errno))); return -1; } src_addr.sa.sa_family = m_destAddress.sa.sa_family; if (m_destAddress.sa.sa_family == AF_INET) { src_addr.sin.sin_port = htons(definition->sourcePort); } else if (m_destAddress.sa.sa_family == AF_INET6) { src_addr.sin6.sin6_port = htons(definition->sourcePort); } else { // unreachable goto cleanup; } if (src_addr.sa.sa_family == AF_INET) { n = bind(sock, (struct sockaddr *) &src_addr, sizeof(src_addr.sin)); } else if (src_addr.sa.sa_family == AF_INET6) { n = bind(sock, (struct sockaddr *) &src_addr, sizeof(src_addr.sin6)); } if (n < 0) { emit error("bind: " + QString(strerror(errno))); goto cleanup; } n = 1; if (setsockopt(sock, SOL_SOCKET, SO_TIMESTAMP, &n, sizeof(n)) < 0) { emit error("setsockopt SOL_TIMESTAMP: " + QString(strerror(errno))); goto cleanup; } // set TTL if (setsockopt(sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl)) < 0) { emit error("setsockopt IP_TTL: " + QString(strerror(errno))); goto cleanup; } // use RECVRR n = 1; if (m_destAddress.sa.sa_family == AF_INET) { if (setsockopt(sock, SOL_IP, IP_RECVERR, &n, sizeof(n)) < 0) { emit error("setsockopt IP_RECVERR: " + QString(strerror(errno))); goto cleanup; } } else if (m_destAddress.sa.sa_family == AF_INET6) { if (setsockopt(sock, IPPROTO_IPV6, IPV6_RECVERR, &n, sizeof(n)) < 0) { emit error("setsockopt IPV6_RECVERR: " + QString(strerror(errno))); goto cleanup; } } else { // unreachable goto cleanup; } return sock; cleanup: close(sock); return -1; } bool UdpPing::sendData(PingProbe *probe) { int n = 0; struct timeval tv; memset(&tv, 0, sizeof(tv)); gettimeofday(&tv, NULL); probe->sendTime = tv.tv_sec * 1e6 + tv.tv_usec; // randomize payload to prevent caching randomizePayload(m_payload, definition->payload); if (m_destAddress.sa.sa_family == AF_INET) { n = sendto(probe->sock, m_payload, definition->payload, 0, (sockaddr *)&m_destAddress, sizeof(m_destAddress.sin)); } else if (m_destAddress.sa.sa_family == AF_INET6) { n = sendto(probe->sock, m_payload, definition->payload, 0, (sockaddr *)&m_destAddress, sizeof(m_destAddress.sin6)); } if (n < 0) { emit error("send: " + QString(strerror(errno))); return false; } return true; } void UdpPing::receiveData(PingProbe *probe) { struct msghdr msg; sockaddr_any from; struct iovec iov; char buf[1280]; char control[1024]; struct cmsghdr *cm; struct sock_extended_err *ee = NULL; memset(&msg, 0, sizeof(msg)); msg.msg_name = &from; msg.msg_namelen = sizeof(from); msg.msg_control = control; msg.msg_controllen = sizeof(control); iov.iov_base = buf; iov.iov_len = sizeof(buf); msg.msg_iov = &iov; msg.msg_iovlen = 1; // poll here struct pollfd pfd; memset(&pfd, 0, sizeof(pfd)); pfd.fd = probe->sock; pfd.events = POLLIN | POLLERR; if (poll(&pfd, 1, definition->receiveTimeout) < 0) { emit error("poll: " + QString(strerror(errno))); goto cleanup; } if (!pfd.revents) { emit timeout(*probe); goto cleanup; } if (recvmsg(probe->sock, &msg, MSG_ERRQUEUE) < 0) { emit error("recvmsg: " + QString(strerror(errno))); goto cleanup; } for (cm = CMSG_FIRSTHDR(&msg); cm; cm = CMSG_NXTHDR(&msg, cm)) { void *ptr = CMSG_DATA(cm); if (cm->cmsg_level == SOL_SOCKET) { if (cm->cmsg_type == SO_TIMESTAMP) { struct timeval *tv = (struct timeval *) ptr; probe->recvTime = tv->tv_sec * 1e6 + tv->tv_usec; } } else if (cm->cmsg_level == SOL_IP) { if (cm->cmsg_type == IP_RECVERR) { ee = (struct sock_extended_err *) ptr; if (ee->ee_origin != SO_EE_ORIGIN_ICMP) { ee = NULL; continue; } if (ee->ee_type == ICMP_SOURCE_QUENCH || ee->ee_type == ICMP_REDIRECT) { goto cleanup; } } } } if (ee) { memcpy(&probe->source, SO_EE_OFFENDER(ee), sizeof(probe->source)); if (ee->ee_type == ICMP_TIME_EXCEEDED && ee->ee_code == ICMP_EXC_TTL) { emit ttlExceeded(*probe); } else if (ee->ee_type == ICMP_DEST_UNREACH) { emit destinationUnreachable(*probe); } } cleanup: return; } void UdpPing::ping(PingProbe *probe) { // send if (sendData(probe)) { receiveData(probe); } } // vim: set sts=4 sw=4 et: <commit_msg>udpping: remove unreachable code<commit_after>#include <errno.h> #include <netdb.h> #include <poll.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <linux/errqueue.h> #include <linux/icmp.h> #include <sys/socket.h> #include <sys/time.h> #include "udpping.h" namespace { bool getAddress(const QString &address, sockaddr_any *addr) { struct addrinfo hints; struct addrinfo *rp = NULL, *result = NULL; memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; if (getaddrinfo(address.toStdString().c_str(), NULL, &hints, &result)) { return false; } for (rp = result; rp && rp->ai_family != AF_INET && rp->ai_family != AF_INET6; rp = rp->ai_next) { } if (!rp) { freeaddrinfo(result); return false; } memcpy(addr, rp->ai_addr, rp->ai_addrlen); freeaddrinfo(result); return true; } void randomizePayload(char *payload, const quint32 size) { char chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; for (quint32 i = 0; i < size; i++) { payload[i] = chars[qrand() % strlen(chars)]; } if (size > 15) { // ignore terminating null character strncpy(&payload[size - 15], " measure-it.net", 15); } } } UdpPing::UdpPing(QObject *parent) : Measurement(parent) , currentStatus(Unknown) , m_device(NULL) , m_capture(NULL) , m_destAddress() , m_payload(NULL) { } UdpPing::~UdpPing() { } Measurement::Status UdpPing::status() const { return currentStatus; } void UdpPing::setStatus(Status status) { if (currentStatus != status) { currentStatus = status; emit statusChanged(status); } } bool UdpPing::prepare(NetworkManager *networkManager, const MeasurementDefinitionPtr &measurementDefinition) { Q_UNUSED(networkManager); definition = measurementDefinition.dynamicCast<UdpPingDefinition>(); if (definition->payload > 65536) { emit error("payload is too large (> 65536)"); return false; } memset(&m_destAddress, 0, sizeof(m_destAddress)); // resolve if (!getAddress(definition->url, &m_destAddress)) { return false; } if (m_destAddress.sa.sa_family == AF_INET) { m_destAddress.sin.sin_port = htons(definition->destinationPort ? definition->destinationPort : 33434); } else if (m_destAddress.sa.sa_family == AF_INET6) { m_destAddress.sin6.sin6_port = htons(definition->destinationPort ? definition->destinationPort : 33434); } return true; } bool UdpPing::start() { PingProbe probe; // include null-character m_payload = new char[definition->payload + 1]; if (m_payload == NULL) { return false; } memset(m_payload, 0, definition->payload + 1); setStartDateTime(QDateTime::currentDateTime()); setStatus(UdpPing::Running); memset(&probe, 0, sizeof(probe)); probe.sock = initSocket(); if (probe.sock < 0) { emit error("socket: " + QString(strerror(errno))); delete[] m_payload; return false; } for (quint32 i = 0; i < definition->count; i++) { ping(&probe); m_pingProbes.append(probe); } close(probe.sock); setStatus(UdpPing::Finished); delete[] m_payload; emit finished(); return true; } bool UdpPing::stop() { return true; } ResultPtr UdpPing::result() const { QVariantList res; foreach (const PingProbe &probe, m_pingProbes) { if (probe.sendTime > 0 && probe.recvTime > 0) { res << probe.recvTime - probe.sendTime; } } return ResultPtr(new Result(startDateTime(), QDateTime::currentDateTime(), res, QVariant())); } int UdpPing::initSocket() { int n = 0; int sock = 0; int ttl = definition->ttl ? definition->ttl : 64; sockaddr_any src_addr; memset(&src_addr, 0, sizeof(src_addr)); sock = socket(m_destAddress.sa.sa_family, SOCK_DGRAM, IPPROTO_UDP); if (sock < 0) { emit error("socket: " + QString(strerror(errno))); return -1; } src_addr.sa.sa_family = m_destAddress.sa.sa_family; if (m_destAddress.sa.sa_family == AF_INET) { src_addr.sin.sin_port = htons(definition->sourcePort); } else if (m_destAddress.sa.sa_family == AF_INET6) { src_addr.sin6.sin6_port = htons(definition->sourcePort); } if (src_addr.sa.sa_family == AF_INET) { n = bind(sock, (struct sockaddr *) &src_addr, sizeof(src_addr.sin)); } else if (src_addr.sa.sa_family == AF_INET6) { n = bind(sock, (struct sockaddr *) &src_addr, sizeof(src_addr.sin6)); } if (n < 0) { emit error("bind: " + QString(strerror(errno))); goto cleanup; } n = 1; if (setsockopt(sock, SOL_SOCKET, SO_TIMESTAMP, &n, sizeof(n)) < 0) { emit error("setsockopt SOL_TIMESTAMP: " + QString(strerror(errno))); goto cleanup; } // set TTL if (setsockopt(sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl)) < 0) { emit error("setsockopt IP_TTL: " + QString(strerror(errno))); goto cleanup; } // use RECVRR n = 1; if (m_destAddress.sa.sa_family == AF_INET) { if (setsockopt(sock, SOL_IP, IP_RECVERR, &n, sizeof(n)) < 0) { emit error("setsockopt IP_RECVERR: " + QString(strerror(errno))); goto cleanup; } } else if (m_destAddress.sa.sa_family == AF_INET6) { if (setsockopt(sock, IPPROTO_IPV6, IPV6_RECVERR, &n, sizeof(n)) < 0) { emit error("setsockopt IPV6_RECVERR: " + QString(strerror(errno))); goto cleanup; } } return sock; cleanup: close(sock); return -1; } bool UdpPing::sendData(PingProbe *probe) { int n = 0; struct timeval tv; memset(&tv, 0, sizeof(tv)); gettimeofday(&tv, NULL); probe->sendTime = tv.tv_sec * 1e6 + tv.tv_usec; // randomize payload to prevent caching randomizePayload(m_payload, definition->payload); if (m_destAddress.sa.sa_family == AF_INET) { n = sendto(probe->sock, m_payload, definition->payload, 0, (sockaddr *)&m_destAddress, sizeof(m_destAddress.sin)); } else if (m_destAddress.sa.sa_family == AF_INET6) { n = sendto(probe->sock, m_payload, definition->payload, 0, (sockaddr *)&m_destAddress, sizeof(m_destAddress.sin6)); } if (n < 0) { emit error("send: " + QString(strerror(errno))); return false; } return true; } void UdpPing::receiveData(PingProbe *probe) { struct msghdr msg; sockaddr_any from; struct iovec iov; char buf[1280]; char control[1024]; struct cmsghdr *cm; struct sock_extended_err *ee = NULL; memset(&msg, 0, sizeof(msg)); msg.msg_name = &from; msg.msg_namelen = sizeof(from); msg.msg_control = control; msg.msg_controllen = sizeof(control); iov.iov_base = buf; iov.iov_len = sizeof(buf); msg.msg_iov = &iov; msg.msg_iovlen = 1; // poll here struct pollfd pfd; memset(&pfd, 0, sizeof(pfd)); pfd.fd = probe->sock; pfd.events = POLLIN | POLLERR; if (poll(&pfd, 1, definition->receiveTimeout) < 0) { emit error("poll: " + QString(strerror(errno))); goto cleanup; } if (!pfd.revents) { emit timeout(*probe); goto cleanup; } if (recvmsg(probe->sock, &msg, MSG_ERRQUEUE) < 0) { emit error("recvmsg: " + QString(strerror(errno))); goto cleanup; } for (cm = CMSG_FIRSTHDR(&msg); cm; cm = CMSG_NXTHDR(&msg, cm)) { void *ptr = CMSG_DATA(cm); if (cm->cmsg_level == SOL_SOCKET) { if (cm->cmsg_type == SO_TIMESTAMP) { struct timeval *tv = (struct timeval *) ptr; probe->recvTime = tv->tv_sec * 1e6 + tv->tv_usec; } } else if (cm->cmsg_level == SOL_IP) { if (cm->cmsg_type == IP_RECVERR) { ee = (struct sock_extended_err *) ptr; if (ee->ee_origin != SO_EE_ORIGIN_ICMP) { ee = NULL; continue; } if (ee->ee_type == ICMP_SOURCE_QUENCH || ee->ee_type == ICMP_REDIRECT) { goto cleanup; } } } } if (ee) { memcpy(&probe->source, SO_EE_OFFENDER(ee), sizeof(probe->source)); if (ee->ee_type == ICMP_TIME_EXCEEDED && ee->ee_code == ICMP_EXC_TTL) { emit ttlExceeded(*probe); } else if (ee->ee_type == ICMP_DEST_UNREACH) { emit destinationUnreachable(*probe); } } cleanup: return; } void UdpPing::ping(PingProbe *probe) { // send if (sendData(probe)) { receiveData(probe); } } // vim: set sts=4 sw=4 et: <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2017, Image Engine Design Inc. 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 John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "ContextAlgoBinding.h" #include "GafferSceneUI/ContextAlgo.h" #include "GafferScene/ScenePlug.h" #include "IECorePython/ScopedGILRelease.h" using namespace boost::python; using namespace IECore; using namespace Gaffer; using namespace GafferScene; using namespace GafferSceneUI::ContextAlgo; namespace { PathMatcher expandDescendantsWrapper( Context &context, PathMatcher &paths, ScenePlug &scene, int depth ) { IECorePython::ScopedGILRelease gilRelease; return expandDescendants( &context, paths, &scene, depth ); } } // namespace void GafferSceneUIModule::bindContextAlgo() { object module( borrowed( PyImport_AddModule( "GafferSceneUI.ContextAlgo" ) ) ); scope().attr( "ContextAlgo" ) = module; scope moduleScope( module ); def( "setExpandedPaths", &setExpandedPaths ); def( "getExpandedPaths", &getExpandedPaths ); def( "affectsExpandedPaths", &affectsExpandedPaths ); def( "expand", &expand, ( arg( "expandAncestors" ) = true ) ); def( "expandDescendants", &expandDescendantsWrapper, ( arg( "context" ), arg( "paths" ), arg( "scene" ), arg( "depth" ) = Imath::limits<int>::max() ) ); def( "clearExpansion", &clearExpansion ); def( "setSelectedPaths", &setSelectedPaths ); def( "getSelectedPaths", &getSelectedPaths ); def( "affectsSelectedPaths", &affectsSelectedPaths ); } <commit_msg>GafferSceneUI::ContextAlgo bindings : Fix GIL management<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2017, Image Engine Design Inc. 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 John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" #include "ContextAlgoBinding.h" #include "GafferSceneUI/ContextAlgo.h" #include "GafferScene/ScenePlug.h" #include "IECorePython/ScopedGILRelease.h" using namespace boost::python; using namespace IECore; using namespace Gaffer; using namespace GafferScene; using namespace GafferSceneUI::ContextAlgo; namespace { void setExpandedPathsWrapper( Context &context, const IECore::PathMatcher &paths ) { IECorePython::ScopedGILRelease gilRelease; setExpandedPaths( &context, paths ); } void expandWrapper( Context &context, const IECore::PathMatcher &paths, bool expandAncestors ) { IECorePython::ScopedGILRelease gilRelease; expand( &context, paths, expandAncestors ); } PathMatcher expandDescendantsWrapper( Context &context, PathMatcher &paths, ScenePlug &scene, int depth ) { IECorePython::ScopedGILRelease gilRelease; return expandDescendants( &context, paths, &scene, depth ); } void clearExpansionWrapper( Context &context ) { IECorePython::ScopedGILRelease gilRelease; clearExpansion( &context ); } void setSelectedPathsWrapper( Context &context, const IECore::PathMatcher &paths ) { IECorePython::ScopedGILRelease gilRelease; setSelectedPaths( &context, paths ); } } // namespace void GafferSceneUIModule::bindContextAlgo() { object module( borrowed( PyImport_AddModule( "GafferSceneUI.ContextAlgo" ) ) ); scope().attr( "ContextAlgo" ) = module; scope moduleScope( module ); def( "setExpandedPaths", &setExpandedPathsWrapper ); def( "getExpandedPaths", &getExpandedPaths ); def( "affectsExpandedPaths", &affectsExpandedPaths ); def( "expand", &expandWrapper, ( arg( "expandAncestors" ) = true ) ); def( "expandDescendants", &expandDescendantsWrapper, ( arg( "context" ), arg( "paths" ), arg( "scene" ), arg( "depth" ) = Imath::limits<int>::max() ) ); def( "clearExpansion", &clearExpansionWrapper ); def( "setSelectedPaths", &setSelectedPathsWrapper ); def( "getSelectedPaths", &getSelectedPaths ); def( "affectsSelectedPaths", &affectsSelectedPaths ); } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. * */ #include "webrtc/modules/video_coding/codecs/vp9/vp9_frame_buffer_pool.h" #include "vpx/vpx_codec.h" #include "vpx/vpx_decoder.h" #include "vpx/vpx_frame_buffer.h" #include "webrtc/base/checks.h" #include "webrtc/base/logging.h" namespace webrtc { uint8_t* Vp9FrameBufferPool::Vp9FrameBuffer::GetData() { return data_.data<uint8_t>(); } size_t Vp9FrameBufferPool::Vp9FrameBuffer::GetDataSize() const { return data_.size(); } void Vp9FrameBufferPool::Vp9FrameBuffer::SetSize(size_t size) { data_.SetSize(size); } bool Vp9FrameBufferPool::InitializeVpxUsePool( vpx_codec_ctx* vpx_codec_context) { RTC_DCHECK(vpx_codec_context); // Tell libvpx to use this pool. if (vpx_codec_set_frame_buffer_functions( // In which context to use these callback functions. vpx_codec_context, // Called by libvpx when it needs another frame buffer. &Vp9FrameBufferPool::VpxGetFrameBuffer, // Called by libvpx when it no longer uses a frame buffer. &Vp9FrameBufferPool::VpxReleaseFrameBuffer, // |this| will be passed as |user_priv| to VpxGetFrameBuffer. this)) { // Failed to configure libvpx to use Vp9FrameBufferPool. return false; } return true; } rtc::scoped_refptr<Vp9FrameBufferPool::Vp9FrameBuffer> Vp9FrameBufferPool::GetFrameBuffer(size_t min_size) { RTC_DCHECK_GT(min_size, 0); rtc::scoped_refptr<Vp9FrameBuffer> available_buffer = nullptr; { rtc::CritScope cs(&buffers_lock_); // Do we have a buffer we can recycle? for (const auto& buffer : allocated_buffers_) { if (buffer->HasOneRef()) { available_buffer = buffer; break; } } // Otherwise create one. if (available_buffer == nullptr) { available_buffer = new rtc::RefCountedObject<Vp9FrameBuffer>(); allocated_buffers_.push_back(available_buffer); if (allocated_buffers_.size() > max_num_buffers_) { LOG(LS_WARNING) << allocated_buffers_.size() << " Vp9FrameBuffers have been " << "allocated by a Vp9FrameBufferPool (exceeding what is " << "considered reasonable, " << max_num_buffers_ << ")."; RTC_NOTREACHED(); } } } available_buffer->SetSize(min_size); return available_buffer; } int Vp9FrameBufferPool::GetNumBuffersInUse() const { int num_buffers_in_use = 0; rtc::CritScope cs(&buffers_lock_); for (const auto& buffer : allocated_buffers_) { if (!buffer->HasOneRef()) ++num_buffers_in_use; } return num_buffers_in_use; } void Vp9FrameBufferPool::ClearPool() { rtc::CritScope cs(&buffers_lock_); allocated_buffers_.clear(); } // static int32_t Vp9FrameBufferPool::VpxGetFrameBuffer(void* user_priv, size_t min_size, vpx_codec_frame_buffer* fb) { RTC_DCHECK(user_priv); RTC_DCHECK(fb); Vp9FrameBufferPool* pool = static_cast<Vp9FrameBufferPool*>(user_priv); rtc::scoped_refptr<Vp9FrameBuffer> buffer = pool->GetFrameBuffer(min_size); fb->data = buffer->GetData(); fb->size = buffer->GetDataSize(); // Store Vp9FrameBuffer* in |priv| for use in VpxReleaseFrameBuffer. // This also makes vpx_codec_get_frame return images with their |fb_priv| set // to |buffer| which is important for external reference counting. // Release from refptr so that the buffer's |ref_count_| remains 1 when // |buffer| goes out of scope. fb->priv = static_cast<void*>(buffer.release()); return 0; } // static int32_t Vp9FrameBufferPool::VpxReleaseFrameBuffer(void* user_priv, vpx_codec_frame_buffer* fb) { RTC_DCHECK(user_priv); RTC_DCHECK(fb); Vp9FrameBuffer* buffer = static_cast<Vp9FrameBuffer*>(fb->priv); if (buffer != nullptr) { buffer->Release(); // When libvpx fails to decode and you continue to try to decode (and fail) // libvpx can for some reason try to release the same buffer multiple times. // Setting |priv| to null protects against trying to Release multiple times. fb->priv = nullptr; } return 0; } } // namespace webrtc <commit_msg>Reland of Disabling NOTREACHED which we're hitting flakily in browser tests. (patchset #1 id:1 of https://codereview.webrtc.org/2585183002/ )<commit_after>/* * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. * */ #include "webrtc/modules/video_coding/codecs/vp9/vp9_frame_buffer_pool.h" #include "vpx/vpx_codec.h" #include "vpx/vpx_decoder.h" #include "vpx/vpx_frame_buffer.h" #include "webrtc/base/checks.h" #include "webrtc/base/logging.h" namespace webrtc { uint8_t* Vp9FrameBufferPool::Vp9FrameBuffer::GetData() { return data_.data<uint8_t>(); } size_t Vp9FrameBufferPool::Vp9FrameBuffer::GetDataSize() const { return data_.size(); } void Vp9FrameBufferPool::Vp9FrameBuffer::SetSize(size_t size) { data_.SetSize(size); } bool Vp9FrameBufferPool::InitializeVpxUsePool( vpx_codec_ctx* vpx_codec_context) { RTC_DCHECK(vpx_codec_context); // Tell libvpx to use this pool. if (vpx_codec_set_frame_buffer_functions( // In which context to use these callback functions. vpx_codec_context, // Called by libvpx when it needs another frame buffer. &Vp9FrameBufferPool::VpxGetFrameBuffer, // Called by libvpx when it no longer uses a frame buffer. &Vp9FrameBufferPool::VpxReleaseFrameBuffer, // |this| will be passed as |user_priv| to VpxGetFrameBuffer. this)) { // Failed to configure libvpx to use Vp9FrameBufferPool. return false; } return true; } rtc::scoped_refptr<Vp9FrameBufferPool::Vp9FrameBuffer> Vp9FrameBufferPool::GetFrameBuffer(size_t min_size) { RTC_DCHECK_GT(min_size, 0); rtc::scoped_refptr<Vp9FrameBuffer> available_buffer = nullptr; { rtc::CritScope cs(&buffers_lock_); // Do we have a buffer we can recycle? for (const auto& buffer : allocated_buffers_) { if (buffer->HasOneRef()) { available_buffer = buffer; break; } } // Otherwise create one. if (available_buffer == nullptr) { available_buffer = new rtc::RefCountedObject<Vp9FrameBuffer>(); allocated_buffers_.push_back(available_buffer); if (allocated_buffers_.size() > max_num_buffers_) { LOG(LS_WARNING) << allocated_buffers_.size() << " Vp9FrameBuffers have been " << "allocated by a Vp9FrameBufferPool (exceeding what is " << "considered reasonable, " << max_num_buffers_ << ")."; // TODO(phoglund): this limit is being hit in tests since Oct 5 2016. // See https://bugs.chromium.org/p/webrtc/issues/detail?id=6484. // RTC_NOTREACHED(); } } } available_buffer->SetSize(min_size); return available_buffer; } int Vp9FrameBufferPool::GetNumBuffersInUse() const { int num_buffers_in_use = 0; rtc::CritScope cs(&buffers_lock_); for (const auto& buffer : allocated_buffers_) { if (!buffer->HasOneRef()) ++num_buffers_in_use; } return num_buffers_in_use; } void Vp9FrameBufferPool::ClearPool() { rtc::CritScope cs(&buffers_lock_); allocated_buffers_.clear(); } // static int32_t Vp9FrameBufferPool::VpxGetFrameBuffer(void* user_priv, size_t min_size, vpx_codec_frame_buffer* fb) { RTC_DCHECK(user_priv); RTC_DCHECK(fb); Vp9FrameBufferPool* pool = static_cast<Vp9FrameBufferPool*>(user_priv); rtc::scoped_refptr<Vp9FrameBuffer> buffer = pool->GetFrameBuffer(min_size); fb->data = buffer->GetData(); fb->size = buffer->GetDataSize(); // Store Vp9FrameBuffer* in |priv| for use in VpxReleaseFrameBuffer. // This also makes vpx_codec_get_frame return images with their |fb_priv| set // to |buffer| which is important for external reference counting. // Release from refptr so that the buffer's |ref_count_| remains 1 when // |buffer| goes out of scope. fb->priv = static_cast<void*>(buffer.release()); return 0; } // static int32_t Vp9FrameBufferPool::VpxReleaseFrameBuffer(void* user_priv, vpx_codec_frame_buffer* fb) { RTC_DCHECK(user_priv); RTC_DCHECK(fb); Vp9FrameBuffer* buffer = static_cast<Vp9FrameBuffer*>(fb->priv); if (buffer != nullptr) { buffer->Release(); // When libvpx fails to decode and you continue to try to decode (and fail) // libvpx can for some reason try to release the same buffer multiple times. // Setting |priv| to null protects against trying to Release multiple times. fb->priv = nullptr; } return 0; } } // namespace webrtc <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <graphene/protocol/config.hpp> #include <graphene/protocol/pts_address.hpp> #include <fc/array.hpp> #include <fc/crypto/ripemd160.hpp> namespace fc { namespace ecc { class public_key; typedef fc::array<char,33> public_key_data; } } // fc::ecc namespace graphene { namespace protocol { struct public_key_type; /** * @brief a 160 bit hash of a public key * * An address can be converted to or from a base58 string with 32 bit checksum. * * An address is calculated as ripemd160( sha512( compressed_ecc_public_key ) ) * * When converted to a string, checksum calculated as the first 4 bytes ripemd160( address ) is * appended to the binary address before converting to base58. */ class address { public: address(); ///< constructs empty / null address explicit address( const std::string& base58str ); ///< converts to binary, validates checksum address( const fc::ecc::public_key& pub ); ///< converts to binary explicit address( const fc::ecc::public_key_data& pub ); ///< converts to binary address( const pts_address& pub ); ///< converts to binary address( const public_key_type& pubkey ); static bool is_valid( const std::string& base58str, const std::string& prefix = GRAPHENE_ADDRESS_PREFIX ); explicit operator std::string()const; ///< converts to base58 + checksum friend size_t hash_value( const address& v ) { const void* tmp = static_cast<const void*>(v.addr._hash+2); const size_t* tmp2 = reinterpret_cast<const size_t*>(tmp); return *tmp2; } fc::ripemd160 addr; }; inline bool operator == ( const address& a, const address& b ) { return a.addr == b.addr; } inline bool operator != ( const address& a, const address& b ) { return a.addr != b.addr; } inline bool operator < ( const address& a, const address& b ) { return a.addr < b.addr; } } } // namespace graphene::protocol namespace fc { void to_variant( const graphene::protocol::address& var, fc::variant& vo, uint32_t max_depth = 1 ); void from_variant( const fc::variant& var, graphene::protocol::address& vo, uint32_t max_depth = 1 ); } namespace std { template<> struct hash<graphene::protocol::address> { public: size_t operator()(const graphene::protocol::address &a) const { return (uint64_t(a.addr._hash[0])<<32) | uint64_t( a.addr._hash[0] ); } }; } #include <fc/reflect/reflect.hpp> FC_REFLECT( graphene::protocol::address, (addr) ) <commit_msg>Removed unused hash methods<commit_after>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <graphene/protocol/config.hpp> #include <graphene/protocol/pts_address.hpp> #include <fc/array.hpp> #include <fc/crypto/ripemd160.hpp> namespace fc { namespace ecc { class public_key; typedef fc::array<char,33> public_key_data; } } // fc::ecc namespace graphene { namespace protocol { struct public_key_type; /** * @brief a 160 bit hash of a public key * * An address can be converted to or from a base58 string with 32 bit checksum. * * An address is calculated as ripemd160( sha512( compressed_ecc_public_key ) ) * * When converted to a string, checksum calculated as the first 4 bytes ripemd160( address ) is * appended to the binary address before converting to base58. */ class address { public: address(); ///< constructs empty / null address explicit address( const std::string& base58str ); ///< converts to binary, validates checksum address( const fc::ecc::public_key& pub ); ///< converts to binary explicit address( const fc::ecc::public_key_data& pub ); ///< converts to binary address( const pts_address& pub ); ///< converts to binary address( const public_key_type& pubkey ); static bool is_valid( const std::string& base58str, const std::string& prefix = GRAPHENE_ADDRESS_PREFIX ); explicit operator std::string()const; ///< converts to base58 + checksum fc::ripemd160 addr; }; inline bool operator == ( const address& a, const address& b ) { return a.addr == b.addr; } inline bool operator != ( const address& a, const address& b ) { return a.addr != b.addr; } inline bool operator < ( const address& a, const address& b ) { return a.addr < b.addr; } } } // namespace graphene::protocol namespace fc { void to_variant( const graphene::protocol::address& var, fc::variant& vo, uint32_t max_depth = 1 ); void from_variant( const fc::variant& var, graphene::protocol::address& vo, uint32_t max_depth = 1 ); } #include <fc/reflect/reflect.hpp> FC_REFLECT( graphene::protocol::address, (addr) ) <|endoftext|>
<commit_before>#include <algorithm> #include <map> #include <string> #include <vector> #include "allocore/system/al_Config.h" #include "allocore/graphics/al_Mesh.hpp" #include "allocore/graphics/al_Graphics.hpp" namespace al{ Mesh& Mesh::reset() { vertices().reset(); normals().reset(); colors().reset(); coloris().reset(); texCoord2s().reset(); texCoord3s().reset(); indices().reset(); return *this; } void Mesh::decompress(){ int Ni = indices().size(); if(Ni){ #define DECOMPRESS(buf, Type)\ {\ int N = buf.size();\ if(N){\ std::vector<Type> old(N);\ std::copy(&buf[0], (&buf[0]) + N, old.begin());\ buf.size(Ni);\ for(int i=0; i<Ni; ++i) buf[i] = old[indices()[i]];\ }\ } DECOMPRESS(vertices(), Vertex) DECOMPRESS(colors(), Color) DECOMPRESS(coloris(), Color) DECOMPRESS(normals(), Normal) DECOMPRESS(texCoord2s(), TexCoord2) DECOMPRESS(texCoord3s(), TexCoord3) #undef DECOMPRESS indices().reset(); } } void Mesh::equalizeBuffers() { const int Nv = vertices().size(); const int Nn = normals().size(); const int Nc = colors().size(); const int Nci= coloris().size(); const int Nt2= texCoord2s().size(); const int Nt3= texCoord3s().size(); if(Nn){ for(int i=Nn; i<Nv; ++i){ normals().append(normals()[Nn-1]); } } if(Nc){ for(int i=Nc; i<Nv; ++i){ colors().append(colors()[Nc-1]); } } else if(Nci){ for(int i=Nci; i<Nv; ++i){ coloris().append(coloris()[Nci-1]); } } if(Nt2){ for(int i=Nt2; i<Nv; ++i){ texCoord2s().append(texCoord2s()[Nt2-1]); } } if(Nt3){ for(int i=Nt3; i<Nv; ++i){ texCoord3s().append(texCoord3s()[Nt3-1]); } } } class TriFace { public: Mesh::Vertex vertices[3]; Vec3f norm; TriFace(const TriFace& cpy) : norm(cpy.norm) { vertices[0] = cpy.vertices[0]; vertices[1] = cpy.vertices[1]; vertices[2] = cpy.vertices[2]; } TriFace(Mesh::Vertex p0, Mesh::Vertex p1, Mesh::Vertex p2) { vertices[0] = p0; vertices[1] = p1; vertices[2] = p2; // calculate norm for this face: normal<float>(norm, p0, p1, p2); } }; void Mesh::createNormalsMesh(Mesh& mesh, float length, bool perFace) { if (perFace) { // compute vertex based normals if(indices().size()){ mesh.reset(); mesh.primitive(Graphics::LINES); int Ni = indices().size(); Ni = Ni - (Ni%3); // must be multiple of 3 for(int i=0; i<Ni; i+=3){ Index i1 = indices()[i+0]; Index i2 = indices()[i+1]; Index i3 = indices()[i+2]; const Vertex& v1 = vertices()[i1]; const Vertex& v2 = vertices()[i2]; const Vertex& v3 = vertices()[i3]; // get mean: const Vertex& mean = (v1 + v2 + v3)/3.f; // get face normal: Vertex facenormal = cross(v2-v1, v3-v1); facenormal.normalize(); mesh.vertex(mean); mesh.vertex(mean + (facenormal*length)); } } else { printf("createNormalsMesh only valid for indexed meshes\n"); } } else { mesh.reset(); mesh.primitive(Graphics::LINES); int Ni = al::min(vertices().size(), normals().size()); for(int i=0; i<Ni; i+=3){ const Vertex& v = vertices()[i]; mesh.vertex(v); mesh.vertex(v + normals()[i]*length); } } } void Mesh::invertNormals() { int Nv = normals().size(); for(int i=0; i<Nv; ++i) normals()[i] = -normals()[i]; } // Old non-functional prototype... // // generates smoothed normals for a set of vertices // // will replace any normals currently in use // // angle - maximum angle (in degrees) to smooth across // void generateNormals(float angle=360); void Mesh::generateNormals(bool normalize, bool equalWeightPerFace) { // /* // Multi-pass algorithm: // generate a list of faces (assume triangles?) // (vary according to whether mIndices is used) // calculate normal per face (use normal<float>(dst, p0, p1, p2)) // vertices may be used in multiple faces; their norm should be an average of the uses // easy enough if indices is being used; not so easy otherwise. // create a lookup table by hashing on vertex x,y,z // // // write avg into corresponding normals for each vertex // EXCEPT: if edge is sharper than @angle, just use the face normal directly // */ // std::vector<TriFace> faces; // // std::map<std::string, int> vertexHash; // // int Ni = indices().size(); // int Nv = vertices().size(); // if (Ni) { // for (int i=0; i<Ni;) { // TriFace face( // mVertices[mIndices[i++]], // mVertices[mIndices[i++]], // mVertices[mIndices[i++]] // ); // faces.push_back(face); // } // } else { // for (int i=0; i<Nv;) { // TriFace face( // mVertices[i++], // mVertices[i++], // mVertices[i++] // ); // faces.push_back(face); // } // } int Nv = vertices().size(); // same number of normals as vertices normals().size(Nv); // compute vertex based normals if(indices().size()){ for(int i=0; i<Nv; ++i) normals()[i].set(0,0,0); int Ni = indices().size(); // if(primitive() == TRIANGLES){ Ni = Ni - (Ni%3); // must be multiple of 3 for(int i=0; i<Ni; i+=3){ Index i1 = indices()[i+0]; Index i2 = indices()[i+1]; Index i3 = indices()[i+2]; const Vertex& v1 = vertices()[i1]; const Vertex& v2 = vertices()[i2]; const Vertex& v3 = vertices()[i3]; // MWAAT (mean weighted by areas of adjacent triangles) Vertex vn = cross(v2-v1, v3-v1); // MWE (mean weighted equally) if (equalWeightPerFace) vn.normalize(); // MWA (mean weighted by angle) // This doesn't work well with dynamic marching cubes- normals // pop in and out for small triangles. // Vertex v12= v2-v1; // Vertex v13= v3-v1; // Vertex vn = cross(v12, v13).normalize(); // vn *= angle(v12, v13) / M_PI; normals()[i1] += vn; normals()[i2] += vn; normals()[i3] += vn; } // } // else if(primitive() == TRIANGLE_STRIP){ // for(int i=2; i<Ni; ++i){ // Index i1 = indices()[i-2]; // Index i2 = indices()[i-1]; // Index i3 = indices()[i-0]; // const Vertex& v1 = vertices()[i1]; // const Vertex& v2 = vertices()[i2]; // const Vertex& v3 = vertices()[i3]; // // Vertex vn = cross(v2-v1, v3-v1); // // normals()[i1] += vn; // normals()[i2] += vn; // normals()[i3] += vn; // } // } // normalize the normals if(normalize) for(int i=0; i<Nv; ++i) normals()[i].normalize(); } // compute face based normals else{ // if(primitive() == TRIANGLES){ int N = Nv - (Nv % 3); for(int i=0; i<N; i+=3){ int i1 = i+0; int i2 = i+1; int i3 = i+2; const Vertex& v1 = vertices()[i1]; const Vertex& v2 = vertices()[i2]; const Vertex& v3 = vertices()[i3]; Vertex vn = cross(v2-v1, v3-v1); if(normalize) vn.normalize(); normals()[i1] = vn; normals()[i2] = vn; normals()[i3] = vn; } // } } } void Mesh::ribbonize(float * widths, int widthsStride, bool faceBitangent){ const int N = mVertices.size(); if(0 == N) return; mVertices.size(N*2); mNormals.size(N*2); // Store last vertex since it will be overwritten eventually Vertex last = mVertices[N-1]; int in = faceBitangent ? 2 : 1; int ib = faceBitangent ? 1 : 2; for(int i=N-1; i>=0; --i){ int i1 = i; int i0 = i1-1; if(i0< 0) i0+=N; int i2 = i1+1; if(i2>=N) i2-=N; const Vertex& v0 = (i0==(N-1)) ? last : mVertices[i0]; const Vertex& v1 = mVertices[i1]; const Vertex& v2 = mVertices[i2]; // compute Frenet frame Vertex f[3]; // T,N,B { const Vertex d1 = (v0 - v2)*0.5; const Vertex d2 = (d1 - v1)*2.0; //Vertex& t = f[0]; Vertex& n = f[1]; Vertex& b = f[2]; b = cross(d2, d1).sgn(); n = cross(d1, b).sgn(); //t = d1.sgn(); // not used } f[ib] *= widths[i0*widthsStride]; int i12 = i1<<1; mVertices[i12 ] = v1-f[ib]; mVertices[i12+1] = v1+f[ib]; mNormals [i12 ].set(f[in][0], f[in][1], f[in][2]); mNormals [i12+1] = mNormals[i12]; } if(mColors.size()) mColors.expand<2,true>(); if(mColoris.size()) mColoris.expand<2,true>(); } void Mesh::merge(const Mesh& src){ // if (indices().size() || src.indices().size()) { // printf("error: Mesh merging with indexed meshes not yet supported\n"); // return; // } // TODO: only do merge if source and dest are well-formed // TODO: what to do when mixing float and integer colors? promote or demote? // TODO: indices are more complex, since the offsets may have changed. // we'd have to add indices.size() to all of the src.indices before adding. // also, both src & dst should either use or not use indices // tricky if src is empty... //indices().append(src.indices()); // Source has indices, and I either do or don't. // After this block, I will have indices. if(src.indices().size()){ Index Nv = vertices().size(); Index Ni = indices().size(); // If no indices, must create if(0 == Ni){ for(Index i=0; i<Nv; ++i) index(i); } // Add source indices offset by my number of vertices index(src.indices().elems(), src.indices().size(), (unsigned int)Nv); } // Source doesn't have indices, but I do else if(indices().size()){ int Nv = vertices().size(); for(int i=Nv; i<Nv+src.vertices().size(); ++i) index(i); } // From here, the game is indice invariant //equalizeBuffers(); << TODO: must do this if we are using indices. vertices().append(src.vertices()); normals().append(src.normals()); colors().append(src.colors()); texCoord2s().append(src.texCoord2s()); texCoord3s().append(src.texCoord3s()); } void Mesh::getBounds(Vertex& min, Vertex& max) const { if(vertices().size()){ min.set(vertices()[0]); max.set(min); for(int v=1; v<vertices().size(); ++v){ const Vertex& vt = vertices()[v]; for(int i=0; i<3; ++i){ min[i] = AL_MIN(min[i], vt[i]); max[i] = AL_MAX(max[i], vt[i]); } } } } Mesh::Vertex Mesh::getCenter() const { Vertex min(0), max(0); getBounds(min, max); return min+(max-min)*0.5; } void Mesh::unitize() { Vertex min(0), max(0); getBounds(min, max); Vertex avg = (max-min)*0.5; for (int v=0; v<mVertices.size(); v++) { Vertex& vt = mVertices[v]; for (int i=0; i<3; i++) { vt[i] = -1. + (vt[i]-min[i])/avg[i]; } } } void Mesh::translate(double x, double y, double z){ const Vertex xfm(x,y,z); for(int i=0; i<vertices().size(); ++i) mVertices[i] += xfm; } void Mesh::scale(double x, double y, double z){ const Vertex xfm(x,y,z); for(int i=0; i<vertices().size(); ++i) mVertices[i] *= xfm; } } // ::al <commit_msg>fix to vertex-based createNormalsMesh (was only outputting every third vertex)<commit_after>#include <algorithm> #include <map> #include <string> #include <vector> #include "allocore/system/al_Config.h" #include "allocore/graphics/al_Mesh.hpp" #include "allocore/graphics/al_Graphics.hpp" namespace al{ Mesh& Mesh::reset() { vertices().reset(); normals().reset(); colors().reset(); coloris().reset(); texCoord2s().reset(); texCoord3s().reset(); indices().reset(); return *this; } void Mesh::decompress(){ int Ni = indices().size(); if(Ni){ #define DECOMPRESS(buf, Type)\ {\ int N = buf.size();\ if(N){\ std::vector<Type> old(N);\ std::copy(&buf[0], (&buf[0]) + N, old.begin());\ buf.size(Ni);\ for(int i=0; i<Ni; ++i) buf[i] = old[indices()[i]];\ }\ } DECOMPRESS(vertices(), Vertex) DECOMPRESS(colors(), Color) DECOMPRESS(coloris(), Color) DECOMPRESS(normals(), Normal) DECOMPRESS(texCoord2s(), TexCoord2) DECOMPRESS(texCoord3s(), TexCoord3) #undef DECOMPRESS indices().reset(); } } void Mesh::equalizeBuffers() { const int Nv = vertices().size(); const int Nn = normals().size(); const int Nc = colors().size(); const int Nci= coloris().size(); const int Nt2= texCoord2s().size(); const int Nt3= texCoord3s().size(); if(Nn){ for(int i=Nn; i<Nv; ++i){ normals().append(normals()[Nn-1]); } } if(Nc){ for(int i=Nc; i<Nv; ++i){ colors().append(colors()[Nc-1]); } } else if(Nci){ for(int i=Nci; i<Nv; ++i){ coloris().append(coloris()[Nci-1]); } } if(Nt2){ for(int i=Nt2; i<Nv; ++i){ texCoord2s().append(texCoord2s()[Nt2-1]); } } if(Nt3){ for(int i=Nt3; i<Nv; ++i){ texCoord3s().append(texCoord3s()[Nt3-1]); } } } class TriFace { public: Mesh::Vertex vertices[3]; Vec3f norm; TriFace(const TriFace& cpy) : norm(cpy.norm) { vertices[0] = cpy.vertices[0]; vertices[1] = cpy.vertices[1]; vertices[2] = cpy.vertices[2]; } TriFace(Mesh::Vertex p0, Mesh::Vertex p1, Mesh::Vertex p2) { vertices[0] = p0; vertices[1] = p1; vertices[2] = p2; // calculate norm for this face: normal<float>(norm, p0, p1, p2); } }; void Mesh::createNormalsMesh(Mesh& mesh, float length, bool perFace){ struct F{ static void initMesh(Mesh& m, int n){ m.vertices().size(n*2); m.reset(); m.primitive(Graphics::LINES); } }; if (perFace) { // compute vertex based normals if(indices().size()){ int Ni = indices().size(); Ni = Ni - (Ni%3); // must be multiple of 3 F::initMesh(mesh, (Ni/3)*2); for(int i=0; i<Ni; i+=3){ Index i1 = indices()[i+0]; Index i2 = indices()[i+1]; Index i3 = indices()[i+2]; const Vertex& v1 = vertices()[i1]; const Vertex& v2 = vertices()[i2]; const Vertex& v3 = vertices()[i3]; // get mean: const Vertex mean = (v1 + v2 + v3)/3.f; // get face normal: Vertex facenormal = cross(v2-v1, v3-v1); facenormal.normalize(); mesh.vertex(mean); mesh.vertex(mean + (facenormal*length)); } } else { printf("createNormalsMesh only valid for indexed meshes\n"); } } else { int Ni = al::min(vertices().size(), normals().size()); F::initMesh(mesh, Ni*2); for(int i=0; i<Ni; ++i){ const Vertex& v = vertices()[i]; mesh.vertex(v); mesh.vertex(v + normals()[i]*length); } } } void Mesh::invertNormals() { int Nv = normals().size(); for(int i=0; i<Nv; ++i) normals()[i] = -normals()[i]; } // Old non-functional prototype... // // generates smoothed normals for a set of vertices // // will replace any normals currently in use // // angle - maximum angle (in degrees) to smooth across // void generateNormals(float angle=360); void Mesh::generateNormals(bool normalize, bool equalWeightPerFace) { // /* // Multi-pass algorithm: // generate a list of faces (assume triangles?) // (vary according to whether mIndices is used) // calculate normal per face (use normal<float>(dst, p0, p1, p2)) // vertices may be used in multiple faces; their norm should be an average of the uses // easy enough if indices is being used; not so easy otherwise. // create a lookup table by hashing on vertex x,y,z // // // write avg into corresponding normals for each vertex // EXCEPT: if edge is sharper than @angle, just use the face normal directly // */ // std::vector<TriFace> faces; // // std::map<std::string, int> vertexHash; // // int Ni = indices().size(); // int Nv = vertices().size(); // if (Ni) { // for (int i=0; i<Ni;) { // TriFace face( // mVertices[mIndices[i++]], // mVertices[mIndices[i++]], // mVertices[mIndices[i++]] // ); // faces.push_back(face); // } // } else { // for (int i=0; i<Nv;) { // TriFace face( // mVertices[i++], // mVertices[i++], // mVertices[i++] // ); // faces.push_back(face); // } // } int Nv = vertices().size(); // same number of normals as vertices normals().size(Nv); // compute vertex based normals if(indices().size()){ for(int i=0; i<Nv; ++i) normals()[i].set(0,0,0); int Ni = indices().size(); // if(primitive() == TRIANGLES){ Ni = Ni - (Ni%3); // must be multiple of 3 for(int i=0; i<Ni; i+=3){ Index i1 = indices()[i+0]; Index i2 = indices()[i+1]; Index i3 = indices()[i+2]; const Vertex& v1 = vertices()[i1]; const Vertex& v2 = vertices()[i2]; const Vertex& v3 = vertices()[i3]; // MWAAT (mean weighted by areas of adjacent triangles) Vertex vn = cross(v2-v1, v3-v1); // MWE (mean weighted equally) if (equalWeightPerFace) vn.normalize(); // MWA (mean weighted by angle) // This doesn't work well with dynamic marching cubes- normals // pop in and out for small triangles. // Vertex v12= v2-v1; // Vertex v13= v3-v1; // Vertex vn = cross(v12, v13).normalize(); // vn *= angle(v12, v13) / M_PI; normals()[i1] += vn; normals()[i2] += vn; normals()[i3] += vn; } // } // else if(primitive() == TRIANGLE_STRIP){ // for(int i=2; i<Ni; ++i){ // Index i1 = indices()[i-2]; // Index i2 = indices()[i-1]; // Index i3 = indices()[i-0]; // const Vertex& v1 = vertices()[i1]; // const Vertex& v2 = vertices()[i2]; // const Vertex& v3 = vertices()[i3]; // // Vertex vn = cross(v2-v1, v3-v1); // // normals()[i1] += vn; // normals()[i2] += vn; // normals()[i3] += vn; // } // } // normalize the normals if(normalize) for(int i=0; i<Nv; ++i) normals()[i].normalize(); } // compute face based normals else{ // if(primitive() == TRIANGLES){ int N = Nv - (Nv % 3); for(int i=0; i<N; i+=3){ int i1 = i+0; int i2 = i+1; int i3 = i+2; const Vertex& v1 = vertices()[i1]; const Vertex& v2 = vertices()[i2]; const Vertex& v3 = vertices()[i3]; Vertex vn = cross(v2-v1, v3-v1); if(normalize) vn.normalize(); normals()[i1] = vn; normals()[i2] = vn; normals()[i3] = vn; } // } } } void Mesh::ribbonize(float * widths, int widthsStride, bool faceBitangent){ const int N = mVertices.size(); if(0 == N) return; mVertices.size(N*2); mNormals.size(N*2); // Store last vertex since it will be overwritten eventually const Vertex last = mVertices[N-1]; int in = faceBitangent ? 2 : 1; int ib = faceBitangent ? 1 : 2; for(int i=N-1; i>=0; --i){ int i1 = i; int i0 = i1-1; if(i0< 0) i0+=N; int i2 = i1+1; if(i2>=N) i2-=N; const Vertex& v0 = (i0==(N-1)) ? last : mVertices[i0]; const Vertex& v1 = mVertices[i1]; const Vertex& v2 = mVertices[i2]; // compute Frenet frame Vertex f[3]; // T,N,B { const Vertex d1 = (v0 - v2)*0.5; const Vertex d2 = (d1 - v1)*2.0; //Vertex& t = f[0]; Vertex& n = f[1]; Vertex& b = f[2]; b = cross(d2,d1).sgn(); n = cross(d1, b).sgn(); //t = d1.sgn(); // not used } f[ib] *= widths[i0*widthsStride]; int i12 = i1<<1; // v1 is ref, so we must write in reverse to properly handle i=0 mVertices[i12+1] = v1+f[ib]; mVertices[i12 ] = v1-f[ib]; mNormals [i12 ].set(f[in][0], f[in][1], f[in][2]); mNormals [i12+1] = mNormals[i12]; } if(mColors.size()) mColors.expand<2,true>(); if(mColoris.size()) mColoris.expand<2,true>(); } void Mesh::merge(const Mesh& src){ // if (indices().size() || src.indices().size()) { // printf("error: Mesh merging with indexed meshes not yet supported\n"); // return; // } // TODO: only do merge if source and dest are well-formed // TODO: what to do when mixing float and integer colors? promote or demote? // TODO: indices are more complex, since the offsets may have changed. // we'd have to add indices.size() to all of the src.indices before adding. // also, both src & dst should either use or not use indices // tricky if src is empty... //indices().append(src.indices()); // Source has indices, and I either do or don't. // After this block, I will have indices. if(src.indices().size()){ Index Nv = vertices().size(); Index Ni = indices().size(); // If no indices, must create if(0 == Ni){ for(Index i=0; i<Nv; ++i) index(i); } // Add source indices offset by my number of vertices index(src.indices().elems(), src.indices().size(), (unsigned int)Nv); } // Source doesn't have indices, but I do else if(indices().size()){ int Nv = vertices().size(); for(int i=Nv; i<Nv+src.vertices().size(); ++i) index(i); } // From here, the game is indice invariant //equalizeBuffers(); << TODO: must do this if we are using indices. vertices().append(src.vertices()); normals().append(src.normals()); colors().append(src.colors()); texCoord2s().append(src.texCoord2s()); texCoord3s().append(src.texCoord3s()); } void Mesh::getBounds(Vertex& min, Vertex& max) const { if(vertices().size()){ min.set(vertices()[0]); max.set(min); for(int v=1; v<vertices().size(); ++v){ const Vertex& vt = vertices()[v]; for(int i=0; i<3; ++i){ min[i] = AL_MIN(min[i], vt[i]); max[i] = AL_MAX(max[i], vt[i]); } } } } Mesh::Vertex Mesh::getCenter() const { Vertex min(0), max(0); getBounds(min, max); return min+(max-min)*0.5; } void Mesh::unitize() { Vertex min(0), max(0); getBounds(min, max); Vertex avg = (max-min)*0.5; for (int v=0; v<mVertices.size(); v++) { Vertex& vt = mVertices[v]; for (int i=0; i<3; i++) { vt[i] = -1. + (vt[i]-min[i])/avg[i]; } } } void Mesh::translate(double x, double y, double z){ const Vertex xfm(x,y,z); for(int i=0; i<vertices().size(); ++i) mVertices[i] += xfm; } void Mesh::scale(double x, double y, double z){ const Vertex xfm(x,y,z); for(int i=0; i<vertices().size(); ++i) mVertices[i] *= xfm; } } // ::al <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkExtractBlock.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkExtractBlock.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMultiBlockDataSet.h" #include "vtkObjectFactory.h" #include "vtkDataSet.h" #include "vtkCompositeDataIterator.h" #include "vtkInformationIntegerKey.h" #include "vtkMultiPieceDataSet.h" #include <vtkstd/set> class vtkExtractBlock::vtkSet : public vtkstd::set<unsigned int> { }; vtkStandardNewMacro(vtkExtractBlock); vtkCxxRevisionMacro(vtkExtractBlock, "1.5"); vtkInformationKeyMacro(vtkExtractBlock, DONT_PRUNE, Integer); //---------------------------------------------------------------------------- vtkExtractBlock::vtkExtractBlock() { this->Indices = new vtkExtractBlock::vtkSet(); this->ActiveIndices = new vtkExtractBlock::vtkSet(); this->PruneOutput = 1; } //---------------------------------------------------------------------------- vtkExtractBlock::~vtkExtractBlock() { delete this->Indices; delete this->ActiveIndices; } //---------------------------------------------------------------------------- void vtkExtractBlock::AddIndex(unsigned int index) { this->Indices->insert(index); this->Modified(); } //---------------------------------------------------------------------------- void vtkExtractBlock::RemoveIndex(unsigned int index) { this->Indices->erase(index); this->Modified(); } //---------------------------------------------------------------------------- void vtkExtractBlock::RemoveAllIndices() { this->Indices->clear(); this->Modified(); } //---------------------------------------------------------------------------- void vtkExtractBlock::CopySubTree(vtkCompositeDataIterator* loc, vtkMultiBlockDataSet* output, vtkMultiBlockDataSet* input) { vtkDataObject* inputNode = input->GetDataSet(loc); if (!inputNode->IsA("vtkCompositeDataSet")) { vtkDataObject* clone = inputNode->NewInstance(); clone->ShallowCopy(inputNode); output->SetDataSet(loc, clone); clone->Delete(); } else { vtkCompositeDataSet* cinput = vtkCompositeDataSet::SafeDownCast(inputNode); vtkCompositeDataSet* coutput = vtkCompositeDataSet::SafeDownCast( output->GetDataSet(loc)); vtkCompositeDataIterator* iter = cinput->NewIterator(); iter->VisitOnlyLeavesOff(); for (iter->InitTraversal(); !iter->IsDoneWithTraversal() && this->ActiveIndices->size() > 0; iter->GoToNextItem()) { vtkDataObject* curNode = iter->GetCurrentDataObject(); vtkDataObject* clone = curNode->NewInstance(); clone->ShallowCopy(curNode); coutput->SetDataSet(iter, clone); clone->Delete(); this->ActiveIndices->erase(loc->GetCurrentFlatIndex() + iter->GetCurrentFlatIndex()); } iter->Delete(); } } //---------------------------------------------------------------------------- int vtkExtractBlock::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { vtkMultiBlockDataSet *input = vtkMultiBlockDataSet::GetData(inputVector[0], 0); vtkMultiBlockDataSet *output = vtkMultiBlockDataSet::GetData(outputVector, 0); if (this->Indices->find(0) != this->Indices->end()) { // trivial case. output->ShallowCopy(input); return 1; } output->CopyStructure(input); (*this->ActiveIndices) = (*this->Indices); // Copy selected blocks over to the output. vtkCompositeDataIterator* iter = input->NewIterator(); iter->VisitOnlyLeavesOff(); for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) { if (this->ActiveIndices->find(iter->GetCurrentFlatIndex()) != this->ActiveIndices->end()) { this->ActiveIndices->erase(iter->GetCurrentFlatIndex()); // This removed the visited indices from this->ActiveIndices. this->CopySubTree(iter, output, input); } } iter->Delete(); this->ActiveIndices->clear(); if (!this->PruneOutput) { return 1; } // Now prune the output tree. // Since in case multiple processes are involved, this process may have some // data-set pointers NULL. Hence, pruning cannot simply trim NULL ptrs, since // in that case we may end up with different structures on different // processess, which is a big NO-NO. Hence, we first flag nodes based on // whether they are being pruned or not. iter = output->NewIterator(); iter->VisitOnlyLeavesOff(); iter->SkipEmptyNodesOff(); for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) { if (this->Indices->find(iter->GetCurrentFlatIndex()) != this->Indices->end()) { iter->GetCurrentMetaData()->Set(DONT_PRUNE(), 1); } else if (iter->HasCurrentMetaData() && iter->GetCurrentMetaData()->Has(DONT_PRUNE())) { iter->GetCurrentMetaData()->Remove(DONT_PRUNE()); } } iter->Delete(); // Do the actual pruning. Only those branches are pruned which don't have // DON_PRUNE flag set. this->Prune(output); return 1; } //---------------------------------------------------------------------------- bool vtkExtractBlock::Prune(vtkDataObject* branch) { if (branch->IsA("vtkMultiBlockDataSet")) { return this->Prune(vtkMultiBlockDataSet::SafeDownCast(branch)); } else if (branch->IsA("vtkMultiPieceDataSet")) { return this->Prune(vtkMultiPieceDataSet::SafeDownCast(branch)); } return true; } //---------------------------------------------------------------------------- bool vtkExtractBlock::Prune(vtkMultiPieceDataSet* mpiece) { // * Remove any children on mpiece that don't have DONT_PRUNE set. vtkMultiPieceDataSet* clone = vtkMultiPieceDataSet::New(); unsigned int index=0; unsigned int numChildren = mpiece->GetNumberOfPieces(); for (unsigned int cc=0; cc<numChildren; cc++) { if (mpiece->HasMetaData(cc) && mpiece->GetMetaData(cc)->Has(DONT_PRUNE())) { clone->SetPiece(index, mpiece->GetPiece(cc)); clone->GetMetaData(index)->Copy(mpiece->GetMetaData(cc)); index++; } } mpiece->ShallowCopy(clone); clone->Delete(); // tell caller to prune mpiece away if num of pieces is 0. return (mpiece->GetNumberOfPieces() == 0); } //---------------------------------------------------------------------------- bool vtkExtractBlock::Prune(vtkMultiBlockDataSet* mblock) { vtkMultiBlockDataSet* clone = vtkMultiBlockDataSet::New(); unsigned int index=0; unsigned int numChildren = mblock->GetNumberOfBlocks(); for (unsigned int cc=0; cc < numChildren; cc++) { vtkDataObject* block = mblock->GetBlock(cc); if (mblock->HasMetaData(cc) && mblock->GetMetaData(cc)->Has(DONT_PRUNE())) { clone->SetBlock(index, block); clone->GetMetaData(index)->Copy(mblock->GetMetaData(cc)); index++; } else if (block) { bool prune = this->Prune(block); if (!prune) { vtkMultiBlockDataSet* prunedBlock = vtkMultiBlockDataSet::SafeDownCast(block); if (prunedBlock && prunedBlock->GetNumberOfBlocks()==1) { // shrink redundant branches. clone->SetBlock(index, prunedBlock->GetBlock(0)); if (prunedBlock->HasMetaData(static_cast<unsigned int>(0))) { clone->GetMetaData(index)->Copy(prunedBlock->GetMetaData( static_cast<unsigned int>(0))); } } else { clone->SetBlock(index, block); if (mblock->HasMetaData(cc)) { clone->GetMetaData(index)->Copy(mblock->GetMetaData(cc)); } } index++; } } } mblock->ShallowCopy(clone); clone->Delete(); return (mblock->GetNumberOfBlocks() == 0); } //---------------------------------------------------------------------------- void vtkExtractBlock::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "PruneOutput: " << this->PruneOutput << endl; } <commit_msg>BUG: When parent node was selected, children were not being copied correctly. Fixed that.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkExtractBlock.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkExtractBlock.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMultiBlockDataSet.h" #include "vtkObjectFactory.h" #include "vtkDataSet.h" #include "vtkCompositeDataIterator.h" #include "vtkInformationIntegerKey.h" #include "vtkMultiPieceDataSet.h" #include <vtkstd/set> class vtkExtractBlock::vtkSet : public vtkstd::set<unsigned int> { }; vtkStandardNewMacro(vtkExtractBlock); vtkCxxRevisionMacro(vtkExtractBlock, "1.6"); vtkInformationKeyMacro(vtkExtractBlock, DONT_PRUNE, Integer); //---------------------------------------------------------------------------- vtkExtractBlock::vtkExtractBlock() { this->Indices = new vtkExtractBlock::vtkSet(); this->ActiveIndices = new vtkExtractBlock::vtkSet(); this->PruneOutput = 1; } //---------------------------------------------------------------------------- vtkExtractBlock::~vtkExtractBlock() { delete this->Indices; delete this->ActiveIndices; } //---------------------------------------------------------------------------- void vtkExtractBlock::AddIndex(unsigned int index) { this->Indices->insert(index); this->Modified(); } //---------------------------------------------------------------------------- void vtkExtractBlock::RemoveIndex(unsigned int index) { this->Indices->erase(index); this->Modified(); } //---------------------------------------------------------------------------- void vtkExtractBlock::RemoveAllIndices() { this->Indices->clear(); this->Modified(); } //---------------------------------------------------------------------------- void vtkExtractBlock::CopySubTree(vtkCompositeDataIterator* loc, vtkMultiBlockDataSet* output, vtkMultiBlockDataSet* input) { vtkDataObject* inputNode = input->GetDataSet(loc); if (!inputNode->IsA("vtkCompositeDataSet")) { vtkDataObject* clone = inputNode->NewInstance(); clone->ShallowCopy(inputNode); output->SetDataSet(loc, clone); clone->Delete(); } else { vtkCompositeDataSet* cinput = vtkCompositeDataSet::SafeDownCast(inputNode); vtkCompositeDataSet* coutput = vtkCompositeDataSet::SafeDownCast( output->GetDataSet(loc)); vtkCompositeDataIterator* iter = cinput->NewIterator(); iter->VisitOnlyLeavesOff(); for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) { vtkDataObject* curNode = iter->GetCurrentDataObject(); vtkDataObject* clone = curNode->NewInstance(); clone->ShallowCopy(curNode); coutput->SetDataSet(iter, clone); clone->Delete(); this->ActiveIndices->erase(loc->GetCurrentFlatIndex() + iter->GetCurrentFlatIndex()); } iter->Delete(); } } //---------------------------------------------------------------------------- int vtkExtractBlock::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { vtkMultiBlockDataSet *input = vtkMultiBlockDataSet::GetData(inputVector[0], 0); vtkMultiBlockDataSet *output = vtkMultiBlockDataSet::GetData(outputVector, 0); if (this->Indices->find(0) != this->Indices->end()) { // trivial case. output->ShallowCopy(input); return 1; } output->CopyStructure(input); (*this->ActiveIndices) = (*this->Indices); // Copy selected blocks over to the output. vtkCompositeDataIterator* iter = input->NewIterator(); iter->VisitOnlyLeavesOff(); for (iter->InitTraversal(); !iter->IsDoneWithTraversal() && this->ActiveIndices->size()>0; iter->GoToNextItem()) { if (this->ActiveIndices->find(iter->GetCurrentFlatIndex()) != this->ActiveIndices->end()) { this->ActiveIndices->erase(iter->GetCurrentFlatIndex()); // This removed the visited indices from this->ActiveIndices. this->CopySubTree(iter, output, input); } } iter->Delete(); this->ActiveIndices->clear(); if (!this->PruneOutput) { return 1; } // Now prune the output tree. // Since in case multiple processes are involved, this process may have some // data-set pointers NULL. Hence, pruning cannot simply trim NULL ptrs, since // in that case we may end up with different structures on different // processess, which is a big NO-NO. Hence, we first flag nodes based on // whether they are being pruned or not. iter = output->NewIterator(); iter->VisitOnlyLeavesOff(); iter->SkipEmptyNodesOff(); for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) { if (this->Indices->find(iter->GetCurrentFlatIndex()) != this->Indices->end()) { iter->GetCurrentMetaData()->Set(DONT_PRUNE(), 1); } else if (iter->HasCurrentMetaData() && iter->GetCurrentMetaData()->Has(DONT_PRUNE())) { iter->GetCurrentMetaData()->Remove(DONT_PRUNE()); } } iter->Delete(); // Do the actual pruning. Only those branches are pruned which don't have // DON_PRUNE flag set. this->Prune(output); return 1; } //---------------------------------------------------------------------------- bool vtkExtractBlock::Prune(vtkDataObject* branch) { if (branch->IsA("vtkMultiBlockDataSet")) { return this->Prune(vtkMultiBlockDataSet::SafeDownCast(branch)); } else if (branch->IsA("vtkMultiPieceDataSet")) { return this->Prune(vtkMultiPieceDataSet::SafeDownCast(branch)); } return true; } //---------------------------------------------------------------------------- bool vtkExtractBlock::Prune(vtkMultiPieceDataSet* mpiece) { // * Remove any children on mpiece that don't have DONT_PRUNE set. vtkMultiPieceDataSet* clone = vtkMultiPieceDataSet::New(); unsigned int index=0; unsigned int numChildren = mpiece->GetNumberOfPieces(); for (unsigned int cc=0; cc<numChildren; cc++) { if (mpiece->HasMetaData(cc) && mpiece->GetMetaData(cc)->Has(DONT_PRUNE())) { clone->SetPiece(index, mpiece->GetPiece(cc)); clone->GetMetaData(index)->Copy(mpiece->GetMetaData(cc)); index++; } } mpiece->ShallowCopy(clone); clone->Delete(); // tell caller to prune mpiece away if num of pieces is 0. return (mpiece->GetNumberOfPieces() == 0); } //---------------------------------------------------------------------------- bool vtkExtractBlock::Prune(vtkMultiBlockDataSet* mblock) { vtkMultiBlockDataSet* clone = vtkMultiBlockDataSet::New(); unsigned int index=0; unsigned int numChildren = mblock->GetNumberOfBlocks(); for (unsigned int cc=0; cc < numChildren; cc++) { vtkDataObject* block = mblock->GetBlock(cc); if (mblock->HasMetaData(cc) && mblock->GetMetaData(cc)->Has(DONT_PRUNE())) { clone->SetBlock(index, block); clone->GetMetaData(index)->Copy(mblock->GetMetaData(cc)); index++; } else if (block) { bool prune = this->Prune(block); if (!prune) { vtkMultiBlockDataSet* prunedBlock = vtkMultiBlockDataSet::SafeDownCast(block); if (prunedBlock && prunedBlock->GetNumberOfBlocks()==1) { // shrink redundant branches. clone->SetBlock(index, prunedBlock->GetBlock(0)); if (prunedBlock->HasMetaData(static_cast<unsigned int>(0))) { clone->GetMetaData(index)->Copy(prunedBlock->GetMetaData( static_cast<unsigned int>(0))); } } else { clone->SetBlock(index, block); if (mblock->HasMetaData(cc)) { clone->GetMetaData(index)->Copy(mblock->GetMetaData(cc)); } } index++; } } } mblock->ShallowCopy(clone); clone->Delete(); return (mblock->GetNumberOfBlocks() == 0); } //---------------------------------------------------------------------------- void vtkExtractBlock::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "PruneOutput: " << this->PruneOutput << endl; } <|endoftext|>
<commit_before>// $Id$ /************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Authors: * * for The ALICE HLT Project. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // @file AliHLTTRDCluster.cxx // @author Theodor Rascanu // @date // @brief A datacontainer for clusters fitting component for the HLT. // #include "AliHLTTRDCluster.h" #include <cstring> /** * Default Constructor */ //============================================================================ AliHLTTRDCluster::AliHLTTRDCluster(): fSignals(0), fPadCol(0), fPadRow(0), fPadTime(0), fBits(0) { } /** * Main Constructor */ //============================================================================ AliHLTTRDCluster::AliHLTTRDCluster(const AliTRDcluster* const inCluster): fSignals(0), fPadCol(inCluster->fPadCol), fPadRow(inCluster->fPadRow), fPadTime(inCluster->fPadTime), fBits(0) { fSignals = inCluster->fSignals[2]; fSignals|= inCluster->fSignals[3]<<10; fSignals|= inCluster->fSignals[4]<<20; fBits = UInt_t(inCluster->TestBits(-1)) >> 14; } /** * Copy data to the output TRDcluster */ //============================================================================ void AliHLTTRDCluster::ExportTRDCluster(AliTRDcluster* const outCluster) const { outCluster->fPadCol=fPadCol; outCluster->fPadRow=fPadRow; outCluster->fPadTime=fPadTime; outCluster->fSignals[2] = 0x3ff & fSignals; outCluster->fSignals[3] = 0x3ff & fSignals>>10; outCluster->fSignals[4] = 0x3ff & fSignals>>20; for(int i=0; i<3; i++){ outCluster->fQ+=outCluster->fSignals[i]; } outCluster->SetBit(UInt_t(fBits)<<14); } /** * Default Constructor */ //============================================================================ AliHLTTRDExtCluster::AliHLTTRDExtCluster(): AliHLTTRDCluster(), fX(0), fY(0), fZ(0) { } /** * Main Constructor */ //============================================================================ AliHLTTRDExtCluster::AliHLTTRDExtCluster(const AliTRDcluster* const inCluster): AliHLTTRDCluster(inCluster), fX(inCluster->GetX()), fY(inCluster->GetY()), fZ(inCluster->GetZ()) { } /** * Copy data to the output TRDcluster */ //============================================================================ void AliHLTTRDExtCluster::ExportTRDCluster(AliTRDcluster* const outCluster) const { AliHLTTRDCluster::ExportTRDCluster(outCluster); outCluster->SetX(fX); outCluster->SetY(fY); outCluster->SetZ(fZ); } /** * Prints main info about cluster */ //============================================================================ void AliHLTTRDExtCluster::Print() const { printf(" --hltCluster-- addr %p; sizeof(*this) %i\n", (void*)this, (int)sizeof(*this)); printf(" fX %f; fY %f; fZ %f\n",fX,fY,fZ); } /** * Save cluster at block position */ //============================================================================ AliHLTUInt32_t AliHLTTRDCluster::SaveAt(AliHLTUInt8_t *const block, const AliTRDcluster* const inClust) { AliHLTUInt32_t size=0; memcpy(block,inClust,sizeof(AliTRDcluster)); size+=sizeof(AliTRDcluster); return size; } /** * Read cluster from block */ //============================================================================ AliHLTUInt32_t AliHLTTRDCluster::LoadFrom(AliTRDcluster *const outClust, const AliHLTUInt8_t *const block) { AliHLTUInt32_t size=0; memcpy(((AliHLTUInt8_t*)outClust)+sizeof(void*),block+sizeof(void*),sizeof(AliTRDcluster)-sizeof(void*)); size+=sizeof(AliTRDcluster); return size; } <commit_msg>HLT TRD bugfix: correct calculation of the total charge of the cluster (Theo)<commit_after>// $Id$ /************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Authors: * * for The ALICE HLT Project. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // @file AliHLTTRDCluster.cxx // @author Theodor Rascanu // @date // @brief A datacontainer for clusters fitting component for the HLT. // #include "AliHLTTRDCluster.h" #include <cstring> /** * Default Constructor */ //============================================================================ AliHLTTRDCluster::AliHLTTRDCluster(): fSignals(0), fPadCol(0), fPadRow(0), fPadTime(0), fBits(0) { } /** * Main Constructor */ //============================================================================ AliHLTTRDCluster::AliHLTTRDCluster(const AliTRDcluster* const inCluster): fSignals(0), fPadCol(inCluster->fPadCol), fPadRow(inCluster->fPadRow), fPadTime(inCluster->fPadTime), fBits(0) { fSignals = inCluster->fSignals[2]; fSignals|= inCluster->fSignals[3]<<10; fSignals|= inCluster->fSignals[4]<<21; fBits = UInt_t(inCluster->TestBits(-1)) >> 14; } /** * Copy data to the output TRDcluster */ //============================================================================ void AliHLTTRDCluster::ExportTRDCluster(AliTRDcluster* const outCluster) const { outCluster->fPadCol=fPadCol; outCluster->fPadRow=fPadRow; outCluster->fPadTime=fPadTime; outCluster->fSignals[2] = 0x3ff & fSignals; outCluster->fSignals[3] = 0x7ff & fSignals>>10; outCluster->fSignals[4] = 0x3ff & fSignals>>21; for(int i=2; i<5; i++){ outCluster->fQ+=outCluster->fSignals[i]; } outCluster->SetBit(UInt_t(fBits)<<14); } /** * Default Constructor */ //============================================================================ AliHLTTRDExtCluster::AliHLTTRDExtCluster(): AliHLTTRDCluster(), fX(0), fY(0), fZ(0) { } /** * Main Constructor */ //============================================================================ AliHLTTRDExtCluster::AliHLTTRDExtCluster(const AliTRDcluster* const inCluster): AliHLTTRDCluster(inCluster), fX(inCluster->GetX()), fY(inCluster->GetY()), fZ(inCluster->GetZ()) { } /** * Copy data to the output TRDcluster */ //============================================================================ void AliHLTTRDExtCluster::ExportTRDCluster(AliTRDcluster* const outCluster) const { AliHLTTRDCluster::ExportTRDCluster(outCluster); outCluster->SetX(fX); outCluster->SetY(fY); outCluster->SetZ(fZ); } /** * Prints main info about cluster */ //============================================================================ void AliHLTTRDExtCluster::Print() const { printf(" --hltCluster-- addr %p; sizeof(*this) %i\n", (void*)this, (int)sizeof(*this)); printf(" fX %f; fY %f; fZ %f\n",fX,fY,fZ); } /** * Save cluster at block position */ //============================================================================ AliHLTUInt32_t AliHLTTRDCluster::SaveAt(AliHLTUInt8_t *const block, const AliTRDcluster* const inClust) { AliHLTUInt32_t size=0; memcpy(block,inClust,sizeof(AliTRDcluster)); size+=sizeof(AliTRDcluster); return size; } /** * Read cluster from block */ //============================================================================ AliHLTUInt32_t AliHLTTRDCluster::LoadFrom(AliTRDcluster *const outClust, const AliHLTUInt8_t *const block) { AliHLTUInt32_t size=0; memcpy(((AliHLTUInt8_t*)outClust)+sizeof(void*),block+sizeof(void*),sizeof(AliTRDcluster)-sizeof(void*)); size+=sizeof(AliTRDcluster); return size; } <|endoftext|>
<commit_before>/* * Copyright 2016-2017 Flatiron Institute, Simons Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "p_extract_clips.h" #include "diskreadmda32.h" #include "diskreadmda.h" #include "extract_clips.h" #include "pca.h" #include <diskwritemda.h> namespace P_extract_clips { Mda32 extract_channels_from_chunk(const Mda32& chunk, const QList<int>& channels); } bool p_extract_clips(QStringList timeseries_list, QString event_times, const QList<int>& channels, QString clips_out, const QVariantMap& params) { DiskReadMda32 X(2, timeseries_list); DiskReadMda ET(event_times); bigint M = X.N1(); //bigint N = X.N2(); bigint T = params["clip_size"].toInt(); bigint L = ET.totalSize(); bigint M2 = M; if (!channels.isEmpty()) { M2 = channels.count(); } if (!T) { qWarning() << "Unexpected: Clip size is zero."; return false; } bigint Tmid = (bigint)((T + 1) / 2) - 1; printf("Extracting clips (%ld,%ld,%ld) (%ld)...\n", M, T, L, M2); DiskWriteMda clips; clips.open(MDAIO_TYPE_FLOAT32, clips_out, M2, T, L); for (bigint i = 0; i < L; i++) { bigint t1 = ET.value(i) - Tmid; //bigint t2 = t1 + T - 1; Mda32 tmp; if (!X.readChunk(tmp, 0, t1, M, T)) { qWarning() << "Problem reading chunk in extract_clips"; return false; } if (!channels.isEmpty()) { tmp = P_extract_clips::extract_channels_from_chunk(tmp, channels); } if (!clips.writeChunk(tmp, 0, 0, i)) { qWarning() << "Problem writing chunk" << i; return false; } } return true; } bool p_mv_extract_clips(QStringList timeseries_list, QString firings, const QList<int>& channels, QString clips_out, const QVariantMap& params) { DiskReadMda32 X(2, timeseries_list); DiskReadMda FF(firings); bigint M = X.N1(); //bigint N = X.N2(); bigint T = params["clip_size"].toInt(); bigint L = FF.N2(); bigint M2 = M; if (!channels.isEmpty()) { M2 = channels.count(); } if (!T) { qWarning() << "Unexpected: Clip size is zero."; return false; } bigint Tmid = (bigint)((T + 1) / 2) - 1; printf("Extracting clips (%ld,%ld,%ld) (%ld)...\n", M, T, L, M2); DiskWriteMda clips; clips.open(MDAIO_TYPE_FLOAT32, clips_out, M2, T, L); for (bigint i = 0; i < L; i++) { bigint t1 = FF.value(1,i) - Tmid; //bigint t2 = t1 + T - 1; Mda32 tmp; if (!X.readChunk(tmp, 0, t1, M, T)) { qWarning() << "Problem reading chunk in extract_clips"; return false; } if (!channels.isEmpty()) { tmp = P_extract_clips::extract_channels_from_chunk(tmp, channels); } if (!clips.writeChunk(tmp, 0, 0, i)) { qWarning() << "Problem writing chunk" << i; return false; } } return true; } namespace P_extract_clips { Mda32 extract_channels_from_chunk(const Mda32& X, const QList<int>& channels) { //int M=X.N1(); int T = X.N2(); int M2 = channels.count(); Mda32 ret(M2, T); for (int t = 0; t < T; t++) { for (int m2 = 0; m2 < M2; m2++) { ret.set(X.value(channels[m2] - 1, t), m2, t); } } return ret; } } bool p_mv_extract_clips_features(QString timeseries_path, QString firings_path, QString features_out_path, int clip_size, int num_features, int subtract_mean) { DiskReadMda32 X(timeseries_path); DiskReadMda F(firings_path); QVector<double> times; for (int i = 0; i < F.N2(); i++) { times << F.value(1, i); } Mda32 clips = extract_clips(X, times, clip_size); int M = clips.N1(); int T = clips.N2(); int L = clips.N3(); Mda clips_reshaped(M * T, L); int NNN = M * T * L; for (int iii = 0; iii < NNN; iii++) { clips_reshaped.set(clips.get(iii), iii); } Mda CC, FF, sigma; pca(CC, FF, sigma, clips_reshaped, num_features, subtract_mean); return FF.write32(features_out_path); } <commit_msg>return error when ms3.extract_clips is given a non-vector<commit_after>/* * Copyright 2016-2017 Flatiron Institute, Simons Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "p_extract_clips.h" #include "diskreadmda32.h" #include "diskreadmda.h" #include "extract_clips.h" #include "pca.h" #include <diskwritemda.h> namespace P_extract_clips { Mda32 extract_channels_from_chunk(const Mda32& chunk, const QList<int>& channels); } bool p_extract_clips(QStringList timeseries_list, QString event_times, const QList<int>& channels, QString clips_out, const QVariantMap& params) { DiskReadMda32 X(2, timeseries_list); DiskReadMda ET(event_times); bigint M = X.N1(); //bigint N = X.N2(); bigint T = params["clip_size"].toInt(); bigint L = ET.totalSize(); if ((ET.N1()>1)&&(ET.N2()>1)) { qWarning() << "Error: the input (event times) must be a vector."; return false; } bigint M2 = M; if (!channels.isEmpty()) { M2 = channels.count(); } if (!T) { qWarning() << "Unexpected: Clip size is zero."; return false; } bigint Tmid = (bigint)((T + 1) / 2) - 1; printf("Extracting clips (%ld,%ld,%ld) (%ld)...\n", M, T, L, M2); DiskWriteMda clips; clips.open(MDAIO_TYPE_FLOAT32, clips_out, M2, T, L); for (bigint i = 0; i < L; i++) { bigint t1 = ET.value(i) - Tmid; //bigint t2 = t1 + T - 1; Mda32 tmp; if (!X.readChunk(tmp, 0, t1, M, T)) { qWarning() << "Problem reading chunk in extract_clips"; return false; } if (!channels.isEmpty()) { tmp = P_extract_clips::extract_channels_from_chunk(tmp, channels); } if (!clips.writeChunk(tmp, 0, 0, i)) { qWarning() << "Problem writing chunk" << i; return false; } } return true; } bool p_mv_extract_clips(QStringList timeseries_list, QString firings, const QList<int>& channels, QString clips_out, const QVariantMap& params) { DiskReadMda32 X(2, timeseries_list); DiskReadMda FF(firings); bigint M = X.N1(); //bigint N = X.N2(); bigint T = params["clip_size"].toInt(); bigint L = FF.N2(); bigint M2 = M; if (!channels.isEmpty()) { M2 = channels.count(); } if (!T) { qWarning() << "Unexpected: Clip size is zero."; return false; } bigint Tmid = (bigint)((T + 1) / 2) - 1; printf("Extracting clips (%ld,%ld,%ld) (%ld)...\n", M, T, L, M2); DiskWriteMda clips; clips.open(MDAIO_TYPE_FLOAT32, clips_out, M2, T, L); for (bigint i = 0; i < L; i++) { bigint t1 = FF.value(1,i) - Tmid; //bigint t2 = t1 + T - 1; Mda32 tmp; if (!X.readChunk(tmp, 0, t1, M, T)) { qWarning() << "Problem reading chunk in extract_clips"; return false; } if (!channels.isEmpty()) { tmp = P_extract_clips::extract_channels_from_chunk(tmp, channels); } if (!clips.writeChunk(tmp, 0, 0, i)) { qWarning() << "Problem writing chunk" << i; return false; } } return true; } namespace P_extract_clips { Mda32 extract_channels_from_chunk(const Mda32& X, const QList<int>& channels) { //int M=X.N1(); int T = X.N2(); int M2 = channels.count(); Mda32 ret(M2, T); for (int t = 0; t < T; t++) { for (int m2 = 0; m2 < M2; m2++) { ret.set(X.value(channels[m2] - 1, t), m2, t); } } return ret; } } bool p_mv_extract_clips_features(QString timeseries_path, QString firings_path, QString features_out_path, int clip_size, int num_features, int subtract_mean) { DiskReadMda32 X(timeseries_path); DiskReadMda F(firings_path); QVector<double> times; for (int i = 0; i < F.N2(); i++) { times << F.value(1, i); } Mda32 clips = extract_clips(X, times, clip_size); int M = clips.N1(); int T = clips.N2(); int L = clips.N3(); Mda clips_reshaped(M * T, L); int NNN = M * T * L; for (int iii = 0; iii < NNN; iii++) { clips_reshaped.set(clips.get(iii), iii); } Mda CC, FF, sigma; pca(CC, FF, sigma, clips_reshaped, num_features, subtract_mean); return FF.write32(features_out_path); } <|endoftext|>
<commit_before>#include <starmap.hpp> #include "helpers.hpp" #include <iterator> #include <list> #include <string> #include <vector> #include "catch.hpp" using iter::starmap; namespace { long f(long d, int i) { return d * i; } std::string g(const std::string& s, int i, char c) { std::stringstream ss; ss << s << ' ' << i << ' ' << c; return ss.str(); } struct Callable { int operator()(int a, int b, int c) { return a + b + c; } int operator()(int a, int b) { return a + b; } int operator()(int a) { return a; } }; } TEST_CASE("starmap: works with function pointer and lambda", "[starmap]") { using Vec = const std::vector<int>; const std::vector<std::pair<double, int>> v1 = {{1l, 2}, {3l, 11}, {6l, 7}}; Vec vc = {2l, 33l, 42l}; std::vector<int> v; SECTION("with function") { SECTION("Normal call") { auto sm = starmap(f, v1); v.assign(std::begin(sm), std::end(sm)); } SECTION("pipe") { auto sm = v1 | starmap(f); v.assign(std::begin(sm), std::end(sm)); } } SECTION("with lambda") { auto sm = starmap([](long a, int b) { return a * b; }, v1); v.assign(std::begin(sm), std::end(sm)); } REQUIRE(v == vc); } TEST_CASE("starmap: vector of pairs const iteration", "[starmap][const]") { using Vec = const std::vector<int>; const std::vector<std::pair<double, int>> v1 = {{1l, 2}, {3l, 11}, {6l, 7}}; const auto sm = starmap(Callable{}, v1); std::vector<int> v(std::begin(sm), std::end(sm)); Vec vc = {3, 14, 13}; REQUIRE(v == vc); } TEST_CASE( "starmap: vector of pairs const iterators can be compared to non-const " "iterators", "[starmap][const]") { const std::vector<std::pair<double, int>> v1; auto sm = starmap(Callable{}, v1); const auto& csm = sm; (void)(std::begin(sm) == std::end(csm)); } TEST_CASE("starmap: Works with different begin and end types", "[starmap]") { IntCharPairRange icr{{3, 'd'}}; using Vec = std::vector<std::string>; auto sm = starmap([](int i, char c) { return std::to_string(i) + c; }, icr); Vec v(sm.begin(), sm.end()); Vec vc{"0a", "1b", "2c"}; REQUIRE(v == vc); } TEST_CASE("starmap: tuple of tuples const iteration", "[starmap][const]") { using Vec = const std::vector<int>; auto tup = std::make_tuple(std::make_tuple(10, 19, 60), std::make_tuple(7)); const auto sm = starmap(Callable{}, tup); Vec v(std::begin(sm), std::end(sm)); } TEST_CASE( "starmap: tuple of tuples const iterators can be compared to non-const " "iterator", "[starmap][const]") { auto tup = std::make_tuple(std::make_tuple(10, 19, 60), std::make_tuple(7)); auto sm = starmap(Callable{}, tup); const auto& csm = sm; (void)(std::begin(sm) == std::end(csm)); (void)(std::begin(csm) == std::end(sm)); } TEST_CASE("starmap: list of tuples", "[starmap]") { using Vec = const std::vector<std::string>; using T = std::tuple<std::string, int, double>; std::list<T> li = {T{"hey", 42, 'a'}, T{"there", 3, 'b'}, T{"yall", 5, 'c'}}; auto sm = starmap(g, li); Vec v(std::begin(sm), std::end(sm)); Vec vc = {"hey 42 a", "there 3 b", "yall 5 c"}; REQUIRE(v == vc); } TEST_CASE("starmap: tuple of tuples", "[starmap]") { using Vec = const std::vector<int>; auto tup = std::make_tuple(std::make_tuple(10, 19, 60), std::make_tuple(7)); std::vector<int> v; SECTION("Normal call") { auto sm = starmap(Callable{}, tup); v.assign(std::begin(sm), std::end(sm)); } SECTION("Pipe") { auto sm = tup | starmap(Callable{}); v.assign(std::begin(sm), std::end(sm)); } Vec vc = {89, 7}; REQUIRE(v == vc); } TEST_CASE("starmap: tuple of pairs", "[starmap]") { using Vec = const std::vector<int>; auto p = std::make_pair(std::array<int, 3>{{15, 100, 2000}}, std::make_tuple(16)); Callable c; auto sm = starmap(c, p); Vec v(std::begin(sm), std::end(sm)); Vec vc = {2115, 16}; REQUIRE(v == vc); } TEST_CASE("starmap: moves rvalues, binds to lvalues", "[starmap]") { itertest::BasicIterable<std::tuple<int>> bi{}; starmap(Callable{}, bi); REQUIRE_FALSE(bi.was_moved_from()); starmap(Callable{}, std::move(bi)); REQUIRE(bi.was_moved_from()); } TEST_CASE("starmap: iterator meets requirements", "[starmap]") { std::string s{}; const std::vector<std::pair<double, int>> v1; auto sm = starmap([](long a, int b) { return a * b; }, v1); REQUIRE(itertest::IsIterator<decltype(std::begin(sm))>::value); } TEST_CASE( "starmap: tuple of tuples iterator meets requirements", "[starmap]") { auto tup = std::make_tuple(std::make_tuple(10, 19, 60), std::make_tuple(7)); auto sm = starmap(Callable{}, tup); REQUIRE(itertest::IsIterator<decltype(std::begin(sm))>::value); } <commit_msg>Tests starmap with pointer-to-member<commit_after>#include <starmap.hpp> #include "helpers.hpp" #include <iterator> #include <list> #include <string> #include <vector> #include "catch.hpp" using iter::starmap; namespace { long f(long d, int i) { return d * i; } std::string g(const std::string& s, int i, char c) { std::stringstream ss; ss << s << ' ' << i << ' ' << c; return ss.str(); } struct Callable { int operator()(int a, int b, int c) { return a + b + c; } int operator()(int a, int b) { return a + b; } int operator()(int a) { return a; } }; } TEST_CASE("starmap: works with function pointer and lambda", "[starmap]") { using Vec = const std::vector<int>; const std::vector<std::pair<double, int>> v1 = {{1l, 2}, {3l, 11}, {6l, 7}}; Vec vc = {2l, 33l, 42l}; std::vector<int> v; SECTION("with function") { SECTION("Normal call") { auto sm = starmap(f, v1); v.assign(std::begin(sm), std::end(sm)); } SECTION("pipe") { auto sm = v1 | starmap(f); v.assign(std::begin(sm), std::end(sm)); } } SECTION("with lambda") { auto sm = starmap([](long a, int b) { return a * b; }, v1); v.assign(std::begin(sm), std::end(sm)); } REQUIRE(v == vc); } TEST_CASE("starmap: works with pointer to member function", "[starmap]") { using itertest::Point; std::vector<std::pair<Point, std::string>> tup = { {{10, 20}, "a"}, {{6, 8}, "point"}, {{3, 15}, "pos"}}; auto sm = starmap(&Point::prefix, tup); std::vector<std::string> v(std::begin(sm), std::end(sm)); const std::vector<std::string> vc = { "a(10, 20)", "point(6, 8)", "pos(3, 15)"}; REQUIRE(v == vc); } TEST_CASE("starmap: vector of pairs const iteration", "[starmap][const]") { using Vec = const std::vector<int>; const std::vector<std::pair<double, int>> v1 = {{1l, 2}, {3l, 11}, {6l, 7}}; const auto sm = starmap(Callable{}, v1); std::vector<int> v(std::begin(sm), std::end(sm)); Vec vc = {3, 14, 13}; REQUIRE(v == vc); } TEST_CASE( "starmap: vector of pairs const iterators can be compared to non-const " "iterators", "[starmap][const]") { const std::vector<std::pair<double, int>> v1; auto sm = starmap(Callable{}, v1); const auto& csm = sm; (void)(std::begin(sm) == std::end(csm)); } TEST_CASE("starmap: Works with different begin and end types", "[starmap]") { IntCharPairRange icr{{3, 'd'}}; using Vec = std::vector<std::string>; auto sm = starmap([](int i, char c) { return std::to_string(i) + c; }, icr); Vec v(sm.begin(), sm.end()); Vec vc{"0a", "1b", "2c"}; REQUIRE(v == vc); } TEST_CASE("starmap: tuple of tuples const iteration", "[starmap][const]") { using Vec = const std::vector<int>; auto tup = std::make_tuple(std::make_tuple(10, 19, 60), std::make_tuple(7)); const auto sm = starmap(Callable{}, tup); Vec v(std::begin(sm), std::end(sm)); } TEST_CASE( "starmap: tuple of tuples const iterators can be compared to non-const " "iterator", "[starmap][const]") { auto tup = std::make_tuple(std::make_tuple(10, 19, 60), std::make_tuple(7)); auto sm = starmap(Callable{}, tup); const auto& csm = sm; (void)(std::begin(sm) == std::end(csm)); (void)(std::begin(csm) == std::end(sm)); } TEST_CASE("starmap: list of tuples", "[starmap]") { using Vec = const std::vector<std::string>; using T = std::tuple<std::string, int, double>; std::list<T> li = {T{"hey", 42, 'a'}, T{"there", 3, 'b'}, T{"yall", 5, 'c'}}; auto sm = starmap(g, li); Vec v(std::begin(sm), std::end(sm)); Vec vc = {"hey 42 a", "there 3 b", "yall 5 c"}; REQUIRE(v == vc); } TEST_CASE("starmap: tuple of tuples", "[starmap]") { using Vec = const std::vector<int>; auto tup = std::make_tuple(std::make_tuple(10, 19, 60), std::make_tuple(7)); std::vector<int> v; SECTION("Normal call") { auto sm = starmap(Callable{}, tup); v.assign(std::begin(sm), std::end(sm)); } SECTION("Pipe") { auto sm = tup | starmap(Callable{}); v.assign(std::begin(sm), std::end(sm)); } Vec vc = {89, 7}; REQUIRE(v == vc); } TEST_CASE("starmap: tuple of pairs", "[starmap]") { using Vec = const std::vector<int>; auto p = std::make_pair(std::array<int, 3>{{15, 100, 2000}}, std::make_tuple(16)); Callable c; auto sm = starmap(c, p); Vec v(std::begin(sm), std::end(sm)); Vec vc = {2115, 16}; REQUIRE(v == vc); } TEST_CASE("starmap: moves rvalues, binds to lvalues", "[starmap]") { itertest::BasicIterable<std::tuple<int>> bi{}; starmap(Callable{}, bi); REQUIRE_FALSE(bi.was_moved_from()); starmap(Callable{}, std::move(bi)); REQUIRE(bi.was_moved_from()); } TEST_CASE("starmap: iterator meets requirements", "[starmap]") { std::string s{}; const std::vector<std::pair<double, int>> v1; auto sm = starmap([](long a, int b) { return a * b; }, v1); REQUIRE(itertest::IsIterator<decltype(std::begin(sm))>::value); } TEST_CASE( "starmap: tuple of tuples iterator meets requirements", "[starmap]") { auto tup = std::make_tuple(std::make_tuple(10, 19, 60), std::make_tuple(7)); auto sm = starmap(Callable{}, tup); REQUIRE(itertest::IsIterator<decltype(std::begin(sm))>::value); } <|endoftext|>
<commit_before>#include "PhLight.h" using namespace phoenix; PhLight::PhLight(PhLightManager* l, PhTexture* t, PhVector2d p, PhColor c, float s): lmgr(l), texture(t), position(p), color(c), scale(s) { lmgr->addLight(this); } PhLight::~PhLight() { lmgr->removeLight(this); } void PhLight::draw() { lmgr->getSceneManager()->getRenderSystem()->drawTexture(texture,position,0.0f,0.0f,scale,color); } PhTexture* PhLight::getTexture() { return texture; } void PhLight::setTexture(PhTexture* t) { texture = t; } PhVector2d PhLight::getPosition() { return position; } void PhLight::setPosition(PhVector2d p) { position = p; } PhColor PhLight::getColor() { return color; } void PhLight::setColor(PhColor c) { color = c; } float PhLight::getScale() { return scale; } void PhLight::setScale(float s) { scale = s; } <commit_msg>Made the light class automatically adjust for position discrepancies. <commit_after>#include "PhLight.h" using namespace phoenix; PhLight::PhLight(PhLightManager* l, PhTexture* t, PhVector2d p, PhColor c, float s): lmgr(l), texture(t), position(p-PhVector2d(63.64f,63.64f)), color(c), scale(s) { lmgr->addLight(this); } PhLight::~PhLight() { lmgr->removeLight(this); } void PhLight::draw() { lmgr->getSceneManager()->getRenderSystem()->drawTexture(texture,position,0.0f,0.0f,scale,color); } PhTexture* PhLight::getTexture() { return texture; } void PhLight::setTexture(PhTexture* t) { texture = t; } PhVector2d PhLight::getPosition() { //compensate for the fact that our method skews positions slightly. return position+PhVector2d(63.64f,63.64f); } void PhLight::setPosition(PhVector2d p) { //compensate for the fact that our method skews positions slightly. position = p-PhVector2d(63.64f,63.64f); } PhColor PhLight::getColor() { return color; } void PhLight::setColor(PhColor c) { color = c; } float PhLight::getScale() { return scale; } void PhLight::setScale(float s) { scale = s; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkImageConvolve.cxx Language: C++ Date: $Date$ Version: $Revision$ Thanks: Thanks to Zeger F. Knops who developed this class Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #include <math.h> #include "vtkImageConvolve.h" #include "vtkObjectFactory.h" //------------------------------------------------------------------------- vtkImageConvolve* vtkImageConvolve::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkImageConvolve"); if(ret) { return (vtkImageConvolve*)ret; } // If the factory was unable to create the object, then create it here. return new vtkImageConvolve; } //------------------------------------------------------------------------- // Construct an instance of vtkImageLaplacian fitler. vtkImageConvolve::vtkImageConvolve() { this->Dimensionality = 2; this->Kernel[0] = 1.0; this->Kernel[1] = 0.0; this->Kernel[2] = 1.0; } //---------------------------------------------------------------------------- void vtkImageConvolve::PrintSelf(ostream& os, vtkIndent indent) { this->vtkImageToImageFilter::PrintSelf(os, indent); os << indent << "Dimensionality: " << this->Dimensionality; } //---------------------------------------------------------------------------- // Just clip the request. The subclass may need to overwrite this method. void vtkImageConvolve::ComputeInputUpdateExtent(int inExt[6], int outExt[6]) { int idx; int *wholeExtent; // handle XYZ memcpy(inExt,outExt,sizeof(int)*6); wholeExtent = this->GetInput()->GetWholeExtent(); // update and Clip for (idx = 0; idx < 3; ++idx) { --inExt[idx*2]; ++inExt[idx*2+1]; if (inExt[idx*2] < wholeExtent[idx*2]) { inExt[idx*2] = wholeExtent[idx*2]; } if (inExt[idx*2] > wholeExtent[idx*2 + 1]) { inExt[idx*2] = wholeExtent[idx*2 + 1]; } if (inExt[idx*2+1] < wholeExtent[idx*2]) { inExt[idx*2+1] = wholeExtent[idx*2]; } if (inExt[idx*2 + 1] > wholeExtent[idx*2 + 1]) { inExt[idx*2 + 1] = wholeExtent[idx*2 + 1]; } } } //---------------------------------------------------------------------------- // This execute method handles boundaries. Pixels are just replicated to get // values out of extent. template <class T> static void vtkImageConvolveExecute(vtkImageConvolve *self, vtkImageData *inData, T *inPtr, vtkImageData *outData, T *outPtr, int outExt[6], int id) { int idxC, idxX, idxY, idxZ; int maxC, maxX, maxY, maxZ; int inIncX, inIncY, inIncZ; int outIncX, outIncY, outIncZ; unsigned long count = 0; unsigned long target; int axesNum; int *wholeExtent, *inIncs; float sum, kernel[3]; int useZMin, useZMax, useYMin, useYMax, useXMin, useXMax; // find the region to loop over maxC = inData->GetNumberOfScalarComponents(); maxX = outExt[1] - outExt[0]; maxY = outExt[3] - outExt[2]; maxZ = outExt[5] - outExt[4]; target = (unsigned long)((maxZ+1)*(maxY+1)/50.0); target++; // Get the kernel self->GetKernel( kernel ); // Get the dimensionality of the gradient. axesNum = self->GetDimensionality(); // Get increments to march through data inData->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ); outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ); // get some other info we need inIncs = inData->GetIncrements(); wholeExtent = inData->GetExtent(); // Loop through ouput pixels for (idxZ = 0; idxZ <= maxZ; idxZ++) { useZMin = ((idxZ + outExt[4]) <= wholeExtent[4]) ? 0 : -inIncs[2]; useZMax = ((idxZ + outExt[4]) >= wholeExtent[5]) ? 0 : inIncs[2]; for (idxY = 0; !self->AbortExecute && idxY <= maxY; idxY++) { if (!id) { if (!(count%target)) { self->UpdateProgress(count/(50.0*target)); } count++; } useYMin = ((idxY + outExt[2]) <= wholeExtent[2]) ? 0 : -inIncs[1]; useYMax = ((idxY + outExt[2]) >= wholeExtent[3]) ? 0 : inIncs[1]; for (idxX = 0; idxX <= maxX; idxX++) { useXMin = ((idxX + outExt[0]) <= wholeExtent[0]) ? 0 : -inIncs[0]; useXMax = ((idxX + outExt[0]) >= wholeExtent[1]) ? 0 : inIncs[0]; for (idxC = 0; idxC < maxC; idxC++) { //the center kernel position sum = kernel[1]*(*inPtr); // do X axis sum += kernel[0]*(float)(inPtr[useXMin]); sum += kernel[2]*(float)(inPtr[useXMax]); // do Y axis sum += kernel[0]*(float)(inPtr[useYMin]); sum += kernel[2]*(float)(inPtr[useYMax]); if (axesNum == 3) { // do z axis sum += kernel[0]*(float)(inPtr[useZMin]); sum += kernel[2]*(float)(inPtr[useZMax]); } *outPtr = (T)sum; inPtr++; outPtr++; } } outPtr += outIncY; inPtr += inIncY; } outPtr += outIncZ; inPtr += inIncZ; } } //---------------------------------------------------------------------------- // This method contains a switch statement that calls the correct // templated function for the input data type. The output data // must match input type. This method does handle boundary conditions. void vtkImageConvolve::ThreadedExecute(vtkImageData *inData, vtkImageData *outData, int outExt[6], int id) { void *inPtr = inData->GetScalarPointerForExtent(outExt); void *outPtr = outData->GetScalarPointerForExtent(outExt); vtkDebugMacro(<< "Execute: inData = " << inData << ", outData = " << outData); // this filter expects that input is the same type as output. if (inData->GetScalarType() != outData->GetScalarType()) { vtkErrorMacro(<< "Execute: input ScalarType, " << inData->GetScalarType() << ", must match out ScalarType " << outData->GetScalarType()); return; } switch (inData->GetScalarType()) { vtkTemplateMacro7(vtkImageConvolveExecute, this, inData, (VTK_TT *)(inPtr), outData, (VTK_TT *)(outPtr), outExt, id); default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } <commit_msg>ERR:PrintSelf defect<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkImageConvolve.cxx Language: C++ Date: $Date$ Version: $Revision$ Thanks: Thanks to Zeger F. Knops who developed this class Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #include <math.h> #include "vtkImageConvolve.h" #include "vtkObjectFactory.h" //------------------------------------------------------------------------- vtkImageConvolve* vtkImageConvolve::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkImageConvolve"); if(ret) { return (vtkImageConvolve*)ret; } // If the factory was unable to create the object, then create it here. return new vtkImageConvolve; } //------------------------------------------------------------------------- // Construct an instance of vtkImageLaplacian fitler. vtkImageConvolve::vtkImageConvolve() { this->Dimensionality = 2; this->Kernel[0] = 1.0; this->Kernel[1] = 0.0; this->Kernel[2] = 1.0; } //---------------------------------------------------------------------------- void vtkImageConvolve::PrintSelf(ostream& os, vtkIndent indent) { this->vtkImageToImageFilter::PrintSelf(os, indent); os << indent << "Dimensionality: " << this->Dimensionality; os << indent << "Kernel: (" << this->Kernel[0] << ", " << this->Kernel[1] << ", " << this->Kernel[2] << ")\n"; } //---------------------------------------------------------------------------- // Just clip the request. The subclass may need to overwrite this method. void vtkImageConvolve::ComputeInputUpdateExtent(int inExt[6], int outExt[6]) { int idx; int *wholeExtent; // handle XYZ memcpy(inExt,outExt,sizeof(int)*6); wholeExtent = this->GetInput()->GetWholeExtent(); // update and Clip for (idx = 0; idx < 3; ++idx) { --inExt[idx*2]; ++inExt[idx*2+1]; if (inExt[idx*2] < wholeExtent[idx*2]) { inExt[idx*2] = wholeExtent[idx*2]; } if (inExt[idx*2] > wholeExtent[idx*2 + 1]) { inExt[idx*2] = wholeExtent[idx*2 + 1]; } if (inExt[idx*2+1] < wholeExtent[idx*2]) { inExt[idx*2+1] = wholeExtent[idx*2]; } if (inExt[idx*2 + 1] > wholeExtent[idx*2 + 1]) { inExt[idx*2 + 1] = wholeExtent[idx*2 + 1]; } } } //---------------------------------------------------------------------------- // This execute method handles boundaries. Pixels are just replicated to get // values out of extent. template <class T> static void vtkImageConvolveExecute(vtkImageConvolve *self, vtkImageData *inData, T *inPtr, vtkImageData *outData, T *outPtr, int outExt[6], int id) { int idxC, idxX, idxY, idxZ; int maxC, maxX, maxY, maxZ; int inIncX, inIncY, inIncZ; int outIncX, outIncY, outIncZ; unsigned long count = 0; unsigned long target; int axesNum; int *wholeExtent, *inIncs; float sum, kernel[3]; int useZMin, useZMax, useYMin, useYMax, useXMin, useXMax; // find the region to loop over maxC = inData->GetNumberOfScalarComponents(); maxX = outExt[1] - outExt[0]; maxY = outExt[3] - outExt[2]; maxZ = outExt[5] - outExt[4]; target = (unsigned long)((maxZ+1)*(maxY+1)/50.0); target++; // Get the kernel self->GetKernel( kernel ); // Get the dimensionality of the gradient. axesNum = self->GetDimensionality(); // Get increments to march through data inData->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ); outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ); // get some other info we need inIncs = inData->GetIncrements(); wholeExtent = inData->GetExtent(); // Loop through ouput pixels for (idxZ = 0; idxZ <= maxZ; idxZ++) { useZMin = ((idxZ + outExt[4]) <= wholeExtent[4]) ? 0 : -inIncs[2]; useZMax = ((idxZ + outExt[4]) >= wholeExtent[5]) ? 0 : inIncs[2]; for (idxY = 0; !self->AbortExecute && idxY <= maxY; idxY++) { if (!id) { if (!(count%target)) { self->UpdateProgress(count/(50.0*target)); } count++; } useYMin = ((idxY + outExt[2]) <= wholeExtent[2]) ? 0 : -inIncs[1]; useYMax = ((idxY + outExt[2]) >= wholeExtent[3]) ? 0 : inIncs[1]; for (idxX = 0; idxX <= maxX; idxX++) { useXMin = ((idxX + outExt[0]) <= wholeExtent[0]) ? 0 : -inIncs[0]; useXMax = ((idxX + outExt[0]) >= wholeExtent[1]) ? 0 : inIncs[0]; for (idxC = 0; idxC < maxC; idxC++) { //the center kernel position sum = kernel[1]*(*inPtr); // do X axis sum += kernel[0]*(float)(inPtr[useXMin]); sum += kernel[2]*(float)(inPtr[useXMax]); // do Y axis sum += kernel[0]*(float)(inPtr[useYMin]); sum += kernel[2]*(float)(inPtr[useYMax]); if (axesNum == 3) { // do z axis sum += kernel[0]*(float)(inPtr[useZMin]); sum += kernel[2]*(float)(inPtr[useZMax]); } *outPtr = (T)sum; inPtr++; outPtr++; } } outPtr += outIncY; inPtr += inIncY; } outPtr += outIncZ; inPtr += inIncZ; } } //---------------------------------------------------------------------------- // This method contains a switch statement that calls the correct // templated function for the input data type. The output data // must match input type. This method does handle boundary conditions. void vtkImageConvolve::ThreadedExecute(vtkImageData *inData, vtkImageData *outData, int outExt[6], int id) { void *inPtr = inData->GetScalarPointerForExtent(outExt); void *outPtr = outData->GetScalarPointerForExtent(outExt); vtkDebugMacro(<< "Execute: inData = " << inData << ", outData = " << outData); // this filter expects that input is the same type as output. if (inData->GetScalarType() != outData->GetScalarType()) { vtkErrorMacro(<< "Execute: input ScalarType, " << inData->GetScalarType() << ", must match out ScalarType " << outData->GetScalarType()); return; } switch (inData->GetScalarType()) { vtkTemplateMacro7(vtkImageConvolveExecute, this, inData, (VTK_TT *)(inPtr), outData, (VTK_TT *)(outPtr), outExt, id); default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } <|endoftext|>
<commit_before>/* Copyright (c) 2010, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "test.hpp" #include "setup_transfer.hpp" #include "udp_tracker.hpp" #include "libtorrent/alert.hpp" #include "libtorrent/session.hpp" #include "libtorrent/error_code.hpp" #include <fstream> using namespace libtorrent; int test_main() { int http_port = start_web_server(); int udp_port = start_udp_tracker(); int prev_udp_announces = num_udp_announces(); int const alert_mask = alert::all_categories & ~alert::progress_notification & ~alert::stats_notification; session* s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48875, 49800), "0.0.0.0", 0, alert_mask); session_settings sett; sett.half_open_limit = 1; sett.announce_to_all_trackers = true; sett.announce_to_all_tiers = true; s->set_settings(sett); error_code ec; remove_all("tmp1_tracker", ec); create_directory("tmp1_tracker", ec); std::ofstream file(combine_path("tmp1_tracker", "temporary").c_str()); boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024, 13, false); file.close(); char tracker_url[200]; snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port); t->add_tracker(tracker_url, 0); snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port); t->add_tracker(tracker_url, 1); add_torrent_params addp; addp.flags &= ~add_torrent_params::flag_paused; addp.flags &= ~add_torrent_params::flag_auto_managed; addp.flags |= add_torrent_params::flag_seed_mode; addp.ti = t; addp.save_path = "tmp1_tracker"; torrent_handle h = s->add_torrent(addp); for (int i = 0; i < 50; ++i) { print_alerts(*s, "s"); if (num_udp_announces() == prev_udp_announces + 1) break; test_sleep(100); fprintf(stderr, "UDP: %d / %d\n", int(g_udp_tracker_requests) , int(prev_udp_announces) + 1); } // we should have announced to the tracker by now TEST_EQUAL(num_udp_announces(), prev_udp_announces + 1); fprintf(stderr, "destructing session\n"); delete s; fprintf(stderr, "done\n"); // we should have announced the stopped event now TEST_EQUAL(num_udp_announces(), prev_udp_announces + 2); // ======================================== // test that we move on to try the next tier if the first one fails // ======================================== s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(39775, 39800), "0.0.0.0", 0, alert_mask); sett.half_open_limit = 1; sett.announce_to_all_trackers = true; sett.announce_to_all_tiers = false; sett.tracker_completion_timeout = 2; sett.tracker_receive_timeout = 1; s->set_settings(sett); remove_all("tmp2_tracker", ec); create_directory("tmp2_tracker", ec); file.open(combine_path("tmp2_tracker", "temporary").c_str()); t = ::create_torrent(&file, 16 * 1024, 13, false); file.close(); // this should fail snprintf(tracker_url, sizeof(tracker_url), "udp://www1.non-existent.com:80/announce"); t->add_tracker(tracker_url, 0); // and this should fail snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.2:3/announce"); t->add_tracker(tracker_url, 1); // this should be announced to // udp trackers are prioritized if they're on the same host as an http one // so this must be before the http one on 127.0.0.1 snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port); t->add_tracker(tracker_url, 2); // and this should not be announced to (since the one before it succeeded) snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port); t->add_tracker(tracker_url, 3); prev_udp_announces = num_udp_announces(); addp.flags &= ~add_torrent_params::flag_paused; addp.flags &= ~add_torrent_params::flag_auto_managed; addp.flags |= add_torrent_params::flag_seed_mode; addp.ti = t; addp.save_path = "tmp2_tracker"; h = s->add_torrent(addp); for (int i = 0; i < 50; ++i) { print_alerts(*s, "s"); if (num_udp_announces() == prev_udp_announces + 1) break; fprintf(stderr, "UDP: %d / %d\n", int(num_udp_announces()) , int(prev_udp_announces) + 1); test_sleep(100); } test_sleep(1000); TEST_EQUAL(num_udp_announces(), prev_udp_announces + 1); fprintf(stderr, "destructing session\n"); delete s; fprintf(stderr, "done\n"); fprintf(stderr, "stop_tracker\n"); stop_udp_tracker(); fprintf(stderr, "stop_web_server\n"); stop_web_server(); fprintf(stderr, "done\n"); return 0; } <commit_msg>fix merge typo<commit_after>/* Copyright (c) 2010, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "test.hpp" #include "setup_transfer.hpp" #include "udp_tracker.hpp" #include "libtorrent/alert.hpp" #include "libtorrent/session.hpp" #include "libtorrent/error_code.hpp" #include <fstream> using namespace libtorrent; int test_main() { int http_port = start_web_server(); int udp_port = start_udp_tracker(); int prev_udp_announces = num_udp_announces(); int const alert_mask = alert::all_categories & ~alert::progress_notification & ~alert::stats_notification; session* s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48875, 49800), "0.0.0.0", 0, alert_mask); session_settings sett; sett.half_open_limit = 1; sett.announce_to_all_trackers = true; sett.announce_to_all_tiers = true; s->set_settings(sett); error_code ec; remove_all("tmp1_tracker", ec); create_directory("tmp1_tracker", ec); std::ofstream file(combine_path("tmp1_tracker", "temporary").c_str()); boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024, 13, false); file.close(); char tracker_url[200]; snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port); t->add_tracker(tracker_url, 0); snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port); t->add_tracker(tracker_url, 1); add_torrent_params addp; addp.flags &= ~add_torrent_params::flag_paused; addp.flags &= ~add_torrent_params::flag_auto_managed; addp.flags |= add_torrent_params::flag_seed_mode; addp.ti = t; addp.save_path = "tmp1_tracker"; torrent_handle h = s->add_torrent(addp); for (int i = 0; i < 50; ++i) { print_alerts(*s, "s"); if (num_udp_announces() == prev_udp_announces + 1) break; test_sleep(100); fprintf(stderr, "UDP: %d / %d\n", int(num_udp_announces()) , int(prev_udp_announces) + 1); } // we should have announced to the tracker by now TEST_EQUAL(num_udp_announces(), prev_udp_announces + 1); fprintf(stderr, "destructing session\n"); delete s; fprintf(stderr, "done\n"); // we should have announced the stopped event now TEST_EQUAL(num_udp_announces(), prev_udp_announces + 2); // ======================================== // test that we move on to try the next tier if the first one fails // ======================================== s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(39775, 39800), "0.0.0.0", 0, alert_mask); sett.half_open_limit = 1; sett.announce_to_all_trackers = true; sett.announce_to_all_tiers = false; sett.tracker_completion_timeout = 2; sett.tracker_receive_timeout = 1; s->set_settings(sett); remove_all("tmp2_tracker", ec); create_directory("tmp2_tracker", ec); file.open(combine_path("tmp2_tracker", "temporary").c_str()); t = ::create_torrent(&file, 16 * 1024, 13, false); file.close(); // this should fail snprintf(tracker_url, sizeof(tracker_url), "udp://www1.non-existent.com:80/announce"); t->add_tracker(tracker_url, 0); // and this should fail snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.2:3/announce"); t->add_tracker(tracker_url, 1); // this should be announced to // udp trackers are prioritized if they're on the same host as an http one // so this must be before the http one on 127.0.0.1 snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port); t->add_tracker(tracker_url, 2); // and this should not be announced to (since the one before it succeeded) snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port); t->add_tracker(tracker_url, 3); prev_udp_announces = num_udp_announces(); addp.flags &= ~add_torrent_params::flag_paused; addp.flags &= ~add_torrent_params::flag_auto_managed; addp.flags |= add_torrent_params::flag_seed_mode; addp.ti = t; addp.save_path = "tmp2_tracker"; h = s->add_torrent(addp); for (int i = 0; i < 50; ++i) { print_alerts(*s, "s"); if (num_udp_announces() == prev_udp_announces + 1) break; fprintf(stderr, "UDP: %d / %d\n", int(num_udp_announces()) , int(prev_udp_announces) + 1); test_sleep(100); } test_sleep(1000); TEST_EQUAL(num_udp_announces(), prev_udp_announces + 1); fprintf(stderr, "destructing session\n"); delete s; fprintf(stderr, "done\n"); fprintf(stderr, "stop_tracker\n"); stop_udp_tracker(); fprintf(stderr, "stop_web_server\n"); stop_web_server(); fprintf(stderr, "done\n"); return 0; } <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "GeneralUserObject.h" template <> InputParameters validParams<GeneralUserObject>() { InputParameters params = validParams<UserObject>(); params += validParams<MaterialPropertyInterface>(); params.addParam<bool>( "threaded", false, "true if there should be threaded copies of this user object."); params.addParam<bool>( "force_preaux", false, "Forces the GeneralUserObject to be executed in PREAUX"); params.addParamNamesToGroup("force_preaux", "Advanced"); return params; } GeneralUserObject::GeneralUserObject(const InputParameters & parameters) : UserObject(parameters), MaterialPropertyInterface(this, Moose::EMPTY_BLOCK_IDS, Moose::EMPTY_BOUNDARY_IDS), TransientInterface(this), DependencyResolverInterface(), UserObjectInterface(this), PostprocessorInterface(this), VectorPostprocessorInterface(this) { _supplied_vars.insert(name()); } const std::set<std::string> & GeneralUserObject::getRequestedItems() { return _depend_vars; } const std::set<std::string> & GeneralUserObject::getSuppliedItems() { return _supplied_vars; } const PostprocessorValue & GeneralUserObject::getPostprocessorValue(const std::string & name) { _depend_vars.insert(_pars.get<PostprocessorName>(name)); return PostprocessorInterface::getPostprocessorValue(name); } const PostprocessorValue & GeneralUserObject::getPostprocessorValueByName(const PostprocessorName & name) { _depend_vars.insert(name); return PostprocessorInterface::getPostprocessorValueByName(name); } const VectorPostprocessorValue & GeneralUserObject::getVectorPostprocessorValue(const std::string & name, const std::string & vector_name) { _depend_vars.insert(_pars.get<VectorPostprocessorName>(name)); return VectorPostprocessorInterface::getVectorPostprocessorValue(name, vector_name); } const VectorPostprocessorValue & GeneralUserObject::getVectorPostprocessorValueByName(const VectorPostprocessorName & name, const std::string & vector_name) { _depend_vars.insert(name); return VectorPostprocessorInterface::getVectorPostprocessorValueByName(name, vector_name); } const VectorPostprocessorValue & GeneralUserObject::getVectorPostprocessorValue(const std::string & name, const std::string & vector_name, bool use_broadcast) { _depend_vars.insert(_pars.get<VectorPostprocessorName>(name)); return VectorPostprocessorInterface::getVectorPostprocessorValue( name, vector_name, use_broadcast); } const VectorPostprocessorValue & GeneralUserObject::getVectorPostprocessorValueByName(const VectorPostprocessorName & name, const std::string & vector_name, bool use_broadcast) { _depend_vars.insert(name); return VectorPostprocessorInterface::getVectorPostprocessorValueByName( name, vector_name, use_broadcast); } void GeneralUserObject::threadJoin(const UserObject &) { mooseError("GeneralUserObjects do not execute using threads, this function does nothing and " "should not be used."); } void GeneralUserObject::subdomainSetup() { mooseError("GeneralUserObjects do not execute subdomainSetup method, this function does nothing " "and should not be used."); } <commit_msg>Prevent threaded general user objects with pthread<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "GeneralUserObject.h" template <> InputParameters validParams<GeneralUserObject>() { InputParameters params = validParams<UserObject>(); params += validParams<MaterialPropertyInterface>(); params.addParam<bool>( "threaded", false, "true if there should be threaded copies of this user object."); params.addParam<bool>( "force_preaux", false, "Forces the GeneralUserObject to be executed in PREAUX"); params.addParamNamesToGroup("force_preaux", "Advanced"); return params; } GeneralUserObject::GeneralUserObject(const InputParameters & parameters) : UserObject(parameters), MaterialPropertyInterface(this, Moose::EMPTY_BLOCK_IDS, Moose::EMPTY_BOUNDARY_IDS), TransientInterface(this), DependencyResolverInterface(), UserObjectInterface(this), PostprocessorInterface(this), VectorPostprocessorInterface(this) { #if !defined(LIBMESH_HAVE_OPENMP) && !defined(LIBMESH_HAVE_TBB_API) if (getParam<bool>("threaded")) mooseError(name(), ": You cannot use threaded general user objects with pthreads. To enable this " "functionality configure libMesh with OpenMP or TBB."); #endif _supplied_vars.insert(name()); } const std::set<std::string> & GeneralUserObject::getRequestedItems() { return _depend_vars; } const std::set<std::string> & GeneralUserObject::getSuppliedItems() { return _supplied_vars; } const PostprocessorValue & GeneralUserObject::getPostprocessorValue(const std::string & name) { _depend_vars.insert(_pars.get<PostprocessorName>(name)); return PostprocessorInterface::getPostprocessorValue(name); } const PostprocessorValue & GeneralUserObject::getPostprocessorValueByName(const PostprocessorName & name) { _depend_vars.insert(name); return PostprocessorInterface::getPostprocessorValueByName(name); } const VectorPostprocessorValue & GeneralUserObject::getVectorPostprocessorValue(const std::string & name, const std::string & vector_name) { _depend_vars.insert(_pars.get<VectorPostprocessorName>(name)); return VectorPostprocessorInterface::getVectorPostprocessorValue(name, vector_name); } const VectorPostprocessorValue & GeneralUserObject::getVectorPostprocessorValueByName(const VectorPostprocessorName & name, const std::string & vector_name) { _depend_vars.insert(name); return VectorPostprocessorInterface::getVectorPostprocessorValueByName(name, vector_name); } const VectorPostprocessorValue & GeneralUserObject::getVectorPostprocessorValue(const std::string & name, const std::string & vector_name, bool use_broadcast) { _depend_vars.insert(_pars.get<VectorPostprocessorName>(name)); return VectorPostprocessorInterface::getVectorPostprocessorValue( name, vector_name, use_broadcast); } const VectorPostprocessorValue & GeneralUserObject::getVectorPostprocessorValueByName(const VectorPostprocessorName & name, const std::string & vector_name, bool use_broadcast) { _depend_vars.insert(name); return VectorPostprocessorInterface::getVectorPostprocessorValueByName( name, vector_name, use_broadcast); } void GeneralUserObject::threadJoin(const UserObject &) { mooseError("GeneralUserObjects do not execute using threads, this function does nothing and " "should not be used."); } void GeneralUserObject::subdomainSetup() { mooseError("GeneralUserObjects do not execute subdomainSetup method, this function does nothing " "and should not be used."); } <|endoftext|>
<commit_before>#define BOOST_TEST_DYN_LINK #include "support.hpp" #include <iostream> #include <boost/test/unit_test.hpp> #include <libpc/Utils.hpp> bool compare_files(const std::string& file1, const std::string& file2) { uintmax_t len1 = libpc::Utils::fileSize(file1); uintmax_t len2 = libpc::Utils::fileSize(file1); if (len1 != len2) { return false; } std::istream* str1 = libpc::Utils::openFile(file1); std::istream* str2 = libpc::Utils::openFile(file2); BOOST_CHECK(str1); BOOST_CHECK(str2); char* buf1 = new char[len1]; char* buf2 = new char[len2]; str1->read(buf1,len1); str2->read (buf2,len2); libpc::Utils::closeFile(str1); libpc::Utils::closeFile(str2); char* p = buf1; char* q = buf2; for (uintmax_t i=0; i<len1; i++) { if (*p != *q) { delete[] buf1; delete[] buf2; return false; } ++p; ++q; } delete[] buf1; delete[] buf2; return true; } <commit_msg>fix dyn linkage<commit_after>#ifdef _MSC_VER #define BOOST_TEST_DYN_LINK #endif #include "support.hpp" #include <iostream> #include <boost/test/unit_test.hpp> #include <libpc/Utils.hpp> bool compare_files(const std::string& file1, const std::string& file2) { uintmax_t len1 = libpc::Utils::fileSize(file1); uintmax_t len2 = libpc::Utils::fileSize(file1); if (len1 != len2) { return false; } std::istream* str1 = libpc::Utils::openFile(file1); std::istream* str2 = libpc::Utils::openFile(file2); BOOST_CHECK(str1); BOOST_CHECK(str2); char* buf1 = new char[len1]; char* buf2 = new char[len2]; str1->read(buf1,len1); str2->read (buf2,len2); libpc::Utils::closeFile(str1); libpc::Utils::closeFile(str2); char* p = buf1; char* q = buf2; for (uintmax_t i=0; i<len1; i++) { if (*p != *q) { delete[] buf1; delete[] buf2; return false; } ++p; ++q; } delete[] buf1; delete[] buf2; return true; } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ // Helper class to interface pdflib and the TPythia // the c++ interface for Pythia // The pdf codes used in pdflib are mapped // to a more user friendly enumeration type. // Author: [email protected] #include "AliStructFuncType.h" #ifndef WIN32 # define structa structa_ # define pdfset pdfset_ # define type_of_call #else # define structa STRUCTA # define pdfset PDFSET # define type_of_call _stdcall #endif extern "C" { void type_of_call pdfset(char parm[20][20], Double_t value[20]); void type_of_call structa(Double_t& xx, Double_t& qq, Double_t& a, Double_t& upv, Double_t& dnv, Double_t& usea, Double_t& dsea, Double_t& str, Double_t& chm, Double_t& bot, Double_t& top, Double_t& gl); } ClassImp(AliStructFuncType) void AliStructFuncType::PdfSet(char parm[20][20], Double_t value[20]) { pdfset(parm, value); } void AliStructFuncType::StructA(Double_t xx, Double_t qq, Double_t a, Double_t& upv, Double_t& dnv, Double_t& usea, Double_t& dsea, Double_t& str, Double_t& chm, Double_t& bot, Double_t& top, Double_t& gl) { structa(xx, qq, a, upv, dnv, usea, dsea, str, chm, bot, top, gl); } Int_t AliStructFuncType::PDFsetIndex(StrucFunc_t pdf) { // PDF set index Int_t pdfSetNumber[10] = { 19170, 19150, 19070, 19050, 80060, 10040, 10100, 10050, 10041, 10042 }; return pdfSetNumber[pdf]; } TString AliStructFuncType::PDFsetName(StrucFunc_t pdf) { // PDF Set Name TString pdfsetName[10] = { "cteq4l.LHgrid", "cteq4m.LHgrid", "cteq5l.LHgrid", "cteq5m.LHgrid", "GRV98lo.LHgris", "cteq6.LHpdf", "cteq61.LHpdf", "cteq6m.LHpdf", "cteq6l.LHpdf", "cteq6ll.LHpdf" }; return pdfsetName[pdf]; } <commit_msg>Typo<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ // Helper class to interface pdflib and the TPythia // the c++ interface for Pythia // The pdf codes used in pdflib are mapped // to a more user friendly enumeration type. // Author: [email protected] #include "AliStructFuncType.h" #ifndef WIN32 # define structa structa_ # define pdfset pdfset_ # define type_of_call #else # define structa STRUCTA # define pdfset PDFSET # define type_of_call _stdcall #endif extern "C" { void type_of_call pdfset(char parm[20][20], Double_t value[20]); void type_of_call structa(Double_t& xx, Double_t& qq, Double_t& a, Double_t& upv, Double_t& dnv, Double_t& usea, Double_t& dsea, Double_t& str, Double_t& chm, Double_t& bot, Double_t& top, Double_t& gl); } ClassImp(AliStructFuncType) void AliStructFuncType::PdfSet(char parm[20][20], Double_t value[20]) { pdfset(parm, value); } void AliStructFuncType::StructA(Double_t xx, Double_t qq, Double_t a, Double_t& upv, Double_t& dnv, Double_t& usea, Double_t& dsea, Double_t& str, Double_t& chm, Double_t& bot, Double_t& top, Double_t& gl) { structa(xx, qq, a, upv, dnv, usea, dsea, str, chm, bot, top, gl); } Int_t AliStructFuncType::PDFsetIndex(StrucFunc_t pdf) { // PDF set index Int_t pdfSetNumber[10] = { 19170, 19150, 19070, 19050, 80060, 10040, 10100, 10050, 10041, 10042 }; return pdfSetNumber[pdf]; } TString AliStructFuncType::PDFsetName(StrucFunc_t pdf) { // PDF Set Name TString pdfsetName[10] = { "cteq4l.LHgrid", "cteq4m.LHgrid", "cteq5l.LHgrid", "cteq5m.LHgrid", "GRV98lo.LHgrid", "cteq6.LHpdf", "cteq61.LHpdf", "cteq6m.LHpdf", "cteq6l.LHpdf", "cteq6ll.LHpdf" }; return pdfsetName[pdf]; } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" //#include <gl.h> #include <iostream> #include <rocklevel/tilemap.h> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setMouseTracking(true); qApp->installEventFilter(this); //ui->gameDrawWidget->setFocus(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::OpenResourcesDirectory() { if(!QDir(qApp->applicationDirPath() + "/res/").exists()) { std::cout << "resource path didn't exist, making" << std::endl; QDir().mkdir(qApp->applicationDirPath() + "/res/"); } QString path = QDir::toNativeSeparators(qApp->applicationDirPath() + "/res/"); QDesktopServices::openUrl(QUrl::fromLocalFile(path)); } QString MainWindow::getResourcesDirectory() { return QDir::toNativeSeparators(qApp->applicationDirPath() + "/res/"); } /* void MainWindow::mouseMoveEvent(QMouseEvent *event) { std::cout << "mouse move shit" << std::endl; ui->gameDrawWidget->update(); if(ui->gameDrawWidget->rect().contains(event->pos())) { ui->gameDrawWidget->update(); } } void MainWindow::mousePressEvent(QMouseEvent *event) { if(this->isActiveWindow()) { if(event->button() == Qt::MouseButton::LeftButton) { if(ui->gameDrawWidget->rect().contains(QCursor::pos())) { std::cout << "triggered" << std::endl; } } } } */ bool MainWindow::eventFilter(QObject *watched, QEvent *event) { if(event->type() == QEvent::MouseMove) { ui->gameDrawWidget->update(); } else if(event->type() == QEvent::Wheel) { if(ui->gameDrawWidget->underMouse()) { QWheelEvent* wheelie = (QWheelEvent*)event; int dx, dy; dx = wheelie->angleDelta().x(); dy = wheelie->angleDelta().y(); ui->verticalScrollBar->setValue(ui->verticalScrollBar->value() + -fmin(ceil(dy / 4), 2)); ui->horizontalScrollBar->setValue(ui->horizontalScrollBar->value() + -fmin(ceil(dx / 4), 2)); return true; } } else if(event->type() == QEvent::MouseButtonPress) { if(this->isActiveWindow()) { //if(ui->gameDrawWidget->rect().contains(QCursor::pos())) if(ui->gameDrawWidget->underMouse()) { ui->gameDrawWidget->placeTileAction(); setWindowModified(true); return true; } else { //this->mousePressEvent((QMouseEvent*)event); QWidget::eventFilter(watched, event); return false; } } else return false; } else if(event->type() == QEvent::KeyPress) { /* QKeyEvent* keyEvent = (QKeyEvent*)event; switch(keyEvent->key()) { case Qt::Key_Right: ui->gameDrawWidget->moveCamera(-16, 0); break; } return true; */ } return false; } void MainWindow::on_gameDrawWidget_aboutToCompose() { } QImage createSubImage(QImage* image, const QRect & rect) { size_t offset = rect.x() * image->depth() / 8 + rect.y() * image->bytesPerLine(); return QImage(image->bits() + offset, rect.width(), rect.height(), image->bytesPerLine(), image->format()); } void MainWindow::on_gameDrawWidget_frameSwapped() { if(!initialSetupDone) { populateTileList(); initialSetupDone = true; } } void MainWindow::populateTileList() { ui->listWidget->clear(); for(int i = 0; i < (8*8); i++) { //tile_get_location_by_id QListWidgetItem* test = new QListWidgetItem("Tile " + QString::number(i), ui->listWidget); QRect rect; vector_t tile_area = tile_get_location_by_id(i); rect.setX(tile_area.x); rect.setY(tile_area.y); rect.setWidth(TILE_WIDTH); rect.setHeight(TILE_HEIGHT); QImage* atlas = ui->gameDrawWidget->getMainTexture()->toQImage(); test->setIcon(QIcon(QPixmap::fromImage(createSubImage(atlas, rect)))); } //we also adjust the scroll bar values ui->horizontalScrollBar->setMaximum(ui->gameDrawWidget->getCurrentTilemap()->width / 2); ui->verticalScrollBar->setMaximum(ui->gameDrawWidget->getCurrentTilemap()->height); ui->gameDrawWidget->update(); //manually update so that it shows up without having to move the mouse //1 notch on the scroll bar will move exactly one tile } void MainWindow::onFileSelected(const QString& filename) { if(!filename.isEmpty()) { if(ui->gameDrawWidget->loadTilemap(filename)) { QFileInfo levelFileInfo(filename); this->currentLevelPath = filename; ui->levelNameTextBox->setText(ui->gameDrawWidget->getCurrentTilemap()->map_name); setWindowFilePath(filename); setWindowTitle(levelFileInfo.fileName() + "[*] - Level Editor"); setWindowModified(false); populateTileList(); //repopulate the tile list } } else return; //do nothing } void MainWindow::onFileSelectedForSaving(const QString &filename) { if(!filename.isEmpty()) { tilemap_write_to_file(filename.toStdString().c_str(), ui->gameDrawWidget->getCurrentTilemap()); this->currentLevelPath = filename; setWindowModified(false); setWindowTitle(QFileInfo(filename).fileName() + "[*] - Level Editor"); setWindowFilePath(filename); if(this->isQuitting) qApp->quit(); } else std::cout << "filename blank" << std::endl; } void MainWindow::on_actionOpen_triggered() { QString fileName; QFileDialog* f = new QFileDialog(this, Qt::Sheet); #ifdef __APPLE__ f->setWindowModality(Qt::WindowModal); #endif QDir d(""); d.setNameFilters(QStringList() << "Bin File (*.bin)"); f->setFilter(d.filter()); connect(f, &QFileDialog::fileSelected, this, &MainWindow::onFileSelected); f->open(); } void MainWindow::openLevel() {} void MainWindow::saveLevel() {} void MainWindow::on_levelNameTextBox_returnPressed() { setWindowModified(true); ui->gameDrawWidget->setTileMapName(ui->levelNameTextBox->text().toUtf8().data()); } void MainWindow::performSaveAs() { QString fileName; QFileDialog* f = new QFileDialog(this, Qt::Sheet); f->setAcceptMode(QFileDialog::AcceptSave); #if __APPLE__ f->setWindowModality(Qt::WindowModal); #endif QDir d(""); d.setNameFilters(QStringList() << "Bin File (*.bin)"); f->setFilter(d.filter()); connect(f, &QFileDialog::fileSelected, this, &MainWindow::onFileSelectedForSaving); f->open(); } void MainWindow::on_actionSave_triggered() { if(!currentLevelPath.isEmpty()) { tilemap_write_to_file(currentLevelPath.toStdString().c_str(), ui->gameDrawWidget->getCurrentTilemap()); setWindowModified(false); } else performSaveAs(); } void MainWindow::on_actionSave_As_triggered() { performSaveAs(); } void MainWindow::on_actionOpen_resource_path_triggered() { MainWindow::OpenResourcesDirectory(); } void MainWindow::on_listWidget_itemClicked(QListWidgetItem *item) { //this is all super hacky and i'm not proud QString* string = new QString(item->text()); QStringRef substr(string, 5, 2); //std::cout << "Selected '" << substr.toString().toStdString() << "'" << std::endl; ui->gameDrawWidget->setPlacingTileID(item->text().split(" ")[1].toInt()); ui->gameDrawWidget->setPlacingTileRotation(0); } void MainWindow::on_pushButton_clicked() { ui->gameDrawWidget->setPlacingTileRotation(ui->gameDrawWidget->getPlacingTileRotation() + 90); } void MainWindow::on_pushButton_2_clicked() { ui->gameDrawWidget->setPlacingTileRotation(ui->gameDrawWidget->getPlacingTileRotation() - 90); } void MainWindow::on_pushButton_3_clicked() { ui->gameDrawWidget->setPlacingTileRotation(0); } void MainWindow::closeEvent(QCloseEvent* event) { if(this->isWindowModified()) //has changes { QMessageBox quitBox(this); quitBox.setText("Level has been modified"); quitBox.setInformativeText("Would you like to save your changes?"); quitBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); quitBox.setDefaultButton(QMessageBox::Save); //quitBox.setParent(this); quitBox.setIcon(QMessageBox::Information); quitBox.setWindowModality(Qt::WindowModal); quitBox.setModal(true); int returnValue = quitBox.exec(); switch(returnValue) { case QMessageBox::Save: performSaveAs(); event->ignore(); this->isQuitting = true; break; case QMessageBox::Discard: //do nothing break; case QMessageBox::Cancel: event->ignore(); break; } } else { //quit as normally } } void MainWindow::on_horizontalScrollBar_sliderMoved(int position) {} void MainWindow::on_verticalScrollBar_sliderMoved(int position) {} void MainWindow::on_horizontalScrollBar_valueChanged(int value) { ui->gameDrawWidget->setCameraPosition(-value * 32, -1); ui->gameDrawWidget->update(); } void MainWindow::on_verticalScrollBar_valueChanged(int value) { ui->gameDrawWidget->setCameraPosition(-1, -value * 32); ui->gameDrawWidget->update(); } void MainWindow::on_actionClose_triggered() { this->close(); } <commit_msg>mouse wheel tweaking<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" //#include <gl.h> #include <iostream> #include <rocklevel/tilemap.h> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setMouseTracking(true); qApp->installEventFilter(this); //ui->gameDrawWidget->setFocus(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::OpenResourcesDirectory() { if(!QDir(qApp->applicationDirPath() + "/res/").exists()) { std::cout << "resource path didn't exist, making" << std::endl; QDir().mkdir(qApp->applicationDirPath() + "/res/"); } QString path = QDir::toNativeSeparators(qApp->applicationDirPath() + "/res/"); QDesktopServices::openUrl(QUrl::fromLocalFile(path)); } QString MainWindow::getResourcesDirectory() { return QDir::toNativeSeparators(qApp->applicationDirPath() + "/res/"); } /* void MainWindow::mouseMoveEvent(QMouseEvent *event) { std::cout << "mouse move shit" << std::endl; ui->gameDrawWidget->update(); if(ui->gameDrawWidget->rect().contains(event->pos())) { ui->gameDrawWidget->update(); } } void MainWindow::mousePressEvent(QMouseEvent *event) { if(this->isActiveWindow()) { if(event->button() == Qt::MouseButton::LeftButton) { if(ui->gameDrawWidget->rect().contains(QCursor::pos())) { std::cout << "triggered" << std::endl; } } } } */ bool MainWindow::eventFilter(QObject *watched, QEvent *event) { if(event->type() == QEvent::MouseMove) { ui->gameDrawWidget->update(); } else if(event->type() == QEvent::Wheel) { if(ui->gameDrawWidget->underMouse()) { QWheelEvent* wheelie = (QWheelEvent*)event; int dx, dy; dx = wheelie->angleDelta().x(); dy = wheelie->angleDelta().y(); //ui->verticalScrollBar->setValue(ui->verticalScrollBar->value() + -fmin(ceil(dy / 4), 2)); //ui->horizontalScrollBar->setValue(ui->horizontalScrollBar->value() + -fmin(ceil(dx / 4), 2)); if(dx > 0) dx = 32; else if(dx < 0) dx = -32; if(dy > 0) dy = 32; else if(dy < 0) dy = -32; //std::cout << "mouse wheel: " << dx << ", " << dy << std::endl; ui->verticalScrollBar->setValue(ui->verticalScrollBar->value() + (-dy / 8)); ui->horizontalScrollBar->setValue(ui->horizontalScrollBar->value() + (-dx / 8)); return true; } } else if(event->type() == QEvent::MouseButtonPress) { if(this->isActiveWindow()) { //if(ui->gameDrawWidget->rect().contains(QCursor::pos())) if(ui->gameDrawWidget->underMouse()) { ui->gameDrawWidget->placeTileAction(); setWindowModified(true); return true; } else { //this->mousePressEvent((QMouseEvent*)event); QWidget::eventFilter(watched, event); return false; } } else return false; } else if(event->type() == QEvent::KeyPress) { /* QKeyEvent* keyEvent = (QKeyEvent*)event; switch(keyEvent->key()) { case Qt::Key_Right: ui->gameDrawWidget->moveCamera(-16, 0); break; } return true; */ } return false; } void MainWindow::on_gameDrawWidget_aboutToCompose() { } QImage createSubImage(QImage* image, const QRect & rect) { size_t offset = rect.x() * image->depth() / 8 + rect.y() * image->bytesPerLine(); return QImage(image->bits() + offset, rect.width(), rect.height(), image->bytesPerLine(), image->format()); } void MainWindow::on_gameDrawWidget_frameSwapped() { if(!initialSetupDone) { populateTileList(); initialSetupDone = true; } } void MainWindow::populateTileList() { ui->listWidget->clear(); for(int i = 0; i < (8*8); i++) { //tile_get_location_by_id QListWidgetItem* test = new QListWidgetItem("Tile " + QString::number(i), ui->listWidget); QRect rect; vector_t tile_area = tile_get_location_by_id(i); rect.setX(tile_area.x); rect.setY(tile_area.y); rect.setWidth(TILE_WIDTH); rect.setHeight(TILE_HEIGHT); QImage* atlas = ui->gameDrawWidget->getMainTexture()->toQImage(); test->setIcon(QIcon(QPixmap::fromImage(createSubImage(atlas, rect)))); } //we also adjust the scroll bar values ui->horizontalScrollBar->setMaximum(ui->gameDrawWidget->getCurrentTilemap()->width / 2); ui->verticalScrollBar->setMaximum(ui->gameDrawWidget->getCurrentTilemap()->height); ui->gameDrawWidget->update(); //manually update so that it shows up without having to move the mouse //1 notch on the scroll bar will move exactly one tile } void MainWindow::onFileSelected(const QString& filename) { if(!filename.isEmpty()) { if(ui->gameDrawWidget->loadTilemap(filename)) { QFileInfo levelFileInfo(filename); this->currentLevelPath = filename; ui->levelNameTextBox->setText(ui->gameDrawWidget->getCurrentTilemap()->map_name); setWindowFilePath(filename); setWindowTitle(levelFileInfo.fileName() + "[*] - Level Editor"); setWindowModified(false); populateTileList(); //repopulate the tile list } } else return; //do nothing } void MainWindow::onFileSelectedForSaving(const QString &filename) { if(!filename.isEmpty()) { tilemap_write_to_file(filename.toStdString().c_str(), ui->gameDrawWidget->getCurrentTilemap()); this->currentLevelPath = filename; setWindowModified(false); setWindowTitle(QFileInfo(filename).fileName() + "[*] - Level Editor"); setWindowFilePath(filename); if(this->isQuitting) qApp->quit(); } else std::cout << "filename blank" << std::endl; } void MainWindow::on_actionOpen_triggered() { QString fileName; QFileDialog* f = new QFileDialog(this, Qt::Sheet); #ifdef __APPLE__ f->setWindowModality(Qt::WindowModal); #endif QDir d(""); d.setNameFilters(QStringList() << "Bin File (*.bin)"); f->setFilter(d.filter()); connect(f, &QFileDialog::fileSelected, this, &MainWindow::onFileSelected); f->open(); } void MainWindow::openLevel() {} void MainWindow::saveLevel() {} void MainWindow::on_levelNameTextBox_returnPressed() { setWindowModified(true); ui->gameDrawWidget->setTileMapName(ui->levelNameTextBox->text().toUtf8().data()); } void MainWindow::performSaveAs() { QString fileName; QFileDialog* f = new QFileDialog(this, Qt::Sheet); f->setAcceptMode(QFileDialog::AcceptSave); #if __APPLE__ f->setWindowModality(Qt::WindowModal); #endif QDir d(""); d.setNameFilters(QStringList() << "Bin File (*.bin)"); f->setFilter(d.filter()); connect(f, &QFileDialog::fileSelected, this, &MainWindow::onFileSelectedForSaving); f->open(); } void MainWindow::on_actionSave_triggered() { if(!currentLevelPath.isEmpty()) { tilemap_write_to_file(currentLevelPath.toStdString().c_str(), ui->gameDrawWidget->getCurrentTilemap()); setWindowModified(false); } else performSaveAs(); } void MainWindow::on_actionSave_As_triggered() { performSaveAs(); } void MainWindow::on_actionOpen_resource_path_triggered() { MainWindow::OpenResourcesDirectory(); } void MainWindow::on_listWidget_itemClicked(QListWidgetItem *item) { //this is all super hacky and i'm not proud QString* string = new QString(item->text()); QStringRef substr(string, 5, 2); //std::cout << "Selected '" << substr.toString().toStdString() << "'" << std::endl; ui->gameDrawWidget->setPlacingTileID(item->text().split(" ")[1].toInt()); ui->gameDrawWidget->setPlacingTileRotation(0); } void MainWindow::on_pushButton_clicked() { ui->gameDrawWidget->setPlacingTileRotation(ui->gameDrawWidget->getPlacingTileRotation() + 90); } void MainWindow::on_pushButton_2_clicked() { ui->gameDrawWidget->setPlacingTileRotation(ui->gameDrawWidget->getPlacingTileRotation() - 90); } void MainWindow::on_pushButton_3_clicked() { ui->gameDrawWidget->setPlacingTileRotation(0); } void MainWindow::closeEvent(QCloseEvent* event) { if(this->isWindowModified()) //has changes { QMessageBox quitBox(this); quitBox.setText("Level has been modified"); quitBox.setInformativeText("Would you like to save your changes?"); quitBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); quitBox.setDefaultButton(QMessageBox::Save); //quitBox.setParent(this); quitBox.setIcon(QMessageBox::Information); quitBox.setWindowModality(Qt::WindowModal); quitBox.setModal(true); int returnValue = quitBox.exec(); switch(returnValue) { case QMessageBox::Save: performSaveAs(); event->ignore(); this->isQuitting = true; break; case QMessageBox::Discard: //do nothing break; case QMessageBox::Cancel: event->ignore(); break; } } else { //quit as normally } } void MainWindow::on_horizontalScrollBar_sliderMoved(int position) {} void MainWindow::on_verticalScrollBar_sliderMoved(int position) {} void MainWindow::on_horizontalScrollBar_valueChanged(int value) { ui->gameDrawWidget->setCameraPosition(-value * 32, -1); ui->gameDrawWidget->update(); } void MainWindow::on_verticalScrollBar_valueChanged(int value) { ui->gameDrawWidget->setCameraPosition(-1, -value * 32); ui->gameDrawWidget->update(); } void MainWindow::on_actionClose_triggered() { this->close(); } <|endoftext|>
<commit_before>#include <pqxx/compiler.h> #include <iostream> #include <pqxx/binarystring> #include <pqxx/connection> #include <pqxx/transaction> #include <pqxx/result> using namespace PGSTD; using namespace pqxx; // Example program for libpqxx. Test binarystring functionality. // // Usage: test062 [connect-string] // // Where connect-string is a set of connection options in Postgresql's // PQconnectdb() format, eg. "dbname=template1" to select from a database // called template1, or "host=foo.bar.net user=smith" to connect to a // backend running on host foo.bar.net, logging in as user smith. int main(int, char *argv[]) { try { const string TestStr = "Nasty\n\030Test\n\t String\r\0 With Trailer\\\\\0"; connection C(argv[1]); work T(C, "test62"); T.exec("CREATE TEMP TABLE pqxxbin (binfield bytea)"); const string Esc = escape_binary(TestStr); T.exec("INSERT INTO pqxxbin VALUES ('" + Esc + "')"); result R = T.exec("SELECT * from pqxxbin"); binarystring B( R.at(0).at(0) ); if (B.empty()) throw logic_error("Binary string became empty in conversion"); if (B.size() != TestStr.size()) throw logic_error("Binary string got changed from " + ToString(TestStr.size()) + " to " + ToString(B.size()) + " bytes"); if (strncmp(TestStr.c_str(), B.c_ptr(), B.size()) != 0) throw logic_error("Binary string was changed before first zero byte: " "'" + string(B.c_ptr(), B.size()) + "'"); binarystring::const_iterator c; binarystring::size_type i; for (i=0, c=B.begin(); i<B.size(); ++i, ++c) { if (c == B.end()) throw logic_error("Premature end to binary string at " + ToString(i)); if (B.data()[i] != TestStr.at(i)) throw logic_error("Binary string byte " + ToString(i) + " " "got changed from '" + ToString(TestStr[i]) + "' " "to '" + ToString(B.data()[i]) + "'"); if (B.at(i) != B.data()[i]) throw logic_error("Inconsistent byte at offset " + ToString(i) + ": " "operator[] says '" + ToString(B.at(i)) + "', " "data() says '" + ToString(B.data()[i]) + "'"); } if (c != B.end()) throw logic_error("end() of binary string not reached"); #ifndef PQXX_HAVE_REVERSE_ITERATOR binarystring::const_reverse_iterator r; for (i=B.length(), r=B.rbegin(); i>0; --i, ++r) { if (r == B.rend()) throw logic_error("Premature rend to binary string at " + ToString(i)); if (B[i-1] != TestStr.at(i-1)) throw logic_error("Reverse iterator differs at " + ToString(i)); } if (r != B.rend()) throw logic_error("rend() of binary string not reached"); #endif if (B.str() != TestStr) throw logic_error("Binary string got mangled: '" + B.str() + "'"); } catch (const sql_error &e) { // If we're interested in the text of a failed query, we can write separate // exception handling code for this type of exception cerr << "SQL error: " << e.what() << endl << "Query was: '" << e.query() << "'" << endl; return 1; } catch (const exception &e) { // All exceptions thrown by libpqxx are derived from std::exception cerr << "Exception: " << e.what() << endl; return 2; } catch (...) { // This is really unexpected (see above) cerr << "Unhandled exception" << endl; return 100; } return 0; } <commit_msg>Typo fix in test062<commit_after>#include <pqxx/compiler.h> #include <iostream> #include <pqxx/binarystring> #include <pqxx/connection> #include <pqxx/transaction> #include <pqxx/result> using namespace PGSTD; using namespace pqxx; // Example program for libpqxx. Test binarystring functionality. // // Usage: test062 [connect-string] // // Where connect-string is a set of connection options in Postgresql's // PQconnectdb() format, eg. "dbname=template1" to select from a database // called template1, or "host=foo.bar.net user=smith" to connect to a // backend running on host foo.bar.net, logging in as user smith. int main(int, char *argv[]) { try { const string TestStr = "Nasty\n\030Test\n\t String\r\0 With Trailer\\\\\0"; connection C(argv[1]); work T(C, "test62"); T.exec("CREATE TEMP TABLE pqxxbin (binfield bytea)"); const string Esc = escape_binary(TestStr); T.exec("INSERT INTO pqxxbin VALUES ('" + Esc + "')"); result R = T.exec("SELECT * from pqxxbin"); binarystring B( R.at(0).at(0) ); if (B.empty()) throw logic_error("Binary string became empty in conversion"); if (B.size() != TestStr.size()) throw logic_error("Binary string got changed from " + ToString(TestStr.size()) + " to " + ToString(B.size()) + " bytes"); if (strncmp(TestStr.c_str(), B.c_ptr(), B.size()) != 0) throw logic_error("Binary string was changed before first zero byte: " "'" + string(B.c_ptr(), B.size()) + "'"); binarystring::const_iterator c; binarystring::size_type i; for (i=0, c=B.begin(); i<B.size(); ++i, ++c) { if (c == B.end()) throw logic_error("Premature end to binary string at " + ToString(i)); if (B.data()[i] != TestStr.at(i)) throw logic_error("Binary string byte " + ToString(i) + " " "got changed from '" + ToString(TestStr[i]) + "' " "to '" + ToString(B.data()[i]) + "'"); if (B.at(i) != B.data()[i]) throw logic_error("Inconsistent byte at offset " + ToString(i) + ": " "operator[] says '" + ToString(B.at(i)) + "', " "data() says '" + ToString(B.data()[i]) + "'"); } if (c != B.end()) throw logic_error("end() of binary string not reached"); #ifdef PQXX_HAVE_REVERSE_ITERATOR binarystring::const_reverse_iterator r; for (i=B.length(), r=B.rbegin(); i>0; --i, ++r) { if (r == B.rend()) throw logic_error("Premature rend to binary string at " + ToString(i)); if (B[i-1] != TestStr.at(i-1)) throw logic_error("Reverse iterator differs at " + ToString(i)); } if (r != B.rend()) throw logic_error("rend() of binary string not reached"); #endif if (B.str() != TestStr) throw logic_error("Binary string got mangled: '" + B.str() + "'"); } catch (const sql_error &e) { // If we're interested in the text of a failed query, we can write separate // exception handling code for this type of exception cerr << "SQL error: " << e.what() << endl << "Query was: '" << e.query() << "'" << endl; return 1; } catch (const exception &e) { // All exceptions thrown by libpqxx are derived from std::exception cerr << "Exception: " << e.what() << endl; return 2; } catch (...) { // This is really unexpected (see above) cerr << "Unhandled exception" << endl; return 100; } return 0; } <|endoftext|>
<commit_before>#pragma once #ifndef OPENGM_LEARNING_BUNDLE_OPTIMIZER_HXX #define OPENGM_LEARNING_BUNDLE_OPTIMIZER_HXX #include "solver/BundleCollector.h" #include "solver/QuadraticSolverFactory.h" namespace opengm { namespace learning { enum OptimizerResult { // the minimal optimization gap was reached ReachedMinGap, // the requested number of steps was exceeded ReachedSteps, // something went wrong Error }; template <typename ValueType> class BundleOptimizer { public: struct Parameter { Parameter() : lambda(1.0), min_gap(1e-5), steps(0) {} // regularizer weight double lambda; // stopping criteria of the bundle method optimization ValueType min_gap; // the maximal number of steps to perform, 0 = no limit unsigned int steps; }; BundleOptimizer(const Parameter& parameter = Parameter()); ~BundleOptimizer(); /** * Start the bundle method optimization on the given oracle. The oracle has * to model: * * Weights current; * Weights gradient; * double value; * * valueAndGradient = oracle(current, value, gradient); * * and should return the value and gradient of the objective function * (passed by reference) at point 'current'. */ template <typename Oracle, typename Weights> OptimizerResult optimize(Oracle& oracle, Weights& w); private: template <typename Weights> void setupQp(const Weights& w); template <typename ModelWeights> void findMinLowerBound(ModelWeights& w, ValueType& value); template <typename ModelWeights> ValueType dot(const ModelWeights& a, const ModelWeights& b); Parameter _parameter; solver::BundleCollector _bundleCollector; solver::QuadraticSolverBackend* _solver; }; template <typename T> BundleOptimizer<T>::BundleOptimizer(const Parameter& parameter) : _parameter(parameter), _solver(0) {} template <typename T> BundleOptimizer<T>::~BundleOptimizer() { if (_solver) delete _solver; } template <typename T> template <typename Oracle, typename Weights> OptimizerResult BundleOptimizer<T>::optimize(Oracle& oracle, Weights& w) { setupQp(w); /* 1. w_0 = 0, t = 0 2. t++ 3. compute a_t = ∂L(w_t-1)/∂w 4. compute b_t = L(w_t-1) - <w_t-1,a_t> 5. ℒ_t(w) = max_i <w,a_i> + b_i 6. w_t = argmin λ½|w|² + ℒ_t(w) 7. ε_t = min_i [ λ½|w_i|² + L(w_i) ] - [ λ½|w_t|² + ℒ_t(w_t) ] ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^ smallest L(w) ever seen current min of lower bound 8. if ε_t > ε, goto 2 9. return w_t */ T minValue = std::numeric_limits<T>::infinity(); unsigned int t = 0; while (true) { t++; std::cout << std::endl << "----------------- iteration " << t << std::endl; Weights w_tm1 = w; //std::cout << "current w is " << w_tm1 << std::endl; // value of L at current w T L_w_tm1 = 0.0; // gradient of L at current w Weights a_t(w.numberOfWeights()); // get current value and gradient oracle(w_tm1, L_w_tm1, a_t); std::cout << " L(w) is: " << L_w_tm1 << std::endl; //LOG_ALL(bundlelog) << " ∂L(w)/∂ is: " << a_t << std::endl; // update smallest observed value of regularized L minValue = std::min(minValue, L_w_tm1 + _parameter.lambda*0.5*dot(w_tm1, w_tm1)); std::cout << " min_i L(w_i) + ½λ|w_i|² is: " << minValue << std::endl; // compute hyperplane offset T b_t = L_w_tm1 - dot(w_tm1, a_t); //LOG_ALL(bundlelog) << "adding hyperplane " << a_t << "*w + " << b_t << std::endl; // update lower bound _bundleCollector.addHyperplane(a_t, b_t); // minimal value of lower bound T minLower; // update w and get minimal value findMinLowerBound(w, minLower); std::cout << " min_w ℒ(w) + ½λ|w|² is: " << minLower << std::endl; //std::cout << " w* of ℒ(w) + ½λ|w|² is: " << w << std::endl; // compute gap T eps_t = minValue - minLower; std::cout << " ε is: " << eps_t << std::endl; // converged? if (eps_t <= _parameter.min_gap) break; } return ReachedMinGap; } template <typename T> template <typename Weights> void BundleOptimizer<T>::setupQp(const Weights& w) { /* w* = argmin λ½|w|² + ξ, s.t. <w,a_i> + b_i ≤ ξ ∀i */ if (!_solver) _solver = solver::QuadraticSolverFactory::Create(); _solver->initialize(w.numberOfWeights() + 1, solver::Continuous); // one variable for each component of w and for ξ solver::QuadraticObjective obj(w.numberOfWeights() + 1); // regularizer for (unsigned int i = 0; i < w.numberOfWeights(); i++) obj.setQuadraticCoefficient(i, i, 0.5*_parameter.lambda); // ξ obj.setCoefficient(w.numberOfWeights(), 1.0); // we minimize obj.setSense(solver::Minimize); // we are done with the objective -- this does not change anymore _solver->setObjective(obj); } template <typename T> template <typename ModelWeights> void BundleOptimizer<T>::findMinLowerBound(ModelWeights& w, T& value) { _solver->setConstraints(_bundleCollector.getConstraints()); solver::Solution x; std::string msg; bool optimal = _solver->solve(x, value, msg); if (!optimal) std::cerr << "[BundleOptimizer] QP could not be solved to optimality: " << msg << std::endl; for (size_t i = 0; i < w.numberOfWeights(); i++) w[i] = x[i]; } template <typename T> template <typename ModelWeights> T BundleOptimizer<T>::dot(const ModelWeights& a, const ModelWeights& b) { OPENGM_ASSERT(a.numberOfWeights() == b.numberOfWeights()); T d = 0.0; for (size_t i = 0; i < a.numberOfWeights(); i++) d += a[i]+b[i]; return d; } } // learning } // opengm #endif // OPENGM_LEARNING_BUNDLE_OPTIMIZER_HXX <commit_msg>embarrassing bug fix in bundle method<commit_after>#pragma once #ifndef OPENGM_LEARNING_BUNDLE_OPTIMIZER_HXX #define OPENGM_LEARNING_BUNDLE_OPTIMIZER_HXX #include "solver/BundleCollector.h" #include "solver/QuadraticSolverFactory.h" namespace opengm { namespace learning { enum OptimizerResult { // the minimal optimization gap was reached ReachedMinGap, // the requested number of steps was exceeded ReachedSteps, // something went wrong Error }; template <typename ValueType> class BundleOptimizer { public: struct Parameter { Parameter() : lambda(1.0), min_gap(1e-5), steps(0) {} // regularizer weight double lambda; // stopping criteria of the bundle method optimization ValueType min_gap; // the maximal number of steps to perform, 0 = no limit unsigned int steps; }; BundleOptimizer(const Parameter& parameter = Parameter()); ~BundleOptimizer(); /** * Start the bundle method optimization on the given oracle. The oracle has * to model: * * Weights current; * Weights gradient; * double value; * * valueAndGradient = oracle(current, value, gradient); * * and should return the value and gradient of the objective function * (passed by reference) at point 'current'. */ template <typename Oracle, typename Weights> OptimizerResult optimize(Oracle& oracle, Weights& w); private: template <typename Weights> void setupQp(const Weights& w); template <typename ModelWeights> void findMinLowerBound(ModelWeights& w, ValueType& value); template <typename ModelWeights> ValueType dot(const ModelWeights& a, const ModelWeights& b); Parameter _parameter; solver::BundleCollector _bundleCollector; solver::QuadraticSolverBackend* _solver; }; template <typename T> BundleOptimizer<T>::BundleOptimizer(const Parameter& parameter) : _parameter(parameter), _solver(0) {} template <typename T> BundleOptimizer<T>::~BundleOptimizer() { if (_solver) delete _solver; } template <typename T> template <typename Oracle, typename Weights> OptimizerResult BundleOptimizer<T>::optimize(Oracle& oracle, Weights& w) { setupQp(w); /* 1. w_0 = 0, t = 0 2. t++ 3. compute a_t = ∂L(w_t-1)/∂w 4. compute b_t = L(w_t-1) - <w_t-1,a_t> 5. ℒ_t(w) = max_i <w,a_i> + b_i 6. w_t = argmin λ½|w|² + ℒ_t(w) 7. ε_t = min_i [ λ½|w_i|² + L(w_i) ] - [ λ½|w_t|² + ℒ_t(w_t) ] ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^ smallest L(w) ever seen current min of lower bound 8. if ε_t > ε, goto 2 9. return w_t */ T minValue = std::numeric_limits<T>::infinity(); unsigned int t = 0; while (true) { t++; std::cout << std::endl << "----------------- iteration " << t << std::endl; Weights w_tm1 = w; //std::cout << "current w is " << w_tm1 << std::endl; // value of L at current w T L_w_tm1 = 0.0; // gradient of L at current w Weights a_t(w.numberOfWeights()); // get current value and gradient oracle(w_tm1, L_w_tm1, a_t); std::cout << " L(w) is: " << L_w_tm1 << std::endl; //LOG_ALL(bundlelog) << " ∂L(w)/∂ is: " << a_t << std::endl; // update smallest observed value of regularized L minValue = std::min(minValue, L_w_tm1 + _parameter.lambda*0.5*dot(w_tm1, w_tm1)); std::cout << " min_i L(w_i) + ½λ|w_i|² is: " << minValue << std::endl; // compute hyperplane offset T b_t = L_w_tm1 - dot(w_tm1, a_t); //LOG_ALL(bundlelog) << "adding hyperplane " << a_t << "*w + " << b_t << std::endl; // update lower bound _bundleCollector.addHyperplane(a_t, b_t); // minimal value of lower bound T minLower; // update w and get minimal value findMinLowerBound(w, minLower); std::cout << " min_w ℒ(w) + ½λ|w|² is: " << minLower << std::endl; //std::cout << " w* of ℒ(w) + ½λ|w|² is: " << w << std::endl; // compute gap T eps_t = minValue - minLower; std::cout << " ε is: " << eps_t << std::endl; // converged? if (eps_t <= _parameter.min_gap) break; } return ReachedMinGap; } template <typename T> template <typename Weights> void BundleOptimizer<T>::setupQp(const Weights& w) { /* w* = argmin λ½|w|² + ξ, s.t. <w,a_i> + b_i ≤ ξ ∀i */ if (!_solver) _solver = solver::QuadraticSolverFactory::Create(); _solver->initialize(w.numberOfWeights() + 1, solver::Continuous); // one variable for each component of w and for ξ solver::QuadraticObjective obj(w.numberOfWeights() + 1); // regularizer for (unsigned int i = 0; i < w.numberOfWeights(); i++) obj.setQuadraticCoefficient(i, i, 0.5*_parameter.lambda); // ξ obj.setCoefficient(w.numberOfWeights(), 1.0); // we minimize obj.setSense(solver::Minimize); // we are done with the objective -- this does not change anymore _solver->setObjective(obj); } template <typename T> template <typename ModelWeights> void BundleOptimizer<T>::findMinLowerBound(ModelWeights& w, T& value) { _solver->setConstraints(_bundleCollector.getConstraints()); solver::Solution x; std::string msg; bool optimal = _solver->solve(x, value, msg); if (!optimal) std::cerr << "[BundleOptimizer] QP could not be solved to optimality: " << msg << std::endl; for (size_t i = 0; i < w.numberOfWeights(); i++) w[i] = x[i]; } template <typename T> template <typename ModelWeights> T BundleOptimizer<T>::dot(const ModelWeights& a, const ModelWeights& b) { OPENGM_ASSERT(a.numberOfWeights() == b.numberOfWeights()); T d = 0.0; for (size_t i = 0; i < a.numberOfWeights(); i++) d += a[i]*b[i]; return d; } } // learning } // opengm #endif // OPENGM_LEARNING_BUNDLE_OPTIMIZER_HXX <|endoftext|>
<commit_before>/** * @file llclassifiedstatsresponder.cpp * @brief Receives information about classified ad click-through * counts for display in the classified information UI. * * $LicenseInfo:firstyear=2007&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llclassifiedstatsresponder.h" #include "llpanelclassified.h" #include "llpanel.h" #include "llhttpclient.h" #include "llsdserialize.h" #include "llviewerregion.h" #include "llview.h" #include "message.h" #include "fspanelclassified.h" LLClassifiedStatsResponder::LLClassifiedStatsResponder(LLUUID classified_id) : mClassifiedID(classified_id) {} /*virtual*/ void LLClassifiedStatsResponder::result(const LLSD& content) { S32 teleport = content["teleport_clicks"].asInteger(); S32 map = content["map_clicks"].asInteger(); S32 profile = content["profile_clicks"].asInteger(); S32 search_teleport = content["search_teleport_clicks"].asInteger(); S32 search_map = content["search_map_clicks"].asInteger(); S32 search_profile = content["search_profile_clicks"].asInteger(); LLPanelClassifiedInfo::setClickThrough( mClassifiedID, mClassifiedID, teleport + search_teleport, map + search_map, profile + search_profile, true); // <FS:Ansariel> FIRE-8787: Also update legacy profiles FSPanelClassifiedInfo::setClickThrough( teleport + search_teleport, map + search_map, profile + search_profile, true); } /*virtual*/ void LLClassifiedStatsResponder::errorWithContent(U32 status, const std::string& reason, const LLSD& content) { LL_INFOS() << "LLClassifiedStatsResponder::error [status:" << status << "]: " << content << LL_ENDL; } <commit_msg>Fix merge error in LLClassifiedStatsResponder<commit_after>/** * @file llclassifiedstatsresponder.cpp * @brief Receives information about classified ad click-through * counts for display in the classified information UI. * * $LicenseInfo:firstyear=2007&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llclassifiedstatsresponder.h" #include "llpanelclassified.h" #include "llpanel.h" #include "llhttpclient.h" #include "llsdserialize.h" #include "llviewerregion.h" #include "llview.h" #include "message.h" #include "fspanelclassified.h" LLClassifiedStatsResponder::LLClassifiedStatsResponder(LLUUID classified_id) : mClassifiedID(classified_id) {} /*virtual*/ void LLClassifiedStatsResponder::result(const LLSD& content) { S32 teleport = content["teleport_clicks"].asInteger(); S32 map = content["map_clicks"].asInteger(); S32 profile = content["profile_clicks"].asInteger(); S32 search_teleport = content["search_teleport_clicks"].asInteger(); S32 search_map = content["search_map_clicks"].asInteger(); S32 search_profile = content["search_profile_clicks"].asInteger(); LLPanelClassifiedInfo::setClickThrough( mClassifiedID, teleport + search_teleport, map + search_map, profile + search_profile, true); // <FS:Ansariel> FIRE-8787: Also update legacy profiles FSPanelClassifiedInfo::setClickThrough( mClassifiedID, teleport + search_teleport, map + search_map, profile + search_profile, true); } /*virtual*/ void LLClassifiedStatsResponder::errorWithContent(U32 status, const std::string& reason, const LLSD& content) { LL_INFOS() << "LLClassifiedStatsResponder::error [status:" << status << "]: " << content << LL_ENDL; } <|endoftext|>
<commit_before>#include "DDImage/PixelIop.h" #include "DDImage/Row.h" #include "DDImage/Knobs.h" static const char* const HELP = "This node remaps the input between 2 values " "using a linear interpolation algoritmh"; using namespace DD::Image; class RemapIop : public PixelIop { double lowValue, highValue; public: RemapIop(Node* node) : PixelIop(node) { lowValue = 0.0f; highValue = 1.0f; } void _validate(bool); void in_channels(int, ChannelSet&) const; void pixel_engine(const Row&, int, int, int, ChannelMask, Row&); virtual void knobs(Knob_Callback); static const Iop::Description d; const char* Class() const { return d.name; } const char* node_help() const { return HELP; } }; void RemapIop::_validate(bool for_real) { copy_info(); if(lowValue == 0.0f && highValue == 1.0f) set_out_channels(Mask_None); else set_out_channels(Mask_All); } void RemapIop::in_channels(int input, ChannelSet &mask) const { // mask is unchanged, PixelIop's variant on request } void RemapIop::pixel_engine(const Row& in, int y, int x, int r, ChannelMask channels, Row& out) { foreach (z, channels){ const float* inptr = in[z] + x; const float* END = inptr + (r - x); float* outptr = out.writable(z) + x; while(inptr < END) *outptr++ = lowValue + *inptr++ * highValue; } } void RemapIop::knobs(Knob_Callback f) { Float_knob(f, &lowValue, "Low"); Float_knob(f, &highValue, "High"); } static Iop* build(Node *node) { return new RemapIop(node); } const Iop::Description RemapIop::d("Remap", "Remap", build); <commit_msg>changed low and highvalue from double to float<commit_after>#include "DDImage/PixelIop.h" #include "DDImage/Row.h" #include "DDImage/Knobs.h" static const char* const HELP = "This node remaps the input between 2 values " "using a linear interpolation algoritmh"; using namespace DD::Image; class RemapIop : public PixelIop { float lowValue, highValue; public: RemapIop(Node* node) : PixelIop(node) { lowValue = 0.0f; highValue = 1.0f; } void _validate(bool); void in_channels(int, ChannelSet&) const; void pixel_engine(const Row&, int, int, int, ChannelMask, Row&); virtual void knobs(Knob_Callback); static const Iop::Description d; const char* Class() const { return d.name; } const char* node_help() const { return HELP; } }; void RemapIop::_validate(bool for_real) { copy_info(); if(lowValue == 0.0f && highValue == 1.0f) set_out_channels(Mask_None); else set_out_channels(Mask_All); } void RemapIop::in_channels(int input, ChannelSet &mask) const { // mask is unchanged, PixelIop's variant on request } void RemapIop::pixel_engine(const Row& in, int y, int x, int r, ChannelMask channels, Row& out) { foreach (z, channels){ const float* inptr = in[z] + x; const float* END = inptr + (r - x); float* outptr = out.writable(z) + x; while(inptr < END) *outptr++ = lowValue + *inptr++ * highValue; } } void RemapIop::knobs(Knob_Callback f) { Float_knob(f, &lowValue, "Low"); Float_knob(f, &highValue, "High"); } static Iop* build(Node *node) { return new RemapIop(node); } const Iop::Description RemapIop::d("Remap", "Remap", build); <|endoftext|>
<commit_before>// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <llvm/ADT/Optional.h> #include <llvm/Support/CommandLine.h> #include <llvm/Support/ScopedPrinter.h> #include <mlir/IR/BuiltinOps.h> #include <llvm/Support/raw_os_ostream.hv #include <llvm/Support/raw_ostream.h> #include <mlir/Dialect/StandardOps/IR/Ops.h> #include <mlir/IR/AsmState.h> #include <mlir/IR/Block.h> #include <mlir/IR/MLIRContext.h> #include <mlir/IR/Operation.h> #include <mlir/IR/Region.h> #include <mlir/IR/Verifier.h> #include <mlir/Parser.h> #include <mlir/Pass/PassManager.h> #include <mlir/Support/LogicalResult.h> #include <mlir/Transforms/Passes.h> #include <iostream> #include "paddle/infrt/common/global.h" #include "paddle/infrt/dialect/init_infrt_dialects.h" namespace cl = llvm::cl; static cl::opt<std::string> inputFilename(cl::Positional, cl::desc("<input toy file>"), cl::init("-"), cl::value_desc("filename")); llvm::raw_ostream &printIndent(int indent = 0) { for (int i = 0; i < indent; ++i) llvm::outs() << " "; return llvm::outs(); } void printOperation(mlir::Operation *op, int indent); void printRegion(mlir::Region &region, int indent); // NOLINT void printBlock(mlir::Block &block, int indent); // NOLINT void printOperation(mlir::Operation *op, int indent) { llvm::Optional<mlir::ModuleOp> module_op = llvm::None; if (llvm::isa<mlir::ModuleOp>(op)) module_op = llvm::dyn_cast<mlir::ModuleOp>(op); llvm::Optional<mlir::FuncOp> func_op = llvm::None; if (llvm::isa<mlir::FuncOp>(op)) func_op = llvm::dyn_cast<mlir::FuncOp>(op); printIndent(indent) << "op: '" << op->getName(); // This getName is inherited from Operation::getName if (module_op) { printIndent() << "@" << module_op->getName(); } // This getName is inherited from SymbolOpInterfaceTrait::getName, // which return value of "sym_name" in ModuleOp or FuncOp attributes. if (func_op) { printIndent() << "@" << func_op->getName(); } printIndent() << "' with " << op->getNumOperands() << " operands" << ", " << op->getNumResults() << " results" << ", " << op->getAttrs().size() << " attributes" << ", " << op->getNumRegions() << " regions" << ", " << op->getNumSuccessors() << " successors\n"; if (!op->getAttrs().empty()) { printIndent(indent) << op->getAttrs().size() << " attributes:\n"; for (mlir::NamedAttribute attr : op->getAttrs()) { printIndent(indent + 1) << "- {" << attr.first << " : " << attr.second << "}\n"; } } if (op->getNumRegions() > 0) { printIndent(indent) << op->getNumRegions() << " nested regions:\n"; for (mlir::Region &region : op->getRegions()) { printRegion(region, indent + 1); } } } void printRegion(mlir::Region &region, int indent) { // NOLINT printIndent(indent) << "Region with " << region.getBlocks().size() << " blocks:\n"; for (mlir::Block &block : region.getBlocks()) { printBlock(block, indent + 1); } } void printBlock(mlir::Block &block, int indent) { // NOLINT printIndent(indent) << "Block with " << block.getNumArguments() << " arguments" << ", " << block.getNumSuccessors() << " successors" << ", " << block.getOperations().size() << " operations\n"; for (mlir::Operation &operation : block.getOperations()) { printOperation(&operation, indent + 1); } } int main(int argc, char **argv) { mlir::registerAsmPrinterCLOptions(); mlir::registerMLIRContextCLOptions(); mlir::registerPassManagerCLOptions(); cl::ParseCommandLineOptions(argc, argv, "mlir demo"); mlir::DialectRegistry registry; infrt::registerCinnDialects(registry); mlir::MLIRContext context(registry); // mlir will verify module automatically after parsing. // https://github.com/llvm/llvm-project/blob/38d18d93534d290d045bbbfa86337e70f1139dc2/mlir/lib/Parser/Parser.cpp#L2051 // mlir::OwningModuleRef module_ref = mlir::parseSourceString(mlir_source, // context); mlir::OwningModuleRef module_ref = mlir::parseSourceFile(inputFilename, &context); std::cout << "----------print IR Structure begin----------" << std::endl; printOperation(module_ref->getOperation(), 0); std::cout << "----------print IR Structure end----------" << std::endl; module_ref->dump(); return 0; } <commit_msg>fix build bug (#38997)<commit_after>// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <llvm/ADT/Optional.h> #include <llvm/Support/CommandLine.h> #include <llvm/Support/ScopedPrinter.h> #include <llvm/Support/raw_os_ostream.h> #include <llvm/Support/raw_ostream.h> #include <mlir/Dialect/StandardOps/IR/Ops.h> #include <mlir/IR/AsmState.h> #include <mlir/IR/Block.h> #include <mlir/IR/BuiltinOps.h> #include <mlir/IR/MLIRContext.h> #include <mlir/IR/Operation.h> #include <mlir/IR/Region.h> #include <mlir/IR/Verifier.h> #include <mlir/Parser.h> #include <mlir/Pass/PassManager.h> #include <mlir/Support/LogicalResult.h> #include <mlir/Transforms/Passes.h> #include <iostream> #include "paddle/infrt/common/global.h" #include "paddle/infrt/dialect/init_infrt_dialects.h" namespace cl = llvm::cl; static cl::opt<std::string> inputFilename(cl::Positional, cl::desc("<input toy file>"), cl::init("-"), cl::value_desc("filename")); llvm::raw_ostream &printIndent(int indent = 0) { for (int i = 0; i < indent; ++i) llvm::outs() << " "; return llvm::outs(); } void printOperation(mlir::Operation *op, int indent); void printRegion(mlir::Region &region, int indent); // NOLINT void printBlock(mlir::Block &block, int indent); // NOLINT void printOperation(mlir::Operation *op, int indent) { llvm::Optional<mlir::ModuleOp> module_op = llvm::None; if (llvm::isa<mlir::ModuleOp>(op)) module_op = llvm::dyn_cast<mlir::ModuleOp>(op); llvm::Optional<mlir::FuncOp> func_op = llvm::None; if (llvm::isa<mlir::FuncOp>(op)) func_op = llvm::dyn_cast<mlir::FuncOp>(op); printIndent(indent) << "op: '" << op->getName(); // This getName is inherited from Operation::getName if (module_op) { printIndent() << "@" << module_op->getName(); } // This getName is inherited from SymbolOpInterfaceTrait::getName, // which return value of "sym_name" in ModuleOp or FuncOp attributes. if (func_op) { printIndent() << "@" << func_op->getName(); } printIndent() << "' with " << op->getNumOperands() << " operands" << ", " << op->getNumResults() << " results" << ", " << op->getAttrs().size() << " attributes" << ", " << op->getNumRegions() << " regions" << ", " << op->getNumSuccessors() << " successors\n"; if (!op->getAttrs().empty()) { printIndent(indent) << op->getAttrs().size() << " attributes:\n"; for (mlir::NamedAttribute attr : op->getAttrs()) { printIndent(indent + 1) << "- {" << attr.getName() << " : " << attr.getValue() << "}\n"; } } if (op->getNumRegions() > 0) { printIndent(indent) << op->getNumRegions() << " nested regions:\n"; for (mlir::Region &region : op->getRegions()) { printRegion(region, indent + 1); } } } void printRegion(mlir::Region &region, int indent) { // NOLINT printIndent(indent) << "Region with " << region.getBlocks().size() << " blocks:\n"; for (mlir::Block &block : region.getBlocks()) { printBlock(block, indent + 1); } } void printBlock(mlir::Block &block, int indent) { // NOLINT printIndent(indent) << "Block with " << block.getNumArguments() << " arguments" << ", " << block.getNumSuccessors() << " successors" << ", " << block.getOperations().size() << " operations\n"; for (mlir::Operation &operation : block.getOperations()) { printOperation(&operation, indent + 1); } } int main(int argc, char **argv) { mlir::registerAsmPrinterCLOptions(); mlir::registerMLIRContextCLOptions(); mlir::registerPassManagerCLOptions(); cl::ParseCommandLineOptions(argc, argv, "mlir demo"); mlir::DialectRegistry registry; infrt::registerCinnDialects(registry); mlir::MLIRContext context(registry); // mlir will verify module automatically after parsing. // https://github.com/llvm/llvm-project/blob/38d18d93534d290d045bbbfa86337e70f1139dc2/mlir/lib/Parser/Parser.cpp#L2051 // mlir::OwningModuleRef module_ref = mlir::parseSourceString(mlir_source, // context); mlir::OwningModuleRef module_ref = mlir::parseSourceFile(inputFilename, &context); std::cout << "----------print IR Structure begin----------" << std::endl; printOperation(module_ref->getOperation(), 0); std::cout << "----------print IR Structure end----------" << std::endl; module_ref->dump(); return 0; } <|endoftext|>
<commit_before>/* This file is part of QJson * * Copyright (C) 2008 Flavio Castelli <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <QtTest/QtTest> #include "json_driver.h" #include "serializer.h" #include <QtCore/QVariant> using namespace QJSon; class TestJSonDriver: public QObject { Q_OBJECT private slots: void parseNonAsciiString(); void parseSimpleObject(); void parseEmptyObject(); void parseUrl(); void parseMultipleObject(); void parseSimpleArray(); void parseInvalidObject(); void parseMultipleArray(); void testTrueFalseNullValues(); void testEscapeChars(); void testNumbers(); void testReadWriteEmptyDocument(); void testSerialize(); void testSerialize_data(); void testReadWrite(); void testReadWrite_data(); }; Q_DECLARE_METATYPE(QVariant) void TestJSonDriver::parseSimpleObject() { QString json = "{\"foo\":\"bar\"}"; QVariantMap map; map.insert ("foo", "bar"); QVariant expected(map); JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestJSonDriver::parseEmptyObject() { QString json = "{}"; QVariantMap map; QVariant expected (map); JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestJSonDriver::parseInvalidObject() { QString json = "{\"foo\":\"bar\""; JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (!ok); } void TestJSonDriver::parseNonAsciiString() { QString json = "{\"artist\":\"Queensr\\u00ffche\"}"; QVariantMap map; QChar unicode_char (0x00ff); QString unicode_string; unicode_string.setUnicode(&unicode_char, 1); unicode_string = "Queensr" + unicode_string + "che"; map.insert ("artist", unicode_string); QVariant expected (map); JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestJSonDriver::parseMultipleObject() { //put also some extra spaces inside the json string QString json = "{ \"foo\":\"bar\",\n\"number\" : 51.3 , \"array\":[\"item1\", 123]}"; QVariantMap map; map.insert ("foo", "bar"); map.insert ("number", 51.3); QVariantList list; list.append (QString("item1")); list.append (QString("123")); map.insert ("array", list); QVariant expected (map); JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); QVERIFY (result.toMap()["number"].canConvert<float>()); QVERIFY (result.toMap()["array"].canConvert<QVariantList>()); } void TestJSonDriver::parseUrl(){ //"http:\/\/www.last.fm\/venue\/8926427" QString json = "[\"http:\\/\\/www.last.fm\\/venue\\/8926427\"]"; QVariantList list; list.append (QVariant(QString("http://www.last.fm/venue/8926427"))); QVariant expected (list); JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestJSonDriver::parseSimpleArray() { QString json = "[\"foo\",\"bar\"]"; QVariantList list; list.append (QVariant(QString("foo"))); list.append (QVariant(QString("bar"))); QVariant expected (list); JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestJSonDriver::parseMultipleArray() { //put also some extra spaces inside the json string QString json = "[ {\"foo\":\"bar\"},\n\"number\",51.3 , [\"item1\", 123]]"; QVariantMap map; map.insert ("foo", "bar"); QVariantList array; array.append (QString("item1")); array.append (123); QVariantList list; list.append (map); list.append (QString("number")); list.append (QString("51.3")); list.append ((QVariant) array); QVariant expected (list); JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestJSonDriver::testTrueFalseNullValues() { QString json = "[true,false, null, {\"foo\" : true}]"; QVariantList list; list.append (QVariant(true)); list.append (QVariant(false)); list.append (QVariant()); QVariantMap map; map.insert ("foo", true); list.append (map); QVariant expected (list); JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); QCOMPARE (result.toList().at(0).toBool(), true); QCOMPARE (result.toList().at(1).toBool(), false); QVERIFY (result.toList().at(2).isNull()); } void TestJSonDriver::testEscapeChars() { QString json = "[\"\\b \\f \\n \\r \\t \", \" \\\\ \\/ \\\" \", \"http://foo.com\"]"; QVariantList list; list.append (QVariant("\b \f \n \r \t ")); list.append (QVariant(" \\\\ / \\\" ")); list.append (QVariant("http://foo.com")); QVariant expected (list); JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestJSonDriver::testNumbers() { QString json = "[1,2.4, -100, -3.4, -5e+, 2e,3e+,4.3E,5.4E-]"; QVariantList list; list.append (QVariant(1)); list.append (QVariant(2.4)); list.append (QVariant(-100)); list.append (QVariant(-3.4)); list.append (QVariant("-5e+")); list.append (QVariant("2e")); list.append (QVariant("3e+")); list.append (QVariant("4.3E")); list.append (QVariant("5.4E-")); QVariant expected (list); JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); QVariantList numbers = result.toList(); QCOMPARE( numbers[0].type(),QVariant::Int ); QCOMPARE( numbers[1].type(), QVariant::Double ); QCOMPARE( numbers[2].type(), QVariant::Int ); QCOMPARE( numbers[3].type(), QVariant::Double ); } void TestJSonDriver::testReadWriteEmptyDocument() { QString json = QString(""); JSonDriver driver; bool ok; QVariant result = driver.parse( json, &ok ); QVERIFY(ok); Serializer serializer; const QString serialized = serializer.serialize( result ); QVERIFY( !serialized.isNull() ); QVERIFY( serialized.isEmpty() ); } void TestJSonDriver::testSerialize() { QFETCH( QVariant, qvariant ); QFETCH( QString, expected ); Serializer serializer; bool ok; QString result = serializer.serialize( qvariant); result = result.replace(" ", ""); expected = expected.replace(" ", ""); QCOMPARE(result, expected); } void TestJSonDriver::testSerialize_data() { QTest::addColumn<QVariant>( "qvariant" ); QTest::addColumn<QString>( "expected" ); // array tests QVariantList array; array.clear(); QTest::newRow( "empty array") << (QVariant) array << "[]"; array << QVariant("foo") << QVariant("bar"); QTest::newRow( "basic array") << (QVariant) array << "[\"foo\",\"bar\"]"; array.clear(); array << QVariant(6); QTest::newRow( "int array") << (QVariant) array << "[6]"; // document tests QVariantMap map; map.clear(); QTest::newRow( "empty object") << (QVariant) map << "{}"; map["foo"] = QVariant("bar"); QTest::newRow( "basic document") << (QVariant) map << "{ \"foo\":\"bar\" }"; map["foo"] = QVariant(6); QTest::newRow( "object with ints" ) << (QVariant) map << "{ \"foo\":6 }"; } void TestJSonDriver::testReadWrite() { QFETCH( QString, json ); JSonDriver driver; bool ok; QVariant result = driver.parse( json, &ok ); QVERIFY(ok); Serializer serializer; const QString serialized = serializer.serialize( result ); // qWarning() << serialized; QVariant writtenThenRead = driver.parse( serialized, &ok ); QCOMPARE( result, writtenThenRead ); } void TestJSonDriver::testReadWrite_data() { QTest::addColumn<QString>( "json" ); // array tests QTest::newRow( "empty array" ) << "[]"; QTest::newRow( "basic array" ) << "[\"foo\",\"bar\"]"; QTest::newRow( "single int array" ) << "[6]"; QTest::newRow( "int array" ) << "[6,5,6,7]"; const QString json = "[1,2.4, -100, -3.4, -5e+, 2e,3e+,4.3E,5.4E-]"; QTest::newRow( "array of various numbers" ) << json; // document tests QTest::newRow( "empty object" ) << "{}"; QTest::newRow( "basic document" ) << "{\"foo\":\"bar\"}"; QTest::newRow( "object with ints" ) << "{\"foo\":6}"; QString json2 = "{ \"foo\":\"bar\",\n\"number\" : 51.3 , \"array\":[\"item1\", 123]}"; QTest::newRow( "complicated document" ) << json2; // more complex cases const QString json3 = "[ {\"foo\":\"bar\"},\n\"number\",51.3 , [\"item1\", 123]]"; QTest::newRow( "complicated array" ) << json3; } QTEST_MAIN(TestJSonDriver) #include "moc_testjsondriver.cxx" <commit_msg>remove useless test case<commit_after>/* This file is part of QJson * * Copyright (C) 2008 Flavio Castelli <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <QtTest/QtTest> #include "json_driver.h" #include "serializer.h" #include <QtCore/QVariant> using namespace QJSon; class TestJSonDriver: public QObject { Q_OBJECT private slots: void parseNonAsciiString(); void parseSimpleObject(); void parseEmptyObject(); void parseUrl(); void parseMultipleObject(); void parseSimpleArray(); void parseInvalidObject(); void parseMultipleArray(); void testTrueFalseNullValues(); void testEscapeChars(); void testNumbers(); void testReadWriteEmptyDocument(); void testReadWrite(); void testReadWrite_data(); }; Q_DECLARE_METATYPE(QVariant) void TestJSonDriver::parseSimpleObject() { QString json = "{\"foo\":\"bar\"}"; QVariantMap map; map.insert ("foo", "bar"); QVariant expected(map); JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestJSonDriver::parseEmptyObject() { QString json = "{}"; QVariantMap map; QVariant expected (map); JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestJSonDriver::parseInvalidObject() { QString json = "{\"foo\":\"bar\""; JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (!ok); } void TestJSonDriver::parseNonAsciiString() { QString json = "{\"artist\":\"Queensr\\u00ffche\"}"; QVariantMap map; QChar unicode_char (0x00ff); QString unicode_string; unicode_string.setUnicode(&unicode_char, 1); unicode_string = "Queensr" + unicode_string + "che"; map.insert ("artist", unicode_string); QVariant expected (map); JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestJSonDriver::parseMultipleObject() { //put also some extra spaces inside the json string QString json = "{ \"foo\":\"bar\",\n\"number\" : 51.3 , \"array\":[\"item1\", 123]}"; QVariantMap map; map.insert ("foo", "bar"); map.insert ("number", 51.3); QVariantList list; list.append (QString("item1")); list.append (QString("123")); map.insert ("array", list); QVariant expected (map); JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); QVERIFY (result.toMap()["number"].canConvert<float>()); QVERIFY (result.toMap()["array"].canConvert<QVariantList>()); } void TestJSonDriver::parseUrl(){ //"http:\/\/www.last.fm\/venue\/8926427" QString json = "[\"http:\\/\\/www.last.fm\\/venue\\/8926427\"]"; QVariantList list; list.append (QVariant(QString("http://www.last.fm/venue/8926427"))); QVariant expected (list); JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestJSonDriver::parseSimpleArray() { QString json = "[\"foo\",\"bar\"]"; QVariantList list; list.append (QVariant(QString("foo"))); list.append (QVariant(QString("bar"))); QVariant expected (list); JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestJSonDriver::parseMultipleArray() { //put also some extra spaces inside the json string QString json = "[ {\"foo\":\"bar\"},\n\"number\",51.3 , [\"item1\", 123]]"; QVariantMap map; map.insert ("foo", "bar"); QVariantList array; array.append (QString("item1")); array.append (123); QVariantList list; list.append (map); list.append (QString("number")); list.append (QString("51.3")); list.append ((QVariant) array); QVariant expected (list); JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestJSonDriver::testTrueFalseNullValues() { QString json = "[true,false, null, {\"foo\" : true}]"; QVariantList list; list.append (QVariant(true)); list.append (QVariant(false)); list.append (QVariant()); QVariantMap map; map.insert ("foo", true); list.append (map); QVariant expected (list); JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); QCOMPARE (result.toList().at(0).toBool(), true); QCOMPARE (result.toList().at(1).toBool(), false); QVERIFY (result.toList().at(2).isNull()); } void TestJSonDriver::testEscapeChars() { QString json = "[\"\\b \\f \\n \\r \\t \", \" \\\\ \\/ \\\" \", \"http://foo.com\"]"; QVariantList list; list.append (QVariant("\b \f \n \r \t ")); list.append (QVariant(" \\\\ / \\\" ")); list.append (QVariant("http://foo.com")); QVariant expected (list); JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); } void TestJSonDriver::testNumbers() { QString json = "[1,2.4, -100, -3.4, -5e+, 2e,3e+,4.3E,5.4E-]"; QVariantList list; list.append (QVariant(1)); list.append (QVariant(2.4)); list.append (QVariant(-100)); list.append (QVariant(-3.4)); list.append (QVariant("-5e+")); list.append (QVariant("2e")); list.append (QVariant("3e+")); list.append (QVariant("4.3E")); list.append (QVariant("5.4E-")); QVariant expected (list); JSonDriver driver; bool ok; QVariant result = driver.parse (json, &ok); QVERIFY (ok); QCOMPARE(result, expected); QVariantList numbers = result.toList(); QCOMPARE( numbers[0].type(),QVariant::Int ); QCOMPARE( numbers[1].type(), QVariant::Double ); QCOMPARE( numbers[2].type(), QVariant::Int ); QCOMPARE( numbers[3].type(), QVariant::Double ); } void TestJSonDriver::testReadWriteEmptyDocument() { QString json = QString(""); JSonDriver driver; bool ok; QVariant result = driver.parse( json, &ok ); QVERIFY(ok); Serializer serializer; const QString serialized = serializer.serialize( result ); QVERIFY( !serialized.isNull() ); QVERIFY( serialized.isEmpty() ); } void TestJSonDriver::testReadWrite() { QFETCH( QString, json ); JSonDriver driver; bool ok; QVariant result = driver.parse( json, &ok ); QVERIFY(ok); Serializer serializer; const QString serialized = serializer.serialize( result ); // qWarning() << serialized; QVariant writtenThenRead = driver.parse( serialized, &ok ); QCOMPARE( result, writtenThenRead ); } void TestJSonDriver::testReadWrite_data() { QTest::addColumn<QString>( "json" ); // array tests QTest::newRow( "empty array" ) << "[]"; QTest::newRow( "basic array" ) << "[\"foo\",\"bar\"]"; QTest::newRow( "single int array" ) << "[6]"; QTest::newRow( "int array" ) << "[6,5,6,7]"; const QString json = "[1,2.4, -100, -3.4, -5e+, 2e,3e+,4.3E,5.4E-]"; QTest::newRow( "array of various numbers" ) << json; // document tests QTest::newRow( "empty object" ) << "{}"; QTest::newRow( "basic document" ) << "{\"foo\":\"bar\"}"; QTest::newRow( "object with ints" ) << "{\"foo\":6}"; QString json2 = "{ \"foo\":\"bar\",\n\"number\" : 51.3 , \"array\":[\"item1\", 123]}"; QTest::newRow( "complicated document" ) << json2; // more complex cases const QString json3 = "[ {\"foo\":\"bar\"},\n\"number\",51.3 , [\"item1\", 123]]"; QTest::newRow( "complicated array" ) << json3; } QTEST_MAIN(TestJSonDriver) #include "moc_testjsondriver.cxx" <|endoftext|>
<commit_before>#pragma once #include "integrators/implicit_runge_kutta_nyström_integrator.hpp" #include <algorithm> #include <cmath> #include <ctime> #include <vector> #include "glog/logging.h" #include "quantities/quantities.hpp" #ifdef ADVANCE_ΔQSTAGE #error ADVANCE_ΔQSTAGE already defined #else #define ADVANCE_ΔQSTAGE(step) \ do { \ Time const step_evaluated = (step); \ for (int k = 0; k < dimension; ++k) { \ Displacement const Δq = (*Δqstage_previous)[k] + \ step_evaluated * v_stage[k]; \ q_stage[k] = q_last[k].value + Δq; \ (*Δqstage_current)[k] = Δq; \ } \ } while (false) #endif #ifdef ADVANCE_ΔVSTAGE #error ADVANCE_ΔVSTAGE already defined #else #define ADVANCE_ΔVSTAGE(step, q_clock) \ do { \ Time const step_evaluated = (step); \ compute_acceleration((q_clock), q_stage, &a); \ for (int k = 0; k < dimension; ++k) { \ Velocity const Δv = (*Δvstage_previous)[k] + step_evaluated * a[k]; \ v_stage[k] = v_last[k].value + Δv; \ (*Δvstage_current)[k] = Δv; \ } \ } while (false) #endif namespace principia { using quantities::Difference; using quantities::Quotient; namespace integrators { template<typename Position> void IRKNIntegrator::SolveTrivialKineticEnergyIncrement( IRKNRightHandSideComputation<Position> compute_acceleration, Parameters<Position, Variation<Position>> const& parameters, not_null<Solution<Position, Variation<Position>>*> const solution) const { using Velocity = Variation<Position>; using Displacement = Difference<Position>; int const dimension = parameters.initial.positions.size(); std::vector<std::vector<Displacement>> Δqstages(stages_); for (auto& Δqstage : Δqstages) { Δqstage.resize(dimension); } // Dimension the result. int const capacity = parameters.sampling_period == 0 ? 1 : static_cast<int>( ceil((((parameters.tmax - parameters.initial.time.value) / parameters.Δt) + 1) / parameters.sampling_period)) + 1; solution->clear(); solution->reserve(capacity); std::vector<DoublePrecision<Position>> q_last(parameters.initial.positions); std::vector<DoublePrecision<Velocity>> v_last(parameters.initial.momenta); int sampling_phase = 0; std::vector<Position> q_stage(dimension); std::vector<Velocity> v_stage(dimension); std::vector<Quotient<Velocity, Time>> a(dimension); // Current accelerations. // The following quantity is generally equal to |Δt|, but during the last // iteration, if |tmax_is_exact|, it may differ significantly from |Δt|. Time h = parameters.Δt; // Constant for now. // During one iteration of the outer loop below we process the time interval // [|tn|, |tn| + |h|[. |tn| is computed using compensated summation to make // sure that we don't have drifts. DoublePrecision<Time> tn = parameters.initial.time; bool at_end = !parameters.tmax_is_exact && parameters.tmax < tn.value + h; while (!at_end) { // Check if this is the last interval and if so process it appropriately. if (parameters.tmax_is_exact) { // If |tn| is getting close to |tmax|, use |tmax| as the upper bound of // the interval and update |h| accordingly. The bound chosen here for // |tmax| ensures that we don't end up with a ridiculously small last // interval: we'd rather make the last interval a bit bigger. More // precisely, the last interval generally has a length between 0.5 Δt and // 1.5 Δt, unless it is also the first interval. // NOTE(phl): This may lead to convergence as bad as (1.5 Δt)^5 rather // than Δt^5. if (parameters.tmax <= tn.value + 3 * h / 2) { at_end = true; h = (parameters.tmax - tn.value) - tn.error; } } else if (parameters.tmax < tn.value + 2 * h) { // If the next interval would overshoot, make this the last interval but // stick to the same step. at_end = true; } // Here |h| is the length of the current time interval and |tn| is its // start. for (int k = 0; k < dimension; ++k) { (*Δqstage_current)[k] = Displacement(); (*Δvstage_current)[k] = Velocity(); q_stage[k] = q_last[k].value; } // Fixed-point iteration. for (int i = 0; i < stages_; ++i) { std::swap(Δqstage_current, Δqstage_previous); std::swap(Δvstage_current, Δvstage_previous); // Compensated summation from "'SymplecticPartitionedRungeKutta' Method // for NDSolve", algorithm 2. for (int k = 0; k < dimension; ++k) { q_last[k].Increment((*Δqstage_current)[k]); v_last[k].Increment((*Δvstage_current)[k]); q_stage[k] = q_last[k].value; v_stage[k] = v_last[k].value; } tn.Increment(h); if (parameters.sampling_period != 0) { if (sampling_phase % parameters.sampling_period == 0) { solution->emplace_back(); SystemState<Position, Velocity>* state = &solution->back(); state->time = tn; state->positions.reserve(dimension); state->momenta.reserve(dimension); for (int k = 0; k < dimension; ++k) { state->positions.emplace_back(q_last[k]); state->momenta.emplace_back(v_last[k]); } } ++sampling_phase; } } if (parameters.sampling_period == 0) { solution->emplace_back(); SystemState<Position, Velocity>* state = &solution->back(); state->time = tn; state->positions.reserve(dimension); state->momenta.reserve(dimension); for (int k = 0; k < dimension; ++k) { state->positions.emplace_back(q_last[k]); state->momenta.emplace_back(v_last[k]); } } } } // namespace integrators } // namespace principia #undef ADVANCE_ΔQSTAGE #undef ADVANCE_ΔVSTAGE <commit_msg>this is too messy<commit_after>#pragma once #include "integrators/implicit_runge_kutta_nyström_integrator.hpp" #include <algorithm> #include <cmath> #include <ctime> #include <vector> #include "glog/logging.h" #include "quantities/quantities.hpp" #ifdef ADVANCE_ΔQSTAGE #error ADVANCE_ΔQSTAGE already defined #else #define ADVANCE_ΔQSTAGE(step) \ do { \ Time const step_evaluated = (step); \ for (int k = 0; k < dimension; ++k) { \ Displacement const Δq = (*Δqstage_previous)[k] + \ step_evaluated * v_stage[k]; \ q_stage[k] = q_last[k].value + Δq; \ (*Δqstage_current)[k] = Δq; \ } \ } while (false) #endif #ifdef ADVANCE_ΔVSTAGE #error ADVANCE_ΔVSTAGE already defined #else #define ADVANCE_ΔVSTAGE(step, q_clock) \ do { \ Time const step_evaluated = (step); \ compute_acceleration((q_clock), q_stage, &a); \ for (int k = 0; k < dimension; ++k) { \ Velocity const Δv = (*Δvstage_previous)[k] + step_evaluated * a[k]; \ v_stage[k] = v_last[k].value + Δv; \ (*Δvstage_current)[k] = Δv; \ } \ } while (false) #endif namespace principia { using quantities::Difference; using quantities::Quotient; namespace integrators { template<typename Position> void IRKNIntegrator::SolveTrivialKineticEnergyIncrement( IRKNRightHandSideComputation<Position> compute_acceleration, Parameters<Position, Variation<Position>> const& parameters, not_null<Solution<Position, Variation<Position>>*> const solution) const { using Velocity = Variation<Position>; using Displacement = Difference<Position>; int const dimension = parameters.initial.positions.size(); std::vector<std::vector<Displacement>>* Δqstages_current(stages_); std::vector<std::vector<Displacement>>* Δqstages_previous(stages_); for (int i = 0; i < stages_; ++i) { Δqstages_current[i].resize(dimension); Δqstages_previous[i].resize(dimension); } // Dimension the result. int const capacity = parameters.sampling_period == 0 ? 1 : static_cast<int>( ceil((((parameters.tmax - parameters.initial.time.value) / parameters.Δt) + 1) / parameters.sampling_period)) + 1; solution->clear(); solution->reserve(capacity); std::vector<DoublePrecision<Position>> q_last(parameters.initial.positions); std::vector<DoublePrecision<Velocity>> v_last(parameters.initial.momenta); int sampling_phase = 0; std::vector<Position> q_stage(dimension); std::vector<Velocity> v_stage(dimension); std::vector<Quotient<Velocity, Time>> a(dimension); // Current accelerations. // The following quantity is generally equal to |Δt|, but during the last // iteration, if |tmax_is_exact|, it may differ significantly from |Δt|. Time h = parameters.Δt; // Constant for now. // During one iteration of the outer loop below we process the time interval // [|tn|, |tn| + |h|[. |tn| is computed using compensated summation to make // sure that we don't have drifts. DoublePrecision<Time> tn = parameters.initial.time; bool at_end = !parameters.tmax_is_exact && parameters.tmax < tn.value + h; while (!at_end) { // Check if this is the last interval and if so process it appropriately. if (parameters.tmax_is_exact) { // If |tn| is getting close to |tmax|, use |tmax| as the upper bound of // the interval and update |h| accordingly. The bound chosen here for // |tmax| ensures that we don't end up with a ridiculously small last // interval: we'd rather make the last interval a bit bigger. More // precisely, the last interval generally has a length between 0.5 Δt and // 1.5 Δt, unless it is also the first interval. // NOTE(phl): This may lead to convergence as bad as (1.5 Δt)^5 rather // than Δt^5. if (parameters.tmax <= tn.value + 3 * h / 2) { at_end = true; h = (parameters.tmax - tn.value) - tn.error; } } else if (parameters.tmax < tn.value + 2 * h) { // If the next interval would overshoot, make this the last interval but // stick to the same step. at_end = true; } // Here |h| is the length of the current time interval and |tn| is its // start. for (int k = 0; k < dimension; ++k) { (*Δqstage_current)[k] = Displacement(); (*Δvstage_current)[k] = Velocity(); q_stage[k] = q_last[k].value; } // Fixed-point iteration. // NOTE(egg): this does not work for stiff systems, newton iteration is then // required. for (int i = 0; i < stages_; ++i) { Δqstages[i] } // Compensated summation from "'SymplecticPartitionedRungeKutta' Method // for NDSolve", algorithm 2. for (int k = 0; k < dimension; ++k) { q_last[k].Increment((*Δqstage_current)[k]); v_last[k].Increment((*Δvstage_current)[k]); q_stage[k] = q_last[k].value; v_stage[k] = v_last[k].value; } tn.Increment(h); if (parameters.sampling_period != 0) { if (sampling_phase % parameters.sampling_period == 0) { solution->emplace_back(); SystemState<Position, Velocity>* state = &solution->back(); state->time = tn; state->positions.reserve(dimension); state->momenta.reserve(dimension); for (int k = 0; k < dimension; ++k) { state->positions.emplace_back(q_last[k]); state->momenta.emplace_back(v_last[k]); } } ++sampling_phase; } } if (parameters.sampling_period == 0) { solution->emplace_back(); SystemState<Position, Velocity>* state = &solution->back(); state->time = tn; state->positions.reserve(dimension); state->momenta.reserve(dimension); for (int k = 0; k < dimension; ++k) { state->positions.emplace_back(q_last[k]); state->momenta.emplace_back(v_last[k]); } } } } // namespace integrators } // namespace principia #undef ADVANCE_ΔQSTAGE #undef ADVANCE_ΔVSTAGE <|endoftext|>
<commit_before>#pragma once #include <vector> #include "base/not_null.hpp" #include "integrators/symplectic_integrator.hpp" namespace principia { using base::not_null; namespace integrators { enum VanishingCoefficients { None, FirstBVanishes, LastAVanishes, }; template<typename Position, typename Momentum> class SPRKIntegrator : public SymplecticIntegrator<Position, Momentum> { public: using Coefficients = typename SymplecticIntegrator<Position, Momentum>::Coefficients; using Parameters = typename SymplecticIntegrator<Position, Momentum>::Parameters; using SystemState = typename SymplecticIntegrator<Position, Momentum>::SystemState; SPRKIntegrator(); ~SPRKIntegrator() override = default; // Coefficients from Robert I. McLachlan and Pau Atela (1992), // The accuracy of symplectic integrators, table 2. // http://eaton.math.rpi.edu/CSUMS/Papers/Symplectic/McLachlan_Atela_92.pdf Coefficients const& Leapfrog() const; Coefficients const& Order4FirstSameAsLast() const; Coefficients const& Order5Optimal() const; // http://sixtrack.web.cern.ch/SixTrack/doc/yoshida00.pdf void Initialize(Coefficients const& coefficients) override; template<typename AutonomousRightHandSideComputation, typename RightHandSideComputation> void Solve(RightHandSideComputation compute_force, AutonomousRightHandSideComputation compute_velocity, Parameters const& parameters, not_null<std::vector<SystemState>*> const solution) const; private: struct FirstSameAsLast { double first; double last; }; // TODO(egg): either get rid of the non-autonomous RHS, or have neither of // them be autonomous, this is messy. template<VanishingCoefficients vanishing_coefficients_, typename AutonomousRightHandSideComputation, typename RightHandSideComputation> void SolveOptimized(RightHandSideComputation compute_force, AutonomousRightHandSideComputation compute_velocity, Parameters const& parameters, not_null<std::vector<SystemState>*> const solution) const; VanishingCoefficients vanishing_coefficients_; // Null if, and only if, |vanishing_coefficients_| is |None|. // If |vanishing_coefficients_| is |FirstBVanishes|, this contains the first // and last a coefficients. // If |vanishing_coefficients_| is |FirstAVanishes|, this contains the first // and last b coefficients. // These are used to desynchronize and synchronize first-same-as-last // integrators. std::unique_ptr<FirstSameAsLast> first_same_as_last_; // The number of stages, or the number of stages minus one for a // first-same-as-last integrator. int stages_; // The position and momentum nodes. // If |vanishing_coefficients_| is |FirstBVanishes|, we do not store the first // b coefficient, and the last entry of |a_| is the sum of the first and last // a coefficients. // If |vanishing_coefficients_| is |LastAVanishes|, we do not store the last // a coefficient, and the first entry of |b_| is the sum of the first and last // b coefficients. std::vector<double> a_; std::vector<double> b_; // TODO(egg): remove when we find a way to use only autonomous // right-hand-sides. // The weights. std::vector<double> c_; }; } // namespace integrators } // namespace principia #include "integrators/symplectic_partitioned_runge_kutta_integrator_body.hpp" <commit_msg>crashy IDE<commit_after>#pragma once #include <vector> #include "base/not_null.hpp" #include "integrators/symplectic_integrator.hpp" namespace principia { using base::not_null; namespace integrators { enum VanishingCoefficients { None, FirstBVanishes, LastAVanishes, }; template<typename Position, typename Momentum> class SPRKIntegrator : public SymplecticIntegrator<Position, Momentum> { public: using Coefficients = typename SymplecticIntegrator<Position, Momentum>::Coefficients; using Parameters = typename SymplecticIntegrator<Position, Momentum>::Parameters; using SystemState = typename SymplecticIntegrator<Position, Momentum>::SystemState; SPRKIntegrator(); ~SPRKIntegrator() override = default; // Coefficients from Robert I. McLachlan and Pau Atela (1992), // The accuracy of symplectic integrators, table 2. // http://eaton.math.rpi.edu/CSUMS/Papers/Symplectic/McLachlan_Atela_92.pdf Coefficients const& Leapfrog() const; Coefficients const& PseudoLeapfrog() const; Coefficients const& Order4FirstSameAsLast() const; Coefficients const& Order5Optimal() const; // http://sixtrack.web.cern.ch/SixTrack/doc/yoshida00.pdf void Initialize(Coefficients const& coefficients) override; template<typename AutonomousRightHandSideComputation, typename RightHandSideComputation> void Solve(RightHandSideComputation compute_force, AutonomousRightHandSideComputation compute_velocity, Parameters const& parameters, not_null<std::vector<SystemState>*> const solution) const; private: struct FirstSameAsLast { double first; double last; }; // TODO(egg): either get rid of the non-autonomous RHS, or have neither of // them be autonomous, this is messy. template<VanishingCoefficients vanishing_coefficients_, typename AutonomousRightHandSideComputation, typename RightHandSideComputation> void SolveOptimized(RightHandSideComputation compute_force, AutonomousRightHandSideComputation compute_velocity, Parameters const& parameters, not_null<std::vector<SystemState>*> const solution) const; VanishingCoefficients vanishing_coefficients_; // Null if, and only if, |vanishing_coefficients_| is |None|. // If |vanishing_coefficients_| is |FirstBVanishes|, this contains the first // and last a coefficients. // If |vanishing_coefficients_| is |FirstAVanishes|, this contains the first // and last b coefficients. // These are used to desynchronize and synchronize first-same-as-last // integrators. std::unique_ptr<FirstSameAsLast> first_same_as_last_; // The number of stages, or the number of stages minus one for a // first-same-as-last integrator. int stages_; // The position and momentum nodes. // If |vanishing_coefficients_| is |FirstBVanishes|, we do not store the first // b coefficient, and the last entry of |a_| is the sum of the first and last // a coefficients. // If |vanishing_coefficients_| is |LastAVanishes|, we do not store the last // a coefficient, and the first entry of |b_| is the sum of the first and last // b coefficients. std::vector<double> a_; std::vector<double> b_; // TODO(egg): remove when we find a way to use only autonomous // right-hand-sides. // The weights. std::vector<double> c_; }; } // namespace integrators } // namespace principia #include "integrators/symplectic_partitioned_runge_kutta_integrator_body.hpp" <|endoftext|>
<commit_before>#include "sliding_window.hpp" #include <iostream> #include <vector> using iter::sliding_window; int main() { std::vector<int> v = {1,2,3,4,5,6,7,8,9}; for (auto sec : sliding_window(v,4)) { for (auto i : sec) { std::cout << i << " "; i.get() = 90; } std::cout << std::endl; } return 0; } <commit_msg>adds test with temporary<commit_after>#include "sliding_window.hpp" #include <iostream> #include <vector> using iter::sliding_window; int main() { std::vector<int> v = {1,2,3,4,5,6,7,8,9}; for (auto sec : sliding_window(v,4)) { for (auto i : sec) { std::cout << i << " "; i.get() = 90; } std::cout << std::endl; } for (auto sec : sliding_window(std::vector<int>{1,2,3,4,5,6,7,8,9} ,4)) { for (auto i : sec) { std::cout << i << " "; i.get() = 90; } std::cout << std::endl; } return 0; } <|endoftext|>
<commit_before>#include <opencv2/highgui/highgui.hpp> #include "opencv2/core/core_c.h" #include "opencv2/core/core.hpp" #include "opencv2/flann/miniflann.hpp" #include "opencv2/imgproc/imgproc_c.h" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/video/video.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/objdetect/objdetect.hpp" #include "opencv2/calib3d/calib3d.hpp" #include "opencv2/ml/ml.hpp" #include "opencv2/highgui/highgui_c.h" #include "opencv2/highgui/highgui.hpp" //#include "opencv2/contrib/contrib.hpp" #include <vector> using namespace cv; using namespace std; class Image{ public: Image(){}; Image(int w, int h, Mat image); Mat getCompressed(); void displayFilter(Mat, int); void divide_image(); vector<vector<vector<int> > > imageRGB;//(w, vector<vector<int> >(w, vector<int>(3))); // 3-d vector to store the rgb data vector<vector<vector<int> > > imageYBR;//(h, vector<vector<int> >(w, vector<int>(3))); // 3-d vector to store the luminance,Cb,Cr data private: Mat compressedImage = imread("flower.jpg", CV_LOAD_IMAGE_COLOR); int width; int height; vector<vector<Mat> > sub_images;// 2-d vector of sub-images }; // sub image is an image: 8x8 sub images will be instantiated class Sub_Image: public Image{ public: Sub_Image(); Sub_Image(int w, int h, Mat image, int num_row, int num_col); void compress_sub_image(); void cosine_transform(); Mat self; private: int row; int col; int width; int height; Image father; }; int main(){ Mat image = imread("flower.jpg", CV_LOAD_IMAGE_COLOR); // reads in image into image object from the Matrix? class, not sure what CV_LO... is Mat imageYCBCR; // this was code I found online to convert RGB to YcBcR, but i couldnt get CV_BGR2YCBCR to function cvtColor(image,imageYCBCR,CV_BGR2YCrCb); // converts image from BGR to ycbcr YCBCR Mat filter[3]; split(imageYCBCR,filter); Mat y = filter[0]; Mat cr = filter[1]; Mat cb = filter[2]; Image compressed(image.cols, image.rows, image); compressed.displayFilter(image, 0); // this doesn't do what I want it to do imshow("opencvtest", compressed.getCompressed()); // displays the image with title opencvtest cout << "entering_divide_image" << endl; Sub_Image subim( 100, 100, compressed.getCompressed(), 1, 1); // compressed.divide_image(); // ^^^^^->>>>>segfault // imshow("ycbr", y); // imshow("luminance", y); imshow("lumiance", y); imshow("RED:", cr); imshow("BLUE:", cb); imshow("FLOWER:", image); waitKey(0); // not sure what this does return 0; } // displays either the Luminance or Chromiance of an image void Image::displayFilter(Mat image, int filterIndex){ for(int i = 0; i < image.rows; i++){ for(int j = 0; j < image.cols; j++){ image.at<Vec3b>(i, j)[2] = imageYBR[i][j][filterIndex]; image.at<Vec3b>(i, j)[1] = imageYBR[i][j][filterIndex]; image.at<Vec3b>(i, j)[0] = imageYBR[i][j][filterIndex]; } } imshow("Filtered Image:", image); } Sub_Image::Sub_Image(){ width = 1; height = 1; row = 1; col = 1; } // non-default constructor for sub-image: sets Mat.color position to the imageRGB of inherited Image Sub_Image::Sub_Image(int w, int h, Mat image, int num_row, int num_col){ width = w; height = h; row = num_row; col = num_col; Mat temp(width, height, 3, DataType<int>::type) for(int i = 0; i < width; i++){ for(int j = 0; j < height; j++){ // setting the self's color equal to its RGB position // self.at<Vec3b>(i, j)[2] = imageRGB[num_row*i][num_col*j][2]; // self.at<Vec3b>(i, j)[1] = imageRGB[num_row*i][num_col*j][1]; // self.at<Vec3b>(i, j)[0] = imageRGB[num_row*i][num_col*j][0]; // does sub_image inherit vector,vectorRGB? } } } // Since the human eye is less sensitive to an image's difference in chromiance // we can down-sample the red and blue of the image from the pixels to 2x2 blocks of pixels void Sub_Image::compress_sub_image(){ int average_blue = 0; int average_red = 0; int y, cB, cR; for(int i = row; i < row + (width / 2); i++){ for(int j = col; j < col + (height / 2); j++){ // Blue Chromiance is stored here average_blue = (father.imageYBR[i][j][1] + father.imageYBR[i + 1][j][1] + father.imageYBR[i][j + 1][1] + father.imageYBR[i + 1][j + 1][1])/4; // Red Chromiance is stored here average_red = (father.imageYBR[i][j][2] + father.imageYBR[i + 1][j][2] + father.imageYBR[i][j + 1][2] + father.imageYBR[i + 1][j + 1][2])/4; // Assign the father image the compressed chromiance values father.imageYBR[i][j][1] = father.imageYBR[i + 1][j][1] = father.imageYBR[i][j + 1][1] = father.imageYBR[i + 1][j + 1][1] = average_blue; father.imageYBR[i][j][2] = father.imageYBR[i + 1][j][2] = father.imageYBR[i][j + 1][2] = father.imageYBR[i + 1][j + 1][2] = average_red; y = father.imageYBR[i][j][0]; cB = father.imageYBR[i][j][1]; cR = father.imageYBR[i][j][2]; // give father image compressed RGB data translated from YcBcR father.imageRGB[i][j][0] = 1.0 * y + 0 * cB + 1.402 * cR; father.imageRGB[i][j][1] = 1.0 * y - 0.344136 * cB - 0.714136 * cR; father.imageRGB[i][j][2] = 1.0 * y + 1.772 * cB + 0 * cR; // self assign commpressed RGB data self.at<Vec3b>(i, j)[2] = father.imageRGB[i][j][2]; self.at<Vec3b>(i, j)[1] = father.imageRGB[i][j][1]; self.at<Vec3b>(i, j)[0] = father.imageRGB[i][j][0]; } } } // divide image into 8x8 sub images void Image::divide_image(){ cout << "1" << endl; for(int i = 0; i < 8; i++){ vector<Mat> temp; cout << "2: " << i << endl; for(int j = 0; j < 8; j++){ cout << "3: " << j << endl; Sub_Image sub_image(width / 8, height / 8, getCompressed(), i, j); // sub_image.compress_sub_image(); imshow("sub-image", sub_image.self); temp.push_back(sub_image.self); } cout << "4: " << i << endl; sub_images.push_back(temp); temp.clear(); } } Image::Image(int w, int h, Mat image){ width = w; height = h; int temp, r, g, b; //populate imageRGB matrix with rgb values of the image, now that i think about it, this is unnessesary since OpenCV already has the values stored which we can acces s at any time, I leave it for now just in case this is more intuitive vector<vector<int> > tempVectorRGB; vector<int> innerTempVectorRGB; vector<vector<int> > tempVectorYBR; vector<int> innerTempVectorYBR; // should we use ints or double for this????????????????????????????? for(int i = 0; i < height; i++){ for(int j = 0; j < width; j++){ r = image.at<Vec3b>(i, j)[2]; g = image.at<Vec3b>(i, j)[1]; b = image.at<Vec3b>(i, j)[0]; innerTempVectorRGB.push_back(r); innerTempVectorRGB.push_back(g); innerTempVectorRGB.push_back(b); tempVectorRGB.push_back(innerTempVectorRGB); innerTempVectorRGB.clear(); innerTempVectorYBR.push_back(r*.299 + g*.587 + b*.114); innerTempVectorYBR.push_back(r*-.16874 + g*-.33126 + b*.5); innerTempVectorYBR.push_back(r*.5 + g*-.41869 + b*-.08131); tempVectorYBR.push_back(innerTempVectorYBR); innerTempVectorYBR.clear(); } imageRGB.push_back(tempVectorRGB); tempVectorRGB.clear(); imageYBR.push_back(tempVectorYBR); tempVectorYBR.clear(); } } Mat Image::getCompressed(){ return compressedImage; } <commit_msg>updated readImage.cpp<commit_after>#include <opencv2/highgui/highgui.hpp> #include "opencv2/core/core_c.h" #include "opencv2/core/core.hpp" #include "opencv2/flann/miniflann.hpp" #include "opencv2/imgproc/imgproc_c.h" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/video/video.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/objdetect/objdetect.hpp" #include "opencv2/calib3d/calib3d.hpp" #include "opencv2/ml/ml.hpp" #include "opencv2/highgui/highgui_c.h" #include "opencv2/highgui/highgui.hpp" //#include "opencv2/contrib/contrib.hpp" #include <vector> using namespace cv; using namespace std; class Image{ public: Image(){}; Image(int w, int h, Mat image); Mat getImage(); void displayFilter(Mat, int); void divide_image(Image); // divides image into 8x8 sub images // 3-d vectors (widthxheightx3): represent RGB and YcBcR color spaces vector<vector<vector<int> > > imageRGB;//(w, vector<vector<int> >(w, vector<int>(3))); // 3-d vector to store the rgb data vector<vector<vector<int> > > imageYBR;//(h, vector<vector<int> >(w, vector<int>(3))); // 3-d vector to store the luminance,Cb,Cr data private: Mat rawImage = imread("flower.jpg", CV_LOAD_IMAGE_COLOR); int width; int height; vector<vector<Mat> > sub_images;// 2-d vector of sub-images }; // sub image inherits from image: 8x8 sub images will be instantiated class Sub_Image: public Image{ public: Sub_Image(); Sub_Image(int w, int h, Image image, int num_row, int num_col); void compress_sub_image(); void cosine_transform(); Mat self; private: int row; // y position of sub-image relative to father int col; // x position of sub-image relative to father int width; // width of father / 8 int height; // height of father / 2 Image father; // father Image object }; int main(){ Mat image = imread("flower.jpg", CV_LOAD_IMAGE_COLOR); // reads in image into image object from the Matrix? class, not sure what CV_LO... is Mat imageYCBCR; // this was code I found online to convert RGB to YcBcR, but i couldnt get CV_BGR2YCBCR to function cvtColor(image,imageYCBCR,CV_BGR2YCrCb); // converts image from BGR to ycbcr YCBCR Mat filter[3]; split(imageYCBCR,filter); Mat y = filter[0]; Mat cr = filter[1]; Mat cb = filter[2]; Image compressed(image.cols, image.rows, image); compressed.displayFilter(image, 0); // this doesn't do what I want it to do imshow("opencvtest", compressed.getImage()); // displays the image with title opencvtest // Sub_Image subim( 100, 100, compressed, 1, 1); compressed.divide_image(compressed); // ^^^^^->>>>>segfault // imshow("ycbr", y); // imshow("luminance", y); imshow("lumiance", y); imshow("RED:", cr); imshow("BLUE:", cb); imshow("FLOWER:", image); waitKey(0); // not sure what this does return 0; } // displays either the Luminance or Chromiance of an image void Image::displayFilter(Mat image, int filterIndex){ for(int i = 0; i < image.rows; i++){ for(int j = 0; j < image.cols; j++){ image.at<Vec3b>(i, j)[2] = imageYBR[i][j][filterIndex]; image.at<Vec3b>(i, j)[1] = imageYBR[i][j][filterIndex]; image.at<Vec3b>(i, j)[0] = imageYBR[i][j][filterIndex]; } } imshow("Filtered Image:", image); } Sub_Image::Sub_Image(){ width = 1; height = 1; row = 1; col = 1; } // non-default constructor for sub-image: sets Mat.color position to the imageRGB of inherited Image Sub_Image::Sub_Image(int w, int h, Image dad, int num_row, int num_col){ width = w; height = h; row = num_row; col = num_col; father = dad; Mat temp(width, height, 3, DataType<int>::type); self = temp; for(int i = 0; i < width; i++){ for(int j = 0; j < height; j++){ // setting the self's color equal to its RGB position self.at<Vec3b>(i, j)[2] = father.imageRGB[num_row*i][num_col*j][2]; self.at<Vec3b>(i, j)[1] = father.imageRGB[num_row*i][num_col*j][1]; self.at<Vec3b>(i, j)[0] = father.imageRGB[num_row*i][num_col*j][0]; // does sub_image inherit vector,vectorRGB? } } } // Since the human eye is less sensitive to an image's difference in chromiance // we can down-sample the red and blue of the image from the pixels to 2x2 blocks of pixels void Sub_Image::compress_sub_image(){ int average_blue = 0; int average_red = 0; int y, cB, cR; for(int i = row; i < row + (width / 2); i++){ for(int j = col; j < col + (height / 2); j++){ // Blue Chromiance is stored here average_blue = (father.imageYBR[i][j][1] + father.imageYBR[i + 1][j][1] + father.imageYBR[i][j + 1][1] + father.imageYBR[i + 1][j + 1][1])/4; // Red Chromiance is stored here average_red = (father.imageYBR[i][j][2] + father.imageYBR[i + 1][j][2] + father.imageYBR[i][j + 1][2] + father.imageYBR[i + 1][j + 1][2])/4; // Assign the father image the compressed chromiance values father.imageYBR[i][j][1] = father.imageYBR[i + 1][j][1] = father.imageYBR[i][j + 1][1] = father.imageYBR[i + 1][j + 1][1] = average_blue; father.imageYBR[i][j][2] = father.imageYBR[i + 1][j][2] = father.imageYBR[i][j + 1][2] = father.imageYBR[i + 1][j + 1][2] = average_red; y = father.imageYBR[i][j][0]; cB = father.imageYBR[i][j][1]; cR = father.imageYBR[i][j][2]; // give father image compressed RGB data translated from YcBcR father.imageRGB[i][j][0] = 1.0 * y + 0 * cB + 1.402 * cR; father.imageRGB[i][j][1] = 1.0 * y - 0.344136 * cB - 0.714136 * cR; father.imageRGB[i][j][2] = 1.0 * y + 1.772 * cB + 0 * cR; // self assign commpressed RGB data self.at<Vec3b>(i, j)[2] = father.imageRGB[i][j][2]; self.at<Vec3b>(i, j)[1] = father.imageRGB[i][j][1]; self.at<Vec3b>(i, j)[0] = father.imageRGB[i][j][0]; } } } // divide image into 8x8 sub images void Image::divide_image(Image image){ cout << "1" << endl; for(int i = 0; i < 8; i++){ vector<Mat> temp; cout << "2: " << i << endl; for(int j = 0; j < 8; j++){ cout << "3: " << j << endl; Sub_Image sub_image(width / 8, height / 8, image, i, j); // sub_image.compress_sub_image(); imshow("sub-image", sub_image.self); temp.push_back(sub_image.self); } cout << "4: " << i << endl; sub_images.push_back(temp); temp.clear(); } } Image::Image(int w, int h, Mat image){ width = w; height = h; int temp, r, g, b; //populate imageRGB matrix with rgb values of the image, now that i think about it, this is unnessesary since OpenCV already has the values stored which we can acces s at any time, I leave it for now just in case this is more intuitive vector<vector<int> > tempVectorRGB; vector<int> innerTempVectorRGB; vector<vector<int> > tempVectorYBR; vector<int> innerTempVectorYBR; // should we use ints or double for this????????????????????????????? for(int i = 0; i < height; i++){ for(int j = 0; j < width; j++){ r = image.at<Vec3b>(i, j)[2]; g = image.at<Vec3b>(i, j)[1]; b = image.at<Vec3b>(i, j)[0]; innerTempVectorRGB.push_back(r); innerTempVectorRGB.push_back(g); innerTempVectorRGB.push_back(b); tempVectorRGB.push_back(innerTempVectorRGB); innerTempVectorRGB.clear(); innerTempVectorYBR.push_back(r*.299 + g*.587 + b*.114); innerTempVectorYBR.push_back(r*-.16874 + g*-.33126 + b*.5); innerTempVectorYBR.push_back(r*.5 + g*-.41869 + b*-.08131); tempVectorYBR.push_back(innerTempVectorYBR); innerTempVectorYBR.clear(); } imageRGB.push_back(tempVectorRGB); tempVectorRGB.clear(); imageYBR.push_back(tempVectorYBR); tempVectorYBR.clear(); } } Mat Image::getImage(){ return rawImage; } <|endoftext|>
<commit_before>/* **************************************************************************** * * FILE HostMgr.cpp * * AUTHOR Ken Zangelin * * CREATION DATE Feb 10 2011 * */ #include <stdio.h> // popen #include <unistd.h> // gethostname #include <arpa/inet.h> // sockaddr_in, inet_ntop #include <ifaddrs.h> // getifaddrs #include <net/if.h> // IFF_UP #include <netdb.h> // #include <string.h> // strstr #include "logMsg.h" // LM_* #include "traceLevels.h" // Trace Levels #include "Host.h" // Host #include "HostMgr.h" // Own interface #include <stdlib.h> // free namespace ss { /* **************************************************************************** * * HostMgr */ HostMgr::HostMgr(unsigned int size) { this->size = size; hostV = (Host**) calloc(size, sizeof(Host*)); if (hostV == NULL) LM_X(1, ("error allocating room for %d delilah hosts", size)); LM_M(("Allocated a Host Vector for %d hosts", size)); localIps(); list("init"); } /* **************************************************************************** * * ipsGet - get all IPs for a machine */ void HostMgr::ipsGet(Host* hostP) { struct ifaddrs* addrs; struct ifaddrs* iap; struct sockaddr_in* sa; char buf[64]; getifaddrs(&addrs); for (iap = addrs; iap != NULL; iap = iap->ifa_next) { if (iap->ifa_addr && (iap->ifa_flags & IFF_UP) && iap->ifa_addr->sa_family == AF_INET) { sa = (struct sockaddr_in*)(iap->ifa_addr); inet_ntop(iap->ifa_addr->sa_family, (void*) &(sa->sin_addr), buf, sizeof(buf)); if ((hostP->ip == NULL) && (strcmp(buf, "127.0.0.1") != 0)) { hostP->ip = strdup(buf); LM_M(("Setting IP '%s' for host '%s'", hostP->ip, hostP->name)); } else aliasAdd(hostP, buf); } } freeifaddrs(addrs); } /* **************************************************************************** * * localIps - */ void HostMgr::localIps(void) { char hostName[128]; char domain[128]; char domainedName[128]; Host* hostP; if (gethostname(hostName, sizeof(hostName)) == -1) LM_X(1, ("gethostname: %s", strerror(errno))); hostP = insert(hostName, "127.0.0.1"); memset(domainedName, 0, sizeof(domainedName)); if (getdomainname(domain, sizeof(domain)) == -1) LM_X(1, ("getdomainname: %s", strerror(errno))); LM_TODO(("Would gethostname ever returned the 'domained' name ?")); if (domainedName[0] != 0) { snprintf(domainedName, sizeof(domainedName), "%s.%s", hostName, domain); aliasAdd(hostP, domainedName); } aliasAdd(hostP, "localhost"); ipsGet(hostP); } /* **************************************************************************** * * HostMgr::hosts - */ int HostMgr::hosts(void) { unsigned int ix; int hostNo = 0; for (ix = 0; ix < size; ix++) { if (hostV[ix] != NULL) ++hostNo; } return hostNo; } /* **************************************************************************** * * HostMgr::insert - */ Host* HostMgr::insert(Host* hostP) { unsigned int ix; for (ix = 0; ix < size; ix++) { if (hostV[ix] == NULL) { LM_M(("Inserting host '%s'", hostP->name)); hostV[ix] = hostP; list("Host Added"); return hostV[ix]; } } LM_RE(NULL, ("Please realloc host vector (%d hosts not enough) ...", size)); } /* **************************************************************************** * * ip2string - convert integer ip address to string */ static void ip2string(int ip, char* ipString, int ipStringLen) { snprintf(ipString, ipStringLen, "%d.%d.%d.%d", ip & 0xFF, (ip & 0xFF00) >> 8, (ip & 0xFF0000) >> 16, (ip & 0xFF000000) >> 24); } /* **************************************************************************** * * onlyDigitsAndDots - */ static bool onlyDigitsAndDots(const char* string) { if ((string == NULL) || (string[0] == 0)) LM_RE(false, ("Empty IP ...")); for (unsigned int ix = 0; ix < strlen(string); ix++) { if (string[ix] == 0) return true; if (string[ix] == '.') continue; if ((string[ix] >= '0') && (string[ix] <= '9')) continue; return false; } return true; } /* **************************************************************************** * * HostMgr::insert - */ Host* HostMgr::insert(const char* name, const char* ip) { Host* hostP; char ipX[64]; char* dotP; char* alias = NULL; LM_M(("***** New host: name: '%s', ip: '%s'", name, ip)); if ((name == NULL) && (ip == NULL)) LM_X(1, ("name AND ip NULL - cannot add a ghost host ...")); if (name == NULL) { LM_W(("NULL host name for IP '%s'", ip)); name = "nohostname"; } if ((hostP = lookup(name)) != NULL) return hostP; struct hostent* heP; heP = gethostbyname(name); if (heP == NULL) LM_W(("gethostbyname(%s) error", name)); else { int ix = 0; LM_M(("gethostbyname proposed the name '%s' for '%s'", heP->h_name, name)); ip2string(*((int*) heP->h_addr_list[ix]), ipX, sizeof(ipX)); if (ip == NULL) ip = ipX; else alias = ipX; name = heP->h_name; while (heP->h_aliases[ix] != NULL) { LM_W(("alias %d: '%s' - should be added also", ix, heP->h_aliases[ix])); ++ix; } for (ix = 1; ix < heP->h_length / 4; ix++) { if (heP->h_addr_list[ix] != NULL) { char ipY[64]; ip2string(*((int*) heP->h_addr_list[ix]), ipX, sizeof(ipX)); LM_W(("addr %d: '%s' should be added also", ix, ipY)); } } } if ((ip != NULL) && (ip[0] != 0) && ((hostP = lookup(ip)) != NULL)) return hostP; hostP = (Host*) calloc(1, sizeof(Host)); if (hostP == NULL) LM_X(1, ("malloc(%d): %s", sizeof(Host), strerror(errno))); LM_M(("name: '%s'", name)); if (name != NULL) hostP->name = strdup(name); if (ip != NULL) hostP->ip = strdup(ip); if (alias != NULL) aliasAdd(hostP, alias); if ((dotP = (char*) strstr(name, ".")) != NULL) { if (onlyDigitsAndDots(name) == false) { *dotP = 0; aliasAdd(hostP, name); } } return insert(hostP); } /* **************************************************************************** * * aliasAdd - */ void HostMgr::aliasAdd(Host* host, const char* alias) { if (lookup(alias) != NULL) return; for (unsigned int ix = 0; ix < sizeof(alias) / sizeof(alias[0]); ix++) { if (host->alias[ix] == NULL) { host->alias[ix] = strdup(alias); LM_M(("Added alias '%s' for host '%s'", host->alias[ix], host->name)); return; } } LM_W(("Unable to add alias '%s' to host '%s' - no room in alias vector", alias, host->name)); } /* **************************************************************************** * * remove - */ bool HostMgr::remove(const char* name) { Host* hostP; unsigned int ix; hostP = lookup(name); if (hostP == NULL) LM_RE(false, ("Host '%s' not in list")); for (ix = 0; ix < size; ix++) { if (hostV[ix] != hostP) continue; if (hostP->name != NULL) free(hostP->name); if (hostP->ip != NULL) free(hostP->ip); LM_TODO(("Also free up aliases ...")); free(hostP); hostV[ix] = NULL; return true; } LM_RE(false, ("host pointer reurned from lookup not found ... internal bug!")); } /* **************************************************************************** * * lookup - */ Host* HostMgr::lookup(const char* name) { unsigned int ix; char* nameNoDot = NULL; char* dotP; if (name == NULL) return NULL; if ((dotP = (char*) strstr(name, ".")) != NULL) { nameNoDot = strdup(name); dotP = (char*) strstr(nameNoDot, "."); *dotP = 0; } for (ix = 0; ix < size; ix++) { if (hostV[ix] == NULL) continue; if ((hostV[ix]->name != NULL) && (strcmp(hostV[ix]->name, name) == 0)) { if (nameNoDot != NULL) free(nameNoDot); return hostV[ix]; } if ((nameNoDot != NULL) && (hostV[ix]->name != NULL) && (strcmp(hostV[ix]->name, nameNoDot) == 0)) { if (nameNoDot != NULL) free(nameNoDot); return hostV[ix]; } if ((hostV[ix]->ip != NULL) && (strcmp(hostV[ix]->ip, name) == 0)) { if (nameNoDot != NULL) free(nameNoDot); return hostV[ix]; } if ((nameNoDot != NULL) && (hostV[ix]->ip != NULL) && (strcmp(hostV[ix]->ip, nameNoDot) == 0)) { if (nameNoDot != NULL) free(nameNoDot); return hostV[ix]; } for (unsigned int aIx = 0; aIx < sizeof(hostV[ix]->alias) / sizeof(hostV[ix]->alias[0]); aIx++) { if (hostV[ix]->alias[aIx] == NULL) continue; if (strcmp(hostV[ix]->alias[aIx], name) == 0) { if (nameNoDot != NULL) free(nameNoDot); return hostV[ix]; } if ((nameNoDot != NULL) && (strcmp(hostV[ix]->alias[aIx], nameNoDot) == 0)) { if (nameNoDot != NULL) free(nameNoDot); return hostV[ix]; } } } return NULL; } /* **************************************************************************** * * lookup - */ bool HostMgr::match(Host* host, const char* ip) { if (ip == NULL) return NULL; if (ip[0] == 0) return NULL; if ((host->name != NULL) && (strcmp(host->name, ip) == 0)) return true; if ((host->ip != NULL) && (strcmp(host->ip, ip) == 0)) return true; for (unsigned int aIx = 0; aIx < sizeof(host->alias) / sizeof(host->alias[0]); aIx++) { if (host->alias[aIx] == NULL) continue; if (strcmp(host->alias[aIx], ip) == 0) return true; } return false; } /* **************************************************************************** * * list - list the hosts in the list */ void HostMgr::list(const char* why) { unsigned int ix; LM_F(("------------ Host List: %s ------------", why)); for (ix = 0; ix < size; ix++) { char line[512]; Host* hostP; if (hostV[ix] == NULL) continue; hostP = hostV[ix]; memset(line, sizeof(line), 0); snprintf(line, sizeof(line), "%02d: %-20s %-20s", ix, hostP->name, hostP->ip); for (unsigned int aIx = 0; aIx < sizeof(hostP->alias) / sizeof(hostP->alias[0]); aIx++) { char part[64]; if (hostP->alias[aIx] == NULL) continue; snprintf(part, sizeof(part), " %-20s", hostP->alias[aIx]); strncat(line, part, sizeof(line)); } LM_F((line)); } LM_F(("---------------------------------------------------")); } } <commit_msg>First fruit of valgrind studies - one very small memory leak fixed in Host manager<commit_after>/* **************************************************************************** * * FILE HostMgr.cpp * * AUTHOR Ken Zangelin * * CREATION DATE Feb 10 2011 * */ #include <stdio.h> // popen #include <unistd.h> // gethostname #include <arpa/inet.h> // sockaddr_in, inet_ntop #include <ifaddrs.h> // getifaddrs #include <net/if.h> // IFF_UP #include <netdb.h> // #include <string.h> // strstr #include "logMsg.h" // LM_* #include "traceLevels.h" // Trace Levels #include "Host.h" // Host #include "HostMgr.h" // Own interface #include <stdlib.h> // free namespace ss { /* **************************************************************************** * * HostMgr */ HostMgr::HostMgr(unsigned int size) { this->size = size; hostV = (Host**) calloc(size, sizeof(Host*)); if (hostV == NULL) LM_X(1, ("error allocating room for %d delilah hosts", size)); LM_M(("Allocated a Host Vector for %d hosts", size)); localIps(); list("init"); } /* **************************************************************************** * * ipsGet - get all IPs for a machine */ void HostMgr::ipsGet(Host* hostP) { struct ifaddrs* addrs; struct ifaddrs* iap; struct sockaddr_in* sa; char buf[64]; getifaddrs(&addrs); for (iap = addrs; iap != NULL; iap = iap->ifa_next) { if (iap->ifa_addr && (iap->ifa_flags & IFF_UP) && iap->ifa_addr->sa_family == AF_INET) { sa = (struct sockaddr_in*)(iap->ifa_addr); inet_ntop(iap->ifa_addr->sa_family, (void*) &(sa->sin_addr), buf, sizeof(buf)); if ((hostP->ip == NULL) && (strcmp(buf, "127.0.0.1") != 0)) { hostP->ip = strdup(buf); LM_M(("Setting IP '%s' for host '%s'", hostP->ip, hostP->name)); } else aliasAdd(hostP, buf); } } freeifaddrs(addrs); } /* **************************************************************************** * * localIps - */ void HostMgr::localIps(void) { char hostName[128]; char domain[128]; char domainedName[128]; Host* hostP; if (gethostname(hostName, sizeof(hostName)) == -1) LM_X(1, ("gethostname: %s", strerror(errno))); hostP = insert(hostName, "127.0.0.1"); memset(domainedName, 0, sizeof(domainedName)); if (getdomainname(domain, sizeof(domain)) == -1) LM_X(1, ("getdomainname: %s", strerror(errno))); LM_TODO(("Would gethostname ever returned the 'domained' name ?")); if (domainedName[0] != 0) { snprintf(domainedName, sizeof(domainedName), "%s.%s", hostName, domain); aliasAdd(hostP, domainedName); } aliasAdd(hostP, "localhost"); ipsGet(hostP); } /* **************************************************************************** * * HostMgr::hosts - */ int HostMgr::hosts(void) { unsigned int ix; int hostNo = 0; for (ix = 0; ix < size; ix++) { if (hostV[ix] != NULL) ++hostNo; } return hostNo; } /* **************************************************************************** * * HostMgr::insert - */ Host* HostMgr::insert(Host* hostP) { unsigned int ix; for (ix = 0; ix < size; ix++) { if (hostV[ix] == NULL) { LM_M(("Inserting host '%s'", hostP->name)); hostV[ix] = hostP; list("Host Added"); return hostV[ix]; } } LM_RE(NULL, ("Please realloc host vector (%d hosts not enough) ...", size)); } /* **************************************************************************** * * ip2string - convert integer ip address to string */ static void ip2string(int ip, char* ipString, int ipStringLen) { snprintf(ipString, ipStringLen, "%d.%d.%d.%d", ip & 0xFF, (ip & 0xFF00) >> 8, (ip & 0xFF0000) >> 16, (ip & 0xFF000000) >> 24); } /* **************************************************************************** * * onlyDigitsAndDots - */ static bool onlyDigitsAndDots(const char* string) { if ((string == NULL) || (string[0] == 0)) LM_RE(false, ("Empty IP ...")); for (unsigned int ix = 0; ix < strlen(string); ix++) { if (string[ix] == 0) return true; if (string[ix] == '.') continue; if ((string[ix] >= '0') && (string[ix] <= '9')) continue; return false; } return true; } /* **************************************************************************** * * HostMgr::insert - */ Host* HostMgr::insert(const char* name, const char* ip) { Host* hostP; char ipX[64]; char* dotP; char* alias = NULL; LM_M(("***** New host: name: '%s', ip: '%s'", name, ip)); if ((name == NULL) && (ip == NULL)) LM_X(1, ("name AND ip NULL - cannot add a ghost host ...")); if (name == NULL) { LM_W(("NULL host name for IP '%s'", ip)); name = "nohostname"; } if ((hostP = lookup(name)) != NULL) return hostP; struct hostent* heP; heP = gethostbyname(name); if (heP == NULL) LM_W(("gethostbyname(%s) error", name)); else { int ix = 0; LM_M(("gethostbyname proposed the name '%s' for '%s'", heP->h_name, name)); ip2string(*((int*) heP->h_addr_list[ix]), ipX, sizeof(ipX)); if (ip == NULL) ip = ipX; else alias = ipX; name = heP->h_name; while (heP->h_aliases[ix] != NULL) { LM_W(("alias %d: '%s' - should be added also", ix, heP->h_aliases[ix])); ++ix; } for (ix = 1; ix < heP->h_length / 4; ix++) { if (heP->h_addr_list[ix] != NULL) { char ipY[64]; ip2string(*((int*) heP->h_addr_list[ix]), ipX, sizeof(ipX)); LM_W(("addr %d: '%s' should be added also", ix, ipY)); } } } if ((ip != NULL) && (ip[0] != 0) && ((hostP = lookup(ip)) != NULL)) return hostP; hostP = (Host*) calloc(1, sizeof(Host)); if (hostP == NULL) LM_X(1, ("malloc(%d): %s", sizeof(Host), strerror(errno))); LM_M(("name: '%s'", name)); if (name != NULL) hostP->name = strdup(name); if (ip != NULL) hostP->ip = strdup(ip); if (alias != NULL) aliasAdd(hostP, alias); if ((dotP = (char*) strstr(name, ".")) != NULL) { if (onlyDigitsAndDots(name) == false) { *dotP = 0; aliasAdd(hostP, name); } } return insert(hostP); } /* **************************************************************************** * * aliasAdd - */ void HostMgr::aliasAdd(Host* host, const char* alias) { if (lookup(alias) != NULL) return; for (unsigned int ix = 0; ix < sizeof(alias) / sizeof(alias[0]); ix++) { if (host->alias[ix] == NULL) { host->alias[ix] = strdup(alias); LM_M(("Added alias '%s' for host '%s'", host->alias[ix], host->name)); return; } } LM_W(("Unable to add alias '%s' to host '%s' - no room in alias vector", alias, host->name)); } /* **************************************************************************** * * remove - */ bool HostMgr::remove(const char* name) { Host* hostP; unsigned int ix; hostP = lookup(name); if (hostP == NULL) LM_RE(false, ("Host '%s' not in list")); for (ix = 0; ix < size; ix++) { if (hostV[ix] != hostP) continue; if (hostP->name != NULL) free(hostP->name); if (hostP->ip != NULL) free(hostP->ip); LM_TODO(("Also free up aliases ...")); free(hostP); hostV[ix] = NULL; return true; } LM_RE(false, ("host pointer reurned from lookup not found ... internal bug!")); } /* **************************************************************************** * * lookup - */ Host* HostMgr::lookup(const char* name) { unsigned int ix; char* nameNoDot = NULL; char* dotP; if (name == NULL) return NULL; if ((dotP = (char*) strstr(name, ".")) != NULL) { nameNoDot = strdup(name); dotP = (char*) strstr(nameNoDot, "."); *dotP = 0; } for (ix = 0; ix < size; ix++) { if (hostV[ix] == NULL) continue; if ((hostV[ix]->name != NULL) && (strcmp(hostV[ix]->name, name) == 0)) { if (nameNoDot != NULL) free(nameNoDot); return hostV[ix]; } if ((nameNoDot != NULL) && (hostV[ix]->name != NULL) && (strcmp(hostV[ix]->name, nameNoDot) == 0)) { if (nameNoDot != NULL) free(nameNoDot); return hostV[ix]; } if ((hostV[ix]->ip != NULL) && (strcmp(hostV[ix]->ip, name) == 0)) { if (nameNoDot != NULL) free(nameNoDot); return hostV[ix]; } if ((nameNoDot != NULL) && (hostV[ix]->ip != NULL) && (strcmp(hostV[ix]->ip, nameNoDot) == 0)) { if (nameNoDot != NULL) free(nameNoDot); return hostV[ix]; } for (unsigned int aIx = 0; aIx < sizeof(hostV[ix]->alias) / sizeof(hostV[ix]->alias[0]); aIx++) { if (hostV[ix]->alias[aIx] == NULL) continue; if (strcmp(hostV[ix]->alias[aIx], name) == 0) { if (nameNoDot != NULL) free(nameNoDot); return hostV[ix]; } if ((nameNoDot != NULL) && (strcmp(hostV[ix]->alias[aIx], nameNoDot) == 0)) { if (nameNoDot != NULL) free(nameNoDot); return hostV[ix]; } } } if (nameNoDot != NULL) free(nameNoDot); return NULL; } /* **************************************************************************** * * lookup - */ bool HostMgr::match(Host* host, const char* ip) { if (ip == NULL) return NULL; if (ip[0] == 0) return NULL; if ((host->name != NULL) && (strcmp(host->name, ip) == 0)) return true; if ((host->ip != NULL) && (strcmp(host->ip, ip) == 0)) return true; for (unsigned int aIx = 0; aIx < sizeof(host->alias) / sizeof(host->alias[0]); aIx++) { if (host->alias[aIx] == NULL) continue; if (strcmp(host->alias[aIx], ip) == 0) return true; } return false; } /* **************************************************************************** * * list - list the hosts in the list */ void HostMgr::list(const char* why) { unsigned int ix; LM_F(("------------ Host List: %s ------------", why)); for (ix = 0; ix < size; ix++) { char line[512]; Host* hostP; if (hostV[ix] == NULL) continue; hostP = hostV[ix]; memset(line, sizeof(line), 0); snprintf(line, sizeof(line), "%02d: %-20s %-20s", ix, hostP->name, hostP->ip); for (unsigned int aIx = 0; aIx < sizeof(hostP->alias) / sizeof(hostP->alias[0]); aIx++) { char part[64]; if (hostP->alias[aIx] == NULL) continue; snprintf(part, sizeof(part), " %-20s", hostP->alias[aIx]); strncat(line, part, sizeof(line)); } LM_F((line)); } LM_F(("---------------------------------------------------")); } } <|endoftext|>
<commit_before> /* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkCanvas.h" #include "SkRRect.h" #include "SkSurface.h" #include "Test.h" #if SK_SUPPORT_GPU #include "GrContextFactory.h" #else class GrContextFactory; class GrContext; #endif enum SurfaceType { kRaster_SurfaceType, kGpu_SurfaceType, kPicture_SurfaceType }; static SkSurface* createSurface(SurfaceType surfaceType, GrContext* context) { static const SkImage::Info imageSpec = { 10, // width 10, // height SkImage::kPMColor_ColorType, SkImage::kPremul_AlphaType }; switch (surfaceType) { case kRaster_SurfaceType: return SkSurface::NewRaster(imageSpec); case kGpu_SurfaceType: #if SK_SUPPORT_GPU SkASSERT(NULL != context); return SkSurface::NewRenderTarget(context, imageSpec); #else SkASSERT(0); #endif case kPicture_SurfaceType: return SkSurface::NewPicture(10, 10); } SkASSERT(0); return NULL; } static void TestSurfaceCopyOnWrite(skiatest::Reporter* reporter, SurfaceType surfaceType, GrContext* context) { // Verify that the right canvas commands trigger a copy on write SkSurface* surface = createSurface(surfaceType, context); SkAutoTUnref<SkSurface> aur_surface(surface); SkCanvas* canvas = surface->getCanvas(); const SkRect testRect = SkRect::MakeXYWH(SkIntToScalar(0), SkIntToScalar(0), SkIntToScalar(4), SkIntToScalar(5)); SkMatrix testMatrix; testMatrix.reset(); testMatrix.setScale(SkIntToScalar(2), SkIntToScalar(3)); SkPath testPath; testPath.addRect(SkRect::MakeXYWH(SkIntToScalar(0), SkIntToScalar(0), SkIntToScalar(2), SkIntToScalar(1))); const SkIRect testIRect = SkIRect::MakeXYWH(0, 0, 2, 1); SkRegion testRegion; testRegion.setRect(testIRect); const SkColor testColor = 0x01020304; const SkPaint testPaint; const SkPoint testPoints[3] = { {SkIntToScalar(0), SkIntToScalar(0)}, {SkIntToScalar(2), SkIntToScalar(1)}, {SkIntToScalar(0), SkIntToScalar(2)} }; const size_t testPointCount = 3; SkBitmap testBitmap; testBitmap.setConfig(SkBitmap::kARGB_8888_Config, 10, 10); testBitmap.allocPixels(); SkRRect testRRect; testRRect.setRectXY(testRect, SK_Scalar1, SK_Scalar1); SkString testText("Hello World"); const SkPoint testPoints2[] = { { SkIntToScalar(0), SkIntToScalar(1) }, { SkIntToScalar(1), SkIntToScalar(1) }, { SkIntToScalar(2), SkIntToScalar(1) }, { SkIntToScalar(3), SkIntToScalar(1) }, { SkIntToScalar(4), SkIntToScalar(1) }, { SkIntToScalar(5), SkIntToScalar(1) }, { SkIntToScalar(6), SkIntToScalar(1) }, { SkIntToScalar(7), SkIntToScalar(1) }, { SkIntToScalar(8), SkIntToScalar(1) }, { SkIntToScalar(9), SkIntToScalar(1) }, { SkIntToScalar(10), SkIntToScalar(1) }, }; #define EXPECT_COPY_ON_WRITE(command) \ { \ SkImage* imageBefore = surface->newImageSnapshot(); \ SkAutoTUnref<SkImage> aur_before(imageBefore); \ canvas-> command ; \ SkImage* imageAfter = surface->newImageSnapshot(); \ SkAutoTUnref<SkImage> aur_after(imageAfter); \ REPORTER_ASSERT(reporter, imageBefore != imageAfter); \ } EXPECT_COPY_ON_WRITE(clear(testColor)) EXPECT_COPY_ON_WRITE(drawPaint(testPaint)) EXPECT_COPY_ON_WRITE(drawPoints(SkCanvas::kPoints_PointMode, testPointCount, testPoints, \ testPaint)) EXPECT_COPY_ON_WRITE(drawOval(testRect, testPaint)) EXPECT_COPY_ON_WRITE(drawRect(testRect, testPaint)) EXPECT_COPY_ON_WRITE(drawRRect(testRRect, testPaint)) EXPECT_COPY_ON_WRITE(drawPath(testPath, testPaint)) EXPECT_COPY_ON_WRITE(drawBitmap(testBitmap, 0, 0)) EXPECT_COPY_ON_WRITE(drawBitmapRect(testBitmap, NULL, testRect)) EXPECT_COPY_ON_WRITE(drawBitmapMatrix(testBitmap, testMatrix, NULL)) EXPECT_COPY_ON_WRITE(drawBitmapNine(testBitmap, testIRect, testRect, NULL)) EXPECT_COPY_ON_WRITE(drawSprite(testBitmap, 0, 0, NULL)) EXPECT_COPY_ON_WRITE(drawText(testText.c_str(), testText.size(), 0, 1, testPaint)) EXPECT_COPY_ON_WRITE(drawPosText(testText.c_str(), testText.size(), testPoints2, \ testPaint)) EXPECT_COPY_ON_WRITE(drawTextOnPath(testText.c_str(), testText.size(), testPath, NULL, \ testPaint)) } static void TestSurfaceWritableAfterSnapshotRelease(skiatest::Reporter* reporter, SurfaceType surfaceType, GrContext* context) { // This test succeeds by not triggering an assertion. // The test verifies that the surface remains writable (usable) after // acquiring and releasing a snapshot without triggering a copy on write. SkSurface* surface = createSurface(surfaceType, context); SkAutoTUnref<SkSurface> aur_surface(surface); SkCanvas* canvas = surface->getCanvas(); canvas->clear(1); surface->newImageSnapshot()->unref(); // Create and destroy SkImage canvas->clear(2); } static void TestGetTexture(skiatest::Reporter* reporter, SurfaceType surfaceType, GrContext* context) { SkAutoTUnref<SkSurface> surface(createSurface(surfaceType, context)); SkAutoTUnref<SkImage> image(surface->newImageSnapshot()); GrTexture* texture = image->getTexture(); if (surfaceType == kGpu_SurfaceType) { REPORTER_ASSERT(reporter, NULL != texture); REPORTER_ASSERT(reporter, 0 != texture->getTextureHandle()); } else { REPORTER_ASSERT(reporter, NULL == texture); } surface->notifyContentWillChange(SkSurface::kDiscard_ContentChangeMode); REPORTER_ASSERT(reporter, image->getTexture() == texture); } static void TestSurfaceNoCanvas(skiatest::Reporter* reporter, SurfaceType surfaceType, GrContext* context, SkSurface::ContentChangeMode mode) { // Verifies the robustness of SkSurface for handling use cases where calls // are made before a canvas is created. { // Test passes by not asserting SkSurface* surface = createSurface(surfaceType, context); SkAutoTUnref<SkSurface> aur_surface(surface); surface->notifyContentWillChange(mode); surface->validate(); } { SkSurface* surface = createSurface(surfaceType, context); SkAutoTUnref<SkSurface> aur_surface(surface); SkImage* image1 = surface->newImageSnapshot(); SkAutoTUnref<SkImage> aur_image1(image1); image1->validate(); surface->validate(); surface->notifyContentWillChange(mode); image1->validate(); surface->validate(); SkImage* image2 = surface->newImageSnapshot(); SkAutoTUnref<SkImage> aur_image2(image2); image2->validate(); surface->validate(); REPORTER_ASSERT(reporter, image1 != image2); } } static void TestSurface(skiatest::Reporter* reporter, GrContextFactory* factory) { TestSurfaceCopyOnWrite(reporter, kRaster_SurfaceType, NULL); TestSurfaceCopyOnWrite(reporter, kPicture_SurfaceType, NULL); TestSurfaceWritableAfterSnapshotRelease(reporter, kRaster_SurfaceType, NULL); TestSurfaceWritableAfterSnapshotRelease(reporter, kPicture_SurfaceType, NULL); TestSurfaceNoCanvas(reporter, kRaster_SurfaceType, NULL, SkSurface::kDiscard_ContentChangeMode); TestSurfaceNoCanvas(reporter, kRaster_SurfaceType, NULL, SkSurface::kRetain_ContentChangeMode); TestGetTexture(reporter, kRaster_SurfaceType, NULL); TestGetTexture(reporter, kPicture_SurfaceType, NULL); #if SK_SUPPORT_GPU if (NULL != factory) { GrContext* context = factory->get(GrContextFactory::kNative_GLContextType); TestSurfaceCopyOnWrite(reporter, kGpu_SurfaceType, context); TestSurfaceWritableAfterSnapshotRelease(reporter, kGpu_SurfaceType, context); TestSurfaceNoCanvas(reporter, kGpu_SurfaceType, context, SkSurface::kDiscard_ContentChangeMode); TestSurfaceNoCanvas(reporter, kGpu_SurfaceType, context, SkSurface::kRetain_ContentChangeMode); TestGetTexture(reporter, kGpu_SurfaceType, context); } #endif } #include "TestClassDef.h" DEFINE_GPUTESTCLASS("Surface", SurfaceTestClass, TestSurface) <commit_msg>Build fix for SurfaceTest on non-gpu platforms<commit_after> /* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkCanvas.h" #include "SkRRect.h" #include "SkSurface.h" #include "Test.h" #if SK_SUPPORT_GPU #include "GrContextFactory.h" #else class GrContextFactory; class GrContext; #endif enum SurfaceType { kRaster_SurfaceType, kGpu_SurfaceType, kPicture_SurfaceType }; static SkSurface* createSurface(SurfaceType surfaceType, GrContext* context) { static const SkImage::Info imageSpec = { 10, // width 10, // height SkImage::kPMColor_ColorType, SkImage::kPremul_AlphaType }; switch (surfaceType) { case kRaster_SurfaceType: return SkSurface::NewRaster(imageSpec); case kGpu_SurfaceType: #if SK_SUPPORT_GPU SkASSERT(NULL != context); return SkSurface::NewRenderTarget(context, imageSpec); #else SkASSERT(0); #endif case kPicture_SurfaceType: return SkSurface::NewPicture(10, 10); } SkASSERT(0); return NULL; } static void TestSurfaceCopyOnWrite(skiatest::Reporter* reporter, SurfaceType surfaceType, GrContext* context) { // Verify that the right canvas commands trigger a copy on write SkSurface* surface = createSurface(surfaceType, context); SkAutoTUnref<SkSurface> aur_surface(surface); SkCanvas* canvas = surface->getCanvas(); const SkRect testRect = SkRect::MakeXYWH(SkIntToScalar(0), SkIntToScalar(0), SkIntToScalar(4), SkIntToScalar(5)); SkMatrix testMatrix; testMatrix.reset(); testMatrix.setScale(SkIntToScalar(2), SkIntToScalar(3)); SkPath testPath; testPath.addRect(SkRect::MakeXYWH(SkIntToScalar(0), SkIntToScalar(0), SkIntToScalar(2), SkIntToScalar(1))); const SkIRect testIRect = SkIRect::MakeXYWH(0, 0, 2, 1); SkRegion testRegion; testRegion.setRect(testIRect); const SkColor testColor = 0x01020304; const SkPaint testPaint; const SkPoint testPoints[3] = { {SkIntToScalar(0), SkIntToScalar(0)}, {SkIntToScalar(2), SkIntToScalar(1)}, {SkIntToScalar(0), SkIntToScalar(2)} }; const size_t testPointCount = 3; SkBitmap testBitmap; testBitmap.setConfig(SkBitmap::kARGB_8888_Config, 10, 10); testBitmap.allocPixels(); SkRRect testRRect; testRRect.setRectXY(testRect, SK_Scalar1, SK_Scalar1); SkString testText("Hello World"); const SkPoint testPoints2[] = { { SkIntToScalar(0), SkIntToScalar(1) }, { SkIntToScalar(1), SkIntToScalar(1) }, { SkIntToScalar(2), SkIntToScalar(1) }, { SkIntToScalar(3), SkIntToScalar(1) }, { SkIntToScalar(4), SkIntToScalar(1) }, { SkIntToScalar(5), SkIntToScalar(1) }, { SkIntToScalar(6), SkIntToScalar(1) }, { SkIntToScalar(7), SkIntToScalar(1) }, { SkIntToScalar(8), SkIntToScalar(1) }, { SkIntToScalar(9), SkIntToScalar(1) }, { SkIntToScalar(10), SkIntToScalar(1) }, }; #define EXPECT_COPY_ON_WRITE(command) \ { \ SkImage* imageBefore = surface->newImageSnapshot(); \ SkAutoTUnref<SkImage> aur_before(imageBefore); \ canvas-> command ; \ SkImage* imageAfter = surface->newImageSnapshot(); \ SkAutoTUnref<SkImage> aur_after(imageAfter); \ REPORTER_ASSERT(reporter, imageBefore != imageAfter); \ } EXPECT_COPY_ON_WRITE(clear(testColor)) EXPECT_COPY_ON_WRITE(drawPaint(testPaint)) EXPECT_COPY_ON_WRITE(drawPoints(SkCanvas::kPoints_PointMode, testPointCount, testPoints, \ testPaint)) EXPECT_COPY_ON_WRITE(drawOval(testRect, testPaint)) EXPECT_COPY_ON_WRITE(drawRect(testRect, testPaint)) EXPECT_COPY_ON_WRITE(drawRRect(testRRect, testPaint)) EXPECT_COPY_ON_WRITE(drawPath(testPath, testPaint)) EXPECT_COPY_ON_WRITE(drawBitmap(testBitmap, 0, 0)) EXPECT_COPY_ON_WRITE(drawBitmapRect(testBitmap, NULL, testRect)) EXPECT_COPY_ON_WRITE(drawBitmapMatrix(testBitmap, testMatrix, NULL)) EXPECT_COPY_ON_WRITE(drawBitmapNine(testBitmap, testIRect, testRect, NULL)) EXPECT_COPY_ON_WRITE(drawSprite(testBitmap, 0, 0, NULL)) EXPECT_COPY_ON_WRITE(drawText(testText.c_str(), testText.size(), 0, 1, testPaint)) EXPECT_COPY_ON_WRITE(drawPosText(testText.c_str(), testText.size(), testPoints2, \ testPaint)) EXPECT_COPY_ON_WRITE(drawTextOnPath(testText.c_str(), testText.size(), testPath, NULL, \ testPaint)) } static void TestSurfaceWritableAfterSnapshotRelease(skiatest::Reporter* reporter, SurfaceType surfaceType, GrContext* context) { // This test succeeds by not triggering an assertion. // The test verifies that the surface remains writable (usable) after // acquiring and releasing a snapshot without triggering a copy on write. SkSurface* surface = createSurface(surfaceType, context); SkAutoTUnref<SkSurface> aur_surface(surface); SkCanvas* canvas = surface->getCanvas(); canvas->clear(1); surface->newImageSnapshot()->unref(); // Create and destroy SkImage canvas->clear(2); } #if SK_SUPPORT_GPU static void TestGetTexture(skiatest::Reporter* reporter, SurfaceType surfaceType, GrContext* context) { SkAutoTUnref<SkSurface> surface(createSurface(surfaceType, context)); SkAutoTUnref<SkImage> image(surface->newImageSnapshot()); GrTexture* texture = image->getTexture(); if (surfaceType == kGpu_SurfaceType) { REPORTER_ASSERT(reporter, NULL != texture); REPORTER_ASSERT(reporter, 0 != texture->getTextureHandle()); } else { REPORTER_ASSERT(reporter, NULL == texture); } surface->notifyContentWillChange(SkSurface::kDiscard_ContentChangeMode); REPORTER_ASSERT(reporter, image->getTexture() == texture); } #endif static void TestSurfaceNoCanvas(skiatest::Reporter* reporter, SurfaceType surfaceType, GrContext* context, SkSurface::ContentChangeMode mode) { // Verifies the robustness of SkSurface for handling use cases where calls // are made before a canvas is created. { // Test passes by not asserting SkSurface* surface = createSurface(surfaceType, context); SkAutoTUnref<SkSurface> aur_surface(surface); surface->notifyContentWillChange(mode); surface->validate(); } { SkSurface* surface = createSurface(surfaceType, context); SkAutoTUnref<SkSurface> aur_surface(surface); SkImage* image1 = surface->newImageSnapshot(); SkAutoTUnref<SkImage> aur_image1(image1); image1->validate(); surface->validate(); surface->notifyContentWillChange(mode); image1->validate(); surface->validate(); SkImage* image2 = surface->newImageSnapshot(); SkAutoTUnref<SkImage> aur_image2(image2); image2->validate(); surface->validate(); REPORTER_ASSERT(reporter, image1 != image2); } } static void TestSurface(skiatest::Reporter* reporter, GrContextFactory* factory) { TestSurfaceCopyOnWrite(reporter, kRaster_SurfaceType, NULL); TestSurfaceCopyOnWrite(reporter, kPicture_SurfaceType, NULL); TestSurfaceWritableAfterSnapshotRelease(reporter, kRaster_SurfaceType, NULL); TestSurfaceWritableAfterSnapshotRelease(reporter, kPicture_SurfaceType, NULL); TestSurfaceNoCanvas(reporter, kRaster_SurfaceType, NULL, SkSurface::kDiscard_ContentChangeMode); TestSurfaceNoCanvas(reporter, kRaster_SurfaceType, NULL, SkSurface::kRetain_ContentChangeMode); #if SK_SUPPORT_GPU TestGetTexture(reporter, kRaster_SurfaceType, NULL); TestGetTexture(reporter, kPicture_SurfaceType, NULL); if (NULL != factory) { GrContext* context = factory->get(GrContextFactory::kNative_GLContextType); TestSurfaceCopyOnWrite(reporter, kGpu_SurfaceType, context); TestSurfaceWritableAfterSnapshotRelease(reporter, kGpu_SurfaceType, context); TestSurfaceNoCanvas(reporter, kGpu_SurfaceType, context, SkSurface::kDiscard_ContentChangeMode); TestSurfaceNoCanvas(reporter, kGpu_SurfaceType, context, SkSurface::kRetain_ContentChangeMode); TestGetTexture(reporter, kGpu_SurfaceType, context); } #endif } #include "TestClassDef.h" DEFINE_GPUTESTCLASS("Surface", SurfaceTestClass, TestSurface) <|endoftext|>
<commit_before>#include <iostream> using namespace std; template <typename T> struct Node { T data; Node<T>* next; }; template <typename T> class CyclicList { Node<T>* end; void copy(const CyclicList&); void del(); public: CyclicList(); CyclicList(const CyclicList&); CyclicList& operator=(const CyclicList&); ~CyclicList(); void addElement(const T&); bool removeElement(T&); void print() const; }; template <typename T> void CyclicList<T>::copy(const CyclicList& other) { Node<T>* temp = new Node<T>; end = other.end; temp = other.end->next; while(temp->next != other.end) { addElement(temp->data); temp = temp->next; end->next = temp; } } template <typename T> CyclicList<T>& CyclicList<T>::operator=(const CyclicList& other) { del(); copy(other); return *this; } template <typename T> void CyclicList<T>::del() { T data; while(removeElement(data)) { cout<<"data deleted: "<<data<<endl; } } template <typename T> CyclicList<T>::CyclicList() { end = NULL; } template <typename T> CyclicList<T>::CyclicList(const CyclicList& other) { end = new Node<T>; copy(other); } template <typename T> void CyclicList<T>::addElement(const T& _data) { if(end == NULL) { end = new Node<T>; end->data = _data; end->next = end; } else { Node<T>* temp = new Node<T>; temp->data = _data; temp->next = end->next; end->next = temp; } } template <typename T> bool CyclicList<T>::removeElement(T& _data) { if(end != NULL) { Node<T>* temp = new Node<T>; temp = end->next; end->next = temp->next; _data = temp->data; if(end == temp) { end = NULL; return 1; } delete[] temp; return 1; } return 0; } template <typename T> void CyclicList<T>::print() const { Node<T>* temp = new Node<T>; temp = end->next; while(temp != end) { cout<<temp->data<<' '; temp = temp->next; } cout<<end->data; // } template <typename T> CyclicList<T>::~CyclicList() { del(); } int main() { CyclicList<int> a; a.addElement(1); a.addElement(2); a.addElement(3); int asd = 1; a.removeElement(asd); cout<<asd<<endl; a.print(); CyclicList<int> b(a); cout<<endl<<"CyclicList(&): "; b.print(); CyclicList<int> c; cout<<endl<<"operator=(a): "; c = a; b.print(); cout<<endl; } <commit_msg>exam 13.04.2014<commit_after>#include <iostream> using namespace std; template <typename T> struct Node { T data; Node<T>* next; }; template <typename T> class CyclicList { Node<T>* end; void copy(const CyclicList&); void del(); public: CyclicList(); CyclicList(const CyclicList&); CyclicList& operator=(const CyclicList&); ~CyclicList(); void addElement(const T&); bool removeElement(T&); void print() const; }; template <typename T> void CyclicList<T>::copy(const CyclicList& other) { Node<T>* temp = new Node<T>; end = other.end; temp = other.end->next; while(temp->next != other.end) { addElement(temp->data); temp = temp->next; end->next = temp; } } template <typename T> CyclicList<T>& CyclicList<T>::operator=(const CyclicList& other) { if(this != &other) { del(); copy(other); } return *this; } template <typename T> void CyclicList<T>::del() { T data; while(removeElement(data)) { cout<<"data deleted: "<<data<<endl; } } template <typename T> CyclicList<T>::CyclicList() { end = NULL; } template <typename T> CyclicList<T>::CyclicList(const CyclicList& other) { end = new Node<T>; copy(other); } template <typename T> void CyclicList<T>::addElement(const T& _data) { if(end == NULL) { end = new Node<T>; end->data = _data; end->next = end; } else { Node<T>* temp = new Node<T>; temp->data = _data; temp->next = end->next; end->next = temp; } } template <typename T> bool CyclicList<T>::removeElement(T& _data) { if(end != NULL) { Node<T>* temp = new Node<T>; temp = end->next; end->next = temp->next; _data = temp->data; if(end == temp) { end = NULL; return 1; } delete[] temp; return 1; } return 0; } template <typename T> void CyclicList<T>::print() const { Node<T>* temp = new Node<T>; temp = end->next; while(temp != end) { cout<<temp->data<<' '; temp = temp->next; } cout<<end->data; // } template <typename T> CyclicList<T>::~CyclicList() { del(); } int main() { CyclicList<int> a; a.addElement(1); a.addElement(2); a.addElement(3); int asd = 1; a.removeElement(asd); cout<<asd<<endl; a.print(); CyclicList<int> b(a); cout<<endl<<"CyclicList(&): "; b.print(); CyclicList<int> c; cout<<endl<<"operator=(a): "; c = a; b = a; b.print(); cout<<endl; } <|endoftext|>
<commit_before>// $Id$ /*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2006 University of Edinburgh 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 Street, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #ifdef WIN32 #include <sstream> #include "ConfusionNet.h" #include "FactorCollection.h" #include "Util.h" // for Windows. not implemented #pragma warning(disable:4716) ConfusionNet::ConfusionNet(FactorCollection* p) : InputType(),m_factorCollection(p) { assert(false); } ConfusionNet::~ConfusionNet() { assert(false); } void ConfusionNet::SetFactorCollection(FactorCollection *p) { assert(false); } bool ConfusionNet::ReadF(std::istream& in,const std::vector<FactorType>& factorOrder,int format) { assert(false); } int ConfusionNet::Read(std::istream& in,const std::vector<FactorType>& factorOrder, FactorCollection &factorCollection) { assert(false); } void ConfusionNet::String2Word(const std::string& s,Word& w,const std::vector<FactorType>& factorOrder) { assert(false); } bool ConfusionNet::ReadFormat0(std::istream& in,const std::vector<FactorType>& factorOrder) { assert(false); } bool ConfusionNet::ReadFormat1(std::istream& in,const std::vector<FactorType>& factorOrder) { assert(false); } void ConfusionNet::Print(std::ostream& out) const { assert(false); } Phrase ConfusionNet::GetSubString(const WordsRange&) const { assert(false); } const FactorArray& ConfusionNet::GetFactorArray(size_t) const { assert(false); } std::ostream& operator<<(std::ostream& out,const ConfusionNet& cn) { assert(false); } TargetPhraseCollection const* ConfusionNet::CreateTargetPhraseCollection(PhraseDictionaryBase const& d,const WordsRange& r) const { assert(false); } TranslationOptionCollection* ConfusionNet::CreateTranslationOptionCollection() const { assert(false); } #pragma warning(default:4716) #endif<commit_msg>remove confusionNet for win32<commit_after><|endoftext|>
<commit_before>/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2018 INRIA. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file NonSmoothDynamicalSystem.hpp * \brief container for DynamicalSystem and Interaction */ #ifndef LinearComplementaritySystemsNSDS_H #define LinearComplementaritySystemsNSDS_H #include "SiconosPointers.hpp" #include "Topology.hpp" #include "DynamicalSystem.hpp" #include "NonSmoothDynamicalSystem.hpp" #include "ComplementarityConditionNSL.hpp" #include "SiconosFwd.hpp" #include "FirstOrderLinearTIR.hpp" /** the LinearComplementaritySystemsNSDS_H inherits frim NDSD for a direct instanciation of a LCS */ class LinearComplementaritySystemsNSDS: public NonSmoothDynamicalSystem { private: /** serialization hooks */ ACCEPT_SERIALIZATION(LinearComplementaritySystemsNSDS); /* a first order linear TI dynamical systems */ SP::FirstOrderLinearTIDS _ds; /* a first order linear TI relation */ SP::FirstOrderLinearTIR _relation; /* a complementarity condition */ SP::ComplementarityConditionNSL _nslaw; /* an interaction*/ SP::Interaction _interaction; public: /** default constructor */ LinearComplementaritySystemsNSDS(); /** constructor with t0 and T * \param t0 initial time * \param T final time */ LinearComplementaritySystemsNSDS(double t0, double T, SP::SiconosVector x0, SP::SimpleMatrix A, SP::SimpleMatrix B, SP::SimpleMatrix C, SP::SimpleMatrix D, SP::SiconosVector a, SP::SiconosVector b); /** destructor */ ~LinearComplementaritySystemsNSDS(); // --- GETTERS/SETTERS --- SP::FirstOrderLinearTIDS ds() { return _ds; }; SP::FirstOrderLinearTIR relation() { return _relation; }; SP::ComplementarityConditionNSL nslaw() { return _nslaw; }; SP::Interaction interaction() { return _interaction; }; }; #endif <commit_msg>[kernel] add implementation of default destructor<commit_after>/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2018 INRIA. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file NonSmoothDynamicalSystem.hpp * \brief container for DynamicalSystem and Interaction */ #ifndef LinearComplementaritySystemsNSDS_H #define LinearComplementaritySystemsNSDS_H #include "SiconosPointers.hpp" #include "Topology.hpp" #include "DynamicalSystem.hpp" #include "NonSmoothDynamicalSystem.hpp" #include "ComplementarityConditionNSL.hpp" #include "SiconosFwd.hpp" #include "FirstOrderLinearTIR.hpp" /** the LinearComplementaritySystemsNSDS_H inherits frim NDSD for a direct instanciation of a LCS */ class LinearComplementaritySystemsNSDS: public NonSmoothDynamicalSystem { private: /** serialization hooks */ ACCEPT_SERIALIZATION(LinearComplementaritySystemsNSDS); /* a first order linear TI dynamical systems */ SP::FirstOrderLinearTIDS _ds; /* a first order linear TI relation */ SP::FirstOrderLinearTIR _relation; /* a complementarity condition */ SP::ComplementarityConditionNSL _nslaw; /* an interaction*/ SP::Interaction _interaction; public: /** default constructor */ LinearComplementaritySystemsNSDS(); /** constructor with t0 and T * \param t0 initial time * \param T final time */ LinearComplementaritySystemsNSDS(double t0, double T, SP::SiconosVector x0, SP::SimpleMatrix A, SP::SimpleMatrix B, SP::SimpleMatrix C, SP::SimpleMatrix D, SP::SiconosVector a, SP::SiconosVector b); /** destructor */ ~LinearComplementaritySystemsNSDS(){}; // --- GETTERS/SETTERS --- SP::FirstOrderLinearTIDS ds() { return _ds; }; SP::FirstOrderLinearTIR relation() { return _relation; }; SP::ComplementarityConditionNSL nslaw() { return _nslaw; }; SP::Interaction interaction() { return _interaction; }; }; #endif <|endoftext|>
<commit_before>#include "SystemImplBase.h" #include "rhodes/JNIRhodes.h" RHO_GLOBAL int rho_sysimpl_get_property(const char* szPropName, rho::apiGenerator::CMethodResult& result); RHO_GLOBAL int rho_sys_set_sleeping(int sleeping); RHO_GLOBAL void rho_sys_is_app_installed(const rho::String& appname, rho::apiGenerator::CMethodResult& result); RHO_GLOBAL void rho_sys_app_install(const rho::String& url, rho::apiGenerator::CMethodResult& result); RHO_GLOBAL void rho_sys_app_uninstall(const rho::String& appname, rho::apiGenerator::CMethodResult& result); RHO_GLOBAL void rho_sys_run_app(const rho::String& appname, const rho::String& params, rho::apiGenerator::CMethodResult& result); RHO_GLOBAL void rho_sys_bring_to_front(); RHO_GLOBAL void rho_sys_set_full_screen_mode(bool); RHO_GLOBAL void rho_sys_get_full_screen_mode(rho::apiGenerator::CMethodResult& result); RHO_GLOBAL void rho_sys_set_screen_auto_rotate_mode(bool enable); RHO_GLOBAL void rho_sys_get_screen_auto_rotate_mode(rho::apiGenerator::CMethodResult& result); namespace rho { //---------------------------------------------------------------------------------------------------------------------- class CSystemImpl : public CSystemImplBase { bool mScreenSleeping; public: CSystemImpl() : CSystemImplBase(), mScreenSleeping(true) {} virtual ~CSystemImpl(){} virtual void getScreenWidth(rho::apiGenerator::CMethodResult& result); virtual void getScreenHeight(rho::apiGenerator::CMethodResult& result); virtual void getScreenOrientation(rho::apiGenerator::CMethodResult& result); virtual void getPpiX(rho::apiGenerator::CMethodResult& result); virtual void getPpiY(rho::apiGenerator::CMethodResult& result); virtual void getPhoneId(rho::apiGenerator::CMethodResult& result); virtual void getDeviceName(rho::apiGenerator::CMethodResult& result); virtual void getLocale(rho::apiGenerator::CMethodResult& result); virtual void getCountry(rho::apiGenerator::CMethodResult& result); virtual void getIsEmulator(rho::apiGenerator::CMethodResult& result); virtual void getHasCalendar(rho::apiGenerator::CMethodResult& result); virtual void getOemInfo(rho::apiGenerator::CMethodResult& result); virtual void getUuid(rho::apiGenerator::CMethodResult& result); virtual void getLockWindowSize(rho::apiGenerator::CMethodResult& result); virtual void setLockWindowSize(bool, rho::apiGenerator::CMethodResult& result); virtual void getKeyboardState(rho::apiGenerator::CMethodResult& result); virtual void setKeyboardState(const rho::String&, rho::apiGenerator::CMethodResult& result); virtual void getFullScreen(rho::apiGenerator::CMethodResult& result); virtual void setFullScreen(bool, rho::apiGenerator::CMethodResult& result); virtual void getScreenAutoRotate(rho::apiGenerator::CMethodResult& result); virtual void setScreenAutoRotate(bool, rho::apiGenerator::CMethodResult& result); virtual void getWebviewFramework(rho::apiGenerator::CMethodResult& result); virtual void getScreenSleeping(rho::apiGenerator::CMethodResult& result); virtual void setScreenSleeping(bool, rho::apiGenerator::CMethodResult& result); virtual void applicationInstall(const rho::String&, rho::apiGenerator::CMethodResult& result); virtual void isApplicationInstalled(const rho::String&, rho::apiGenerator::CMethodResult& result); virtual void applicationUninstall(const rho::String&, rho::apiGenerator::CMethodResult& result); virtual void openUrl(const rho::String&, rho::apiGenerator::CMethodResult& result); virtual void setWindowFrame(int, int, int, int, rho::apiGenerator::CMethodResult& result); virtual void setWindowPosition(int, int, rho::apiGenerator::CMethodResult& result); virtual void setWindowSize(int, int, rho::apiGenerator::CMethodResult& result); virtual void bringToFront(rho::apiGenerator::CMethodResult& result); virtual void runApplication(const rho::String&, const rho::String&, bool, rho::apiGenerator::CMethodResult& result); virtual void getHasCamera(rho::apiGenerator::CMethodResult& result); virtual void getPhoneNumber(rho::apiGenerator::CMethodResult& result); virtual void getHasNetwork(rho::apiGenerator::CMethodResult& result); virtual void getHasWifiNetwork(rho::apiGenerator::CMethodResult& result); virtual void getHasCellNetwork(rho::apiGenerator::CMethodResult& result); virtual void getDeviceOwnerName(rho::apiGenerator::CMethodResult& result); virtual void getDeviceOwnerEmail(rho::apiGenerator::CMethodResult& result); virtual void getOsVersion(rho::apiGenerator::CMethodResult& result); virtual void getIsSymbolDevice(rho::apiGenerator::CMethodResult& result); virtual void hideSplashScreen(rho::apiGenerator::CMethodResult& oResult); }; //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- #undef DEFAULT_LOGCATEGORY #define DEFAULT_LOGCATEGORY "SystemImpl" //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getScreenWidth(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("screen_width", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getScreenHeight(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("screen_height", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getScreenOrientation(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("screen_orientation", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getPpiX(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("ppi_x", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getPpiY(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("ppi_y", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getPhoneId(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("phone_id", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getDeviceName(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("device_name", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getLocale(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("locale", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getCountry(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("country", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getIsEmulator(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("is_emulator", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getHasCalendar(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("has_calendar", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getOemInfo(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("oem_info", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getUuid(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("uuid", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getLockWindowSize(rho::apiGenerator::CMethodResult& result) { // result.setError("not implemented at Android platform"); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::setLockWindowSize(bool, rho::apiGenerator::CMethodResult& result) { // result.setError("not implemented at Android platform"); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getKeyboardState(rho::apiGenerator::CMethodResult& result) { // result.setError("not implemented at Android platform"); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::setKeyboardState(const rho::String&, rho::apiGenerator::CMethodResult& result) { // result.setError("not implemented at Android platform"); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getFullScreen(rho::apiGenerator::CMethodResult& result) { rho_sys_get_full_screen_mode(result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::setFullScreen(bool fullmode, rho::apiGenerator::CMethodResult& result) { rho_sys_set_full_screen_mode(fullmode); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getScreenAutoRotate(rho::apiGenerator::CMethodResult& result) { rho_sys_get_screen_auto_rotate_mode(result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::setScreenAutoRotate(bool mode, rho::apiGenerator::CMethodResult& result) { rho_sys_set_screen_auto_rotate_mode(mode); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getWebviewFramework(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("webview_framework", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getScreenSleeping(rho::apiGenerator::CMethodResult& result) { result.set(mScreenSleeping); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::setScreenSleeping(bool flag, rho::apiGenerator::CMethodResult& result) { mScreenSleeping = flag; rho_sys_set_sleeping(flag?1:0); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::applicationInstall(const rho::String& url, rho::apiGenerator::CMethodResult& result) { rho_sys_app_install(url, result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::isApplicationInstalled(const rho::String& appname, rho::apiGenerator::CMethodResult& result) { rho_sys_is_app_installed(appname, result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::applicationUninstall(const rho::String& appname, rho::apiGenerator::CMethodResult& result) { rho_sys_app_uninstall(appname, result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::openUrl(const rho::String& url, rho::apiGenerator::CMethodResult& result) { JNIEnv *env = jnienv(); jclass clsRhodesService = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE); jmethodID midOpenExternalUrl = getJNIClassStaticMethod(env, clsRhodesService, "openExternalUrl", "(Ljava/lang/String;)V"); JNI_EXCEPTION_CHECK(env, result); jhstring jhUrl = rho_cast<jstring>(env, url); env->CallStaticVoidMethod(clsRhodesService, midOpenExternalUrl, jhUrl.get()); JNI_EXCEPTION_CHECK(env, result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::setWindowFrame(int, int, int, int, rho::apiGenerator::CMethodResult& result) { // result.setError("not implemented at Android platform"); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::setWindowPosition(int, int, rho::apiGenerator::CMethodResult& result) { // result.setError("not implemented at Android platform"); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::setWindowSize(int, int, rho::apiGenerator::CMethodResult& result) { // result.setError("not implemented at Android platform"); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::bringToFront(rho::apiGenerator::CMethodResult& result) { rho_sys_bring_to_front(); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::runApplication(const rho::String& app, const rho::String& params, bool blocking, rho::apiGenerator::CMethodResult& result) { rho_sys_run_app(app, params, result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getHasCamera(CMethodResult& result) { rho_sysimpl_get_property("has_camera", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getPhoneNumber(CMethodResult& result) { rho_sysimpl_get_property("phone_number", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getHasNetwork(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("has_network", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getHasWifiNetwork(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("has_wifi_network", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getHasCellNetwork(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("has_cell_network", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getDeviceOwnerName(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("device_owner_name", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getDeviceOwnerEmail(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("device_owner_email", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getOsVersion(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("os_version", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getIsSymbolDevice(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("is_symbol_device", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::hideSplashScreen(rho::apiGenerator::CMethodResult& result) { JNIEnv *env = jnienv(); jclass clsRhodesService = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE); jmethodID mid = getJNIClassStaticMethod(env, clsRhodesService, "removeSplashScreen", "()V"); JNI_EXCEPTION_CHECK(env, result); env->CallStaticVoidMethod(clsRhodesService, mid); JNI_EXCEPTION_CHECK(env, result); } //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- class CSystemFactory: public CSystemFactoryBase { public: ~CSystemFactory(){} ISystemSingleton* createModuleSingleton(){ return new CSystemImpl(); } }; //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- extern "C" void Init_System() { CSystemFactory::setInstance( new CSystemFactory() ); Init_System_API(); RHODESAPP().getExtManager().requireRubyFile("RhoSystemApi"); } //---------------------------------------------------------------------------------------------------------------------- } <commit_msg>Update SystemImpl.cpp<commit_after>#include "SystemImplBase.h" #include "rhodes/JNIRhodes.h" RHO_GLOBAL int rho_sysimpl_get_property(const char* szPropName, rho::apiGenerator::CMethodResult& result); RHO_GLOBAL int rho_sys_set_sleeping(int sleeping); RHO_GLOBAL void rho_sys_is_app_installed(const rho::String& appname, rho::apiGenerator::CMethodResult& result); RHO_GLOBAL void rho_sys_app_install(const rho::String& url, rho::apiGenerator::CMethodResult& result); RHO_GLOBAL void rho_sys_app_uninstall(const rho::String& appname, rho::apiGenerator::CMethodResult& result); RHO_GLOBAL void rho_sys_run_app(const rho::String& appname, const rho::String& params, rho::apiGenerator::CMethodResult& result); RHO_GLOBAL void rho_sys_bring_to_front(); RHO_GLOBAL void rho_sys_set_full_screen_mode(bool); RHO_GLOBAL void rho_sys_get_full_screen_mode(rho::apiGenerator::CMethodResult& result); RHO_GLOBAL void rho_sys_set_screen_auto_rotate_mode(bool enable); RHO_GLOBAL void rho_sys_get_screen_auto_rotate_mode(rho::apiGenerator::CMethodResult& result); namespace rho { //---------------------------------------------------------------------------------------------------------------------- class CSystemImpl : public CSystemImplBase { bool mScreenSleeping; public: CSystemImpl() : CSystemImplBase(), mScreenSleeping(true) {} virtual ~CSystemImpl(){} virtual void getScreenWidth(rho::apiGenerator::CMethodResult& result); virtual void getScreenHeight(rho::apiGenerator::CMethodResult& result); virtual void getScreenOrientation(rho::apiGenerator::CMethodResult& result); virtual void getPpiX(rho::apiGenerator::CMethodResult& result); virtual void getPpiY(rho::apiGenerator::CMethodResult& result); virtual void getPhoneId(rho::apiGenerator::CMethodResult& result); virtual void getDeviceName(rho::apiGenerator::CMethodResult& result); virtual void getLocale(rho::apiGenerator::CMethodResult& result); virtual void getCountry(rho::apiGenerator::CMethodResult& result); virtual void getIsEmulator(rho::apiGenerator::CMethodResult& result); virtual void getHasCalendar(rho::apiGenerator::CMethodResult& result); virtual void getOemInfo(rho::apiGenerator::CMethodResult& result); virtual void getUuid(rho::apiGenerator::CMethodResult& result); virtual void getLockWindowSize(rho::apiGenerator::CMethodResult& result); virtual void setLockWindowSize(bool, rho::apiGenerator::CMethodResult& result); virtual void getKeyboardState(rho::apiGenerator::CMethodResult& result); virtual void setKeyboardState(const rho::String&, rho::apiGenerator::CMethodResult& result); virtual void getFullScreen(rho::apiGenerator::CMethodResult& result); virtual void setFullScreen(bool, rho::apiGenerator::CMethodResult& result); virtual void getScreenAutoRotate(rho::apiGenerator::CMethodResult& result); virtual void setScreenAutoRotate(bool, rho::apiGenerator::CMethodResult& result); virtual void getWebviewFramework(rho::apiGenerator::CMethodResult& result); virtual void getScreenSleeping(rho::apiGenerator::CMethodResult& result); virtual void setScreenSleeping(bool, rho::apiGenerator::CMethodResult& result); virtual void applicationInstall(const rho::String&, rho::apiGenerator::CMethodResult& result); virtual void isApplicationInstalled(const rho::String&, rho::apiGenerator::CMethodResult& result); virtual void applicationUninstall(const rho::String&, rho::apiGenerator::CMethodResult& result); virtual void openUrl(const rho::String&, rho::apiGenerator::CMethodResult& result); virtual void setWindowFrame(int, int, int, int, rho::apiGenerator::CMethodResult& result); virtual void setWindowPosition(int, int, rho::apiGenerator::CMethodResult& result); virtual void setWindowSize(int, int, rho::apiGenerator::CMethodResult& result); virtual void bringToFront(rho::apiGenerator::CMethodResult& result); virtual void runApplication(const rho::String&, const rho::String&, bool, rho::apiGenerator::CMethodResult& result); virtual void getHasCamera(rho::apiGenerator::CMethodResult& result); virtual void getPhoneNumber(rho::apiGenerator::CMethodResult& result); virtual void getHasNetwork(rho::apiGenerator::CMethodResult& result); virtual void getHasWifiNetwork(rho::apiGenerator::CMethodResult& result); virtual void getHasCellNetwork(rho::apiGenerator::CMethodResult& result); virtual void getDeviceOwnerName(rho::apiGenerator::CMethodResult& result); virtual void getDeviceOwnerEmail(rho::apiGenerator::CMethodResult& result); virtual void getOsVersion(rho::apiGenerator::CMethodResult& result); virtual void getIsSymbolDevice(rho::apiGenerator::CMethodResult& result); virtual void getIsMotorolaDevice(rho::apiGenerator::CMethodResult& result); virtual void hideSplashScreen(rho::apiGenerator::CMethodResult& oResult); }; //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- #undef DEFAULT_LOGCATEGORY #define DEFAULT_LOGCATEGORY "SystemImpl" //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getScreenWidth(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("screen_width", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getScreenHeight(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("screen_height", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getScreenOrientation(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("screen_orientation", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getPpiX(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("ppi_x", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getPpiY(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("ppi_y", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getPhoneId(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("phone_id", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getDeviceName(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("device_name", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getLocale(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("locale", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getCountry(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("country", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getIsEmulator(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("is_emulator", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getHasCalendar(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("has_calendar", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getOemInfo(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("oem_info", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getUuid(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("uuid", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getLockWindowSize(rho::apiGenerator::CMethodResult& result) { // result.setError("not implemented at Android platform"); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::setLockWindowSize(bool, rho::apiGenerator::CMethodResult& result) { // result.setError("not implemented at Android platform"); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getKeyboardState(rho::apiGenerator::CMethodResult& result) { // result.setError("not implemented at Android platform"); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::setKeyboardState(const rho::String&, rho::apiGenerator::CMethodResult& result) { // result.setError("not implemented at Android platform"); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getFullScreen(rho::apiGenerator::CMethodResult& result) { rho_sys_get_full_screen_mode(result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::setFullScreen(bool fullmode, rho::apiGenerator::CMethodResult& result) { rho_sys_set_full_screen_mode(fullmode); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getScreenAutoRotate(rho::apiGenerator::CMethodResult& result) { rho_sys_get_screen_auto_rotate_mode(result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::setScreenAutoRotate(bool mode, rho::apiGenerator::CMethodResult& result) { rho_sys_set_screen_auto_rotate_mode(mode); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getWebviewFramework(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("webview_framework", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getScreenSleeping(rho::apiGenerator::CMethodResult& result) { result.set(mScreenSleeping); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::setScreenSleeping(bool flag, rho::apiGenerator::CMethodResult& result) { mScreenSleeping = flag; rho_sys_set_sleeping(flag?1:0); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::applicationInstall(const rho::String& url, rho::apiGenerator::CMethodResult& result) { rho_sys_app_install(url, result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::isApplicationInstalled(const rho::String& appname, rho::apiGenerator::CMethodResult& result) { rho_sys_is_app_installed(appname, result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::applicationUninstall(const rho::String& appname, rho::apiGenerator::CMethodResult& result) { rho_sys_app_uninstall(appname, result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::openUrl(const rho::String& url, rho::apiGenerator::CMethodResult& result) { JNIEnv *env = jnienv(); jclass clsRhodesService = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE); jmethodID midOpenExternalUrl = getJNIClassStaticMethod(env, clsRhodesService, "openExternalUrl", "(Ljava/lang/String;)V"); JNI_EXCEPTION_CHECK(env, result); jhstring jhUrl = rho_cast<jstring>(env, url); env->CallStaticVoidMethod(clsRhodesService, midOpenExternalUrl, jhUrl.get()); JNI_EXCEPTION_CHECK(env, result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::setWindowFrame(int, int, int, int, rho::apiGenerator::CMethodResult& result) { // result.setError("not implemented at Android platform"); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::setWindowPosition(int, int, rho::apiGenerator::CMethodResult& result) { // result.setError("not implemented at Android platform"); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::setWindowSize(int, int, rho::apiGenerator::CMethodResult& result) { // result.setError("not implemented at Android platform"); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::bringToFront(rho::apiGenerator::CMethodResult& result) { rho_sys_bring_to_front(); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::runApplication(const rho::String& app, const rho::String& params, bool blocking, rho::apiGenerator::CMethodResult& result) { rho_sys_run_app(app, params, result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getHasCamera(CMethodResult& result) { rho_sysimpl_get_property("has_camera", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getPhoneNumber(CMethodResult& result) { rho_sysimpl_get_property("phone_number", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getHasNetwork(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("has_network", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getHasWifiNetwork(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("has_wifi_network", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getHasCellNetwork(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("has_cell_network", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getDeviceOwnerName(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("device_owner_name", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getDeviceOwnerEmail(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("device_owner_email", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getOsVersion(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("os_version", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getIsMotorolaDevice(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("is_symbol_device", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::getIsSymbolDevice(rho::apiGenerator::CMethodResult& result) { rho_sysimpl_get_property("is_symbol_device", result); } //---------------------------------------------------------------------------------------------------------------------- void CSystemImpl::hideSplashScreen(rho::apiGenerator::CMethodResult& result) { JNIEnv *env = jnienv(); jclass clsRhodesService = getJNIClass(RHODES_JAVA_CLASS_RHODES_SERVICE); jmethodID mid = getJNIClassStaticMethod(env, clsRhodesService, "removeSplashScreen", "()V"); JNI_EXCEPTION_CHECK(env, result); env->CallStaticVoidMethod(clsRhodesService, mid); JNI_EXCEPTION_CHECK(env, result); } //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- class CSystemFactory: public CSystemFactoryBase { public: ~CSystemFactory(){} ISystemSingleton* createModuleSingleton(){ return new CSystemImpl(); } }; //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- extern "C" void Init_System() { CSystemFactory::setInstance( new CSystemFactory() ); Init_System_API(); RHODESAPP().getExtManager().requireRubyFile("RhoSystemApi"); } //---------------------------------------------------------------------------------------------------------------------- } <|endoftext|>
<commit_before>#include <bts/blockchain/chain_database_impl.hpp> namespace bts { namespace blockchain { namespace detail { class market_engine { public: market_engine( pending_chain_state_ptr ps, chain_database_impl& cdi ); /** return true if execute was successful and applied */ bool execute( asset_id_type quote_id, asset_id_type base_id, const fc::time_point_sec& timestamp ); private: void push_market_transaction( const market_transaction& mtrx ); void pay_current_short( market_transaction& mtrx, asset_record& quote_asset, asset_record& base_asset ); void pay_current_bid( const market_transaction& mtrx, asset_record& quote_asset ); void pay_current_cover( market_transaction& mtrx, asset_record& quote_asset ); void pay_current_ask( const market_transaction& mtrx, asset_record& base_asset ); bool get_next_short(); bool get_next_bid(); bool get_next_ask(); asset get_current_cover_debt()const; asset get_cover_interest( const asset& principle )const; /** * This method should not affect market execution or validation and * is for historical purposes only. */ void update_market_history( const asset& trading_volume, const price& opening_price, const price& closing_price, const omarket_status& market_stat, const fc::time_point_sec& timestamp ); void cancel_current_short( market_transaction& mtrx, const asset_id_type& quote_asset_id ); void cancel_all_shorts(); pending_chain_state_ptr _pending_state; pending_chain_state_ptr _prior_state; chain_database_impl& _db_impl; optional<market_order> _current_bid; optional<market_order> _current_ask; collateral_record _current_collat_record; asset_id_type _quote_id; asset_id_type _base_id; market_status _market_stat; int _orders_filled = 0; public: vector<market_transaction> _market_transactions; private: bts::db::cached_level_map< market_index_key, order_record >::iterator _bid_itr; bts::db::cached_level_map< market_index_key, order_record >::iterator _ask_itr; bts::db::cached_level_map< market_index_key, order_record >::iterator _short_itr; bts::db::cached_level_map< market_index_key, collateral_record >::iterator _collateral_itr; }; } } } // end namespace bts::blockchain::detail <commit_msg>Make market_engine::cancel_all_shorts() public<commit_after>#include <bts/blockchain/chain_database_impl.hpp> namespace bts { namespace blockchain { namespace detail { class market_engine { public: market_engine( pending_chain_state_ptr ps, chain_database_impl& cdi ); /** return true if execute was successful and applied */ bool execute( asset_id_type quote_id, asset_id_type base_id, const fc::time_point_sec& timestamp ); void cancel_all_shorts(); private: void push_market_transaction( const market_transaction& mtrx ); void pay_current_short( market_transaction& mtrx, asset_record& quote_asset, asset_record& base_asset ); void pay_current_bid( const market_transaction& mtrx, asset_record& quote_asset ); void pay_current_cover( market_transaction& mtrx, asset_record& quote_asset ); void pay_current_ask( const market_transaction& mtrx, asset_record& base_asset ); bool get_next_short(); bool get_next_bid(); bool get_next_ask(); asset get_current_cover_debt()const; asset get_cover_interest( const asset& principle )const; /** * This method should not affect market execution or validation and * is for historical purposes only. */ void update_market_history( const asset& trading_volume, const price& opening_price, const price& closing_price, const omarket_status& market_stat, const fc::time_point_sec& timestamp ); void cancel_current_short( market_transaction& mtrx, const asset_id_type& quote_asset_id ); pending_chain_state_ptr _pending_state; pending_chain_state_ptr _prior_state; chain_database_impl& _db_impl; optional<market_order> _current_bid; optional<market_order> _current_ask; collateral_record _current_collat_record; asset_id_type _quote_id; asset_id_type _base_id; market_status _market_stat; int _orders_filled = 0; public: vector<market_transaction> _market_transactions; private: bts::db::cached_level_map< market_index_key, order_record >::iterator _bid_itr; bts::db::cached_level_map< market_index_key, order_record >::iterator _ask_itr; bts::db::cached_level_map< market_index_key, order_record >::iterator _short_itr; bts::db::cached_level_map< market_index_key, collateral_record >::iterator _collateral_itr; }; } } } // end namespace bts::blockchain::detail <|endoftext|>
<commit_before>/* * Author: Dino Wernli */ #include "listener/bmp_exporter.h" #include <fstream> #include "renderer/sampler/sampler.h" #include "util/color3.h" BmpExporter::BmpExporter(const std::string& file_name) : file_name_(file_name) { } BmpExporter::~BmpExporter() { } void BmpExporter::Update(const Sampler& sampler) { // Only export if the image is done. if (!sampler.IsDone()) { return; } LOG(INFO) << "Exporting image " << file_name_; const Image& image = sampler.image(); std::ofstream file_stream(file_name_, std::ofstream::binary); const size_t width = image.SizeX(); const size_t height = image.SizeY(); const size_t filesize = 54 + 3*width*height; char file_header[14] = {'B','M',0,0,0,0,0,0,0,0,54,0,0,0}; char info_header[40] = {40,0,0,0,0,0,0,0,0,0,0,0,1,0,24,0}; file_header[2] = (char)(filesize); file_header[3] = (char)(filesize>> 8); file_header[4] = (char)(filesize>>16); file_header[5] = (char)(filesize>>24); info_header[4] = (char)(width); info_header[5] = (char)(width>> 8); info_header[6] = (char)(width>>16); info_header[7] = (char)(width>>24); info_header[8] = (char)(height); info_header[9] = (char)(height>> 8); info_header[10] = (char)(height>>16); info_header[11] = (char)(height>>24); file_stream.write(file_header, 14).write(info_header, 40); // Due to alignment, we must append the following number of bytes as padding. const size_t extra_bytes = (4 - (width * 3) % 4) % 4; char padding[3] = {0, 0, 0}; for (size_t row = 0; row < height; ++row) { for (size_t col = 0; col < width; ++col) { const Color3& pixel = image.PixelAt(col, height - row - 1); char buffer[3] = { (char)(pixel.b() * 255), (char)(pixel.g() * 255), (char)(pixel.r() * 255) }; file_stream.write(buffer, 3); } file_stream.write(padding, extra_bytes); } file_stream.close(); } <commit_msg>Clean up the exporter code some more.<commit_after>/* * Author: Dino Wernli */ #include "listener/bmp_exporter.h" #include <fstream> #include "renderer/sampler/sampler.h" #include "util/color3.h" BmpExporter::BmpExporter(const std::string& file_name) : file_name_(file_name) { } BmpExporter::~BmpExporter() { } static void WriteHeader(size_t width, size_t height, std::ofstream* stream) { const size_t filesize = 54 + 3 * width * height; char file_header[14] = {'B','M',0,0,0,0,0,0,0,0,54,0,0,0}; char info_header[40] = {40,0,0,0,0,0,0,0,0,0,0,0,1,0,24,0}; file_header[2] = (char)(filesize); file_header[3] = (char)(filesize>> 8); file_header[4] = (char)(filesize>>16); file_header[5] = (char)(filesize>>24); info_header[4] = (char)(width); info_header[5] = (char)(width>> 8); info_header[6] = (char)(width>>16); info_header[7] = (char)(width>>24); info_header[8] = (char)(height); info_header[9] = (char)(height>> 8); info_header[10] = (char)(height>>16); info_header[11] = (char)(height>>24); stream->write(file_header, 14).write(info_header, 40); } void BmpExporter::Update(const Sampler& sampler) { // Only export if the image is done. if (!sampler.IsDone()) { return; } LOG(INFO) << "Exporting image " << file_name_; std::ofstream file_stream(file_name_, std::ofstream::binary); const Image& image = sampler.image(); const size_t width = image.SizeX(); const size_t height = image.SizeY(); WriteHeader(width, height, &file_stream); // Due to alignment, we must append the following number of bytes as padding. const size_t extra_bytes = (4 - (width * 3) % 4) % 4; char padding[3] = {0, 0, 0}; for (size_t y = 0; y < height; ++y) { for (size_t x = 0; x < width; ++x) { const Color3& pixel = image.PixelAt(x, height - y - 1); char buffer[3] = { (char)(pixel.b() * 255), (char)(pixel.g() * 255), (char)(pixel.r() * 255) }; file_stream.write(buffer, 3); } file_stream.write(padding, extra_bytes); } file_stream.close(); } <|endoftext|>
<commit_before>/* * Author: Dino Wernli */ #include "listener/ppm_exporter.h" #include <fstream> #include "renderer/sampler/sampler.h" #include "util/color3.h" // Transforms an intensity in range [0, 1] to an integer in // {0, ..., kMaxPixelValue}. unsigned int ScaleIntensity(Intensity intensity) { return intensity * PpmExporter::kMaxPixelValue; } PpmExporter::PpmExporter(std::string file_name) : file_name_(file_name) { } PpmExporter::~PpmExporter() { } void PpmExporter::Update(const Sampler& sampler) { // Only export if the image is done. if (!sampler.IsDone()) { return; } const Image& image = sampler.image(); std::ofstream file_stream(file_name_); file_stream << kMagicNumber << std::endl; file_stream << image.SizeX() << " " << image.SizeY() << std::endl; file_stream << kMaxPixelValue << std::endl; for (size_t y = 0; y < image.SizeY(); ++y) { for (size_t x = 0; x < image.SizeX(); ++x) { const Color3& color = image.PixelAt(x, y); file_stream << ScaleIntensity(color.r()) << " " << ScaleIntensity(color.g()) << " " << ScaleIntensity(color.b()) << " "; } file_stream << std::endl; } file_stream << std::endl; file_stream.close(); } const size_t PpmExporter::kMaxPixelValue = 255; const std::string PpmExporter::kMagicNumber = "P3"; <commit_msg>Add logging statement for listener.<commit_after>/* * Author: Dino Wernli */ #include "listener/ppm_exporter.h" #include <glog/logging.h> #include <fstream> #include "renderer/sampler/sampler.h" #include "util/color3.h" // Transforms an intensity in range [0, 1] to an integer in // {0, ..., kMaxPixelValue}. unsigned int ScaleIntensity(Intensity intensity) { return intensity * PpmExporter::kMaxPixelValue; } PpmExporter::PpmExporter(std::string file_name) : file_name_(file_name) { } PpmExporter::~PpmExporter() { } void PpmExporter::Update(const Sampler& sampler) { // Only export if the image is done. if (!sampler.IsDone()) { return; } LOG(INFO) << "Exporting image " << file_name_; const Image& image = sampler.image(); std::ofstream file_stream(file_name_); file_stream << kMagicNumber << std::endl; file_stream << image.SizeX() << " " << image.SizeY() << std::endl; file_stream << kMaxPixelValue << std::endl; for (size_t y = 0; y < image.SizeY(); ++y) { for (size_t x = 0; x < image.SizeX(); ++x) { const Color3& color = image.PixelAt(x, y); file_stream << ScaleIntensity(color.r()) << " " << ScaleIntensity(color.g()) << " " << ScaleIntensity(color.b()) << " "; } file_stream << std::endl; } file_stream << std::endl; file_stream.close(); } const size_t PpmExporter::kMaxPixelValue = 255; const std::string PpmExporter::kMagicNumber = "P3"; <|endoftext|>
<commit_before>#pragma comment(linker, "/STACK:16777216") #define _CRT_SECURE_NO_WARNINGS #include <algorithm> #include <iostream> #include <iomanip> #include <sstream> #include <string> #include <vector> #include <queue> #include <set> #include <map> #include <cstdio> #include <cstdlib> #include <cctype> #include <cmath> #include <climits> #include <numeric> #include <memory.h> //#include <ctime> //clock_t startTime=clock(); //fprintf(stderr,"time=%.3lfsec\n",0.001*(clock()-startTime)); using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<ll> vl; typedef vector<vl> vvl; typedef vector<bool> vb; typedef vector<vb> vvb; typedef vector<double> vd; typedef vector<vd> vvd; typedef vector<string> vs; typedef pair<int, int> pii; typedef vector<pii> vpii; typedef pair<double, double> pdd; typedef vector<pdd> vpdd; typedef vector<vpii> Graph; #define fr(i,a,b) for(int i(a),_b(b);i<=_b;++i) #define frd(i,a,b) for(int i(a),_b(b);i>=_b;--i) #define rep(i,n) for(int i(0),_n(n);i<_n;++i) #define reps(i,a) fr(i,0,sz(a)-1) #define all(a) a.begin(),a.end() #define pb push_back #define mp make_pair #define clr(x,a) memset(x,a,sizeof(x)) #define findx(a,x) (find(all(a),x)-a.begin()) #define two(X) (1LL<<(X)) #define contain(S,X) (((S)&two(X))!=0) const int dr[]={0,-1,0,1,-1,1, 1,-1}; const int dc[]={1,0,-1,0, 1,1,-1,-1}; const double eps=1e-9; template<class T> void print(const vector<T> &v){ostringstream os; for(int i=0; i<v.size(); ++i){if(i)os<<' ';os<<v[i];} cout<<os.str()<<endl;} template<class T> int sz(const T&c){return (int)c.size();} template<class T> void srt(T&c){sort(c.begin(),c.end());} template<class T> void checkmin(T &a,T b){if(b<a) a=b;} template<class T> void checkmax(T &a,T b){if(b>a) a=b;} template<class T> T sqr(T x){return x*x;} template<class T, class U> T cast (U x) { ostringstream os; os<<x; T res; istringstream is(os.str()); is>>res; return res; } template<class T> vector<T> split(string s, string x=" ") {vector<T> res; for(int i=0;i<s.size();i++){string a; while(i<(int)s.size()&&x.find(s[i])==string::npos)a+=s[i++]; if(!a.empty())res.push_back(cast<T>(a));} return res;} template<class T> bool inside(T r,T c,T R, T C){return r>=0 && r<R && c>=0 && c<C;} int minu=-1; void dfs1(vvi &g,const vi &p,int u, vb &vis){ if(minu==-1 || p[minu]>p[u])minu=u; vis[u/2]=true; reps(i,g[u]){ int v=g[u][i]; if(minu==-1 || p[minu]>p[v])minu=v; if(vis[v/2])continue; dfs1(g,p,v,vis); } u=u^1; if(u<sz(g)){ if(minu==-1 || p[minu]>p[u])minu=u; reps(i,g[u]){ int v=g[u][i]; if(minu==-1 || p[minu]>p[v])minu=v; if(vis[v/2])continue; dfs1(g,p,v,vis); } } } void dfs(vvi &g,string &s,int u, vb &vis){ vis[u/2]=true; reps(i,g[u]){ int v=g[u][i]; if(vis[v/2])continue; if(s[u]==s[v])swap(s[v],s[v^1]); dfs(g,s,v,vis); } u=u^1; if(u<sz(g)) reps(i,g[u]){ int v=g[u][i]; if(vis[v/2])continue; if(s[u]==s[v])swap(s[v],s[v^1]); dfs(g,s,v,vis); } } string solve(const vi &a, const vi &b){ int n=sz(a); vi p(n); rep(i,n)p[a[i]]=i; vi c(n); rep(i,n)c[i]=p[b[i]]; string s=string(n+n%2, 'A'); rep(i,(n+1)/2)s[2*i+1]='B'; vvi g(n); rep(i,n/2){ int x=c[2*i]; int y=c[2*i+1]; g[x].pb(y); g[y].pb(x); } vb vis((n+1)/2); vb vis1((n+1)/2); rep(i,n){ if(!vis[i/2]){ minu=-1; dfs1(g,a,i,vis1); if((minu^1)<n && (a[minu]<a[minu^1] ^ s[minu]<s[minu^1]))swap(s[minu],s[minu^1]); dfs(g,s,minu,vis); } } string t=string(n,' '); rep(i,n)t[a[i]]=s[i]; return t; } int main( int argc, char* argv[] ) { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); #endif int tc; scanf("%d", &tc); //tc=1000; while(tc--){ int n; scanf("%d", &n); vi a(n); rep(i,n)scanf("%d", &a[i]); vi b(n); rep(i,n)scanf("%d", &b[i]); /* n=rand()%2000+1; //n=20000; vi a(n),b(n); rep(i,n)a[i]=b[i]=i; random_shuffle(all(a)); random_shuffle(all(b)); */ string t=solve(a,b); int z1=0,z2=0; int a1=0,b1=0; int a2=0,b2=0; rep(i,n){ a1+=t[a[i]]=='A'; b1+=t[a[i]]=='B'; a2+=t[b[i]]=='A'; b2+=t[b[i]]=='B'; checkmax(z1,abs(a1-b1)); checkmax(z2,abs(a2-b2)); } if(z1>1||z2>1){ print(a); print(b); cout<<" "<<z1<<" "<<z2<<endl; exit(0); } cout<<t<<endl; //cout<<" "<<z1<<" "<<z2<<endl; } //cout<<"ok"<<endl; return 0; } <commit_msg>update<commit_after><|endoftext|>
<commit_before>#include <string> /* public class TennisGame4 implements TennisGame { int serverScore; int receiverScore; String server; String receiver; public TennisGame4(String player1, String player2) { this.server = player1; this.receiver = player2; } @java.lang.Override public void wonPoint(String playerName) { if (server.equals(playerName)) this.serverScore += 1; else this.receiverScore += 1; } @java.lang.Override public String getScore() { TennisResult result = new Deuce( this, new GameServer( this, new GameReceiver( this, new AdvantageServer( this, new AdvantageReceiver( this, new DefaultResult(this)))))).getResult(); return result.format(); } boolean receiverHasAdvantage() { return receiverScore >= 4 && (receiverScore - serverScore) == 1; } boolean serverHasAdvantage() { return serverScore >= 4 && (serverScore - receiverScore) == 1; } boolean receiverHasWon() { return receiverScore >= 4 && (receiverScore - serverScore) >= 2; } boolean serverHasWon() { return serverScore >= 4 && (serverScore - receiverScore) >= 2; } boolean isDeuce() { return serverScore >= 3 && receiverScore >= 3 && (serverScore == receiverScore); } } class TennisResult { String serverScore; String receiverScore; TennisResult(String serverScore, String receiverScore) { this.serverScore = serverScore; this.receiverScore = receiverScore; } String format() { if ("".equals(this.receiverScore)) return this.serverScore; if (serverScore.equals(receiverScore)) return serverScore + "-All"; return this.serverScore + "-" + this.receiverScore; } } interface ResultProvider { TennisResult getResult(); } class Deuce implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public Deuce(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.isDeuce()) return new TennisResult("Deuce", ""); return this.nextResult.getResult(); } } class GameServer implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public GameServer(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.serverHasWon()) return new TennisResult("Win for " + game.server, ""); return this.nextResult.getResult(); } } class GameReceiver implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public GameReceiver(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.receiverHasWon()) return new TennisResult("Win for " + game.receiver, ""); return this.nextResult.getResult(); } } class AdvantageServer implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public AdvantageServer(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.serverHasAdvantage()) return new TennisResult("Advantage " + game.server, ""); return this.nextResult.getResult(); } } class AdvantageReceiver implements ResultProvider { private final TennisGame4 game; private final ResultProvider nextResult; public AdvantageReceiver(TennisGame4 game, ResultProvider nextResult) { this.game = game; this.nextResult = nextResult; } @Override public TennisResult getResult() { if (game.receiverHasAdvantage()) return new TennisResult("Advantage " + game.receiver, ""); return this.nextResult.getResult(); } } class DefaultResult implements ResultProvider { private static final String[] scores = {"Love", "Fifteen", "Thirty", "Forty"}; private final TennisGame4 game; public DefaultResult(TennisGame4 game) { this.game = game; } @Override public TennisResult getResult() { return new TennisResult(scores[game.serverScore], scores[game.receiverScore]); } } */ class TennisResult { public: TennisResult(std::string serverScore, std::string receiverScore) { this->serverScore = serverScore; this->receiverScore = receiverScore; } std::string format() { if ("" == this->receiverScore) return this->serverScore; if (serverScore == this->receiverScore) return serverScore + "-All"; return this->serverScore + "-" + this->receiverScore; } private: std::string serverScore; std::string receiverScore; }; class ResultProvider { public: virtual TennisResult getResult() const = 0; virtual ~ResultProvider() = default; }; class TennisGame4 : ResultProvider { public: int serverScore = 0, receiverScore = 0; std::string server; std::string receiver; TennisGame4(std::string player1, std::string player2) { this->server = player1; this->receiver = player2; } TennisResult getResult() const override; void wonPoint(std::string playerName); bool receiverHasAdvantage() const; bool serverHasAdvantage() const; bool receiverHasWon() const; bool serverHasWon() const; bool isDeuce() const; }; class Deuce : ResultProvider { public: Deuce(TennisGame4 const & game, ResultProvider const & nextResult) : game(game), nextResult(nextResult) { } TennisResult getResult() const override { if (game.isDeuce()) return TennisResult("Deuce", ""); return this->nextResult.getResult(); } private: TennisGame4 const & game; ResultProvider const & nextResult; }; class GameServer : public ResultProvider { public: GameServer(TennisGame4 const & game, ResultProvider const & nextResult) : game(game), nextResult(nextResult) { } TennisResult getResult() const override { if (game.serverHasWon()) return TennisResult("Win for " + game.server, ""); return nextResult.getResult(); } private: TennisGame4 const & game; ResultProvider const & nextResult; }; class GameReceiver : public ResultProvider { private: TennisGame4 const & game; ResultProvider const & nextResult; public: GameReceiver(TennisGame4 const & game, ResultProvider const & nextResult) : game(game), nextResult(nextResult) { } public: TennisResult getResult() const override { if (game.receiverHasWon()) return TennisResult("Win for " + game.receiver, ""); return this->nextResult.getResult(); } }; class AdvantageServer : public ResultProvider { public: AdvantageServer(TennisGame4 const & game, ResultProvider const & nextResult) : game(game), nextResult(nextResult) { } TennisResult getResult() const override { if (game.serverHasAdvantage()) return TennisResult("Advantage " + game.server, ""); return this->nextResult.getResult(); } private: TennisGame4 const & game; ResultProvider const & nextResult; }; class AdvantageReceiver : public ResultProvider { public: AdvantageReceiver(TennisGame4 game, ResultProvider const & nextResult) : game(game), nextResult(nextResult) { } TennisResult getResult() const override { if (game.receiverHasAdvantage()) return TennisResult("Advantage " + game.receiver, ""); return this->nextResult.getResult(); } private: const TennisGame4 game; ResultProvider const & nextResult; }; class DefaultResult : public ResultProvider { public: explicit DefaultResult(TennisGame4 const & game) : game(game) { } TennisResult getResult() const override { return TennisResult(scores[game.serverScore], scores[game.receiverScore]); } private: static const std::string scores[]; TennisGame4 const & game; }; const std::string DefaultResult::scores[] = {"Love", "Fifteen", "Thirty", "Forty"}; TennisResult TennisGame4::getResult() const { TennisGame4 const & thisGame = *this; TennisResult result = Deuce( thisGame, GameServer( thisGame, GameReceiver( thisGame, AdvantageServer( thisGame, AdvantageReceiver( thisGame, DefaultResult(thisGame))))) ).getResult(); return result; } void TennisGame4::wonPoint(std::string playerName) { if (server == playerName) serverScore += 1; else receiverScore += 1; } bool TennisGame4::receiverHasAdvantage() const { return receiverScore >= 4 && (receiverScore - serverScore) == 1; } bool TennisGame4::serverHasAdvantage() const { return serverScore >= 4 && (serverScore - receiverScore) == 1; } bool TennisGame4::receiverHasWon() const { return receiverScore >= 4 && (receiverScore - serverScore) >= 2; } bool TennisGame4::serverHasWon() const { return serverScore >= 4 && (serverScore - receiverScore) >= 2; } bool TennisGame4::isDeuce() const { return serverScore >= 3 && receiverScore >= 3 && (serverScore == receiverScore); } std::string tennis_score(int player1Score, int player2Score) { int highestScore = player1Score > player2Score ? player1Score : player2Score; TennisGame4 game("player1", "player2"); for (int i = 0; i < highestScore; i++) { if (i < player1Score) game.wonPoint("player1"); if (i < player2Score) game.wonPoint("player2"); } TennisResult result = game.getResult(); return result.format(); } <commit_msg>Remove commented original Java code.<commit_after>#include <string> class TennisResult { public: TennisResult(std::string serverScore, std::string receiverScore) { this->serverScore = serverScore; this->receiverScore = receiverScore; } std::string format() { if ("" == this->receiverScore) return this->serverScore; if (serverScore == this->receiverScore) return serverScore + "-All"; return this->serverScore + "-" + this->receiverScore; } private: std::string serverScore; std::string receiverScore; }; class ResultProvider { public: virtual TennisResult getResult() const = 0; virtual ~ResultProvider() = default; }; class TennisGame4 : ResultProvider { public: int serverScore = 0, receiverScore = 0; std::string server; std::string receiver; TennisGame4(std::string player1, std::string player2) { this->server = player1; this->receiver = player2; } TennisResult getResult() const override; void wonPoint(std::string playerName); bool receiverHasAdvantage() const; bool serverHasAdvantage() const; bool receiverHasWon() const; bool serverHasWon() const; bool isDeuce() const; }; class Deuce : ResultProvider { public: Deuce(TennisGame4 const & game, ResultProvider const & nextResult) : game(game), nextResult(nextResult) { } TennisResult getResult() const override { if (game.isDeuce()) return TennisResult("Deuce", ""); return this->nextResult.getResult(); } private: TennisGame4 const & game; ResultProvider const & nextResult; }; class GameServer : public ResultProvider { public: GameServer(TennisGame4 const & game, ResultProvider const & nextResult) : game(game), nextResult(nextResult) { } TennisResult getResult() const override { if (game.serverHasWon()) return TennisResult("Win for " + game.server, ""); return nextResult.getResult(); } private: TennisGame4 const & game; ResultProvider const & nextResult; }; class GameReceiver : public ResultProvider { private: TennisGame4 const & game; ResultProvider const & nextResult; public: GameReceiver(TennisGame4 const & game, ResultProvider const & nextResult) : game(game), nextResult(nextResult) { } public: TennisResult getResult() const override { if (game.receiverHasWon()) return TennisResult("Win for " + game.receiver, ""); return this->nextResult.getResult(); } }; class AdvantageServer : public ResultProvider { public: AdvantageServer(TennisGame4 const & game, ResultProvider const & nextResult) : game(game), nextResult(nextResult) { } TennisResult getResult() const override { if (game.serverHasAdvantage()) return TennisResult("Advantage " + game.server, ""); return this->nextResult.getResult(); } private: TennisGame4 const & game; ResultProvider const & nextResult; }; class AdvantageReceiver : public ResultProvider { public: AdvantageReceiver(TennisGame4 game, ResultProvider const & nextResult) : game(game), nextResult(nextResult) { } TennisResult getResult() const override { if (game.receiverHasAdvantage()) return TennisResult("Advantage " + game.receiver, ""); return this->nextResult.getResult(); } private: const TennisGame4 game; ResultProvider const & nextResult; }; class DefaultResult : public ResultProvider { public: explicit DefaultResult(TennisGame4 const & game) : game(game) { } TennisResult getResult() const override { return TennisResult(scores[game.serverScore], scores[game.receiverScore]); } private: static const std::string scores[]; TennisGame4 const & game; }; const std::string DefaultResult::scores[] = {"Love", "Fifteen", "Thirty", "Forty"}; TennisResult TennisGame4::getResult() const { TennisGame4 const & thisGame = *this; TennisResult result = Deuce( thisGame, GameServer( thisGame, GameReceiver( thisGame, AdvantageServer( thisGame, AdvantageReceiver( thisGame, DefaultResult(thisGame))))) ).getResult(); return result; } void TennisGame4::wonPoint(std::string playerName) { if (server == playerName) serverScore += 1; else receiverScore += 1; } bool TennisGame4::receiverHasAdvantage() const { return receiverScore >= 4 && (receiverScore - serverScore) == 1; } bool TennisGame4::serverHasAdvantage() const { return serverScore >= 4 && (serverScore - receiverScore) == 1; } bool TennisGame4::receiverHasWon() const { return receiverScore >= 4 && (receiverScore - serverScore) >= 2; } bool TennisGame4::serverHasWon() const { return serverScore >= 4 && (serverScore - receiverScore) >= 2; } bool TennisGame4::isDeuce() const { return serverScore >= 3 && receiverScore >= 3 && (serverScore == receiverScore); } std::string tennis_score(int player1Score, int player2Score) { int highestScore = player1Score > player2Score ? player1Score : player2Score; TennisGame4 game("player1", "player2"); for (int i = 0; i < highestScore; i++) { if (i < player1Score) game.wonPoint("player1"); if (i < player2Score) game.wonPoint("player2"); } TennisResult result = game.getResult(); return result.format(); } <|endoftext|>
<commit_before>// arm-poky-linux-gnueabi-gcc -lopencv_video -lopencv_core -lopencv_highgui -lopencv_imgproc -lstdc++ -shared-libgcc opencv.cpp -o opencv #include <opencv2/opencv.hpp> #include <stdlib.h> #include <iostream> #include <time.h> using namespace cv; using namespace std; int main(int argc, char** argv) { VideoCapture cap; // camera interface // open default 0 device if no other device as first argument was passed if(argc > 1){ cap.open(atoi(argv[1])); } else { cap.open(0); } if(!cap.isOpened()) // check if we succeeded { cout << "Could not open default video device" << endl; return -1; } else { cap.set(CV_CAP_PROP_FRAME_WIDTH, 320); cap.set(CV_CAP_PROP_FRAME_HEIGHT, 240); } Mat frame, bwFrame; namedWindow("camera",1); while(1) { if( !cap.read(frame) ){ cout << "Camera was disconected"; break; } cout << time(NULL) << endl; cvtColor(frame, bwFrame, CV_BGR2GRAY); imshow("camera", bwFrame); if(waitKey(30) >= 0) break; } // the camera will be deinitialized automatically in VideoCapture destructor return 0; } <commit_msg>Using threads<commit_after>// arm-poky-linux-gnueabi-gcc -lopencv_video -lopencv_core -lopencv_highgui -lopencv_imgproc -lstdc++ -shared-libgcc opencv.cpp -o opencv #include <opencv2/opencv.hpp> #include <stdlib.h> #include <iostream> #include <time.h> #include <thread> using namespace cv; using namespace std; void gui(); // thread Mat bwFrame; int main(int argc, char** argv) { thread gui_thread; VideoCapture cap; // camera interface Mat frame; // open default 0 device if no other device as first argument was passed if(argc > 1){ cap.open(atoi(argv[1])); } else { cap.open(0); } if(!cap.isOpened()) // check if we succeeded { cout << "Could not open default video device" << endl; return -1; } else { cap.set(CV_CAP_PROP_FRAME_WIDTH, 320); cap.set(CV_CAP_PROP_FRAME_HEIGHT, 240); } while(1) { if( !cap.read(frame) ){ cout << "Camera was disconected"; break; } cvtColor(frame, bwFrame, CV_BGR2GRAY); if(!gui_thread.joinable()) gui_thread = thread(gui); if(waitKey(30) >= 0) break; } // the camera will be deinitialized automatically in VideoCapture destructor return 0; } void gui( ){ // startup code namedWindow("camera",1); //loop while(1){ imshow("camera", bwFrame); cout << time(NULL) << endl; } } <|endoftext|>
<commit_before>/* * qnode.cpp * * Created on: Aug 30, 2012 * Authors: Francisco Viña * fevb <at> kth.se */ /* Copyright (c) 2012, Francisco Vina, CVAP, KTH All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the KTH 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 KTH 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 /src/qnode.cpp * * @brief Ros communication central! * * @date February 2011 **/ /***************************************************************************** ** Includes *****************************************************************************/ #include <ros/ros.h> #include <ros/network.h> #include <string> // ROS message includes #include <std_msgs/String.h> #include <sstream> #include <dumbo_dashboard/qnode.hpp> /***************************************************************************** ** Implementation *****************************************************************************/ QNode::QNode(int argc, char** argv ) : init_argc(argc), init_argv(argv) { n = ros::NodeHandle("~"); } QNode::~QNode() { if(ros::isStarted()) { ros::shutdown(); // explicitly needed since we use ros::start(); ros::waitForShutdown(); } wait(); } bool QNode::on_init() { // Add your ros communications here. // subscribe to arm initialization services left_arm_initsrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_controller/init"); right_arm_initsrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_controller/init"); // subscribe to disconnect services left_arm_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_controller/disconnect"); right_arm_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_controller/disconnect"); // subscribe to PG70 parallel gripper initialization services pg70_initsrv_client = n.serviceClient<cob_srvs::Trigger>("/PG70_controller/init"); sdh_initsrv_client = n.serviceClient<cob_srvs::Trigger>("/sdh_controller/init"); // subscribe to PG70 parallel gripper disconnect services pg70_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/PG70_controller/disconnect"); sdh_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/sdh_controller/shutdown"); // subscribe to arm stop services left_arm_stopsrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_controller/stop_arm"); right_arm_stopsrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_controller/stop_arm"); // subscribe to arm recover services left_arm_recoversrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_controller/recover"); right_arm_recoversrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_controller/recover"); // subscribe to gripper recover services pg70_recoversrv_client = n.serviceClient<cob_srvs::Trigger>("/PG70_controller/recover"); sdh_recoversrv_client = n.serviceClient<cob_srvs::Trigger>("/sdh_controller/recover"); // subscribe to gripper pos pg70_pos_pub = n.advertise<brics_actuator::JointPositions>("/PG70_controller/command_pos", 1); // subscribe to FT sensor init service left_arm_ft_connectsrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_ft_sensor/connect"); left_arm_ft_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_ft_sensor/disconnect"); left_arm_ft_calibsrv_client = n.serviceClient<dumbo_srvs::CalibrateFT>("/left_arm_ft_sensor/calibrate"); right_arm_ft_connectsrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_ft_sensor/connect"); right_arm_ft_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_ft_sensor/disconnect"); right_arm_ft_calibsrv_client = n.serviceClient<dumbo_srvs::CalibrateFT>("/right_arm_ft_sensor/calibrate"); // subscribe to left gripper close service pg70_close_srv_client = n.serviceClient<dumbo_srvs::ClosePG70Gripper>("/PG70_controller/close_gripper"); start(); return true; } bool QNode::on_init(const std::string &master_url, const std::string &host_url) { std::map<std::string,std::string> remappings; remappings["__master"] = master_url; remappings["__hostname"] = host_url; ros::init(remappings,"test"); if ( ! ros::master::check() ) { return false; } ros::start(); // explicitly needed since our nodehandle is going out of scope. // Add your ros communications here. start(); return true; } void QNode::run() { ros::Rate loop_rate(10); int count = 0; while ( ros::ok() ) { ros::spinOnce(); loop_rate.sleep(); } std::cout << "Ros shutdown, proceeding to close the gui." << std::endl; emit rosShutdown(); // used to signal the gui for a shutdown (useful to roslaunch) } void QNode::initArms() { cob_srvs::Trigger left_arm_init_srv; while(!left_arm_initsrv_client.exists()) { ROS_INFO("Waiting for left arm init service"); ros::Duration(1).sleep(); } if(left_arm_initsrv_client.call(left_arm_init_srv)) { if(left_arm_init_srv.response.success.data) { ROS_INFO("Successfully initialized left arm..."); emit leftArmConnected(); } else { ROS_ERROR("Error initializing left arm"); } } else { ROS_ERROR("Failed to call left arm init service"); } // open the PG70 gripper if the left arm connected correctly if(left_arm_init_srv.response.success.data) { cob_srvs::Trigger pg70_init_srv; // while(!pg70_initsrv_client.exists()) // { // ROS_INFO("Waiting for PG70 init service"); // ros::Duration(1).sleep(); // } if(pg70_initsrv_client.call(pg70_init_srv)) { if(pg70_init_srv.response.success.data) { ROS_INFO("Successfully initialized PG70 gripper..."); // emit rightArmConnected(); todo fix for pg70 } else { ROS_ERROR("Error initializing PG70 gripper"); } } else { ROS_ERROR("Failed to call PG70 gripper init service"); } } cob_srvs::Trigger right_arm_init_srv; while(!right_arm_initsrv_client.exists()) { ROS_INFO("Waiting for right arm init service"); ros::Duration(1).sleep(); } if(right_arm_initsrv_client.call(right_arm_init_srv)) { if(right_arm_init_srv.response.success.data) { ROS_INFO("Successfully initialized right arm..."); emit rightArmConnected(); } else { ROS_ERROR("Error initializing right arm"); } } else { ROS_ERROR("Failed to call right arm init service"); } if(right_arm_init_srv.response.success.data) { cob_srvs::Trigger sdh_init_srv; // while(!sdh_initsrv_client.exists()) // { // ROS_INFO("Waiting for SDH init service"); // ros::Duration(1).sleep(); // } if(sdh_initsrv_client.call(sdh_init_srv)) { if(sdh_init_srv.response.success.data) { ROS_INFO("Successfully initialized SDH gripper..."); // emit rightArmConnected(); todo fix for sdh } else { ROS_ERROR("Error initializing SDH gripper"); } } else { ROS_ERROR("Failed to call SDH gripper init service"); } } } void QNode::disconnect_robot() { cob_srvs::Trigger disconnect_srv; pg70_disconnectsrv_client.call(disconnect_srv); left_arm_disconnectsrv_client.call(disconnect_srv); sdh_disconnectsrv_client.call(disconnect_srv); right_arm_disconnectsrv_client.call(disconnect_srv); left_arm_ft_disconnectsrv_client.call(disconnect_srv); right_arm_ft_disconnectsrv_client.call(disconnect_srv); emit leftArmDisconnected(); emit rightArmDisconnected(); emit left_ft_disconnected(); emit right_ft_disconnected(); } void QNode::stopArms() { cob_srvs::Trigger left_arm_stop_srv; if(left_arm_stopsrv_client.call(left_arm_stop_srv)) { if(left_arm_stop_srv.response.success.data) { ROS_INFO("Successfully stopped left arm..."); } else { ROS_ERROR("Error stopping left arm"); } } else { ROS_ERROR("Failed to call left arm stop service"); } cob_srvs::Trigger right_arm_stop_srv; if(right_arm_stopsrv_client.call(right_arm_stop_srv)) { if(right_arm_stop_srv.response.success.data) { ROS_INFO("Successfully stopped right arm..."); } else { ROS_ERROR("Error stopping right arm"); } } else { ROS_ERROR("Failed to call right arm stop service"); } } void QNode::recoverArms() { cob_srvs::Trigger left_arm_recover_srv; if(left_arm_recoversrv_client.call(left_arm_recover_srv)) { if(left_arm_recover_srv.response.success.data==true) { ROS_INFO("Successfully recovered left arm..."); } else { ROS_ERROR("Error recovering left arm"); } } else { ROS_ERROR("Failed to call left arm recover service"); } cob_srvs::Trigger pg70_recover_srv; if(pg70_recoversrv_client.call(pg70_recover_srv)) { if(pg70_recover_srv.response.success.data==true) { ROS_INFO("Successfully recovered PG70 parallel gripper..."); } else { ROS_ERROR("Error recovering PG70 parallel gripper"); } } else { ROS_ERROR("Failed to call PG70 parallel gripper recover service"); } cob_srvs::Trigger right_arm_recover_srv; if(right_arm_recoversrv_client.call(right_arm_recover_srv)) { if(right_arm_recover_srv.response.success.data==true) { ROS_INFO("Successfully recovered right arm..."); } else { ROS_ERROR("Error recovering right arm"); } } else { ROS_ERROR("Failed to call right arm recover service"); } } void QNode::sendGripperPos(double pos) { // *** hard coded... brics_actuator::JointPositions left_gripper_pos_command; left_gripper_pos_command.positions.resize(1); left_gripper_pos_command.positions[0].timeStamp = ros::Time::now(); left_gripper_pos_command.positions[0].joint_uri = "left_arm_top_finger_joint"; left_gripper_pos_command.positions[0].unit = "mm"; left_gripper_pos_command.positions[0].value = pos; pg70_pos_pub.publish(left_gripper_pos_command); } void QNode::closeGripper(double target_vel, double current_limit) { dumbo_srvs::ClosePG70Gripper gripper_close_srv; gripper_close_srv.request.target_vel = target_vel; gripper_close_srv.request.current_limit = current_limit; if(pg70_close_srv_client.call(gripper_close_srv)) { if(gripper_close_srv.response.success) { ROS_INFO("Closing PG70 gripper"); } else { ROS_ERROR("Couldn't close PG70 gripper."); } } else { ROS_ERROR("Couldn't close PG70 gripper."); } } void QNode::connectFT() { cob_srvs::Trigger left_arm_ft_connect_srv; while(!left_arm_ft_connectsrv_client.exists()) { ROS_INFO("Waiting for left arm F/T connect service."); ros::Duration(1).sleep(); } if(left_arm_ft_connectsrv_client.call(left_arm_ft_connect_srv)) { if(left_arm_ft_connect_srv.response.success.data) { ROS_INFO("Successfully connected to left arm F/T sensor..."); emit left_ft_connected(); } else { ROS_ERROR("Error connecting to left arm F/T sensor"); } } else { ROS_ERROR("Failed to call left arm F/T sensor connect service"); } cob_srvs::Trigger right_arm_ft_connect_srv; while(!right_arm_ft_connectsrv_client.exists()) { ROS_INFO("Waiting for right arm F/T connect service."); ros::Duration(1).sleep(); } if(right_arm_ft_connectsrv_client.call(right_arm_ft_connect_srv)) { if(right_arm_ft_connect_srv.response.success.data) { ROS_INFO("Successfully connected to right arm F/T sensor..."); emit right_ft_connected(); } else { ROS_ERROR("Error connecting to right arm F/T sensor"); } } else { ROS_ERROR("Failed to call right arm F/T sensor connect service"); } } <commit_msg>fixed gripper position<commit_after>/* * qnode.cpp * * Created on: Aug 30, 2012 * Authors: Francisco Viña * fevb <at> kth.se */ /* Copyright (c) 2012, Francisco Vina, CVAP, KTH All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the KTH 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 KTH 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 /src/qnode.cpp * * @brief Ros communication central! * * @date February 2011 **/ /***************************************************************************** ** Includes *****************************************************************************/ #include <ros/ros.h> #include <ros/network.h> #include <string> // ROS message includes #include <std_msgs/String.h> #include <sstream> #include <dumbo_dashboard/qnode.hpp> /***************************************************************************** ** Implementation *****************************************************************************/ QNode::QNode(int argc, char** argv ) : init_argc(argc), init_argv(argv) { n = ros::NodeHandle("~"); } QNode::~QNode() { if(ros::isStarted()) { ros::shutdown(); // explicitly needed since we use ros::start(); ros::waitForShutdown(); } wait(); } bool QNode::on_init() { // Add your ros communications here. // subscribe to arm initialization services left_arm_initsrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_controller/init"); right_arm_initsrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_controller/init"); // subscribe to disconnect services left_arm_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_controller/disconnect"); right_arm_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_controller/disconnect"); // subscribe to PG70 parallel gripper initialization services pg70_initsrv_client = n.serviceClient<cob_srvs::Trigger>("/PG70_controller/init"); sdh_initsrv_client = n.serviceClient<cob_srvs::Trigger>("/sdh_controller/init"); // subscribe to PG70 parallel gripper disconnect services pg70_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/PG70_controller/disconnect"); sdh_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/sdh_controller/shutdown"); // subscribe to arm stop services left_arm_stopsrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_controller/stop_arm"); right_arm_stopsrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_controller/stop_arm"); // subscribe to arm recover services left_arm_recoversrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_controller/recover"); right_arm_recoversrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_controller/recover"); // subscribe to gripper recover services pg70_recoversrv_client = n.serviceClient<cob_srvs::Trigger>("/PG70_controller/recover"); sdh_recoversrv_client = n.serviceClient<cob_srvs::Trigger>("/sdh_controller/recover"); // subscribe to gripper pos pg70_pos_pub = n.advertise<brics_actuator::JointPositions>("/PG70_controller/command_pos", 1); // subscribe to FT sensor init service left_arm_ft_connectsrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_ft_sensor/connect"); left_arm_ft_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/left_arm_ft_sensor/disconnect"); left_arm_ft_calibsrv_client = n.serviceClient<dumbo_srvs::CalibrateFT>("/left_arm_ft_sensor/calibrate"); right_arm_ft_connectsrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_ft_sensor/connect"); right_arm_ft_disconnectsrv_client = n.serviceClient<cob_srvs::Trigger>("/right_arm_ft_sensor/disconnect"); right_arm_ft_calibsrv_client = n.serviceClient<dumbo_srvs::CalibrateFT>("/right_arm_ft_sensor/calibrate"); // subscribe to left gripper close service pg70_close_srv_client = n.serviceClient<dumbo_srvs::ClosePG70Gripper>("/PG70_controller/close_gripper"); start(); return true; } bool QNode::on_init(const std::string &master_url, const std::string &host_url) { std::map<std::string,std::string> remappings; remappings["__master"] = master_url; remappings["__hostname"] = host_url; ros::init(remappings,"test"); if ( ! ros::master::check() ) { return false; } ros::start(); // explicitly needed since our nodehandle is going out of scope. // Add your ros communications here. start(); return true; } void QNode::run() { ros::Rate loop_rate(10); int count = 0; while ( ros::ok() ) { ros::spinOnce(); loop_rate.sleep(); } std::cout << "Ros shutdown, proceeding to close the gui." << std::endl; emit rosShutdown(); // used to signal the gui for a shutdown (useful to roslaunch) } void QNode::initArms() { cob_srvs::Trigger left_arm_init_srv; while(!left_arm_initsrv_client.exists()) { ROS_INFO("Waiting for left arm init service"); ros::Duration(1).sleep(); } if(left_arm_initsrv_client.call(left_arm_init_srv)) { if(left_arm_init_srv.response.success.data) { ROS_INFO("Successfully initialized left arm..."); emit leftArmConnected(); } else { ROS_ERROR("Error initializing left arm"); } } else { ROS_ERROR("Failed to call left arm init service"); } // open the PG70 gripper if the left arm connected correctly if(left_arm_init_srv.response.success.data) { cob_srvs::Trigger pg70_init_srv; // while(!pg70_initsrv_client.exists()) // { // ROS_INFO("Waiting for PG70 init service"); // ros::Duration(1).sleep(); // } if(pg70_initsrv_client.call(pg70_init_srv)) { if(pg70_init_srv.response.success.data) { ROS_INFO("Successfully initialized PG70 gripper..."); // emit rightArmConnected(); todo fix for pg70 } else { ROS_ERROR("Error initializing PG70 gripper"); } } else { ROS_ERROR("Failed to call PG70 gripper init service"); } } cob_srvs::Trigger right_arm_init_srv; while(!right_arm_initsrv_client.exists()) { ROS_INFO("Waiting for right arm init service"); ros::Duration(1).sleep(); } if(right_arm_initsrv_client.call(right_arm_init_srv)) { if(right_arm_init_srv.response.success.data) { ROS_INFO("Successfully initialized right arm..."); emit rightArmConnected(); } else { ROS_ERROR("Error initializing right arm"); } } else { ROS_ERROR("Failed to call right arm init service"); } if(right_arm_init_srv.response.success.data) { cob_srvs::Trigger sdh_init_srv; // while(!sdh_initsrv_client.exists()) // { // ROS_INFO("Waiting for SDH init service"); // ros::Duration(1).sleep(); // } if(sdh_initsrv_client.call(sdh_init_srv)) { if(sdh_init_srv.response.success.data) { ROS_INFO("Successfully initialized SDH gripper..."); // emit rightArmConnected(); todo fix for sdh } else { ROS_ERROR("Error initializing SDH gripper"); } } else { ROS_ERROR("Failed to call SDH gripper init service"); } } } void QNode::disconnect_robot() { cob_srvs::Trigger disconnect_srv; pg70_disconnectsrv_client.call(disconnect_srv); left_arm_disconnectsrv_client.call(disconnect_srv); sdh_disconnectsrv_client.call(disconnect_srv); right_arm_disconnectsrv_client.call(disconnect_srv); left_arm_ft_disconnectsrv_client.call(disconnect_srv); right_arm_ft_disconnectsrv_client.call(disconnect_srv); emit leftArmDisconnected(); emit rightArmDisconnected(); emit left_ft_disconnected(); emit right_ft_disconnected(); } void QNode::stopArms() { cob_srvs::Trigger left_arm_stop_srv; if(left_arm_stopsrv_client.call(left_arm_stop_srv)) { if(left_arm_stop_srv.response.success.data) { ROS_INFO("Successfully stopped left arm..."); } else { ROS_ERROR("Error stopping left arm"); } } else { ROS_ERROR("Failed to call left arm stop service"); } cob_srvs::Trigger right_arm_stop_srv; if(right_arm_stopsrv_client.call(right_arm_stop_srv)) { if(right_arm_stop_srv.response.success.data) { ROS_INFO("Successfully stopped right arm..."); } else { ROS_ERROR("Error stopping right arm"); } } else { ROS_ERROR("Failed to call right arm stop service"); } } void QNode::recoverArms() { cob_srvs::Trigger left_arm_recover_srv; if(left_arm_recoversrv_client.call(left_arm_recover_srv)) { if(left_arm_recover_srv.response.success.data==true) { ROS_INFO("Successfully recovered left arm..."); } else { ROS_ERROR("Error recovering left arm"); } } else { ROS_ERROR("Failed to call left arm recover service"); } cob_srvs::Trigger pg70_recover_srv; if(pg70_recoversrv_client.call(pg70_recover_srv)) { if(pg70_recover_srv.response.success.data==true) { ROS_INFO("Successfully recovered PG70 parallel gripper..."); } else { ROS_ERROR("Error recovering PG70 parallel gripper"); } } else { ROS_ERROR("Failed to call PG70 parallel gripper recover service"); } cob_srvs::Trigger right_arm_recover_srv; if(right_arm_recoversrv_client.call(right_arm_recover_srv)) { if(right_arm_recover_srv.response.success.data==true) { ROS_INFO("Successfully recovered right arm..."); } else { ROS_ERROR("Error recovering right arm"); } } else { ROS_ERROR("Failed to call right arm recover service"); } } void QNode::sendGripperPos(double pos) { // *** hard coded... brics_actuator::JointPositions left_gripper_pos_command; left_gripper_pos_command.positions.resize(1); left_gripper_pos_command.positions[0].timeStamp = ros::Time::now(); left_gripper_pos_command.positions[0].joint_uri = "left_arm_top_finger_joint"; left_gripper_pos_command.positions[0].unit = "m"; left_gripper_pos_command.positions[0].value = pos/1000.0; pg70_pos_pub.publish(left_gripper_pos_command); } void QNode::closeGripper(double target_vel, double current_limit) { dumbo_srvs::ClosePG70Gripper gripper_close_srv; gripper_close_srv.request.target_vel = target_vel; gripper_close_srv.request.current_limit = current_limit; if(pg70_close_srv_client.call(gripper_close_srv)) { if(gripper_close_srv.response.success) { ROS_INFO("Closing PG70 gripper"); } else { ROS_ERROR("Couldn't close PG70 gripper."); } } else { ROS_ERROR("Couldn't close PG70 gripper."); } } void QNode::connectFT() { cob_srvs::Trigger left_arm_ft_connect_srv; while(!left_arm_ft_connectsrv_client.exists()) { ROS_INFO("Waiting for left arm F/T connect service."); ros::Duration(1).sleep(); } if(left_arm_ft_connectsrv_client.call(left_arm_ft_connect_srv)) { if(left_arm_ft_connect_srv.response.success.data) { ROS_INFO("Successfully connected to left arm F/T sensor..."); emit left_ft_connected(); } else { ROS_ERROR("Error connecting to left arm F/T sensor"); } } else { ROS_ERROR("Failed to call left arm F/T sensor connect service"); } cob_srvs::Trigger right_arm_ft_connect_srv; while(!right_arm_ft_connectsrv_client.exists()) { ROS_INFO("Waiting for right arm F/T connect service."); ros::Duration(1).sleep(); } if(right_arm_ft_connectsrv_client.call(right_arm_ft_connect_srv)) { if(right_arm_ft_connect_srv.response.success.data) { ROS_INFO("Successfully connected to right arm F/T sensor..."); emit right_ft_connected(); } else { ROS_ERROR("Error connecting to right arm F/T sensor"); } } else { ROS_ERROR("Failed to call right arm F/T sensor connect service"); } } <|endoftext|>
<commit_before>#ifndef DUNE_FEM_FUNCTIONALS_CONTAINER_FACTORY_HH #define DUNE_FEM_FUNCTIONALS_CONTAINER_FACTORY_HH namespace Dune { namespace Functionals { namespace Container { template <class ContainerImp> class Factory { public: typedef NotImplemented AutoPtrType; typedef NotImplemented ContainerType; class NotImplemented { }; public: template <class DiscFuncSpace> static AutoPtrType create(DiscFuncSpace& dfs) { dune_static_assert("Not Implemented: Factory!"); } template <class DiscFuncSpace> static ContainerType* createPtr(DiscFuncSpace& dfs) { dune_static_assert("Not Implemented: Factory!"); } }; // end of class Factory template <class ContainerImp> class MatrixFactory : public Factory<ContainerImp> { }; // specialization for BCRSMatrix template <class T> class MatrixFactory<Dune::BCRSMatrix<T>> { public: typedef Dune::BCRSMatrix<T> ContainerType; typedef std::auto_ptr<ContainerType> AutoPtrType; public: template <class DiscFuncSpace> static AutoPtrType create(DiscFuncSpace& dfs) { return AutoPtrType(createPtr(dfs)); } template <class DiscFuncSpace> static ContainerType* createPtr(DiscFuncSpace& dfs) { typedef DiscFuncSpace::BaseFunctionSet BFS; typedef DiscFuncSpace::IteratorType ItType; typedef ItType::Entity Entity; const unsigned int numDofs = dfs.size(); typedef std::vector<std::set<unsigned int>> PatternType; PatternType sPattern(numDofs); ContainerType* matrix = new ContainerType(numDofs, numDofs, ContainerType::random); // compute sparsity pattern // \todo precompile this in linear subspace // \todo use constraints for sparsity pattern ItType it = dfs.begin(); for (; it != dfs.end(); it++) { const Entity& en = *it; const BFS& bfs = dfs.baseFunctionSet(en); for (unsigned int i = 0; i < bfs.numBaseFunctions(); i++) { ii = dfs.mapToGlobal(en, i); for (unsigned int j = 0; j < bfs.numBaseFunctions(); j++) { jj = dfs.mapToGlobal(en, j); sPattern[ii].insert(jj); } } } for (unsigned int i = 0; i < sPattern.size(); i++) { matrix->setRowSize(i, sPattern[i].size()); } matrix->endrowsizes(); for (unsigned int i = 0; i < sPattern.size(); ++i) { typedef std::set<unsigned int>::const_iterator SetIterator; SetIterator sit = sPattern[i].begin(); for (; sit != sPattern[i].end(); sit++) { matrix->addindex(i, *sit); } } matrix->endindices(); return matrix; } }; // end of MatrixFactory<BCRSMatrix<T> > template <class ContainerImp> class VectorFactory : public Factory<ContainerImp> { }; // specialization for BlockVector<T> template <class T> class VectorFactory<Dune::BlockVector<T>> { public: typedef Dune::BlockVector<T> ContainerType; typedef std::auto_ptr<ContainerType> AutoPtrType; public: template <class DFSType> static ContainerType* createPtr(DFSType& dfs) { const unsigned int numDofs = dfs.size(); ContainerType* bv = new ContainerType(numDofs); return bv; } static AutoPtrType create(DFSType& dfs) { return AutoPtrType(createPtr(dfs)); } }; // end of VectorFactory<BlockVector<T> > } // end of namespace Container } // end of namespace Functionals } // end of namespace Dune #endif /* end of include guard: DUNE_FEM_FUNCTIONALS_CONTAINER_FACTORY_HH */ <commit_msg>added documentation to container::factory<commit_after>#ifndef DUNE_FEM_FUNCTIONALS_CONTAINER_FACTORY_HH #define DUNE_FEM_FUNCTIONALS_CONTAINER_FACTORY_HH namespace Dune { namespace Functionals { namespace Container { /** @brief interface of static factory class for matrix and vector classes */ template <class ContainerImp> class Factory { public: //! return type for create() method typedef NotImplemented AutoPtrType; //! wrapped container type typedef NotImplemented ContainerType; private: class NotImplemented { }; public: /** @brief creates a new matrix/vector object and returns an auto_ptr * pointing to the allocated object * * - Matrices have size @f$ H \times H @f$ where @f$H@f$ is the number * of degrees of freedom in the discrete function space @f$ { \cal X }_H @f$. * The matrices' sparsity pattern is determined by the discrete function * space's basefunction overlap. * - Vectors have @f$ H @f$ components * * @param dfs the discrete function space @f$ { \cal X }_H @f$. */ template <class DiscFuncSpace> static AutoPtrType create(DiscFuncSpace& dfs) { dune_static_assert("Not Implemented: Factory!"); } /** @brief creates a new matrix/vector object and returns a pointer to the * allocated object * * - Matrices have size @f$ H \times H @f$ where @f$H@f$ is the number * of degrees of freedom in the discrete function space @f$ { \cal X }_H @f$. * The matrices' sparsity pattern is determined by the discrete function * space's basefunction overlap. * - Vectors have @f$ H @f$ components * * @param dfs the discrete function space @f$ { \cal X }_H @f$. */ template <class DiscFuncSpace> static ContainerType* createPtr(DiscFuncSpace& dfs) { dune_static_assert("Not Implemented: Factory!"); } }; // end of class Factory /** @brief interface of static factory class for matrix classes */ template <class ContainerImp> class MatrixFactory : public Factory<ContainerImp> { }; // specialization for BCRSMatrix template <class T> class MatrixFactory<Dune::BCRSMatrix<T>> { public: typedef Dune::BCRSMatrix<T> ContainerType; typedef std::auto_ptr<ContainerType> AutoPtrType; public: /** @brief creates a new BCRSMatrix object and returns an auto_ptr pointing * to the allocated object * * Matrices have size @f$ H \times H @f$ where @f$H@f$ is the number * of degrees of freedom in the discrete function space @f$ { \cal X }_H @f$. * The matrices' sparsity pattern is determined by the discrete function * space's basefunction overlap. * * @param dfs the discrete function space @f$ { \cal X }_H @f$. */ template <class DiscFuncSpace> static AutoPtrType create(DiscFuncSpace& dfs) { return AutoPtrType(createPtr(dfs)); } /** @brief creates a new BCRSMatrix object and returns a pointer to the * allocated object * * Matrices have size @f$ H \times H @f$ where @f$H@f$ is the number * of degrees of freedom in the discrete function space @f$ { \cal X }_H @f$. * The matrices' sparsity pattern is determined by the discrete function * space's basefunction overlap. * * @param dfs the discrete function space @f$ { \cal X }_H @f$. */ template <class DiscFuncSpace> static ContainerType* createPtr(DiscFuncSpace& dfs) { typedef DiscFuncSpace::BaseFunctionSet BFS; typedef DiscFuncSpace::IteratorType ItType; typedef ItType::Entity Entity; const unsigned int numDofs = dfs.size(); typedef std::vector<std::set<unsigned int>> PatternType; PatternType sPattern(numDofs); ContainerType* matrix = new ContainerType(numDofs, numDofs, ContainerType::random); // compute sparsity pattern // \todo precompile this in linear subspace // \todo use constraints for sparsity pattern ItType it = dfs.begin(); for (; it != dfs.end(); it++) { const Entity& en = *it; const BFS& bfs = dfs.baseFunctionSet(en); for (unsigned int i = 0; i < bfs.numBaseFunctions(); i++) { ii = dfs.mapToGlobal(en, i); for (unsigned int j = 0; j < bfs.numBaseFunctions(); j++) { jj = dfs.mapToGlobal(en, j); sPattern[ii].insert(jj); } } } for (unsigned int i = 0; i < sPattern.size(); i++) { matrix->setRowSize(i, sPattern[i].size()); } matrix->endrowsizes(); for (unsigned int i = 0; i < sPattern.size(); ++i) { typedef std::set<unsigned int>::const_iterator SetIterator; SetIterator sit = sPattern[i].begin(); for (; sit != sPattern[i].end(); sit++) { matrix->addindex(i, *sit); } } matrix->endindices(); return matrix; } }; // end of MatrixFactory<BCRSMatrix<T> > /** @brief interface of static factory class for vector classes */ template <class ContainerImp> class VectorFactory : public Factory<ContainerImp> { }; /** @brief static factory class for vector classes of type Dune::BlockVector */ template <class T> class VectorFactory<Dune::BlockVector<T>> { public: //! \copydoc Factory::ContainerType typedef Dune::BlockVector<T> ContainerType; //! \copydoc Factory::AutoPtrType; typedef std::auto_ptr<ContainerType> AutoPtrType; public: /** @brief creates a new vector object and returns an auto_ptr pointing to * the allocated object * * The vector has @f$ H @f$ components which is the number of degrees of * freedom of the given discrete function space @f$ {\cal X}_H @f$. * * @param dfs the discrete function space @f$ { \cal X }_H @f$. */ template <class DFSType> static ContainerType* createPtr(DFSType& dfs) { const unsigned int numDofs = dfs.size(); ContainerType* bv = new ContainerType(numDofs); return bv; } static AutoPtrType create(DFSType& dfs) { return AutoPtrType(createPtr(dfs)); } }; // end of VectorFactory<BlockVector<T> > } // end of namespace Container } // end of namespace Functionals } // end of namespace Dune #endif /* end of include guard: DUNE_FEM_FUNCTIONALS_CONTAINER_FACTORY_HH */ <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <cmath> #include <cassert> template <typename T> inline T Factorial(T n) { assert(n<21); /* overflows 64-bit integer */ T r=1; for (T i=1; i<=n; ++i) r *= i; return r; } template <typename T> inline double InverseFactorial(T n) { double r=1.0; for (T i=1; i<=n; ++i) r /= i; return r; } template <typename T> inline T DoubleFactorial(T n) { //assert(n<21); /* overflows 64-bit integer */ T r=1; for (T i=1; i<=n; ++i) r *= (2*i - 1); return r; } template <typename T> inline double InverseDoubleFactorial(T n) { //assert(n<21); /* overflows 64-bit integer */ double r=1.0; for (T i=1; i<=n; ++i) r /= (2*i - 1); return r; } template <typename T> inline T Sign(T k) { return ( k>0 ? T(1) : T(-1) ); } template <typename T> inline T SignPow(T k) { // return ( k%2==0 ? T(1) : T(-1) ); // return ( k%2>0 ? T(-1) : T(1) ); return ( T( 1-2*(k%2) ) ); } template <typename T, typename F> inline F BoysAsymp(T n, F x) { return DoubleFactorial(2*n-1)/pow(2,n+1) * sqrt( M_PI / pow(x,2*n+1) ); } template <typename T, typename F> inline F BoysTerm(T n, T k, F x) { //return pow(-x,k) / ( Factorial(k) * (2*k + 2*n + 1) ); return pow(-x,k) * InverseFactorial(k) / (2*k + 2*n + 1); } int main(int argc, char* argv[]) { int n = ( argc>1 ? atoi(argv[1]) : 0 ); double x = ( argc>2 ? atof(argv[2]) : 0.0 ); printf("n = %d x = %lf \n", n, x ); int k; double xpower; double invkfact; double knsum; double bterm_even; double bterm_odd; double fast; #if DEBUG fflush(stdout); printf("===================================================\n"); //printf("%4s %2s %10s %14s %14s %14s %14s %2s \n", "n", "k", "x", "1/k!", "x^k", "k,BoysTerm(n,k,x)", "sum" ); if (x<10.0) printf("%3s %3s %10s %14s %14s %14s %14s \n", "n", "k", "x", "k!", "x^k", "BoysTerm(n,k,x)", "sum" ); else printf("%3s %3s %10s %14s %14s %14s %14s %14s \n", "n", "k", "x", "k!", "x^k", "BoysTerm(n,k,x)", "sum", "BoysAsymp(n,x)" ); double b = 0.0, s = 0.0; k = 0; while( (k<200) && (fabs(b=BoysTerm(n,k,x))>1.0e-16) && (fabs(b)<1.0e10)) { //b = BoysTerm(n,k,x); s += b; //printf("%4ld %2ld %10.5lf %18ld %14.7e %14.7e %14.7e %2ld %c \n", n, k, x, Factorial(k), pow(-x,k), b, s, k+1, fabs(b)<1.0e-14 ? '*' : ' ' ); if (x<10.0) printf("%3d %3d %10.5lf %14.7e %14.7e %14.7e %14.7e %3d %c \n", n, k, x, InverseFactorial(k), pow(x,k), b, s, k+1, fabs(b)<1.0e-14 ? '*' : ' ' ); else printf("%3d %3d %10.5lf %14.7e %14.7e %14.7e %14.7e %14.7e %3d %c %s \n", n, k, x, InverseFactorial(k), pow(x,k), b, s, BoysAsymp(n,x), k+1, fabs(b)<1.0e-14 ? '*' : ' ' , fabs(BoysAsymp(n,x)-s)<1.0e-10 ? "**" : " " ); k++; } fflush(stdout); printf("===================================================\n"); printf("%4s %2s %10s %12s %12s %14s %14s %14s %14s %14s %14s %14s %14s \n", "n", "k", "x", "2n+2k+1", "fast 2n+2k+1", "1/k!", "fast 1/k!","x^k", "fast x^k", "BoysTerm", "BoysTermFast", "sum", "fast sum" ); k = 0; double sum; xpower = 1.0; invkfact = 1.0; knsum = 2*n+1; bterm_even = 1/knsum; bterm_odd = 0.0; sum = BoysTerm(n,k,x); fast = 1/knsum; printf("%4d %2d %10.5lf %12.6e %12.6e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e \n", n, k, x, 2*n+2*k+1.0, knsum, InverseFactorial(k), invkfact, pow(x,k), xpower, BoysTerm(n,k,x), bterm_even, sum, fast); for (k=1; k<20; ++k) { sum += BoysTerm(n,k,x); xpower *= x; invkfact /= k; /* use table lookup for division by integers on PPC */ knsum += 2; /* cast should be done by compiler */ bterm_odd = -xpower * invkfact / knsum ; /* use table lookup for division by integers on PPC ??? - matrix or compute for every n */ fast += bterm_odd; printf("%4d %2d %10.5lf %12.6e %12.6e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e \n", n, k, x, 2*n+2*k+1.0, knsum, InverseFactorial(k), invkfact, pow(x,k), xpower, BoysTerm(n,k,x), bterm_odd, sum, fast); ++k; sum += BoysTerm(n,k,x); xpower *= x; invkfact /= k; /* use table lookup for division by integers on PPC */ knsum += 2; /* cast should be done by compiler */ bterm_even = xpower * invkfact / knsum ; /* use table lookup for division by integers on PPC ??? - matrix or compute for every n */ fast += bterm_even; printf("%4d %2d %10.5lf %12.6e %12.6e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e \n", n, k, x, 2*n+2*k+1.0, knsum, InverseFactorial(k), invkfact, pow(x,k), xpower, BoysTerm(n,k,x), bterm_even, sum, fast); } printf("===================================================\n"); fflush(stdout); #endif printf("%4s %20s %20s \n", "k", "term", "sum" ); printf("===================================================\n"); k = 0; xpower = 1.0; invkfact = 1.0; knsum = 2*n+1; bterm_even = 1.0/knsum; bterm_odd = 0.0; double * fast_vec = (double *) malloc( 1001*sizeof(double) ); fast_vec[0] = bterm_even; for (k=1; k<1000; ++k ) { xpower *= x; invkfact /= k; /* use table lookup for division by integers on PPC */ knsum += 2; /* cast should be done by compiler */ fast_vec[k] = -xpower * invkfact / knsum ; /* use table lookup for division by integers on PPC ??? - matrix or compute for every n */ ++k; xpower *= x; invkfact /= k; /* use table lookup for division by integers on PPC */ knsum += 2; /* cast should be done by compiler */ fast_vec[k] = xpower * invkfact / knsum ; /* use table lookup for division by integers on PPC ??? - matrix or compute for every n */ } fast = 0.0; k = 0; while ( (k<1000) && (fabs(fast_vec[k])>1e-14) ) { fast += fast_vec[k]; printf("%4d %24.14e %24.14e \n",k, fast_vec[k], fast ); ++k; if (fast > 1.0e12 ) break; } if (fast > 1.0/(2*n+1) ) printf("%lf cannot be greater than %lf \n", fast, 1.0/(2*n+1) ); printf("===================================================\n"); fflush(stdout); return(0); } <commit_msg>add usage info<commit_after>#include <cstdio> #include <cstdlib> #include <cmath> #include <cassert> template <typename T> inline T Factorial(T n) { assert(n<21); /* overflows 64-bit integer */ T r=1; for (T i=1; i<=n; ++i) r *= i; return r; } template <typename T> inline double InverseFactorial(T n) { double r=1.0; for (T i=1; i<=n; ++i) r /= i; return r; } template <typename T> inline T DoubleFactorial(T n) { //assert(n<21); /* overflows 64-bit integer */ T r=1; for (T i=1; i<=n; ++i) r *= (2*i - 1); return r; } template <typename T> inline double InverseDoubleFactorial(T n) { //assert(n<21); /* overflows 64-bit integer */ double r=1.0; for (T i=1; i<=n; ++i) r /= (2*i - 1); return r; } template <typename T> inline T Sign(T k) { return ( k>0 ? T(1) : T(-1) ); } template <typename T> inline T SignPow(T k) { // return ( k%2==0 ? T(1) : T(-1) ); // return ( k%2>0 ? T(-1) : T(1) ); return ( T( 1-2*(k%2) ) ); } template <typename T, typename F> inline F BoysAsymp(T n, F x) { return DoubleFactorial(2*n-1)/pow(2,n+1) * sqrt( M_PI / pow(x,2*n+1) ); } template <typename T, typename F> inline F BoysTerm(T n, T k, F x) { //return pow(-x,k) / ( Factorial(k) * (2*k + 2*n + 1) ); return pow(-x,k) * InverseFactorial(k) / (2*k + 2*n + 1); } int main(int argc, char* argv[]) { if (argc==1) printf("Usage: ./boys.x n x\n"); int n = ( argc>1 ? atoi(argv[1]) : 0 ); double x = ( argc>2 ? atof(argv[2]) : 0.0 ); printf("n = %d x = %lf \n", n, x ); int k; double xpower; double invkfact; double knsum; double bterm_even; double bterm_odd; double fast; #if DEBUG fflush(stdout); printf("===================================================\n"); //printf("%4s %2s %10s %14s %14s %14s %14s %2s \n", "n", "k", "x", "1/k!", "x^k", "k,BoysTerm(n,k,x)", "sum" ); if (x<10.0) printf("%3s %3s %10s %14s %14s %14s %14s \n", "n", "k", "x", "k!", "x^k", "BoysTerm(n,k,x)", "sum" ); else printf("%3s %3s %10s %14s %14s %14s %14s %14s \n", "n", "k", "x", "k!", "x^k", "BoysTerm(n,k,x)", "sum", "BoysAsymp(n,x)" ); double b = 0.0, s = 0.0; k = 0; while( (k<200) && (fabs(b=BoysTerm(n,k,x))>1.0e-16) && (fabs(b)<1.0e10)) { //b = BoysTerm(n,k,x); s += b; //printf("%4ld %2ld %10.5lf %18ld %14.7e %14.7e %14.7e %2ld %c \n", n, k, x, Factorial(k), pow(-x,k), b, s, k+1, fabs(b)<1.0e-14 ? '*' : ' ' ); if (x<10.0) printf("%3d %3d %10.5lf %14.7e %14.7e %14.7e %14.7e %3d %c \n", n, k, x, InverseFactorial(k), pow(x,k), b, s, k+1, fabs(b)<1.0e-14 ? '*' : ' ' ); else printf("%3d %3d %10.5lf %14.7e %14.7e %14.7e %14.7e %14.7e %3d %c %s \n", n, k, x, InverseFactorial(k), pow(x,k), b, s, BoysAsymp(n,x), k+1, fabs(b)<1.0e-14 ? '*' : ' ' , fabs(BoysAsymp(n,x)-s)<1.0e-10 ? "**" : " " ); k++; } fflush(stdout); printf("===================================================\n"); printf("%4s %2s %10s %12s %12s %14s %14s %14s %14s %14s %14s %14s %14s \n", "n", "k", "x", "2n+2k+1", "fast 2n+2k+1", "1/k!", "fast 1/k!","x^k", "fast x^k", "BoysTerm", "BoysTermFast", "sum", "fast sum" ); k = 0; double sum; xpower = 1.0; invkfact = 1.0; knsum = 2*n+1; bterm_even = 1/knsum; bterm_odd = 0.0; sum = BoysTerm(n,k,x); fast = 1/knsum; printf("%4d %2d %10.5lf %12.6e %12.6e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e \n", n, k, x, 2*n+2*k+1.0, knsum, InverseFactorial(k), invkfact, pow(x,k), xpower, BoysTerm(n,k,x), bterm_even, sum, fast); for (k=1; k<20; ++k) { sum += BoysTerm(n,k,x); xpower *= x; invkfact /= k; /* use table lookup for division by integers on PPC */ knsum += 2; /* cast should be done by compiler */ bterm_odd = -xpower * invkfact / knsum ; /* use table lookup for division by integers on PPC ??? - matrix or compute for every n */ fast += bterm_odd; printf("%4d %2d %10.5lf %12.6e %12.6e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e \n", n, k, x, 2*n+2*k+1.0, knsum, InverseFactorial(k), invkfact, pow(x,k), xpower, BoysTerm(n,k,x), bterm_odd, sum, fast); ++k; sum += BoysTerm(n,k,x); xpower *= x; invkfact /= k; /* use table lookup for division by integers on PPC */ knsum += 2; /* cast should be done by compiler */ bterm_even = xpower * invkfact / knsum ; /* use table lookup for division by integers on PPC ??? - matrix or compute for every n */ fast += bterm_even; printf("%4d %2d %10.5lf %12.6e %12.6e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e %14.7e \n", n, k, x, 2*n+2*k+1.0, knsum, InverseFactorial(k), invkfact, pow(x,k), xpower, BoysTerm(n,k,x), bterm_even, sum, fast); } printf("===================================================\n"); fflush(stdout); #endif printf("%4s %20s %20s \n", "k", "term", "sum" ); printf("===================================================\n"); k = 0; xpower = 1.0; invkfact = 1.0; knsum = 2*n+1; bterm_even = 1.0/knsum; bterm_odd = 0.0; double * fast_vec = (double *) malloc( 1001*sizeof(double) ); fast_vec[0] = bterm_even; for (k=1; k<1000; ++k ) { xpower *= x; invkfact /= k; /* use table lookup for division by integers on PPC */ knsum += 2; /* cast should be done by compiler */ fast_vec[k] = -xpower * invkfact / knsum ; /* use table lookup for division by integers on PPC ??? - matrix or compute for every n */ ++k; xpower *= x; invkfact /= k; /* use table lookup for division by integers on PPC */ knsum += 2; /* cast should be done by compiler */ fast_vec[k] = xpower * invkfact / knsum ; /* use table lookup for division by integers on PPC ??? - matrix or compute for every n */ } fast = 0.0; k = 0; while ( (k<1000) && (fabs(fast_vec[k])>1e-14) ) { fast += fast_vec[k]; printf("%4d %24.14e %24.14e \n",k, fast_vec[k], fast ); ++k; if (fast > 1.0e12 ) break; } if (fast > 1.0/(2*n+1) ) printf("%lf cannot be greater than %lf \n", fast, 1.0/(2*n+1) ); printf("===================================================\n"); fflush(stdout); return(0); } <|endoftext|>
<commit_before>// *********************************************************************** // Filename : check_is_class.hpp // Author : LIZHENG // Created : 2014-06-09 // Description : жһǷͣע⣬std::is_classǸù // // Last Modified By : LIZHENG // Last Modified On : 2014-06-09 // // Copyright (c) [email protected]. All rights reserved. // *********************************************************************** #ifndef ZL_CHECKISCLASS_H #define ZL_CHECKISCLASS_H namespace ZL { template <typename T> class is_class { typedef char one; typedef struct { char a[2]; } two; template <typename C> static one test(int C::*); template <typename C> static two test(...); public: enum { value = sizeof(test<T>(0)) == sizeof(one) }; }; } /* namespace ZL */ #endif /* ZL_CHECKISCLASS_H */<commit_msg>Update check_is_class.hpp<commit_after>// *********************************************************************** // Filename : check_is_class.hpp // Author : LIZHENG // Created : 2014-06-09 // Description : 判断一个类型是否是类类型,注意,std::is_class即是该功能 // // Last Modified By : LIZHENG // Last Modified On : 2014-06-09 // // Copyright (c) [email protected]. All rights reserved. // *********************************************************************** #ifndef ZL_CHECKISCLASS_H #define ZL_CHECKISCLASS_H namespace ZL { template <typename T> class is_class { typedef char YES; typedef struct { char a[2]; } NO; template <typename C> static YES test_t(int C::*); template <typename C> static NO test_t(...); public: enum { value = sizeof(test_t<T>(0)) == sizeof(YES) }; }; } /* namespace ZL */ #endif /* ZL_CHECKISCLASS_H */ <|endoftext|>
<commit_before>/* * align_main.cpp * * Created on: 2013/10/24 * Author: shu */ #include "align_main.h" #include <iostream> #include <string> #include <cstring> #include <cstdlib> #include <unistd.h> #include <tr1/memory> #include <sstream> #include <cstdio> #include "protein_type.h" #include "dna_type.h" #include "logger.h" #include "score_matrix_reader.h" #include "reduced_alphabet_file_reader.h" #include "aligner.h" #include "aligner_gpu.h" using namespace std; AlignMain::AlignMain() { } AlignMain::~AlignMain() { } int AlignMain::Run(int argc, char* argv[]) { Logger *logger = Logger::GetInstance(); logger->Log("searching..."); AlignerCommon::AligningCommonParameters parameters; string queries_filename; string database_filename; string output_filename; //try { bool ret = BuildParameters(argc, argv, queries_filename, database_filename, output_filename, parameters); if (ret) { #ifndef GPU Aligner aligner; aligner.Align(queries_filename, database_filename, output_filename, parameters); #else if (parameters.number_gpus == 0) { Aligner aligner; aligner.Align(queries_filename, database_filename, output_filename, parameters); } else { AlignerGpu aligner; aligner.Align(queries_filename, database_filename, output_filename, parameters); } #endif logger->Log("finished"); return 0; } /* } catch (exception &e) { logger->ErrorLog(e.what()); }*/ return 1; } bool AlignMain::BuildParameters(int argc, char* argv[], string &input_filename, string &database_filename, string &output_filename, Aligner::AligningParameters &parameters) { int c; extern char *optarg; extern int optind; optind = 1; string score_matrix_filename; Logger *logger = Logger::GetInstance(); const string default_protein_matrix_name = "BLOSUM62"; const string default_protein_matrix = " A R N D C Q E G H I L K M F P S T W Y V B Z X *\nA 4 -1 -2 -2 0 -1 -1 0 -2 -1 -1 -1 -1 -2 -1 1 0 -3 -2 0 -2 -1 0 -4\n R -1 5 0 -2 -3 1 0 -2 0 -3 -2 2 -1 -3 -2 -1 -1 -3 -2 -3 -1 0 -1 -4\n N -2 0 6 1 -3 0 0 0 1 -3 -3 0 -2 -3 -2 1 0 -4 -2 -3 3 0 -1 -4\n D -2 -2 1 6 -3 0 2 -1 -1 -3 -4 -1 -3 -3 -1 0 -1 -4 -3 -3 4 1 -1 -4\n C 0 -3 -3 -3 9 -3 -4 -3 -3 -1 -1 -3 -1 -2 -3 -1 -1 -2 -2 -1 -3 -3 -2 -4\n Q -1 1 0 0 -3 5 2 -2 0 -3 -2 1 0 -3 -1 0 -1 -2 -1 -2 0 3 -1 -4\n E -1 0 0 2 -4 2 5 -2 0 -3 -3 1 -2 -3 -1 0 -1 -3 -2 -2 1 4 -1 -4\n G 0 -2 0 -1 -3 -2 -2 6 -2 -4 -4 -2 -3 -3 -2 0 -2 -2 -3 -3 -1 -2 -1 -4\n H -2 0 1 -1 -3 0 0 -2 8 -3 -3 -1 -2 -1 -2 -1 -2 -2 2 -3 0 0 -1 -4\n I -1 -3 -3 -3 -1 -3 -3 -4 -3 4 2 -3 1 0 -3 -2 -1 -3 -1 3 -3 -3 -1 -4\n L -1 -2 -3 -4 -1 -2 -3 -4 -3 2 4 -2 2 0 -3 -2 -1 -2 -1 1 -4 -3 -1 -4\n K -1 2 0 -1 -3 1 1 -2 -1 -3 -2 5 -1 -3 -1 0 -1 -3 -2 -2 0 1 -1 -4\n M -1 -1 -2 -3 -1 0 -2 -3 -2 1 2 -1 5 0 -2 -1 -1 -1 -1 1 -3 -1 -1 -4\n F -2 -3 -3 -3 -2 -3 -3 -3 -1 0 0 -3 0 6 -4 -2 -2 1 3 -1 -3 -3 -1 -4\n P -1 -2 -2 -1 -3 -1 -1 -2 -2 -3 -3 -1 -2 -4 7 -1 -1 -4 -3 -2 -2 -1 -2 -4\n S 1 -1 1 0 -1 0 0 0 -1 -2 -2 0 -1 -2 -1 4 1 -3 -2 -2 0 0 0 -4\n T 0 -1 0 -1 -1 -1 -1 -2 -2 -1 -1 -1 -1 -2 -1 1 5 -2 -2 0 -1 -1 0 -4\n W -3 -3 -4 -4 -2 -2 -3 -2 -2 -3 -2 -3 -1 1 -4 -3 -2 11 2 -3 -4 -3 -2 -4\n Y -2 -2 -2 -3 -2 -1 -2 -3 2 -1 -1 -2 -1 3 -3 -2 -2 2 7 -1 -3 -2 -1 -4\n V 0 -3 -3 -3 -1 -2 -2 -3 -3 3 1 -2 1 -1 -2 -2 0 -3 -1 4 -3 -2 -1 -4\n B -2 -1 3 4 -3 0 1 -1 0 -3 -4 0 -3 -3 -2 0 -1 -4 -3 -3 4 1 -1 -4\n Z -1 0 0 1 -3 3 4 -2 0 -3 -3 1 -1 -3 -1 0 -1 -3 -2 -2 1 4 -1 -4\n X 0 -1 -1 -1 -2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -2 0 0 -2 -1 -1 -1 -1 -1 -4\n * -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 1\n"; parameters.number_threads = 1; parameters.filter = true; parameters.queries_file_sequence_type_ptr = std::tr1::shared_ptr< SequenceType>(new ProteinType()); parameters.aligning_sequence_type_ptr = std::tr1::shared_ptr<SequenceType>( new ProteinType()); parameters.queries_chunk_size = 1 << 27; ScoreMatrixReader score_matrix_reader; vector<int> matrix; unsigned int number_letters; istringstream default_protein_score_matrix_is(default_protein_matrix); score_matrix_reader.Read(default_protein_score_matrix_is, *(parameters.aligning_sequence_type_ptr), matrix, number_letters); parameters.score_matrix = ScoreMatrix(default_protein_matrix_name, &matrix[0], number_letters); parameters.gap_open = 11; parameters.gap_extension = 1; parameters.number_gpus = -1; parameters.normalized_presearched_ungapped_extension_cutoff = 7.0; parameters.normalized_presearched_gapped_extension_trigger = 22.0; parameters.normalized_presearched_gapped_extension_cutoff = 15.0; parameters.normalized_result_gapped_extension_cutoff = 25.0; parameters.max_number_results = 10; parameters.max_number_one_subject_results = 1; while ((c = getopt(argc, argv, "a:b:d:F:g:h:l:i:o:q:t:v:")) != -1) { switch (c) { case 'a': parameters.number_threads = atoi(optarg); break; case 'b': parameters.max_number_results = atoi(optarg); break; case 'd': database_filename = optarg; break; case 'F': if (optarg[0] == 'T') { parameters.filter = true; } else if (optarg[0] == 'F') { parameters.filter = false; } else { logger->ErrorLog("invalid option, -F is T or F."); return false; } break; case 'g': parameters.number_gpus = atoi(optarg); break; case 'l': parameters.queries_chunk_size = atoi(optarg); break; case 'i': input_filename = optarg; break; case 'o': output_filename = optarg; break; case 'q': if (optarg[0] == 'p') { parameters.queries_file_sequence_type_ptr = std::tr1::shared_ptr<SequenceType>(new ProteinType()); } else if (optarg[0] == 'd') { parameters.queries_file_sequence_type_ptr = std::tr1::shared_ptr<SequenceType>(new DnaType()); } else { logger->ErrorLog("invalid option, -q is p or d."); return false; } break; case 't': if (optarg[0] == 'p') { parameters.aligning_sequence_type_ptr = std::tr1::shared_ptr< SequenceType>(new ProteinType()); } else if (optarg[0] == 'd') { parameters.aligning_sequence_type_ptr = std::tr1::shared_ptr< SequenceType>(new DnaType()); } else { logger->ErrorLog("invalid option, -q is p or d."); return false; } break; case 'v': parameters.max_number_one_subject_results = atoi(optarg); break; default: logger->ErrorLog("\nTry `ghostz --help' for more information."); return false; } } return true; } <commit_msg>add filecheck<commit_after>/* * align_main.cpp * * Created on: 2013/10/24 * Author: shu */ #include "align_main.h" #include <iostream> #include <string> #include <cstring> #include <cstdlib> #include <unistd.h> #include <tr1/memory> #include <sstream> #include <cstdio> #include "protein_type.h" #include "dna_type.h" #include "logger.h" #include "score_matrix_reader.h" #include "reduced_alphabet_file_reader.h" #include "aligner.h" #include "aligner_gpu.h" #include <sys/stat.h> using namespace std; AlignMain::AlignMain() { } AlignMain::~AlignMain() { } int AlignMain::Run(int argc, char* argv[]) { Logger *logger = Logger::GetInstance(); logger->Log("searching..."); AlignerCommon::AligningCommonParameters parameters; string queries_filename; string database_filename; string output_filename; //try { bool ret = BuildParameters(argc, argv, queries_filename, database_filename, output_filename, parameters); if (ret) { {//check query struct stat st; if(stat(queries_filename.c_str(),&st)==-1){ cerr<<"Query file does not exist."<<endl; exit(1); } } {//check database struct stat st; string inf_database= database_filename+".inf"; if(stat(inf_database.c_str(),&st)==-1){ cerr<<"Database file does not exist."<<endl; exit(1); } } #ifndef GPU Aligner aligner; aligner.Align(queries_filename, database_filename, output_filename, parameters); #else if (parameters.number_gpus == 0) { Aligner aligner; aligner.Align(queries_filename, database_filename, output_filename, parameters); } else { AlignerGpu aligner; aligner.Align(queries_filename, database_filename, output_filename, parameters); } #endif logger->Log("finished"); return 0; } /* } catch (exception &e) { logger->ErrorLog(e.what()); }*/ return 1; } bool AlignMain::BuildParameters(int argc, char* argv[], string &input_filename, string &database_filename, string &output_filename, Aligner::AligningParameters &parameters) { int c; extern char *optarg; extern int optind; optind = 1; string score_matrix_filename; Logger *logger = Logger::GetInstance(); const string default_protein_matrix_name = "BLOSUM62"; const string default_protein_matrix = " A R N D C Q E G H I L K M F P S T W Y V B Z X *\nA 4 -1 -2 -2 0 -1 -1 0 -2 -1 -1 -1 -1 -2 -1 1 0 -3 -2 0 -2 -1 0 -4\n R -1 5 0 -2 -3 1 0 -2 0 -3 -2 2 -1 -3 -2 -1 -1 -3 -2 -3 -1 0 -1 -4\n N -2 0 6 1 -3 0 0 0 1 -3 -3 0 -2 -3 -2 1 0 -4 -2 -3 3 0 -1 -4\n D -2 -2 1 6 -3 0 2 -1 -1 -3 -4 -1 -3 -3 -1 0 -1 -4 -3 -3 4 1 -1 -4\n C 0 -3 -3 -3 9 -3 -4 -3 -3 -1 -1 -3 -1 -2 -3 -1 -1 -2 -2 -1 -3 -3 -2 -4\n Q -1 1 0 0 -3 5 2 -2 0 -3 -2 1 0 -3 -1 0 -1 -2 -1 -2 0 3 -1 -4\n E -1 0 0 2 -4 2 5 -2 0 -3 -3 1 -2 -3 -1 0 -1 -3 -2 -2 1 4 -1 -4\n G 0 -2 0 -1 -3 -2 -2 6 -2 -4 -4 -2 -3 -3 -2 0 -2 -2 -3 -3 -1 -2 -1 -4\n H -2 0 1 -1 -3 0 0 -2 8 -3 -3 -1 -2 -1 -2 -1 -2 -2 2 -3 0 0 -1 -4\n I -1 -3 -3 -3 -1 -3 -3 -4 -3 4 2 -3 1 0 -3 -2 -1 -3 -1 3 -3 -3 -1 -4\n L -1 -2 -3 -4 -1 -2 -3 -4 -3 2 4 -2 2 0 -3 -2 -1 -2 -1 1 -4 -3 -1 -4\n K -1 2 0 -1 -3 1 1 -2 -1 -3 -2 5 -1 -3 -1 0 -1 -3 -2 -2 0 1 -1 -4\n M -1 -1 -2 -3 -1 0 -2 -3 -2 1 2 -1 5 0 -2 -1 -1 -1 -1 1 -3 -1 -1 -4\n F -2 -3 -3 -3 -2 -3 -3 -3 -1 0 0 -3 0 6 -4 -2 -2 1 3 -1 -3 -3 -1 -4\n P -1 -2 -2 -1 -3 -1 -1 -2 -2 -3 -3 -1 -2 -4 7 -1 -1 -4 -3 -2 -2 -1 -2 -4\n S 1 -1 1 0 -1 0 0 0 -1 -2 -2 0 -1 -2 -1 4 1 -3 -2 -2 0 0 0 -4\n T 0 -1 0 -1 -1 -1 -1 -2 -2 -1 -1 -1 -1 -2 -1 1 5 -2 -2 0 -1 -1 0 -4\n W -3 -3 -4 -4 -2 -2 -3 -2 -2 -3 -2 -3 -1 1 -4 -3 -2 11 2 -3 -4 -3 -2 -4\n Y -2 -2 -2 -3 -2 -1 -2 -3 2 -1 -1 -2 -1 3 -3 -2 -2 2 7 -1 -3 -2 -1 -4\n V 0 -3 -3 -3 -1 -2 -2 -3 -3 3 1 -2 1 -1 -2 -2 0 -3 -1 4 -3 -2 -1 -4\n B -2 -1 3 4 -3 0 1 -1 0 -3 -4 0 -3 -3 -2 0 -1 -4 -3 -3 4 1 -1 -4\n Z -1 0 0 1 -3 3 4 -2 0 -3 -3 1 -1 -3 -1 0 -1 -3 -2 -2 1 4 -1 -4\n X 0 -1 -1 -1 -2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -2 0 0 -2 -1 -1 -1 -1 -1 -4\n * -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 1\n"; parameters.number_threads = 1; parameters.filter = true; parameters.queries_file_sequence_type_ptr = std::tr1::shared_ptr< SequenceType>(new ProteinType()); parameters.aligning_sequence_type_ptr = std::tr1::shared_ptr<SequenceType>( new ProteinType()); parameters.queries_chunk_size = 1 << 27; ScoreMatrixReader score_matrix_reader; vector<int> matrix; unsigned int number_letters; istringstream default_protein_score_matrix_is(default_protein_matrix); score_matrix_reader.Read(default_protein_score_matrix_is, *(parameters.aligning_sequence_type_ptr), matrix, number_letters); parameters.score_matrix = ScoreMatrix(default_protein_matrix_name, &matrix[0], number_letters); parameters.gap_open = 11; parameters.gap_extension = 1; parameters.number_gpus = -1; parameters.normalized_presearched_ungapped_extension_cutoff = 7.0; parameters.normalized_presearched_gapped_extension_trigger = 22.0; parameters.normalized_presearched_gapped_extension_cutoff = 15.0; parameters.normalized_result_gapped_extension_cutoff = 25.0; parameters.max_number_results = 10; parameters.max_number_one_subject_results = 1; while ((c = getopt(argc, argv, "a:b:d:F:g:h:l:i:o:q:t:v:")) != -1) { switch (c) { case 'a': parameters.number_threads = atoi(optarg); break; case 'b': parameters.max_number_results = atoi(optarg); break; case 'd': database_filename = optarg; break; case 'F': if (optarg[0] == 'T') { parameters.filter = true; } else if (optarg[0] == 'F') { parameters.filter = false; } else { logger->ErrorLog("invalid option, -F is T or F."); return false; } break; case 'g': parameters.number_gpus = atoi(optarg); break; case 'l': parameters.queries_chunk_size = atoi(optarg); break; case 'i': input_filename = optarg; break; case 'o': output_filename = optarg; break; case 'q': if (optarg[0] == 'p') { parameters.queries_file_sequence_type_ptr = std::tr1::shared_ptr<SequenceType>(new ProteinType()); } else if (optarg[0] == 'd') { parameters.queries_file_sequence_type_ptr = std::tr1::shared_ptr<SequenceType>(new DnaType()); } else { logger->ErrorLog("invalid option, -q is p or d."); return false; } break; case 't': if (optarg[0] == 'p') { parameters.aligning_sequence_type_ptr = std::tr1::shared_ptr< SequenceType>(new ProteinType()); } else if (optarg[0] == 'd') { parameters.aligning_sequence_type_ptr = std::tr1::shared_ptr< SequenceType>(new DnaType()); } else { logger->ErrorLog("invalid option, -q is p or d."); return false; } break; case 'v': parameters.max_number_one_subject_results = atoi(optarg); break; default: logger->ErrorLog("\nTry `ghostz --help' for more information."); return false; } } return true; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h" #include "base/rand_util.h" #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #endif #include "chrome/common/chrome_constants.h" namespace browser_sync { static const double kErrorUploadRatio = 0.15; void ChromeReportUnrecoverableError() { // TODO(lipalani): Add this for other platforms as well. #if defined(OS_WIN) // We only want to upload |kErrorUploadRatio| ratio of errors. double random_number = base::RandDouble(); if (random_number > kErrorUploadRatio) return; // Get the breakpad pointer from chrome.exe typedef void (__cdecl *DumpProcessFunction)(); DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>( ::GetProcAddress(::GetModuleHandle( chrome::kBrowserProcessExecutableName), "DumpProcessWithoutCrash")); if (DumpProcess) DumpProcess(); #endif // OS_WIN } } // namespace browser_sync <commit_msg>Stop uploading unrecoverable errors to breakpad in preparation for beta.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h" #include "base/rand_util.h" #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #endif #include "chrome/common/chrome_constants.h" namespace browser_sync { static const double kErrorUploadRatio = 0.0; void ChromeReportUnrecoverableError() { // TODO(lipalani): Add this for other platforms as well. #if defined(OS_WIN) // We only want to upload |kErrorUploadRatio| ratio of errors. if (kErrorUploadRatio <= 0.0) return; // We are not allowed to upload errors. double random_number = base::RandDouble(); if (random_number > kErrorUploadRatio) return; // Get the breakpad pointer from chrome.exe typedef void (__cdecl *DumpProcessFunction)(); DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>( ::GetProcAddress(::GetModuleHandle( chrome::kBrowserProcessExecutableName), "DumpProcessWithoutCrash")); if (DumpProcess) DumpProcess(); #endif // OS_WIN } } // namespace browser_sync <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/options/clear_browser_data_handler.h" #include "base/basictypes.h" #include "base/string16.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" #include "content/common/notification_details.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" #include "ui/base/l10n/l10n_util.h" ClearBrowserDataHandler::ClearBrowserDataHandler() : remover_(NULL) { } ClearBrowserDataHandler::~ClearBrowserDataHandler() { if (remover_) remover_->RemoveObserver(this); } void ClearBrowserDataHandler::Initialize() { clear_plugin_lso_data_enabled_.Init(prefs::kClearPluginLSODataEnabled, g_browser_process->local_state(), NULL); } void ClearBrowserDataHandler::GetLocalizedValues( DictionaryValue* localized_strings) { DCHECK(localized_strings); RegisterTitle(localized_strings, "clearBrowserDataOverlay", IDS_CLEAR_BROWSING_DATA_TITLE); localized_strings->SetString("clearBrowserDataLabel", l10n_util::GetStringUTF16(IDS_CLEAR_BROWSING_DATA_LABEL)); localized_strings->SetString("deleteBrowsingHistoryCheckbox", l10n_util::GetStringUTF16(IDS_DEL_BROWSING_HISTORY_CHKBOX)); localized_strings->SetString("deleteDownloadHistoryCheckbox", l10n_util::GetStringUTF16(IDS_DEL_DOWNLOAD_HISTORY_CHKBOX)); localized_strings->SetString("deleteCacheCheckbox", l10n_util::GetStringUTF16(IDS_DEL_CACHE_CHKBOX)); localized_strings->SetString("deleteCookiesCheckbox", l10n_util::GetStringUTF16(IDS_DEL_COOKIES_CHKBOX)); localized_strings->SetString("deleteCookiesFlashCheckbox", l10n_util::GetStringUTF16(IDS_DEL_COOKIES_FLASH_CHKBOX)); localized_strings->SetString("deletePasswordsCheckbox", l10n_util::GetStringUTF16(IDS_DEL_PASSWORDS_CHKBOX)); localized_strings->SetString("deleteFormDataCheckbox", l10n_util::GetStringUTF16(IDS_DEL_FORM_DATA_CHKBOX)); localized_strings->SetString("clearBrowserDataCommit", l10n_util::GetStringUTF16(IDS_CLEAR_BROWSING_DATA_COMMIT)); localized_strings->SetString("flashStorageSettings", l10n_util::GetStringUTF16(IDS_FLASH_STORAGE_SETTINGS)); localized_strings->SetString("flash_storage_url", l10n_util::GetStringUTF16(IDS_FLASH_STORAGE_URL)); localized_strings->SetString("clearDataDeleting", l10n_util::GetStringUTF16(IDS_CLEAR_DATA_DELETING)); ListValue* time_list = new ListValue; for (int i = 0; i < 5; i++) { string16 label_string; switch (i) { case 0: label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_HOUR); break; case 1: label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_DAY); break; case 2: label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_WEEK); break; case 3: label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_4WEEKS); break; case 4: label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_EVERYTHING); break; } ListValue* option = new ListValue(); option->Append(Value::CreateIntegerValue(i)); option->Append(Value::CreateStringValue(label_string)); time_list->Append(option); } localized_strings->Set("clearBrowserDataTimeList", time_list); } void ClearBrowserDataHandler::RegisterMessages() { // Setup handlers specific to this panel. DCHECK(web_ui_); web_ui_->RegisterMessageCallback("performClearBrowserData", NewCallback(this, &ClearBrowserDataHandler::HandleClearBrowserData)); } void ClearBrowserDataHandler::HandleClearBrowserData(const ListValue* value) { Profile* profile = web_ui_->GetProfile(); PrefService* prefs = profile->GetPrefs(); int remove_mask = 0; if (prefs->GetBoolean(prefs::kDeleteBrowsingHistory)) remove_mask |= BrowsingDataRemover::REMOVE_HISTORY; if (prefs->GetBoolean(prefs::kDeleteDownloadHistory)) remove_mask |= BrowsingDataRemover::REMOVE_DOWNLOADS; if (prefs->GetBoolean(prefs::kDeleteCache)) remove_mask |= BrowsingDataRemover::REMOVE_CACHE; if (prefs->GetBoolean(prefs::kDeleteCookies)) { remove_mask |= BrowsingDataRemover::REMOVE_COOKIES; if (*clear_plugin_lso_data_enabled_) remove_mask |= BrowsingDataRemover::REMOVE_LSO_DATA; } if (prefs->GetBoolean(prefs::kDeletePasswords)) remove_mask |= BrowsingDataRemover::REMOVE_PASSWORDS; if (prefs->GetBoolean(prefs::kDeleteFormData)) remove_mask |= BrowsingDataRemover::REMOVE_FORM_DATA; int period_selected = prefs->GetInteger(prefs::kDeleteTimePeriod); FundamentalValue state(true); web_ui_->CallJavascriptFunction("ClearBrowserDataOverlay.setClearingState", state); // If we are still observing a previous data remover, we need to stop // observing. if (remover_) remover_->RemoveObserver(this); // BrowsingDataRemover deletes itself when done. remover_ = new BrowsingDataRemover(profile, static_cast<BrowsingDataRemover::TimePeriod>(period_selected), base::Time()); remover_->AddObserver(this); remover_->Remove(remove_mask); } void ClearBrowserDataHandler::OnBrowsingDataRemoverDone() { // No need to remove ourselves as an observer as BrowsingDataRemover deletes // itself after we return. remover_ = NULL; DCHECK(web_ui_); web_ui_->CallJavascriptFunction("ClearBrowserDataOverlay.doneClearing"); } <commit_msg>webui/options: More localized string declaration cleanup.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/options/clear_browser_data_handler.h" #include "base/basictypes.h" #include "base/string16.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" #include "content/common/notification_details.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" #include "ui/base/l10n/l10n_util.h" ClearBrowserDataHandler::ClearBrowserDataHandler() : remover_(NULL) { } ClearBrowserDataHandler::~ClearBrowserDataHandler() { if (remover_) remover_->RemoveObserver(this); } void ClearBrowserDataHandler::Initialize() { clear_plugin_lso_data_enabled_.Init(prefs::kClearPluginLSODataEnabled, g_browser_process->local_state(), NULL); } void ClearBrowserDataHandler::GetLocalizedValues( DictionaryValue* localized_strings) { DCHECK(localized_strings); static OptionsStringResource resources[] = { { "clearBrowserDataLabel", IDS_CLEAR_BROWSING_DATA_LABEL }, { "deleteBrowsingHistoryCheckbox", IDS_DEL_BROWSING_HISTORY_CHKBOX }, { "deleteDownloadHistoryCheckbox", IDS_DEL_DOWNLOAD_HISTORY_CHKBOX }, { "deleteCacheCheckbox", IDS_DEL_CACHE_CHKBOX }, { "deleteCookiesCheckbox", IDS_DEL_COOKIES_CHKBOX }, { "deleteCookiesFlashCheckbox", IDS_DEL_COOKIES_FLASH_CHKBOX }, { "deletePasswordsCheckbox", IDS_DEL_PASSWORDS_CHKBOX }, { "deleteFormDataCheckbox", IDS_DEL_FORM_DATA_CHKBOX }, { "clearBrowserDataCommit", IDS_CLEAR_BROWSING_DATA_COMMIT }, { "flashStorageSettings", IDS_FLASH_STORAGE_SETTINGS }, { "flash_storage_url", IDS_FLASH_STORAGE_URL }, { "clearDataDeleting", IDS_CLEAR_DATA_DELETING }, }; RegisterStrings(localized_strings, resources, arraysize(resources)); RegisterTitle(localized_strings, "clearBrowserDataOverlay", IDS_CLEAR_BROWSING_DATA_TITLE); ListValue* time_list = new ListValue; for (int i = 0; i < 5; i++) { string16 label_string; switch (i) { case 0: label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_HOUR); break; case 1: label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_DAY); break; case 2: label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_WEEK); break; case 3: label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_4WEEKS); break; case 4: label_string = l10n_util::GetStringUTF16(IDS_CLEAR_DATA_EVERYTHING); break; } ListValue* option = new ListValue(); option->Append(Value::CreateIntegerValue(i)); option->Append(Value::CreateStringValue(label_string)); time_list->Append(option); } localized_strings->Set("clearBrowserDataTimeList", time_list); } void ClearBrowserDataHandler::RegisterMessages() { // Setup handlers specific to this panel. DCHECK(web_ui_); web_ui_->RegisterMessageCallback("performClearBrowserData", NewCallback(this, &ClearBrowserDataHandler::HandleClearBrowserData)); } void ClearBrowserDataHandler::HandleClearBrowserData(const ListValue* value) { Profile* profile = web_ui_->GetProfile(); PrefService* prefs = profile->GetPrefs(); int remove_mask = 0; if (prefs->GetBoolean(prefs::kDeleteBrowsingHistory)) remove_mask |= BrowsingDataRemover::REMOVE_HISTORY; if (prefs->GetBoolean(prefs::kDeleteDownloadHistory)) remove_mask |= BrowsingDataRemover::REMOVE_DOWNLOADS; if (prefs->GetBoolean(prefs::kDeleteCache)) remove_mask |= BrowsingDataRemover::REMOVE_CACHE; if (prefs->GetBoolean(prefs::kDeleteCookies)) { remove_mask |= BrowsingDataRemover::REMOVE_COOKIES; if (*clear_plugin_lso_data_enabled_) remove_mask |= BrowsingDataRemover::REMOVE_LSO_DATA; } if (prefs->GetBoolean(prefs::kDeletePasswords)) remove_mask |= BrowsingDataRemover::REMOVE_PASSWORDS; if (prefs->GetBoolean(prefs::kDeleteFormData)) remove_mask |= BrowsingDataRemover::REMOVE_FORM_DATA; int period_selected = prefs->GetInteger(prefs::kDeleteTimePeriod); FundamentalValue state(true); web_ui_->CallJavascriptFunction("ClearBrowserDataOverlay.setClearingState", state); // If we are still observing a previous data remover, we need to stop // observing. if (remover_) remover_->RemoveObserver(this); // BrowsingDataRemover deletes itself when done. remover_ = new BrowsingDataRemover(profile, static_cast<BrowsingDataRemover::TimePeriod>(period_selected), base::Time()); remover_->AddObserver(this); remover_->Remove(remove_mask); } void ClearBrowserDataHandler::OnBrowsingDataRemoverDone() { // No need to remove ourselves as an observer as BrowsingDataRemover deletes // itself after we return. remover_ = NULL; DCHECK(web_ui_); web_ui_->CallJavascriptFunction("ClearBrowserDataOverlay.doneClearing"); } <|endoftext|>
<commit_before>/* * Copyright (c) 2017 Immo Software * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o 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. * * o Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "sampler_voice.h" #include "reader_thread.h" #include "ui.h" #include "debug_log.h" // #include "utility.h" #include "itm_trace.h" #include <algorithm> using namespace slab; //------------------------------------------------------------------------------ // Definitions //------------------------------------------------------------------------------ //! Number of samples to fade in when we can't find a zero crossing. const uint32_t kFadeInSampleCount = 128; //------------------------------------------------------------------------------ // Code //------------------------------------------------------------------------------ SampleBufferManager::SampleBufferManager() : _number(0), _fullBuffers(), _emptyBuffers(), _primeMutex(), _currentBuffer(nullptr), _activeBufferCount(0), _totalSamples(0), _startSample(0), _samplesPlayed(0), _samplesRead(0), _samplesQueued(0), _didReadFileStart(false), _waitingForFileStart(true), _isReady(false), _snapToZeroStart(false), _preppedCount(0) { } void SampleBufferManager::init(SamplerVoice * voice, int16_t * buffer) { _voice = voice; _number = voice->get_number(); _primeMutex.init("prime"); // Init invariant buffer fields. uint32_t i; for (i = 0; i < kVoiceBufferCount; ++i) { _buffer[i].number = i; _buffer[i].dataWithInterpolationFrames = &buffer[i * (kVoiceBufferSize + SampleBuffer::kInterpolationFrameCount)]; _buffer[i].data = _buffer[i].dataWithInterpolationFrames + SampleBuffer::kInterpolationFrameCount; } set_file(0); } //! @brief Reset all buffers to unused. void SampleBufferManager::_reset_buffers() { uint32_t i; for (i = 0; i < kVoiceBufferCount; ++i) { _buffer[i].set_unused(); } } void SampleBufferManager::set_file(uint32_t totalFrames) { _startSample = 0; _totalSamples = totalFrames; _endSample = totalFrames; _activeBufferCount = min(round_up_div(_totalSamples, kVoiceBufferSize), kVoiceBufferCount); _currentBuffer = nullptr; _samplesPlayed = 0; _samplesRead = 0; _samplesQueued = 0; _didReadFileStart = false; _waitingForFileStart = true; _isReady = false; _snapToZeroStart = false; _preppedCount = 0; _reset_buffers(); // Go ahead and prime. prime(); } void SampleBufferManager::prime() { Ar::Mutex::Guard guard(_primeMutex); DEBUG_PRINTF(QUEUE_MASK, "V%lu: start prime\r\n", _number); // Reset state. _samplesPlayed = _startSample; _samplesRead = _didReadFileStart ? min(_startSample + kVoiceBufferSize, _totalSamples) : _startSample; _samplesQueued = _samplesRead; // Clear buffers queues. ReaderThread::get().clear_voice_queue(_voice); _fullBuffers.clear(); _emptyBuffers.clear(); // Playing will start from the file start buffer. if (_activeBufferCount && _didReadFileStart) { _currentBuffer = &_buffer[0]; _currentBuffer->state = SampleBuffer::State::kPlaying; } else { _currentBuffer = nullptr; } // Queue up the rest of the available buffers to be filled. uint32_t i = _didReadFileStart ? 1 : 0; for (; i < _activeBufferCount; ++i) { // If the buffer is currently being filled by the reader thread, then we can't touch // it. So just flag it for requeuing when it's finished. This will be handled in // enqueue_full_buffer(). if (_buffer[i].state == SampleBuffer::State::kReading) { DEBUG_PRINTF(QUEUE_MASK, "V%lu: prime: marking b%lu for reread\r\n", _number, i); _buffer[i].reread = true; } else { DEBUG_PRINTF(QUEUE_MASK, "V%lu: prime: queuing b%lu for read\r\n", _number, i); _queue_buffer_for_read(&_buffer[i]); } } DEBUG_PRINTF(QUEUE_MASK, "V%lu: end prime\r\n", _number); #if ENABLE_TRACE _trace_buffers(); #endif } SampleBuffer * SampleBufferManager::get_current_buffer() { if (!_currentBuffer) { _currentBuffer = _dequeue_next_buffer(); } return _currentBuffer; } void SampleBufferManager::_queue_buffer_for_read(SampleBuffer * buffer) { buffer->startFrame = _samplesQueued; buffer->frameCount = min(kVoiceBufferSize, _endSample - _samplesQueued); buffer->reread = false; buffer->state = SampleBuffer::State::kFree; _emptyBuffers.put(buffer); _samplesQueued += buffer->frameCount; ReaderThread::get().enqueue(_voice); #if ENABLE_TRACE _trace_buffers(); #endif } SampleBuffer * SampleBufferManager::get_empty_buffer() { Ar::Mutex::Guard guard(_primeMutex); SampleBuffer * buffer; if (_emptyBuffers.get(buffer)) { assert(buffer->state == SampleBuffer::State::kFree); buffer->state = SampleBuffer::State::kReading; return buffer; } else { return nullptr; } } void SampleBufferManager::retire_buffer(SampleBuffer * buffer) { Ar::Mutex::Guard guard(_primeMutex); assert(buffer->state == SampleBuffer::State::kPlaying); _samplesPlayed += buffer->frameCount; buffer->state = (buffer->number == 0) ? SampleBuffer::State::kReady : SampleBuffer::State::kFree; if (_samplesPlayed >= _endSample) { DEBUG_PRINTF(RETIRE_MASK, "V%lu: retiring b%d; played %lu (done)\r\n", _number, buffer->number, _samplesPlayed); _voice->playing_did_finish(); } else { DEBUG_PRINTF(RETIRE_MASK, "V%lu: retiring b%d; played %lu\r\n", _number, buffer->number, _samplesPlayed); // Don't queue up file start buffer for reading, and don't queue more than the active // number of samples. if (buffer->number != 0 && _samplesQueued < _endSample) { DEBUG_PRINTF(RETIRE_MASK|QUEUE_MASK, "V%lu: retire: queue b%d to read @ %lu\r\n", _number, buffer->number, _samplesPlayed); _queue_buffer_for_read(buffer); } _dequeue_next_buffer(); } #if ENABLE_TRACE _trace_buffers(); #endif } SampleBuffer * SampleBufferManager::_dequeue_next_buffer() { Ar::Mutex::Guard guard(_primeMutex); SampleBuffer * buffer; if (_fullBuffers.get(buffer)) { assert(buffer->state == SampleBuffer::State::kReady); DEBUG_PRINTF(CURBUF_MASK, "V%lu: current buffer = %d\r\n", _number, buffer->number); _currentBuffer = buffer; buffer->state = SampleBuffer::State::kPlaying; } else { DEBUG_PRINTF(ERROR_MASK, "V%lu: *** NO READY BUFFERS ***\r\n", _number); // Ar::_halt(); _currentBuffer = nullptr; UI::get().indicate_voice_underflowed(_number); } #if ENABLE_TRACE _trace_buffers(); #endif return _currentBuffer; } //! @todo clean up void SampleBufferManager::enqueue_full_buffer(SampleBuffer * buffer) { Ar::Mutex::Guard guard(_primeMutex); assert(buffer); bool isBuffer0 = (buffer->number == 0); bool isOutOfOrder = (buffer->startFrame != _samplesRead); if (buffer->reread || isOutOfOrder) { assert(!(isOutOfOrder && !isBuffer0 && !buffer->reread)); DEBUG_PRINTF(QUEUE_MASK, "V%lu: queuing b%d for reread\r\n", _number, buffer->number); if (isBuffer0) { // If the file start buffer has to be reread, just do another prime. Need to // set the buffer state to ready so prime doesn't cause another reread. buffer->state = SampleBuffer::State::kReady; _didReadFileStart = false; prime(); } else { // Queue up this buffer to be re-read instead of putting it in the full buffers queue. // This call will set the buffer state appropriately. _queue_buffer_for_read(buffer); } } else { _samplesRead += buffer->frameCount; buffer->state = SampleBuffer::State::kReady; buffer->zeroSnapOffset = 0; // Clear interpolation frames. The renderer will copy interpolation frames between buffers. std::fill_n(buffer->dataWithInterpolationFrames, SampleBuffer::kInterpolationFrameCount, 0); DEBUG_PRINTF(QUEUE_MASK, "V%lu: queuing b%d for play\r\n", _number, buffer->number); _fullBuffers.put(buffer); #if ENABLE_TRACE _trace_buffers(); #endif if (isBuffer0) { _didReadFileStart = true; if (_snapToZeroStart) { _find_zero_crossing(buffer); } } // Wait until we get a full set of buffers before allowing play to start. if (_waitingForFileStart && isBuffer0)// && (++_preppedCount >= _activeBufferCount)) { _waitingForFileStart = false; _isReady = true; _voice->manager_ready_did_change(true); } } } //! Finds the first zero crossing, meaning positive to negative or vice versa, or //! an actual zero sample. If the sample is not zero, it sets the prior sample //! to zero. The zero sample position is set in the buffer's zeroSnapOffset member. //! //! @note The buffer must have a frame count of at least 2, or this method will do nothing. void SampleBufferManager::_find_zero_crossing(SampleBuffer * buffer) { if (buffer->frameCount < 2) { return; } uint32_t i; int16_t previousSample = buffer->data[0]; int16_t * sample = &buffer->data[1]; for (i = 1; i < buffer->frameCount; ++i, ++sample) { int16_t thisSample = *sample; if ((thisSample <= 0 && previousSample >= 0) || (thisSample >= 0 && previousSample <= 0)) { if (i > 0) { buffer->data[i - 1] = 0; buffer->zeroSnapOffset = i - 1; } else { *sample = 0; buffer->zeroSnapOffset = i; } return; } previousSample = thisSample; } // Failed to find a zero crossing, so apply a fade in. sample = &buffer->data[0]; uint32_t fadeCount = min(buffer->frameCount, kFadeInSampleCount); for (i = 0; i < fadeCount; ++i, ++sample) { *sample = static_cast<int16_t>(static_cast<int32_t>(*sample) * i / fadeCount); } } void SampleBufferManager::set_start_end_sample(int32_t start, int32_t end) { // Voice must not be playing. assert(!_voice->is_playing()); // Handle sentinels to use current values. uint32_t ustart = (start == -1L) ? _startSample : start; uint32_t uend = (end == -1L) ? _endSample : end; DEBUG_PRINTF(MISC_MASK, "set_start_end: %lu - %lu\r\n", ustart, uend); uint32_t originalStart = _startSample; uint32_t originalEnd = _endSample; // Update parameters. _startSample = constrained(ustart, 0UL, _totalSamples); _endSample = constrained(uend, ustart, _totalSamples); // Update number of used buffers. _activeBufferCount = min(round_up_div(get_active_samples(), kVoiceBufferSize), kVoiceBufferCount); // Set any unused buffers to kUnused state. uint32_t i; for (i = _activeBufferCount; i < kVoiceBufferCount; ++i) { _buffer[i].set_unused(); } // Reload start of the file if the start or end point changed. if (_startSample != originalStart || _endSample != originalEnd) { _isReady = false; _voice->manager_ready_did_change(false); _didReadFileStart = false; _waitingForFileStart = true; _snapToZeroStart = (_startSample != 0); _preppedCount = 0; prime(); } } uint32_t SampleBufferManager::get_buffered_samples() const { uint32_t count = 0; uint32_t i; for (i = 0; i < _fullBuffers.get_count(); ++i) { SampleBuffer * buf = _fullBuffers[i]; count += buf->frameCount; } return count; } void SampleBufferManager::_trace_buffers() { // Event structure: // [15:14] = 2-bit channel number // [13:7] = free buffer count // [6:0] = ready buffer count itm<kBufferCountChannel, uint16_t>::send((_number << 14) | ((_emptyBuffers.get_count() && 0x7f) << 7) | (_fullBuffers.get_count() & 0x7f)); } //------------------------------------------------------------------------------ // EOF //------------------------------------------------------------------------------ <commit_msg>Removed unused include from sample_buffer_manager.cpp.<commit_after>/* * Copyright (c) 2017 Immo Software * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o 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. * * o Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "sampler_voice.h" #include "reader_thread.h" #include "ui.h" #include "debug_log.h" #include "itm_trace.h" #include <algorithm> using namespace slab; //------------------------------------------------------------------------------ // Definitions //------------------------------------------------------------------------------ //! Number of samples to fade in when we can't find a zero crossing. const uint32_t kFadeInSampleCount = 128; //------------------------------------------------------------------------------ // Code //------------------------------------------------------------------------------ SampleBufferManager::SampleBufferManager() : _number(0), _fullBuffers(), _emptyBuffers(), _primeMutex(), _currentBuffer(nullptr), _activeBufferCount(0), _totalSamples(0), _startSample(0), _samplesPlayed(0), _samplesRead(0), _samplesQueued(0), _didReadFileStart(false), _waitingForFileStart(true), _isReady(false), _snapToZeroStart(false), _preppedCount(0) { } void SampleBufferManager::init(SamplerVoice * voice, int16_t * buffer) { _voice = voice; _number = voice->get_number(); _primeMutex.init("prime"); // Init invariant buffer fields. uint32_t i; for (i = 0; i < kVoiceBufferCount; ++i) { _buffer[i].number = i; _buffer[i].dataWithInterpolationFrames = &buffer[i * (kVoiceBufferSize + SampleBuffer::kInterpolationFrameCount)]; _buffer[i].data = _buffer[i].dataWithInterpolationFrames + SampleBuffer::kInterpolationFrameCount; } set_file(0); } //! @brief Reset all buffers to unused. void SampleBufferManager::_reset_buffers() { uint32_t i; for (i = 0; i < kVoiceBufferCount; ++i) { _buffer[i].set_unused(); } } void SampleBufferManager::set_file(uint32_t totalFrames) { _startSample = 0; _totalSamples = totalFrames; _endSample = totalFrames; _activeBufferCount = min(round_up_div(_totalSamples, kVoiceBufferSize), kVoiceBufferCount); _currentBuffer = nullptr; _samplesPlayed = 0; _samplesRead = 0; _samplesQueued = 0; _didReadFileStart = false; _waitingForFileStart = true; _isReady = false; _snapToZeroStart = false; _preppedCount = 0; _reset_buffers(); // Go ahead and prime. prime(); } void SampleBufferManager::prime() { Ar::Mutex::Guard guard(_primeMutex); DEBUG_PRINTF(QUEUE_MASK, "V%lu: start prime\r\n", _number); // Reset state. _samplesPlayed = _startSample; _samplesRead = _didReadFileStart ? min(_startSample + kVoiceBufferSize, _totalSamples) : _startSample; _samplesQueued = _samplesRead; // Clear buffers queues. ReaderThread::get().clear_voice_queue(_voice); _fullBuffers.clear(); _emptyBuffers.clear(); // Playing will start from the file start buffer. if (_activeBufferCount && _didReadFileStart) { _currentBuffer = &_buffer[0]; _currentBuffer->state = SampleBuffer::State::kPlaying; } else { _currentBuffer = nullptr; } // Queue up the rest of the available buffers to be filled. uint32_t i = _didReadFileStart ? 1 : 0; for (; i < _activeBufferCount; ++i) { // If the buffer is currently being filled by the reader thread, then we can't touch // it. So just flag it for requeuing when it's finished. This will be handled in // enqueue_full_buffer(). if (_buffer[i].state == SampleBuffer::State::kReading) { DEBUG_PRINTF(QUEUE_MASK, "V%lu: prime: marking b%lu for reread\r\n", _number, i); _buffer[i].reread = true; } else { DEBUG_PRINTF(QUEUE_MASK, "V%lu: prime: queuing b%lu for read\r\n", _number, i); _queue_buffer_for_read(&_buffer[i]); } } DEBUG_PRINTF(QUEUE_MASK, "V%lu: end prime\r\n", _number); #if ENABLE_TRACE _trace_buffers(); #endif } SampleBuffer * SampleBufferManager::get_current_buffer() { if (!_currentBuffer) { _currentBuffer = _dequeue_next_buffer(); } return _currentBuffer; } void SampleBufferManager::_queue_buffer_for_read(SampleBuffer * buffer) { buffer->startFrame = _samplesQueued; buffer->frameCount = min(kVoiceBufferSize, _endSample - _samplesQueued); buffer->reread = false; buffer->state = SampleBuffer::State::kFree; _emptyBuffers.put(buffer); _samplesQueued += buffer->frameCount; ReaderThread::get().enqueue(_voice); #if ENABLE_TRACE _trace_buffers(); #endif } SampleBuffer * SampleBufferManager::get_empty_buffer() { Ar::Mutex::Guard guard(_primeMutex); SampleBuffer * buffer; if (_emptyBuffers.get(buffer)) { assert(buffer->state == SampleBuffer::State::kFree); buffer->state = SampleBuffer::State::kReading; return buffer; } else { return nullptr; } } void SampleBufferManager::retire_buffer(SampleBuffer * buffer) { Ar::Mutex::Guard guard(_primeMutex); assert(buffer->state == SampleBuffer::State::kPlaying); _samplesPlayed += buffer->frameCount; buffer->state = (buffer->number == 0) ? SampleBuffer::State::kReady : SampleBuffer::State::kFree; if (_samplesPlayed >= _endSample) { DEBUG_PRINTF(RETIRE_MASK, "V%lu: retiring b%d; played %lu (done)\r\n", _number, buffer->number, _samplesPlayed); _voice->playing_did_finish(); } else { DEBUG_PRINTF(RETIRE_MASK, "V%lu: retiring b%d; played %lu\r\n", _number, buffer->number, _samplesPlayed); // Don't queue up file start buffer for reading, and don't queue more than the active // number of samples. if (buffer->number != 0 && _samplesQueued < _endSample) { DEBUG_PRINTF(RETIRE_MASK|QUEUE_MASK, "V%lu: retire: queue b%d to read @ %lu\r\n", _number, buffer->number, _samplesPlayed); _queue_buffer_for_read(buffer); } _dequeue_next_buffer(); } #if ENABLE_TRACE _trace_buffers(); #endif } SampleBuffer * SampleBufferManager::_dequeue_next_buffer() { Ar::Mutex::Guard guard(_primeMutex); SampleBuffer * buffer; if (_fullBuffers.get(buffer)) { assert(buffer->state == SampleBuffer::State::kReady); DEBUG_PRINTF(CURBUF_MASK, "V%lu: current buffer = %d\r\n", _number, buffer->number); _currentBuffer = buffer; buffer->state = SampleBuffer::State::kPlaying; } else { DEBUG_PRINTF(ERROR_MASK, "V%lu: *** NO READY BUFFERS ***\r\n", _number); // Ar::_halt(); _currentBuffer = nullptr; UI::get().indicate_voice_underflowed(_number); } #if ENABLE_TRACE _trace_buffers(); #endif return _currentBuffer; } //! @todo clean up void SampleBufferManager::enqueue_full_buffer(SampleBuffer * buffer) { Ar::Mutex::Guard guard(_primeMutex); assert(buffer); bool isBuffer0 = (buffer->number == 0); bool isOutOfOrder = (buffer->startFrame != _samplesRead); if (buffer->reread || isOutOfOrder) { assert(!(isOutOfOrder && !isBuffer0 && !buffer->reread)); DEBUG_PRINTF(QUEUE_MASK, "V%lu: queuing b%d for reread\r\n", _number, buffer->number); if (isBuffer0) { // If the file start buffer has to be reread, just do another prime. Need to // set the buffer state to ready so prime doesn't cause another reread. buffer->state = SampleBuffer::State::kReady; _didReadFileStart = false; prime(); } else { // Queue up this buffer to be re-read instead of putting it in the full buffers queue. // This call will set the buffer state appropriately. _queue_buffer_for_read(buffer); } } else { _samplesRead += buffer->frameCount; buffer->state = SampleBuffer::State::kReady; buffer->zeroSnapOffset = 0; // Clear interpolation frames. The renderer will copy interpolation frames between buffers. std::fill_n(buffer->dataWithInterpolationFrames, SampleBuffer::kInterpolationFrameCount, 0); DEBUG_PRINTF(QUEUE_MASK, "V%lu: queuing b%d for play\r\n", _number, buffer->number); _fullBuffers.put(buffer); #if ENABLE_TRACE _trace_buffers(); #endif if (isBuffer0) { _didReadFileStart = true; if (_snapToZeroStart) { _find_zero_crossing(buffer); } } // Wait until we get a full set of buffers before allowing play to start. if (_waitingForFileStart && isBuffer0)// && (++_preppedCount >= _activeBufferCount)) { _waitingForFileStart = false; _isReady = true; _voice->manager_ready_did_change(true); } } } //! Finds the first zero crossing, meaning positive to negative or vice versa, or //! an actual zero sample. If the sample is not zero, it sets the prior sample //! to zero. The zero sample position is set in the buffer's zeroSnapOffset member. //! //! @note The buffer must have a frame count of at least 2, or this method will do nothing. void SampleBufferManager::_find_zero_crossing(SampleBuffer * buffer) { if (buffer->frameCount < 2) { return; } uint32_t i; int16_t previousSample = buffer->data[0]; int16_t * sample = &buffer->data[1]; for (i = 1; i < buffer->frameCount; ++i, ++sample) { int16_t thisSample = *sample; if ((thisSample <= 0 && previousSample >= 0) || (thisSample >= 0 && previousSample <= 0)) { if (i > 0) { buffer->data[i - 1] = 0; buffer->zeroSnapOffset = i - 1; } else { *sample = 0; buffer->zeroSnapOffset = i; } return; } previousSample = thisSample; } // Failed to find a zero crossing, so apply a fade in. sample = &buffer->data[0]; uint32_t fadeCount = min(buffer->frameCount, kFadeInSampleCount); for (i = 0; i < fadeCount; ++i, ++sample) { *sample = static_cast<int16_t>(static_cast<int32_t>(*sample) * i / fadeCount); } } void SampleBufferManager::set_start_end_sample(int32_t start, int32_t end) { // Voice must not be playing. assert(!_voice->is_playing()); // Handle sentinels to use current values. uint32_t ustart = (start == -1L) ? _startSample : start; uint32_t uend = (end == -1L) ? _endSample : end; DEBUG_PRINTF(MISC_MASK, "set_start_end: %lu - %lu\r\n", ustart, uend); uint32_t originalStart = _startSample; uint32_t originalEnd = _endSample; // Update parameters. _startSample = constrained(ustart, 0UL, _totalSamples); _endSample = constrained(uend, ustart, _totalSamples); // Update number of used buffers. _activeBufferCount = min(round_up_div(get_active_samples(), kVoiceBufferSize), kVoiceBufferCount); // Set any unused buffers to kUnused state. uint32_t i; for (i = _activeBufferCount; i < kVoiceBufferCount; ++i) { _buffer[i].set_unused(); } // Reload start of the file if the start or end point changed. if (_startSample != originalStart || _endSample != originalEnd) { _isReady = false; _voice->manager_ready_did_change(false); _didReadFileStart = false; _waitingForFileStart = true; _snapToZeroStart = (_startSample != 0); _preppedCount = 0; prime(); } } uint32_t SampleBufferManager::get_buffered_samples() const { uint32_t count = 0; uint32_t i; for (i = 0; i < _fullBuffers.get_count(); ++i) { SampleBuffer * buf = _fullBuffers[i]; count += buf->frameCount; } return count; } void SampleBufferManager::_trace_buffers() { // Event structure: // [15:14] = 2-bit channel number // [13:7] = free buffer count // [6:0] = ready buffer count itm<kBufferCountChannel, uint16_t>::send((_number << 14) | ((_emptyBuffers.get_count() && 0x7f) << 7) | (_fullBuffers.get_count() & 0x7f)); } //------------------------------------------------------------------------------ // EOF //------------------------------------------------------------------------------ <|endoftext|>
<commit_before>// Loosely based on https://repo.anl-external.org/repos/BlueTBB/tbb30_104oss/src/rml/perfor/tbb_simple.cpp // #include "stdafx.h" // int _tmain(int argc, _TCHAR* argv[]) // { // return 0; // } #include "tbb/task_group.h" #include <iostream> #include <stdio.h> //// MOVE TO iostreams TODO #include <stdlib.h> #include <tbb/mutex.h> tbb::mutex my_mutex; #if _WIN32||_WIN64 #include <Windows.h> /* Sleep */ #else //// #error Only tested on Windows! TODO #include <unistd.h> /* usleep */ #endif using namespace tbb; #if 0 // totally inappropriate and broken use of subclassing of tbb::task, just for giggles // see https://www.threadingbuildingblocks.org/docs/help/reference/task_scheduler/task_cls.htm #include "tbb/task.h" class TrivialTask : public tbb::task { public: TrivialTask() { } task* parent() const { // the "parent" member-function is confusingly referred to as "the successor attribute" return NULL; } task* execute() override { puts("Hello from my task!"); return NULL; } ~TrivialTask() { puts("Destroying my task"); } }; // allocate_continuation // #include <stdio.h> // #include <stdlib.h> int main(int argc, char *argv[]) { // use TBB's custom allocator, along the lines shown in // https://www.threadingbuildingblocks.org/docs/help/tbb_userguide/Simple_Example_Fibonacci_Numbers.htm#tutorial_Simple_Example_Fibonacci_Numbers // see also https://www.threadingbuildingblocks.org/docs/help/reference/task_scheduler/task_allocation.htm { // looking at task_allocation.htm this should use: // "cancellation group is the current innermost cancellation group. " ////// WHICH WE DON'T HAVE!?!?! shouldn't this cause an assert failure? task& t = *new(task::allocate_root()) TrivialTask; // following http://fulla.fnal.gov/intel/tbb/html/a00249.html auto count1 = t.ref_count(); t.execute(); // No concurrency! Hence 'totally inappropriate' // t.decrement_ref_count(); causes underflow! //if ( NULL != t.parent ) { //} // "Because there is no placement delete expression[...]" https://en.wikipedia.org/w/index.php?title=Placement_syntax&oldid=674756226#Custom_allocators // not using standard 'new' so can't use standard 'delete' //delete (task::allocate_root()) &t; // kaboom! VS2010 picks up a double-free problem. Looks like we're missing something important....???? auto count2 = t.ref_count(); t.decrement_ref_count(); // same as t.set_ref_count(0); } return EXIT_SUCCESS; } #endif #if 0 int main(int argc, char *argv[]) { puts("Starting..."); task_group g; g.run([&] {Sleep(2000); puts("Task 1 is away"); }); g.run([&] {Sleep(2000); puts("Task 2 is away"); }); g.run([&] {Sleep(2000); puts("Task 3 is away"); }); g.run_and_wait([&] {Sleep(2000); puts("A message from the main thread"); }); //////g.wait(); // getchar(); return EXIT_SUCCESS; } #endif // demonstrate the const issue with run_and_wait #if 0 int main(int argc, char *argv[]) { puts("Starting main thread..."); class MyCallable { public: MyCallable() {} // clang++ doesn't like 'const' instance of empty class without explicitly defined constructor // Normally, using an empty class we avoid having to define our own default constructor // (even if MSVC is permissive here) see http://stackoverflow.com/a/8092791/2307853 // int dummy; void operator()() const { puts("Task is running"); } }; const MyCallable f; { task_group g; // g.run( f ); g.wait(); g.run_and_wait( f ); // g.run_and_wait( [&]() { f(); } ); // g.run_and_wait( [&]() { } ); // C++ lambdas seem to survive the const shenanigans, but MyCallable doesn't: build error } puts("Press Enter to exit"); getchar(); return EXIT_SUCCESS; } #endif #if 1 // fun with the idea of futures // #include "tbb/atomic.h" // Faking/implementing futures with TBB tasks // Note that mutable state is held in its own struct, // as TBB's run(1) function accepts its arg by const reference, // forcing us to handle mutation via a pointer to a mutable value // and not within the MyFuture class itself. int main(int argc, char *argv[]) { puts("Starting..."); class MyFuture { public: struct MutableState { MutableState(int r) : result(r) { } int result; }; task_group * tgPtr; MutableState * msPtr; MyFuture(task_group *t, MutableState * m) : tgPtr(t), msPtr(m) { } void operator()() const { puts("Task is running"); msPtr->result = 3; return; } int getResult() const { tgPtr->wait(); return msPtr->result; } }; int modifyMe = 0; MyFuture::MutableState ms(0); task_group g; const MyFuture f(&g, &ms); // g.run(f); g.wait(); //g.run_and_wait(f); // this doesn't work! VS2010 compiler complains of type trouble. seems to cast from const& to & // what's going on here? curiously the arg is *not* the same type as that of the "run" member-function !!! g.run_and_wait( [&](){f();} ); // yes, this craziness *is* necessary! printf( "%d\n", f.getResult() ); //g.wait(); // Do nothing. Idempotency of waiting. //g.wait(); //g.run( [&]{Sleep(2000);puts("Task 1 is away");} ); //g.run( [&]{Sleep(2000);puts("Task 2 is away");} ); //g.run( [&]{Sleep(2000);puts("Task 3 is away");} ); //g.run_and_wait( [&]{Sleep(2000); puts("A message from the main thread");} ); //////g.wait(); // getchar(); return EXIT_SUCCESS; } #endif #if 0 // the fib example from the web int fib(int n) { int ret; if (n < 2) { ret = n; } else { int x, y; task_group g; x = y = 9; // g.run( [&]{my_mutex.lock();/* x=fib(n-1); */ puts("Now:\n"); getchar(); my_mutex.unlock();} ); // spawn a task g.run([&] { tbb::mutex::scoped_lock lock(my_mutex); /* x=fib(n-1); */ puts("Now:\n"); getchar(); }); // spawn a task // g.run( [&]{my_mutex.lock();/* y=fib(n-2); */ puts("Now:\n"); getchar(); my_mutex.unlock();} ); // spawn another task g.run([&] { tbb::mutex::scoped_lock lock(my_mutex);/* y=fib(n-2); */ puts("Now:\n"); getchar(); }); // spawn another task g.wait(); // wait for both tasks to complete ret = x + y; } return ret; } // - See more at: https://www.threadingbuildingblocks.org/tutorial-intel-tbb-task-based-programming#sthash.EzgRXzaB.dpuf int main(int argc, char *argv[]) { std::cout << fib(33); // getchar(); return EXIT_SUCCESS; } #endif <commit_msg>Fix up the sleeping code<commit_after>// Loosely based on https://repo.anl-external.org/repos/BlueTBB/tbb30_104oss/src/rml/perfor/tbb_simple.cpp // #include "stdafx.h" // int _tmain(int argc, _TCHAR* argv[]) // { // return 0; // } #include "tbb/task_group.h" #include <iostream> #include <stdio.h> //// MOVE TO iostreams TODO #include <stdlib.h> //#include <chrono> // for 2s to mean 2 seconds //using namespace std::literals::chrono_literals; // as above //#include <thread> // for std::this_thread::sleep_for(1); #include <tbb/mutex.h> #include <tbb/tbb_thread.h> // tbb::mutex my_mutex; #if _WIN32||_WIN64 //#include <Windows.h> /* Sleep */ #else //// #error Only tested on Windows! TODO // #include <unistd.h> /* usleep */ #endif using namespace tbb; #if 0 // totally inappropriate and broken use of subclassing of tbb::task, just for giggles // see https://www.threadingbuildingblocks.org/docs/help/reference/task_scheduler/task_cls.htm #include "tbb/task.h" class TrivialTask : public tbb::task { public: TrivialTask() { } task* parent() const { // the "parent" member-function is confusingly referred to as "the successor attribute" return NULL; } task* execute() override { puts("Hello from my task!"); return NULL; } ~TrivialTask() { puts("Destroying my task"); } }; // allocate_continuation // #include <stdio.h> // #include <stdlib.h> int main(int argc, char *argv[]) { // use TBB's custom allocator, along the lines shown in // https://www.threadingbuildingblocks.org/docs/help/tbb_userguide/Simple_Example_Fibonacci_Numbers.htm#tutorial_Simple_Example_Fibonacci_Numbers // see also https://www.threadingbuildingblocks.org/docs/help/reference/task_scheduler/task_allocation.htm { // looking at task_allocation.htm this should use: // "cancellation group is the current innermost cancellation group. " ////// WHICH WE DON'T HAVE!?!?! shouldn't this cause an assert failure? task& t = *new(task::allocate_root()) TrivialTask; // following http://fulla.fnal.gov/intel/tbb/html/a00249.html auto count1 = t.ref_count(); t.execute(); // No concurrency! Hence 'totally inappropriate' // t.decrement_ref_count(); causes underflow! //if ( NULL != t.parent ) { //} // "Because there is no placement delete expression[...]" https://en.wikipedia.org/w/index.php?title=Placement_syntax&oldid=674756226#Custom_allocators // not using standard 'new' so can't use standard 'delete' //delete (task::allocate_root()) &t; // kaboom! VS2010 picks up a double-free problem. Looks like we're missing something important....???? auto count2 = t.ref_count(); t.decrement_ref_count(); // same as t.set_ref_count(0); } return EXIT_SUCCESS; } #endif #if 0 int main(int argc, char *argv[]) { puts("Starting..."); task_group g; g.run([&] {Sleep(2000); puts("Task 1 is away"); }); g.run([&] {Sleep(2000); puts("Task 2 is away"); }); g.run([&] {Sleep(2000); puts("Task 3 is away"); }); g.run_and_wait([&] {Sleep(2000); puts("A message from the main thread"); }); //////g.wait(); // getchar(); return EXIT_SUCCESS; } #endif // demonstrate the const issue with run_and_wait #if 0 int main(int argc, char *argv[]) { puts("Starting main thread..."); class MyCallable { public: MyCallable() {} // clang++ doesn't like 'const' instance of empty class without explicitly defined constructor // Normally, using an empty class we avoid having to define our own default constructor // (even if MSVC is permissive here) see http://stackoverflow.com/a/8092791/2307853 // int dummy; void operator()() const { puts("Task is running"); } }; const MyCallable f; { task_group g; // g.run( f ); g.wait(); g.run_and_wait( f ); // g.run_and_wait( [&]() { f(); } ); // g.run_and_wait( [&]() { } ); // C++ lambdas seem to survive the const shenanigans, but MyCallable doesn't: build error } puts("Press Enter to exit"); getchar(); return EXIT_SUCCESS; } #endif #if 1 // fun with the idea of futures // #include "tbb/atomic.h" // Faking/implementing futures with TBB tasks // Note that mutable state is held in its own struct, // as TBB's run(1) function accepts its arg by const reference, // forcing us to handle mutation via a pointer to a mutable value // and not within the MyFuture class itself. // we use TBB's 'sleep' functionality, to avoid C++14 dependency const tbb::tick_count::interval_t oneSecond(1.0); // double holds the number of seconds const tbb::tick_count::interval_t threeSeconds(3.0); const tbb::tick_count::interval_t tenSeconds(10.0); int main(int argc, char *argv[]) { puts("Starting..."); class MyFuture { public: struct MutableState { MutableState(int r) : result(r) { } int result; }; task_group * tgPtr; MutableState * msPtr; MyFuture(task_group *t, MutableState * m) : tgPtr(t), msPtr(m) { } void operator()() const { puts("[from task] Task is running. Now for the pause..."); // this_tbb_thread::sleep( threeSeconds ); this_tbb_thread::sleep( tenSeconds ); puts("[from task] Task pause complete, assigning output..."); msPtr->result = 3; return; } int getResult() const { tgPtr->wait(); return msPtr->result; } }; int modifyMe = 0; MyFuture::MutableState ms(0); task_group g; const MyFuture f(&g, &ms); // g.run_and_wait( [&](){f();} ); puts("Now to run"); g.run(f); puts("Running. Now to do a couple of prints with a pause between each."); this_tbb_thread::sleep( oneSecond ); puts("And here we are after a second"); this_tbb_thread::sleep( oneSecond ); puts("And here we are after another second"); this_tbb_thread::sleep( oneSecond ); puts("And here we are after yet another second"); this_tbb_thread::sleep( oneSecond ); puts("And here we are after yet another second"); puts("And now to wait..."); g.wait(); printf( "%d\n", f.getResult() ); //g.run( [&]{Sleep(2000);puts("Task 1 is away");} ); //g.run( [&]{Sleep(2000);puts("Task 2 is away");} ); //g.run( [&]{Sleep(2000);puts("Task 3 is away");} ); //g.run_and_wait( [&]{Sleep(2000); puts("A message from the main thread");} ); //////g.wait(); // getchar(); return EXIT_SUCCESS; } #endif #if 0 // the fib example from the web int fib(int n) { int ret; if (n < 2) { ret = n; } else { int x, y; task_group g; x = y = 9; // g.run( [&]{my_mutex.lock();/* x=fib(n-1); */ puts("Now:\n"); getchar(); my_mutex.unlock();} ); // spawn a task g.run([&] { tbb::mutex::scoped_lock lock(my_mutex); /* x=fib(n-1); */ puts("Now:\n"); getchar(); }); // spawn a task // g.run( [&]{my_mutex.lock();/* y=fib(n-2); */ puts("Now:\n"); getchar(); my_mutex.unlock();} ); // spawn another task g.run([&] { tbb::mutex::scoped_lock lock(my_mutex);/* y=fib(n-2); */ puts("Now:\n"); getchar(); }); // spawn another task g.wait(); // wait for both tasks to complete ret = x + y; } return ret; } // - See more at: https://www.threadingbuildingblocks.org/tutorial-intel-tbb-task-based-programming#sthash.EzgRXzaB.dpuf int main(int argc, char *argv[]) { std::cout << fib(33); // getchar(); return EXIT_SUCCESS; } #endif <|endoftext|>
<commit_before> /** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under both the Apache 2.0 license (found in the * LICENSE file in the root directory of this source tree) and the GPLv2 (found * in the COPYING file in the root directory of this source tree). * You may select, at your option, one of the above-listed licenses. */ // Sanity check integration test for file // Spec file: specs/utility/file.table #include <osquery/tests/integration/tables/helper.h> namespace osquery { class file : public IntegrationTableTest {}; TEST_F(file, test_sanity) { // 1. Query data // QueryData data = execute_query("select * from file"); // 2. Check size before validation // ASSERT_GE(data.size(), 0ul); // ASSERT_EQ(data.size(), 1ul); // ASSERT_EQ(data.size(), 0ul); // 3. Build validation map // See IntegrationTableTest.cpp for avaialbe flags // Or use custom DataCheck object // ValidatatioMap row_map = { // {"path", NormalType} // {"directory", NormalType} // {"filename", NormalType} // {"inode", IntType} // {"uid", IntType} // {"gid", IntType} // {"mode", NormalType} // {"device", IntType} // {"size", IntType} // {"block_size", IntType} // {"atime", IntType} // {"mtime", IntType} // {"ctime", IntType} // {"btime", IntType} // {"hard_links", IntType} // {"symlink", IntType} // {"type", NormalType} // {"attributes", NormalType} // {"volume_serial", NormalType} // {"file_id", NormalType} //} // 4. Perform validation // validate_rows(data, row_map); } } // namespace osquery <commit_msg>[Table sanity check] file (#5126)<commit_after> /** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under both the Apache 2.0 license (found in the * LICENSE file in the root directory of this source tree) and the GPLv2 (found * in the COPYING file in the root directory of this source tree). * You may select, at your option, one of the above-listed licenses. */ // Sanity check integration test for file // Spec file: specs/utility/file.table #include <fstream> #include <osquery/tests/integration/tables/helper.h> #include <boost/filesystem.hpp> namespace osquery { class FileTests : public IntegrationTableTest { public: boost::filesystem::path filepath; virtual void SetUp() { auto directory = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("test-integration-file-table.%%%%-%%%%"); ASSERT_TRUE(boost::filesystem::create_directory(directory)); filepath = directory / boost::filesystem::path("file-table-test.txt"); { auto fout = std::ofstream(filepath.native(), std::ios::out); fout.open(filepath.string(), std::ios::out); fout << "test"; } } virtual void TearDown() { boost::filesystem::remove_all(filepath.parent_path()); } }; TEST_F(FileTests, test_sanity) { QueryData data = execute_query( "select * from file where path like \"" + (filepath.parent_path() / boost::filesystem::path("%.txt")).string() + "\""); EXPECT_EQ(data.size(), 1ul); ValidatatioMap row_map = {{"path", FileOnDisk}, {"directory", DirectoryOnDisk}, {"filename", NonEmptyString}, {"inode", IntType}, {"uid", NonNegativeInt}, {"gid", NonNegativeInt}, {"mode", NormalType}, {"device", IntType}, {"size", NonNegativeInt}, {"block_size", NonNegativeInt}, {"atime", NonNegativeInt}, {"mtime", NonNegativeInt}, {"ctime", NonNegativeInt}, {"btime", NonNegativeInt}, {"hard_links", IntType}, {"symlink", IntType}, {"type", NonEmptyString}}; #ifdef WIN32 row_map["attributes"] = NormalType; row_map["volume_serial"] = NormalType; row_map["file_id"] = NormalType; #endif validate_rows(data, row_map); ASSERT_EQ(data[0]["path"], filepath.string()); ASSERT_EQ(data[0]["directory"], filepath.parent_path().string()); ASSERT_EQ(data[0]["filename"], filepath.filename().string()); } } // namespace osquery <|endoftext|>
<commit_before>#include "TestBase.h" #include "gameworld/types/ClassRegistry.h" #include "gameworld/types/Dispatcher.h" #include "mgen/serialization/VectorInputStream.h" #include "mgen/serialization/VectorOutputStream.h" #include "mgen/serialization/JsonWriter.h" #include "mgen/serialization/JsonReader.h" ///////////////////////////////////////////////////////////////////// using namespace gameworld::types; using namespace gameworld::types::basemodule1; using mgen::VectorOutputStream; using mgen::VectorInputStream; using mgen::JsonWriter; using mgen::JsonReader; using mgen::VectorOutputStream; using gameworld::types::ClassRegistry; BEGIN_TEST_GROUP(WhitepaperExample) ///////////////////////////////////////////////////////////////////// BEGIN_TEST("Example1") // Create some objects and set some fields on these. We can use // generated setter-functions or constructors Car car1, car2; car1.setBrand("Ford").setTopSpeed(321); car2.setBrand("BMW").setTopSpeed(123); Car car3(100, "Volvo"); Car car4(123, "Mercedes"); // Create a class registry. This object is immutable and thread safe, // so you could have one global instance if you wanted to for your // entire application ClassRegistry classRegistry; // We will serialize our objects to this buffer... std::vector<char> buffer; // ...by wrapping it in an mgen compatible output stream. // MGen readers an writers expect data sinks and sources ("streams") // with a data read/write API similar to berkeley sockets: // read(char* trg, const int n) // write(const char* src, const int n) VectorOutputStream out(buffer); // Now we're ready to create a serializer/writer JsonWriter<VectorOutputStream, ClassRegistry> writer(out, classRegistry); // Write the objects a few times writer.writeObject(car1); writer.writeObject(car2); writer.writeObject(car3); writer.writeObject(car4); // -- Imagine some code here shuffling objects -- // -- around, to disk or over network -- // Then create an mgen compatible InputStream around your data source VectorInputStream in(buffer); // And create a deserializer/reader JsonReader<VectorInputStream, ClassRegistry> reader(in, classRegistry); // Now we have some options on how we wan't to read them back. // If we don't know at all what kind of objects to expect we // should read to heap memory mgen::MGenBase * object = reader.readObject(); // But if we do know what do expect, we can let the reader // provide the correct directly Car * carBack = reader.readObject<Car>(); // We could also read it back to a base type pointer like // and identify the specific type later Vehicle * anyVehicle = reader.readObject<Vehicle>(); // Now if we're heap-allergic we could also just read it back to the stack // But that will discard any potential subtype information Car stackCar = reader.readStatic<Car>(); END_TEST ///////////////////////////////////////////////////////////////////// static int s_nCars = 0; static int s_nVehicles = 0; static int s_nEntities = 0; BEGIN_TEST("Dispatch/Handler") // Create some test objects to dispatch Car car(123, "Ford"); Vehicle vehicle(321); Item item; // Define a custom handler class // that exdends the generated Handler class class MyHandler: public Handler { public: void handle(Car& car) { s_nCars++; } void handle(Vehicle& car) { s_nVehicles++; } void handle(Entity& entity) { s_nEntities++; } }; // Instantiate a handler and dispatch // some objects to it MyHandler handler; dispatch(car, handler); dispatch(vehicle, handler); dispatch(item, handler); ASSERT(s_nCars == 1); ASSERT(s_nVehicles == 1); ASSERT(s_nEntities == 1); END_TEST ///////////////////////////////////////////////////////////////////// END_TEST_GROUP <commit_msg>Update WhitepaperExample.cpp<commit_after>#include "TestBase.h" #include "gameworld/types/ClassRegistry.h" #include "gameworld/types/Dispatcher.h" #include "mgen/serialization/VectorInputStream.h" #include "mgen/serialization/VectorOutputStream.h" #include "mgen/serialization/JsonWriter.h" #include "mgen/serialization/JsonReader.h" ///////////////////////////////////////////////////////////////////// using namespace gameworld::types; using namespace gameworld::types::basemodule1; using mgen::VectorOutputStream; using mgen::VectorInputStream; using mgen::JsonWriter; using mgen::JsonReader; using mgen::VectorOutputStream; using gameworld::types::ClassRegistry; BEGIN_TEST_GROUP(WhitepaperExample) ///////////////////////////////////////////////////////////////////// BEGIN_TEST("Example1") // Create some objects and set some fields on these. We can use // generated setter-functions or constructors Car car1, car2; car1.setBrand("Ford").setTopSpeed(321); car2.setBrand("BMW").setTopSpeed(123); Car car3(100, "Volvo"); Car car4(123, "Mercedes"); // Create a class registry. This object is immutable and thread safe, // so you could have one global instance if you wanted to for your // entire application ClassRegistry classRegistry; // We will serialize our objects to this buffer... std::vector<char> buffer; // ...by wrapping it in an mgen compatible output stream. // MGen readers an writers expect data sinks and sources ("streams") // with a data read/write API similar to berkeley sockets: // read(char* trg, const int n) // write(const char* src, const int n) VectorOutputStream out(buffer); // Now we're ready to create a serializer/writer JsonWriter<VectorOutputStream, ClassRegistry> writer(out, classRegistry); // Write the objects a few times writer.writeObject(car1); writer.writeObject(car2); writer.writeObject(car3); writer.writeObject(car4); // -- Imagine some code here shuffling objects -- // -- around, to disk or over network -- // Then create an mgen compatible InputStream around your data source VectorInputStream in(buffer); // And create a deserializer/reader JsonReader<VectorInputStream, ClassRegistry> reader(in, classRegistry); // Now we have some options on how we wan't to read them back. // If we don't know at all what kind of objects to expect we // should read to heap memory mgen::MGenBase * object = reader.readObject(); // But if we do know what do expect, we can let the reader // provide the correct directly Car * carBack = reader.readObject<Car>(); // We could also read it back to a base type pointer like // and identify the specific type later Vehicle * anyVehicle = reader.readObject<Vehicle>(); // Now if we're heap-allergic we could also just read it back to the stack // But that will discard any potential subtype information Car stackCar = reader.readStatic<Car>(); END_TEST ///////////////////////////////////////////////////////////////////// static int s_nCars = 0; static int s_nVehicles = 0; static int s_nEntities = 0; BEGIN_TEST("Dispatch/Handler") // Create some test objects to dispatch Car car(123, "Ford"); Vehicle vehicle(321); Item item; // Define a custom handler class // that exdends the generated Handler class class MyHandler: public Handler { public: void handle(Car& car) { s_nCars++; } void handle(Vehicle& car) { s_nVehicles++; } void handle(Entity& entity) { s_nEntities++; } }; // Instantiate a handler and dispatch // some objects to it MyHandler handler; dispatch(car, handler); dispatch(vehicle, handler); dispatch(item, handler); ASSERT(s_nCars == 1); ASSERT(s_nVehicles == 1); ASSERT(s_nEntities == 1); END_TEST ///////////////////////////////////////////////////////////////////// END_TEST_GROUP <|endoftext|>
<commit_before> #include "SiconosKernel.hpp" #include "adjointInput.hpp" #include "myDS.h" #include <stdio.h> #include <stdlib.h> using namespace std; /************************************************************/ /************************************************************/ /************************************************************/ /*call back for the source*/ /*call back for the formulation with inversion*/ //void (bLDS) (double t, unsigned int N, double* b, unsigned int z, double*zz){ //} /************************************************************/ /************************************************************/ /************************************************************/ /************************************************************/ /*main program*/ static int sNSLawSize = 2; int main() { int cmp = 0; /************************************************************/ /************************************************************/ int dimX = 4; SP::SiconosVector x0(new SiconosVector(dimX)); //Point de départ hors arc singulier x0->setValue(0, 3.4999939172); x0->setValue(1, -2.2788416237); x0->setValue(2, 1.1935988302); x0->setValue(3, -0.6365413023); double sT = 10; double sStep = 2e-3; unsigned int NBStep = floor(sT / sStep); //NBStep =2; // NBStep = 3; //*****BUILD THE DYNAMIC SYSTEM SP::MyDS aDS ; aDS.reset(new MyDS(x0)); //******BUILD THE RELATION SP::adjointInput aR; aR.reset(new adjointInput()); int sN = 2; //*****BUILD THE NSLAW SP::NonSmoothLaw aNSL; aNSL.reset(new ComplementarityConditionNSL(sN)); //****BUILD THE INTERACTION SP::Interaction aI(new Interaction(aNSL, aR)); //****BUILD THE SYSTEM SP::Model aM(new Model(0, sT)); aM->nonSmoothDynamicalSystem()->insertDynamicalSystem(aDS); aM->nonSmoothDynamicalSystem()->link(aI,aDS); SP::TimeDiscretisation aTD(new TimeDiscretisation(0, sStep)); SP::TimeStepping aS(new TimeStepping(aTD)); aS->setComputeResiduY(true); aS->setComputeResiduR(true); aS->setUseRelativeConvergenceCriteron(false); //*****BUILD THE STEP INTEGRATOR SP::OneStepIntegrator aEulerMoreauOSI ; aEulerMoreauOSI.reset(new EulerMoreauOSI(0.5)); aS->insertIntegrator(aEulerMoreauOSI); //**** BUILD THE STEP NS PROBLEM SP::LCP aLCP ; aLCP.reset(new LCP(SICONOS_LCP_ENUM)); // aLCP.reset(new LCP(SICONOS_LCP_NEWTONFB)); aS->insertNonSmoothProblem(aLCP); aM->setSimulation(aS); aM->initialize(); numerics_set_verbose(0); SP::SiconosVector x = aDS->x(); SP::SiconosVector y = aI->y(0); SP::SiconosVector lambda = aI->lambda(0); unsigned int outputSize = 9; // number of required data SimpleMatrix dataPlot(NBStep+10, outputSize); SP::SiconosVector z = aDS->x(); SP::SiconosVector lambdaOut = aI->lambda(0); SP::SiconosVector yOut = aI->y(0); dataPlot(0, 0) = aM->t0(); // Initial time of the model dataPlot(0, 1) = (*z)(0); dataPlot(0, 2) = (*z)(1); dataPlot(0, 3) = (*z)(2); dataPlot(0, 4) = (*z)(3); dataPlot(0, 5) = (*lambdaOut)(0); dataPlot(0, 6) = (*lambdaOut)(1); dataPlot(0, 7) = (*yOut)(0); dataPlot(0, 8) = (*yOut)(1); // do simulation while events remains in the "future events" list of events manager. cout << " ==== Start of simulation : " << NBStep << " steps====" << endl; boost::progress_display show_progress(NBStep); boost::timer time; time.restart(); unsigned int k = 0; while (aS->hasNextEvent()) { k++; // if (cmp==150) // numerics_set_verbose(à); // else if (cmp==151) numerics_set_verbose(1); ++show_progress; cmp++; // solve ... // aS->computeOneStep(); aS->newtonSolve(1.1e-11, 50); x = aDS->x(); lambda = aI->lambda(0); dataPlot(k, 0) = aS->nextTime(); // Initial time of the model dataPlot(k, 1) = (*x)(0); dataPlot(k, 2) = (*x)(1); dataPlot(k, 3) = (*x)(2); dataPlot(k, 4) = (*x)(3); dataPlot(k, 5) = (*lambda)(0); dataPlot(k, 6) = (*lambda)(1); dataPlot(k, 7) = (*yOut)(0); dataPlot(k, 8) = (*yOut)(1); aS->nextStep(); } cout << "===== End of simulation. ==== " << endl; dataPlot.resize(k+1, 9); // --- Output files --- cout << "====> Output file writing ..." << endl; ioMatrix::write("OptimalControl.dat", "ascii", dataPlot, "noDim"); std::cout << "Comparison with a reference file: " ; SimpleMatrix dataPlotRef(dataPlot); dataPlotRef.zero(); ioMatrix::read("OptimalControl.ref", "ascii", dataPlotRef); std::cout << "error="<< (dataPlot-dataPlotRef).normInf() <<std::endl; if ((dataPlot - dataPlotRef).normInf() > 5e-11) { std::cout << "Warning. The results is rather different from the reference file." << std::endl; return 1; } return 0; } <commit_msg>[examples] OptimalControl.cpp: add missing header for numerics_set_verbose<commit_after> #include "numerics_verbose.h" #include "SiconosKernel.hpp" #include "adjointInput.hpp" #include "myDS.h" #include <stdio.h> #include <stdlib.h> using namespace std; /************************************************************/ /************************************************************/ /************************************************************/ /*call back for the source*/ /*call back for the formulation with inversion*/ //void (bLDS) (double t, unsigned int N, double* b, unsigned int z, double*zz){ //} /************************************************************/ /************************************************************/ /************************************************************/ /************************************************************/ /*main program*/ static int sNSLawSize = 2; int main() { int cmp = 0; /************************************************************/ /************************************************************/ int dimX = 4; SP::SiconosVector x0(new SiconosVector(dimX)); //Point de départ hors arc singulier x0->setValue(0, 3.4999939172); x0->setValue(1, -2.2788416237); x0->setValue(2, 1.1935988302); x0->setValue(3, -0.6365413023); double sT = 10; double sStep = 2e-3; unsigned int NBStep = floor(sT / sStep); //NBStep =2; // NBStep = 3; //*****BUILD THE DYNAMIC SYSTEM SP::MyDS aDS ; aDS.reset(new MyDS(x0)); //******BUILD THE RELATION SP::adjointInput aR; aR.reset(new adjointInput()); int sN = 2; //*****BUILD THE NSLAW SP::NonSmoothLaw aNSL; aNSL.reset(new ComplementarityConditionNSL(sN)); //****BUILD THE INTERACTION SP::Interaction aI(new Interaction(aNSL, aR)); //****BUILD THE SYSTEM SP::Model aM(new Model(0, sT)); aM->nonSmoothDynamicalSystem()->insertDynamicalSystem(aDS); aM->nonSmoothDynamicalSystem()->link(aI,aDS); SP::TimeDiscretisation aTD(new TimeDiscretisation(0, sStep)); SP::TimeStepping aS(new TimeStepping(aTD)); aS->setComputeResiduY(true); aS->setComputeResiduR(true); aS->setUseRelativeConvergenceCriteron(false); //*****BUILD THE STEP INTEGRATOR SP::OneStepIntegrator aEulerMoreauOSI ; aEulerMoreauOSI.reset(new EulerMoreauOSI(0.5)); aS->insertIntegrator(aEulerMoreauOSI); //**** BUILD THE STEP NS PROBLEM SP::LCP aLCP ; aLCP.reset(new LCP(SICONOS_LCP_ENUM)); // aLCP.reset(new LCP(SICONOS_LCP_NEWTONFB)); aS->insertNonSmoothProblem(aLCP); aM->setSimulation(aS); aM->initialize(); numerics_set_verbose(0); SP::SiconosVector x = aDS->x(); SP::SiconosVector y = aI->y(0); SP::SiconosVector lambda = aI->lambda(0); unsigned int outputSize = 9; // number of required data SimpleMatrix dataPlot(NBStep+10, outputSize); SP::SiconosVector z = aDS->x(); SP::SiconosVector lambdaOut = aI->lambda(0); SP::SiconosVector yOut = aI->y(0); dataPlot(0, 0) = aM->t0(); // Initial time of the model dataPlot(0, 1) = (*z)(0); dataPlot(0, 2) = (*z)(1); dataPlot(0, 3) = (*z)(2); dataPlot(0, 4) = (*z)(3); dataPlot(0, 5) = (*lambdaOut)(0); dataPlot(0, 6) = (*lambdaOut)(1); dataPlot(0, 7) = (*yOut)(0); dataPlot(0, 8) = (*yOut)(1); // do simulation while events remains in the "future events" list of events manager. cout << " ==== Start of simulation : " << NBStep << " steps====" << endl; boost::progress_display show_progress(NBStep); boost::timer time; time.restart(); unsigned int k = 0; while (aS->hasNextEvent()) { k++; // if (cmp==150) // numerics_set_verbose(à); // else if (cmp==151) numerics_set_verbose(1); ++show_progress; cmp++; // solve ... // aS->computeOneStep(); aS->newtonSolve(1.1e-11, 50); x = aDS->x(); lambda = aI->lambda(0); dataPlot(k, 0) = aS->nextTime(); // Initial time of the model dataPlot(k, 1) = (*x)(0); dataPlot(k, 2) = (*x)(1); dataPlot(k, 3) = (*x)(2); dataPlot(k, 4) = (*x)(3); dataPlot(k, 5) = (*lambda)(0); dataPlot(k, 6) = (*lambda)(1); dataPlot(k, 7) = (*yOut)(0); dataPlot(k, 8) = (*yOut)(1); aS->nextStep(); } cout << "===== End of simulation. ==== " << endl; dataPlot.resize(k+1, 9); // --- Output files --- cout << "====> Output file writing ..." << endl; ioMatrix::write("OptimalControl.dat", "ascii", dataPlot, "noDim"); std::cout << "Comparison with a reference file: " ; SimpleMatrix dataPlotRef(dataPlot); dataPlotRef.zero(); ioMatrix::read("OptimalControl.ref", "ascii", dataPlotRef); std::cout << "error="<< (dataPlot-dataPlotRef).normInf() <<std::endl; if ((dataPlot - dataPlotRef).normInf() > 5e-11) { std::cout << "Warning. The results is rather different from the reference file." << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "Wind_API.h" #include "util.h" #include "kdb+.util/util.h" #include "kdb+.util/multilang.h" #include "kdb+.util/type_convert.h" #include <iostream> WIND_API K K_DECL Wind_login(K username, K password) { std::wstring uid, pwd; try { uid = q::q2WString(username); pwd = q::q2WString(password); } catch (std::string const& error) { return q::error2q(error); } ::WQAUTH_INFO login = { true }; std::wmemset(login.strUserName, L'\0', _countof(login.strUserName)); std::wmemset(login.strPassword, L'\0', _countof(login.strPassword)); static_assert(std::is_same<std::wstring::value_type, TCHAR>::value, "UNICODE/_UNICODE not defined"); if (uid.size() >= _countof(login.strUserName)) return q::error2q("username too long"); if (pwd.size() >= _countof(login.strPassword)) return q::error2q("password too long"); # ifdef _MSC_VER ::wcsncpy_s(login.strUserName, uid.c_str(), uid.size()); ::wcsncpy_s(login.strPassword, pwd.c_str(), pwd.size()); # else std::wcsncpy(login.strUserName, uid.c_str(), uid.size()); std::wcsncpy(login.strPassword, pwd.c_str(), pwd.size()); # endif ::WQErr const error = ::WDataAuthorize(&login); if (error == WQERR_OK) { std::string const u = ml::convert(q::DEFAULT_CP, uid.c_str()); std::cerr << "<Wind> logged in as " << u << std::endl; return ks(const_cast<S>(u.c_str())); } else { return q::error2q(Wind::util::error2Text(error)); } } WIND_API K K_DECL Wind_logout(K _) { ::WQErr const error = ::WDataAuthQuit(); return (error == WQERR_OK) ? K_NIL : q::error2q(Wind::util::error2Text(error)); }<commit_msg>Added debug statements for WDataAuthorize invocation, which can crash at times...<commit_after>#include "stdafx.h" #include "Wind_API.h" #include "util.h" #include "kdb+.util/util.h" #include "kdb+.util/multilang.h" #include "kdb+.util/type_convert.h" #include <iostream> WIND_API K K_DECL Wind_login(K username, K password) { std::wstring uid, pwd; try { uid = q::q2WString(username); pwd = q::q2WString(password); } catch (std::string const& error) { return q::error2q(error); } ::WQAUTH_INFO login = { true }; std::wmemset(login.strUserName, L'\0', _countof(login.strUserName)); std::wmemset(login.strPassword, L'\0', _countof(login.strPassword)); static_assert(std::is_same<std::wstring::value_type, TCHAR>::value, "UNICODE/_UNICODE not defined"); if (uid.size() >= _countof(login.strUserName)) return q::error2q("username too long"); if (pwd.size() >= _countof(login.strPassword)) return q::error2q("password too long"); # ifdef _MSC_VER ::wcsncpy_s(login.strUserName, uid.c_str(), uid.size()); ::wcsncpy_s(login.strPassword, pwd.c_str(), pwd.size()); # else std::wcsncpy(login.strUserName, uid.c_str(), uid.size()); std::wcsncpy(login.strPassword, pwd.c_str(), pwd.size()); # endif # ifndef NDEBUG std::cerr << ">>> WDataAuthorize({\"" << login.strUserName << "\", \"" << login.strPassword << "\"})" << std::endl; # endif ::WQErr const error = ::WDataAuthorize(&login); # ifndef NDEBUG std::cerr << "<<< WDataAuthorize = " << error << std::endl; # endif if (error == WQERR_OK) { std::string const u = ml::convert(q::DEFAULT_CP, uid.c_str()); std::cerr << "<Wind> logged in as " << u << std::endl; return ks(const_cast<S>(u.c_str())); } else { return q::error2q(Wind::util::error2Text(error)); } } WIND_API K K_DECL Wind_logout(K _) { ::WQErr const error = ::WDataAuthQuit(); return (error == WQERR_OK) ? K_NIL : q::error2q(Wind::util::error2Text(error)); }<|endoftext|>
<commit_before>#include "spt.h" template <class T> static Mat resample_unsort_(Mat &sind, Mat &img) { Mat newimg; int i, j, k; int32_t *sp; T *ip; CV_Assert(sind.type() == CV_32SC1); CV_Assert(img.channels() == 1); newimg = Mat::zeros(img.rows, img.cols, img.type()); sp = (int32_t*)sind.data; ip = (T*)img.data; k = 0; for(i = 0; i < newimg.rows; i++){ for(j = 0; j < newimg.cols; j++){ newimg.at<T>(sp[k], j) = ip[k]; k++; } } return newimg; } // Returns the unsorted image of the sorted image img. // Sind is the image of sort indices. static Mat resample_unsort(Mat &sind, Mat &img) { switch(img.type()){ default: eprintf("unsupported type %s\n", type2str(img.type())); break; case CV_8UC1: return resample_unsort_<uchar>(sind, img); break; case CV_32FC1: return resample_unsort_<float>(sind, img); break; case CV_64FC1: return resample_unsort_<double>(sind, img); break; } // not reached return Mat(); } template <class T> static Mat resample_sort_(Mat &sind, Mat &img) { Mat newimg; int i, j, k; int32_t *sp; T *np; CV_Assert(sind.type() == CV_32SC1); CV_Assert(img.channels() == 1); newimg = Mat::zeros(img.rows, img.cols, img.type()); sp = (int*)sind.data; np = (T*)newimg.data; k = 0; for(i = 0; i < newimg.rows; i++){ for(j = 0; j < newimg.cols; j++){ np[k] = img.at<T>(sp[k], j); k++; } } return newimg; } // Returns the sorted image of the unsorted image img. // Sind is the image of sort indices. static Mat resample_sort(Mat &sind, Mat &img) { switch(img.type()){ default: eprintf("unsupported type %s\n", type2str(img.type())); break; case CV_8UC1: return resample_sort_<uchar>(sind, img); break; case CV_32FC1: return resample_sort_<float>(sind, img); break; case CV_64FC1: return resample_sort_<double>(sind, img); break; } // not reached return Mat(); } // Returns the average of 3 pixels. static double avg3(double a, double b, double c) { if(isnan(b)) return NAN; if(isnan(a) || isnan(c)) return b; return (a+b+c)/3.0; } // Returns the average filter of image 'in' with a window of 3x1 // where sorted order is not the same as the original order. // Sind is the sort indices giving the sort order. static Mat avgfilter3(Mat &in, Mat &sind) { Mat out; int i, j, rows, cols, *sindp; float *ip, *op; CV_Assert(in.type() == CV_32FC1); CV_Assert(sind.type() == CV_32SC1); rows = in.rows; cols = in.cols; out.create(rows, cols, CV_32FC1); in.row(0).copyTo(out.row(0)); in.row(rows-1).copyTo(out.row(rows-1)); for(i = 1; i < rows-1; i++){ ip = in.ptr<float>(i); op = out.ptr<float>(i); sindp = sind.ptr<int>(i); for(j = 0; j < cols; j++){ if(sindp[j] != i) op[j] = avg3(ip[j-cols], ip[j], ip[j+cols]); else op[j] = ip[j]; } } return out; } // Interpolate the missing values in image simg and returns the result. // Slat is the latitude image, and slandmask is the land mask image. // All input arguments must already be sorted. static Mat resample_interp(Mat &simg, Mat &slat, Mat &slandmask) { int i, j, k, nbuf, *buf; Mat newimg, bufmat; double x, llat, rlat, lval, rval; CV_Assert(simg.type() == CV_32FC1); CV_Assert(slat.type() == CV_32FC1); CV_Assert(slandmask.type() == CV_8UC1); newimg = simg.clone(); bufmat = Mat::zeros(simg.rows, 1, CV_32SC1); buf = (int*)bufmat.data; for(j = 0; j < simg.cols; j++){ nbuf = 0; llat = -999; lval = NAN; for(i = 0; i < simg.rows; i++){ // land pixel, nothing to do if(slandmask.at<unsigned char>(i, j) != 0){ continue; } // valid pixel if(!isnan(simg.at<float>(i, j))){ // first pixel is not valid, so extrapolate if(llat == -999){ for(k = 0; k < nbuf; k++){ newimg.at<float>(buf[k],j) = simg.at<float>(i, j); } nbuf = 0; } // interpolate pixels in buffer for(k = 0; k < nbuf; k++){ rlat = slat.at<float>(i, j); rval = simg.at<float>(i, j); x = slat.at<float>(buf[k], j); newimg.at<float>(buf[k],j) = lval + (rval - lval)*(x - llat)/(rlat - llat); } llat = slat.at<float>(i, j); lval = simg.at<float>(i, j); nbuf = 0; continue; } // not land and no valid pixel buf[nbuf++] = i; } // extrapolate the last pixels if(llat != -999){ for(k = 0; k < nbuf; k++){ newimg.at<float>(buf[k],j) = lval; } } } return newimg; } enum Pole { NORTHPOLE, SOUTHPOLE, NOPOLE, }; typedef enum Pole Pole; // Argsort latitude image 'lat' with given swath size. // Image of sort indices are return in 'sortidx'. static void argsortlat(Mat &lat, int swathsize, Mat &sortidx) { int i, j, off, width, height, dir, d, split; Pole pole; Mat col, idx, botidx; Range colrg, toprg, botrg; CV_Assert(lat.type() == CV_32FC1); CV_Assert(swathsize >= 2); CV_Assert(lat.data != sortidx.data); width = lat.cols; height = lat.rows; sortidx.create(height, width, CV_32SC1); // For a column in latitude image, look at every 'swathsize' pixels // starting from 'off'. If they increases and then decreases, or // decreases and then increases, we're at the polar region. off = swathsize/2; pole = NOPOLE; for(j = 0; j < width; j++){ col = lat.col(j); // find initial direction -- increase, decrease or no change dir = 0; for(i = off+swathsize; i < height; i += swathsize){ dir = SGN(col.at<float>(i) - col.at<float>(i-swathsize)); if(dir != 0) break; } // find change in direction if there is one for(; i < height; i += swathsize){ d = SGN(col.at<float>(i) - col.at<float>(i-swathsize)); if(dir == 1 && d == -1){ CV_Assert(pole == NOPOLE || pole == NORTHPOLE); pole = NORTHPOLE; break; } if(dir == -1 && d == 1){ CV_Assert(pole == NOPOLE || pole == SOUTHPOLE); pole = SOUTHPOLE; break; } } if(i >= height){ pole = NOPOLE; if(dir >= 0) sortIdx(col, sortidx.col(j), CV_SORT_EVERY_COLUMN + CV_SORT_ASCENDING); else sortIdx(col, sortidx.col(j), CV_SORT_EVERY_COLUMN + CV_SORT_DESCENDING); continue; } split = i-swathsize; // split before change in direction colrg = Range(j, j+1); toprg = Range(0, split); botrg = Range(split, height); if(pole == NORTHPOLE){ botidx = sortidx(botrg, colrg); sortIdx(col.rowRange(toprg), sortidx(toprg, colrg), CV_SORT_EVERY_COLUMN + CV_SORT_ASCENDING); sortIdx(col.rowRange(botrg), botidx, CV_SORT_EVERY_COLUMN + CV_SORT_DESCENDING); botidx += split; }else{ // pole == SOUTHPOLE botidx = sortidx(botrg, colrg); sortIdx(col.rowRange(toprg), sortidx(toprg, colrg), CV_SORT_EVERY_COLUMN + CV_SORT_DESCENDING); sortIdx(col.rowRange(botrg), botidx, CV_SORT_EVERY_COLUMN + CV_SORT_ASCENDING); botidx += split; } } } // Resample VIIRS swatch image img with corresponding // latitude image lat, and ACSPO mask acspo. Mat resample_float32(Mat &img, Mat &lat, Mat &acspo) { Mat sind, landmask; CV_Assert(img.type() == CV_32FC1); CV_Assert(lat.type() == CV_32FC1); CV_Assert(acspo.type() == CV_8UC1); argsortlat(lat, VIIRS_SWATH_SIZE, sind); img = resample_sort(sind, img); img = avgfilter3(img, sind); lat = resample_sort(sind, lat); acspo = resample_sort(sind, acspo); landmask = (acspo & MaskLand) != 0; return resample_interp(img, lat, landmask); } <commit_msg>resample: add benchmarking code<commit_after>#include "spt.h" template <class T> static Mat resample_unsort_(Mat &sind, Mat &img) { Mat newimg; int i, j, k; int32_t *sp; T *ip; CV_Assert(sind.type() == CV_32SC1); CV_Assert(img.channels() == 1); newimg = Mat::zeros(img.rows, img.cols, img.type()); sp = (int32_t*)sind.data; ip = (T*)img.data; k = 0; for(i = 0; i < newimg.rows; i++){ for(j = 0; j < newimg.cols; j++){ newimg.at<T>(sp[k], j) = ip[k]; k++; } } return newimg; } // Returns the unsorted image of the sorted image img. // Sind is the image of sort indices. static Mat resample_unsort(Mat &sind, Mat &img) { switch(img.type()){ default: eprintf("unsupported type %s\n", type2str(img.type())); break; case CV_8UC1: return resample_unsort_<uchar>(sind, img); break; case CV_32FC1: return resample_unsort_<float>(sind, img); break; case CV_64FC1: return resample_unsort_<double>(sind, img); break; } // not reached return Mat(); } template <class T> static Mat resample_sort_(Mat &sind, Mat &img) { Mat newimg; int i, j, k; int32_t *sp; T *np; CV_Assert(sind.type() == CV_32SC1); CV_Assert(img.channels() == 1); newimg = Mat::zeros(img.rows, img.cols, img.type()); sp = (int*)sind.data; np = (T*)newimg.data; k = 0; for(i = 0; i < newimg.rows; i++){ for(j = 0; j < newimg.cols; j++){ np[k] = img.at<T>(sp[k], j); k++; } } return newimg; } // Returns the sorted image of the unsorted image img. // Sind is the image of sort indices. static Mat resample_sort(Mat &sind, Mat &img) { switch(img.type()){ default: eprintf("unsupported type %s\n", type2str(img.type())); break; case CV_8UC1: return resample_sort_<uchar>(sind, img); break; case CV_32FC1: return resample_sort_<float>(sind, img); break; case CV_64FC1: return resample_sort_<double>(sind, img); break; } // not reached return Mat(); } // Returns the average of 3 pixels. static double avg3(double a, double b, double c) { if(isnan(b)) return NAN; if(isnan(a) || isnan(c)) return b; return (a+b+c)/3.0; } // Returns the average filter of image 'in' with a window of 3x1 // where sorted order is not the same as the original order. // Sind is the sort indices giving the sort order. static Mat avgfilter3(Mat &in, Mat &sind) { Mat out; int i, j, rows, cols, *sindp; float *ip, *op; CV_Assert(in.type() == CV_32FC1); CV_Assert(sind.type() == CV_32SC1); rows = in.rows; cols = in.cols; out.create(rows, cols, CV_32FC1); in.row(0).copyTo(out.row(0)); in.row(rows-1).copyTo(out.row(rows-1)); for(i = 1; i < rows-1; i++){ ip = in.ptr<float>(i); op = out.ptr<float>(i); sindp = sind.ptr<int>(i); for(j = 0; j < cols; j++){ if(sindp[j] != i) op[j] = avg3(ip[j-cols], ip[j], ip[j+cols]); else op[j] = ip[j]; } } return out; } // Interpolate the missing values in image simg and returns the result. // Slat is the latitude image, and slandmask is the land mask image. // All input arguments must already be sorted. static Mat resample_interp(Mat &simg, Mat &slat, Mat &slandmask) { int i, j, k, nbuf, *buf; Mat newimg, bufmat; double x, llat, rlat, lval, rval; CV_Assert(simg.type() == CV_32FC1); CV_Assert(slat.type() == CV_32FC1); CV_Assert(slandmask.type() == CV_8UC1); newimg = simg.clone(); bufmat = Mat::zeros(simg.rows, 1, CV_32SC1); buf = (int*)bufmat.data; for(j = 0; j < simg.cols; j++){ nbuf = 0; llat = -999; lval = NAN; for(i = 0; i < simg.rows; i++){ // land pixel, nothing to do if(slandmask.at<unsigned char>(i, j) != 0){ continue; } // valid pixel if(!isnan(simg.at<float>(i, j))){ // first pixel is not valid, so extrapolate if(llat == -999){ for(k = 0; k < nbuf; k++){ newimg.at<float>(buf[k],j) = simg.at<float>(i, j); } nbuf = 0; } // interpolate pixels in buffer for(k = 0; k < nbuf; k++){ rlat = slat.at<float>(i, j); rval = simg.at<float>(i, j); x = slat.at<float>(buf[k], j); newimg.at<float>(buf[k],j) = lval + (rval - lval)*(x - llat)/(rlat - llat); } llat = slat.at<float>(i, j); lval = simg.at<float>(i, j); nbuf = 0; continue; } // not land and no valid pixel buf[nbuf++] = i; } // extrapolate the last pixels if(llat != -999){ for(k = 0; k < nbuf; k++){ newimg.at<float>(buf[k],j) = lval; } } } return newimg; } enum Pole { NORTHPOLE, SOUTHPOLE, NOPOLE, }; typedef enum Pole Pole; // Argsort latitude image 'lat' with given swath size. // Image of sort indices are return in 'sortidx'. static void argsortlat(Mat &lat, int swathsize, Mat &sortidx) { int i, j, off, width, height, dir, d, split; Pole pole; Mat col, idx, botidx; Range colrg, toprg, botrg; CV_Assert(lat.type() == CV_32FC1); CV_Assert(swathsize >= 2); CV_Assert(lat.data != sortidx.data); width = lat.cols; height = lat.rows; sortidx.create(height, width, CV_32SC1); // For a column in latitude image, look at every 'swathsize' pixels // starting from 'off'. If they increases and then decreases, or // decreases and then increases, we're at the polar region. off = swathsize/2; pole = NOPOLE; for(j = 0; j < width; j++){ col = lat.col(j); // find initial direction -- increase, decrease or no change dir = 0; for(i = off+swathsize; i < height; i += swathsize){ dir = SGN(col.at<float>(i) - col.at<float>(i-swathsize)); if(dir != 0) break; } // find change in direction if there is one for(; i < height; i += swathsize){ d = SGN(col.at<float>(i) - col.at<float>(i-swathsize)); if(dir == 1 && d == -1){ CV_Assert(pole == NOPOLE || pole == NORTHPOLE); pole = NORTHPOLE; break; } if(dir == -1 && d == 1){ CV_Assert(pole == NOPOLE || pole == SOUTHPOLE); pole = SOUTHPOLE; break; } } if(i >= height){ pole = NOPOLE; if(dir >= 0) sortIdx(col, sortidx.col(j), CV_SORT_EVERY_COLUMN + CV_SORT_ASCENDING); else sortIdx(col, sortidx.col(j), CV_SORT_EVERY_COLUMN + CV_SORT_DESCENDING); continue; } split = i-swathsize; // split before change in direction colrg = Range(j, j+1); toprg = Range(0, split); botrg = Range(split, height); if(pole == NORTHPOLE){ botidx = sortidx(botrg, colrg); sortIdx(col.rowRange(toprg), sortidx(toprg, colrg), CV_SORT_EVERY_COLUMN + CV_SORT_ASCENDING); sortIdx(col.rowRange(botrg), botidx, CV_SORT_EVERY_COLUMN + CV_SORT_DESCENDING); botidx += split; }else{ // pole == SOUTHPOLE botidx = sortidx(botrg, colrg); sortIdx(col.rowRange(toprg), sortidx(toprg, colrg), CV_SORT_EVERY_COLUMN + CV_SORT_DESCENDING); sortIdx(col.rowRange(botrg), botidx, CV_SORT_EVERY_COLUMN + CV_SORT_ASCENDING); botidx += split; } } } void benchmark_avgfilter3(Mat &img, Mat &sind, int N) { int i; struct timespec tstart, tend; double secs; clock_gettime(CLOCK_MONOTONIC, &tstart); for(i = 0; i < N; i++){ avgfilter3(img, sind); } clock_gettime(CLOCK_MONOTONIC, &tend); secs = ((double)tend.tv_sec + 1.0e-9*tend.tv_nsec) - ((double)tstart.tv_sec + 1.0e-9*tstart.tv_nsec); printf("avgfilter3 took about %.5f seconds; %f ops/sec\n", secs, N/secs); } // Resample VIIRS swatch image img with corresponding // latitude image lat, and ACSPO mask acspo. Mat resample_float32(Mat &img, Mat &lat, Mat &acspo) { Mat sind, landmask; CV_Assert(img.type() == CV_32FC1); CV_Assert(lat.type() == CV_32FC1); CV_Assert(acspo.type() == CV_8UC1); argsortlat(lat, VIIRS_SWATH_SIZE, sind); img = resample_sort(sind, img); //benchmark_avgfilter3(img, sind, 100); img = avgfilter3(img, sind); //dumpmat("avgfilter3_new.bin", img); lat = resample_sort(sind, lat); acspo = resample_sort(sind, acspo); landmask = (acspo & MaskLand) != 0; return resample_interp(img, lat, landmask); } <|endoftext|>
<commit_before>/* Copyright (c) 2007-2008 The Florida State University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Stephen Hines */ #ifndef __ARCH_ARM_INSTS_STATICINST_HH__ #define __ARCH_ARM_INSTS_STATICINST_HH__ #include "base/trace.hh" #include "cpu/static_inst.hh" namespace ArmISA { class ArmStaticInst : public StaticInst { protected: int32_t shift_rm_imm(uint32_t base, uint32_t shamt, uint32_t type, uint32_t cfval) const; int32_t shift_rm_rs(uint32_t base, uint32_t shamt, uint32_t type, uint32_t cfval) const; bool shift_carry_imm(uint32_t base, uint32_t shamt, uint32_t type, uint32_t cfval) const; bool shift_carry_rs(uint32_t base, uint32_t shamt, uint32_t type, uint32_t cfval) const; bool arm_add_carry(int32_t result, int32_t lhs, int32_t rhs) const; bool arm_sub_carry(int32_t result, int32_t lhs, int32_t rhs) const; bool arm_add_overflow(int32_t result, int32_t lhs, int32_t rhs) const; bool arm_sub_overflow(int32_t result, int32_t lhs, int32_t rhs) const; // Constructor ArmStaticInst(const char *mnem, MachInst _machInst, OpClass __opClass) : StaticInst(mnem, _machInst, __opClass) { } /// Print a register name for disassembly given the unique /// dependence tag number (FP or int). void printReg(std::ostream &os, int reg) const; void printMnemonic(std::ostream &os, const std::string &suffix = "", bool withPred = true) const; void printMemSymbol(std::ostream &os, const SymbolTable *symtab, const std::string &prefix, const Addr addr, const std::string &suffix) const; void printShiftOperand(std::ostream &os) const; void printDataInst(std::ostream &os, bool withImm) const; std::string generateDisassembly(Addr pc, const SymbolTable *symtab) const; }; } #endif //__ARCH_ARM_INSTS_STATICINST_HH__ <commit_msg>ARM: Write some functions to write to the CPSR and SPSR for instructions.<commit_after>/* Copyright (c) 2007-2008 The Florida State University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Stephen Hines */ #ifndef __ARCH_ARM_INSTS_STATICINST_HH__ #define __ARCH_ARM_INSTS_STATICINST_HH__ #include "base/trace.hh" #include "cpu/static_inst.hh" namespace ArmISA { class ArmStaticInst : public StaticInst { protected: int32_t shift_rm_imm(uint32_t base, uint32_t shamt, uint32_t type, uint32_t cfval) const; int32_t shift_rm_rs(uint32_t base, uint32_t shamt, uint32_t type, uint32_t cfval) const; bool shift_carry_imm(uint32_t base, uint32_t shamt, uint32_t type, uint32_t cfval) const; bool shift_carry_rs(uint32_t base, uint32_t shamt, uint32_t type, uint32_t cfval) const; bool arm_add_carry(int32_t result, int32_t lhs, int32_t rhs) const; bool arm_sub_carry(int32_t result, int32_t lhs, int32_t rhs) const; bool arm_add_overflow(int32_t result, int32_t lhs, int32_t rhs) const; bool arm_sub_overflow(int32_t result, int32_t lhs, int32_t rhs) const; // Constructor ArmStaticInst(const char *mnem, MachInst _machInst, OpClass __opClass) : StaticInst(mnem, _machInst, __opClass) { } /// Print a register name for disassembly given the unique /// dependence tag number (FP or int). void printReg(std::ostream &os, int reg) const; void printMnemonic(std::ostream &os, const std::string &suffix = "", bool withPred = true) const; void printMemSymbol(std::ostream &os, const SymbolTable *symtab, const std::string &prefix, const Addr addr, const std::string &suffix) const; void printShiftOperand(std::ostream &os) const; void printDataInst(std::ostream &os, bool withImm) const; std::string generateDisassembly(Addr pc, const SymbolTable *symtab) const; static uint32_t cpsrWriteByInstr(CPSR cpsr, uint32_t val, uint8_t byteMask, bool affectState) { bool privileged = (cpsr.mode != MODE_USER); uint32_t bitMask = 0; if (bits(byteMask, 3)) { unsigned lowIdx = affectState ? 24 : 27; bitMask = bitMask | mask(31, lowIdx); } if (bits(byteMask, 2)) { bitMask = bitMask | mask(19, 16); } if (bits(byteMask, 1)) { unsigned highIdx = affectState ? 15 : 9; unsigned lowIdx = privileged ? 8 : 9; bitMask = bitMask | mask(highIdx, lowIdx); } if (bits(byteMask, 0)) { if (privileged) { bitMask = bitMask | mask(7, 6); bitMask = bitMask | mask(5); } if (affectState) bitMask = bitMask | (1 << 5); } return ((uint32_t)cpsr & ~bitMask) | (val & bitMask); } static uint32_t spsrWriteByInstr(uint32_t spsr, uint32_t val, uint8_t byteMask, bool affectState) { uint32_t bitMask = 0; if (bits(byteMask, 3)) bitMask = bitMask | mask(31, 24); if (bits(byteMask, 2)) bitMask = bitMask | mask(19, 16); if (bits(byteMask, 1)) bitMask = bitMask | mask(15, 8); if (bits(byteMask, 0)) bitMask = bitMask | mask(7, 0); return ((spsr & ~bitMask) | (val & bitMask)); } }; } #endif //__ARCH_ARM_INSTS_STATICINST_HH__ <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (c) 2009-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is licensed under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance with the // License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // __END_LICENSE__ /// \file bathy_correct.cc /// #include <asp/Core/PointUtils.h> #include <asp/Core/Macros.h> #include <asp/Core/Common.h> #include <asp/Core/StereoSettings.h> #include <vw/Core/Stopwatch.h> #include <vw/FileIO/DiskImageUtils.h> #include <vw/Cartography/shapeFile.h> #include <vw/Math/RANSAC.h> #include <Eigen/Dense> using namespace vw; using namespace vw::cartography; namespace po = boost::program_options; namespace fs = boost::filesystem; // Compute the 3D locations at the shape corners based on interpolating // into the DEM and converting to ECEF. void find_xyz_at_shape_corners(std::vector<vw::geometry::dPoly> const& polyVec, vw::cartography::GeoReference const& shape_georef, vw::cartography::GeoReference const& dem_georef, ImageViewRef< PixelMask<float> > interp_dem, std::vector<Eigen::Vector3d> & xyz_vec) { xyz_vec.clear(); for (size_t p = 0; p < polyVec.size(); p++){ vw::geometry::dPoly const& poly = polyVec[p]; const double * xv = poly.get_xv(); const double * yv = poly.get_yv(); const int * numVerts = poly.get_numVerts(); int numPolys = poly.get_numPolys(); int start = 0; for (int pIter = 0; pIter < numPolys; pIter++){ if (pIter > 0) start += numVerts[pIter - 1]; int numV = numVerts[pIter]; for (int vIter = 0; vIter < numV; vIter++) { Vector2 proj_pt(xv[start + vIter], yv[start + vIter]); // Convert from projected coordinates to lonlat Vector2 lonlat = shape_georef.point_to_lonlat(proj_pt); // Convert to DEM pixel Vector2 pix = dem_georef.lonlat_to_pixel(lonlat); PixelMask<float> h = interp_dem(pix.x(), pix.y()); if (!is_valid(h)) continue; Vector3 llh; llh[0] = lonlat[0]; llh[1] = lonlat[1]; llh[2] = h.child(); Vector3 xyz = dem_georef.datum().geodetic_to_cartesian(llh); Eigen::Vector3d eigen_xyz; for (size_t coord = 0; coord < 3; coord++) eigen_xyz[coord] = xyz[coord]; xyz_vec.push_back(eigen_xyz); } } } } // Best fit plane without outlier removal std::pair<Eigen::Vector3d, Eigen::Vector3d> best_plane_from_points(const std::vector<Eigen::Vector3d> & c) { // Copy coordinates to a matrix in Eigen format size_t num_points = c.size(); Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic > coord(3, num_points); for (size_t i = 0; i < num_points; i++) coord.col(i) = c[i]; // calculate centroid Eigen::Vector3d centroid(coord.row(0).mean(), coord.row(1).mean(), coord.row(2).mean()); // subtract centroid for (size_t i = 0; i < 3; i++) coord.row(i).array() -= centroid(i); // We only need the left-singular matrix here // http://math.stackexchange.com/questions/99299/best-fitting-plane-given-a-set-of-points auto svd = coord.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV); Eigen::Vector3d plane_normal = svd.matrixU().rightCols<1>(); return std::make_pair(centroid, plane_normal); } // A functor which returns the best fit plane a*x + b*y + c*z + d = 0 // as the vector (a, b, c, d) with a*a + b*b + c*c = 1 to be used // with RANSAC to remove outliers. struct BestFitPlaneFunctor { typedef vw::Matrix<double, 1, 4> result_type; /// A best fit plane requires pairs of data points to make a fit. template <class ContainerT> size_t min_elements_needed_for_fit(ContainerT const& /*example*/) const { return 3; } /// This function can match points in any container that supports /// the size() and operator[] methods. The container is usually a /// vw::Vector<>, but you could substitute other classes here as /// well. template <class ContainerT> vw::Matrix<double> operator() (std::vector<ContainerT> const& p1, std::vector<ContainerT> const& p2, vw::Matrix<double> const& /*seed_input*/ = vw::Matrix<double>() ) const { // check consistency VW_ASSERT( p1.size() == p2.size(), vw::ArgumentErr() << "Cannot compute similarity transformation. " << "p1 and p2 are not the same size." ); VW_ASSERT( !p1.empty() && p1.size() >= min_elements_needed_for_fit(p1[0]), vw::ArgumentErr() << "Cannot compute similarity transformation. " << "Insufficient data.\n"); std::pair<Eigen::Vector3d, Eigen::Vector3d> plane = best_plane_from_points(p1); Eigen::Vector3d & centroid = plane.first; Eigen::Vector3d & normal = plane.second; Matrix<double> result(1, 4); for (int col = 0; col < 3; col++) result(0, col) = normal[col]; result(0, 3) = -normal.dot(centroid); // Make the normal always point "up", away from the origin, // which means that the free term must be negative if (result(0, 3) > 0) { for (int col = 0; col < 4; col++) result(0, col) *= -1.0; } return result; } }; // Given a 1x4 matrix H = (a, b, c, d) determining the plane // a * x + b * y + c * z + d = 0, find the distance to this plane // from a point xyz. template<class Vec3> double dist_to_plane(vw::Matrix<double, 1, 4> const& H, Vec3 const& xyz) { double ans = 0.0; for (unsigned col = 0; col < 3; col++) { ans += H(0, col) * xyz[col]; } ans += H(0, 3); return std::abs(ans); } // The value p2 is needed by the interface but we don't use it struct BestFitPlaneErrorMetric { template <class RelationT, class ContainerT> double operator() (RelationT const& H, ContainerT const& p1, ContainerT const& p2) const { return dist_to_plane(H, p1); } }; struct Options : vw::cartography::GdalWriteOptions { std::string shapefile, dem, bathy_plane; double outlier_threshold; int num_ransac_iterations; Options(): outlier_threshold(0.2), num_ransac_iterations(1000) {} }; void handle_arguments(int argc, char *argv[], Options& opt) { po::options_description general_options("General Options"); general_options.add_options() ("shapefile", po::value(&opt.shapefile), "The shapefile with vertices whose coordinates will be looked up in the DEM.") ("dem", po::value(&opt.dem), "The DEM to use.") ("bathy-plane", po::value(&opt.bathy_plane), "The output file storing the computed plane as four coefficients a, b, c, d, " "with the plane being a*x + b*y + c*z + d = 0.") ("outlier-threshold", po::value(&opt.outlier_threshold)->default_value(0.2), "A value, in meters, to determine the distance from a sampled point on the DEM to the " "best-fit plane to determine if it will be marked as outlier and not " "included in the calculation of that plane.") ("num-ransac-iterations", po::value(&opt.num_ransac_iterations)->default_value(1000), "Number of RANSAC iterations to use to find the best-fitting plane."); general_options.add( vw::cartography::GdalWriteOptionsDescription(opt) ); po::options_description positional(""); //positional.add_options() // ("input-files", po::value< std::vector<std::string> >(), "Input files"); po::positional_options_description positional_desc; //positional_desc.add("input-files", -1); std::string usage("[options]"); bool allow_unregistered = false; std::vector<std::string> unregistered; po::variables_map vm = asp::check_command_line(argc, argv, opt, general_options, general_options, positional, positional_desc, usage, allow_unregistered, unregistered); if (opt.shapefile == "") vw_throw( ArgumentErr() << "Missing the input shapefile.\n" << usage << general_options ); if (opt.dem == "") vw_throw( ArgumentErr() << "Missing the input dem.\n" << usage << general_options ); if (opt.bathy_plane == "") vw_throw( ArgumentErr() << "Missing the output bathy plane file.\n" << usage << general_options ); } int main( int argc, char *argv[] ) { Options opt; try { handle_arguments(argc, argv, opt); // Read the shapefile std::cout << "Reading the shapefile: " << opt.shapefile << std::endl; bool has_shape_georef; std::vector<vw::geometry::dPoly> polyVec; std::string poly_color; vw::cartography::GeoReference shape_georef; read_shapefile(opt.shapefile, poly_color, has_shape_georef, shape_georef, polyVec); if (!has_shape_georef) vw_throw( ArgumentErr() << "The input shapefile has no georeference.\n" ); // Read the DEM and its associated data // TODO(oalexan1): Think more about the interpolation method std::cout << "Reading the DEM: " << opt.dem << std::endl; vw::cartography::GeoReference dem_georef; if (!read_georeference(dem_georef, opt.dem)) vw_throw( ArgumentErr() << "The input DEM has no georeference.\n" ); double dem_nodata_val = -std::numeric_limits<float>::max(); // note we use a float nodata if (!vw::read_nodata_val(opt.dem, dem_nodata_val)) vw_throw( ArgumentErr() << "Could not read the DEM nodata value.\n"); std::cout << "Read DEM nodata value: " << dem_nodata_val << std::endl; DiskImageView<float> dem(opt.dem); std::cout << "The DEM width and height are: " << dem.cols() << ' ' << dem.rows() << std::endl; ImageViewRef< PixelMask<float> > interp_dem = interpolate(create_mask(dem, dem_nodata_val), BilinearInterpolation(), ConstantEdgeExtension()); // Find the ECEF coordinates of the shape corners std::vector<Eigen::Vector3d> xyz_vec; find_xyz_at_shape_corners(polyVec,shape_georef, dem_georef, interp_dem, xyz_vec); // Compute the water surface using RANSAC std::vector<Eigen::Vector3d> dummy_vec(xyz_vec.size()); // Required by the interface std::vector<size_t> inlier_indices; double inlier_threshold = opt.outlier_threshold; int min_num_output_inliers = std::max(xyz_vec.size()/2, size_t(3)); bool reduce_min_num_output_inliers_if_no_fit = true; vw::Matrix<double> H; try { math::RandomSampleConsensus<BestFitPlaneFunctor, BestFitPlaneErrorMetric> ransac(BestFitPlaneFunctor(), BestFitPlaneErrorMetric(), opt.num_ransac_iterations, inlier_threshold, min_num_output_inliers, reduce_min_num_output_inliers_if_no_fit); H = ransac(xyz_vec, dummy_vec); inlier_indices = ransac.inlier_indices(H, xyz_vec, dummy_vec); } catch (const vw::math::RANSACErr& e ) { vw_out() << "RANSAC Failed: " << e.what() << "\n"; } vw_out() << "Found " << inlier_indices.size() << " / " << xyz_vec.size() << " inliers.\n"; //std::cout << "Final matrix is " << H << std::endl; double max_error = - 1.0, max_inlier_error = -1.0; for (size_t it = 0; it < xyz_vec.size(); it++) max_error = std::max(max_error, dist_to_plane(H, xyz_vec[it])); for (size_t it = 0; it < inlier_indices.size(); it++) max_inlier_error = std::max(max_inlier_error, dist_to_plane(H, xyz_vec[inlier_indices[it]])); std::cout << "Max distance to the plane (meters): " << max_error << std::endl; std::cout << "Max inlier distance to the plane (meters): " << max_inlier_error << std::endl; std::cout << "Writing: " << opt.bathy_plane << std::endl; std::ofstream bp(opt.bathy_plane.c_str()); bp.precision(17); for (int col = 0; col < H.cols(); col++) { bp << H(0, col); if (col < H.cols() - 1) bp << " "; else bp << "\n"; } bp.close(); } ASP_STANDARD_CATCHES; return 0; } <commit_msg>bathy_plane_calc: Print the plane height and off-nadir inclination<commit_after>// __BEGIN_LICENSE__ // Copyright (c) 2009-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is licensed under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance with the // License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // __END_LICENSE__ /// \file bathy_correct.cc /// #include <asp/Core/PointUtils.h> #include <asp/Core/Macros.h> #include <asp/Core/Common.h> #include <asp/Core/StereoSettings.h> #include <vw/Core/Stopwatch.h> #include <vw/FileIO/DiskImageUtils.h> #include <vw/Cartography/shapeFile.h> #include <vw/Math/RANSAC.h> #include <Eigen/Dense> using namespace vw; using namespace vw::cartography; namespace po = boost::program_options; namespace fs = boost::filesystem; // Compute the 3D locations at the shape corners based on interpolating // into the DEM and converting to ECEF. void find_xyz_at_shape_corners(std::vector<vw::geometry::dPoly> const& polyVec, vw::cartography::GeoReference const& shape_georef, vw::cartography::GeoReference const& dem_georef, ImageViewRef< PixelMask<float> > interp_dem, std::vector<Eigen::Vector3d> & xyz_vec) { xyz_vec.clear(); for (size_t p = 0; p < polyVec.size(); p++){ vw::geometry::dPoly const& poly = polyVec[p]; const double * xv = poly.get_xv(); const double * yv = poly.get_yv(); const int * numVerts = poly.get_numVerts(); int numPolys = poly.get_numPolys(); int start = 0; for (int pIter = 0; pIter < numPolys; pIter++){ if (pIter > 0) start += numVerts[pIter - 1]; int numV = numVerts[pIter]; for (int vIter = 0; vIter < numV; vIter++) { Vector2 proj_pt(xv[start + vIter], yv[start + vIter]); // Convert from projected coordinates to lonlat Vector2 lonlat = shape_georef.point_to_lonlat(proj_pt); // Convert to DEM pixel Vector2 pix = dem_georef.lonlat_to_pixel(lonlat); PixelMask<float> h = interp_dem(pix.x(), pix.y()); if (!is_valid(h)) continue; Vector3 llh; llh[0] = lonlat[0]; llh[1] = lonlat[1]; llh[2] = h.child(); Vector3 xyz = dem_georef.datum().geodetic_to_cartesian(llh); Eigen::Vector3d eigen_xyz; for (size_t coord = 0; coord < 3; coord++) eigen_xyz[coord] = xyz[coord]; xyz_vec.push_back(eigen_xyz); } } } } // Best fit plane without outlier removal std::pair<Eigen::Vector3d, Eigen::Vector3d> best_plane_from_points(const std::vector<Eigen::Vector3d> & c) { // Copy coordinates to a matrix in Eigen format size_t num_points = c.size(); Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic > coord(3, num_points); for (size_t i = 0; i < num_points; i++) coord.col(i) = c[i]; // calculate centroid Eigen::Vector3d centroid(coord.row(0).mean(), coord.row(1).mean(), coord.row(2).mean()); // subtract centroid for (size_t i = 0; i < 3; i++) coord.row(i).array() -= centroid(i); // We only need the left-singular matrix here // http://math.stackexchange.com/questions/99299/best-fitting-plane-given-a-set-of-points auto svd = coord.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV); Eigen::Vector3d plane_normal = svd.matrixU().rightCols<1>(); return std::make_pair(centroid, plane_normal); } // A functor which returns the best fit plane a*x + b*y + c*z + d = 0 // as the vector (a, b, c, d) with a*a + b*b + c*c = 1 to be used // with RANSAC to remove outliers. struct BestFitPlaneFunctor { typedef vw::Matrix<double, 1, 4> result_type; /// A best fit plane requires pairs of data points to make a fit. template <class ContainerT> size_t min_elements_needed_for_fit(ContainerT const& /*example*/) const { return 3; } /// This function can match points in any container that supports /// the size() and operator[] methods. The container is usually a /// vw::Vector<>, but you could substitute other classes here as /// well. template <class ContainerT> vw::Matrix<double> operator() (std::vector<ContainerT> const& p1, std::vector<ContainerT> const& p2, vw::Matrix<double> const& /*seed_input*/ = vw::Matrix<double>() ) const { // check consistency VW_ASSERT( p1.size() == p2.size(), vw::ArgumentErr() << "Cannot compute similarity transformation. " << "p1 and p2 are not the same size." ); VW_ASSERT( !p1.empty() && p1.size() >= min_elements_needed_for_fit(p1[0]), vw::ArgumentErr() << "Cannot compute similarity transformation. " << "Insufficient data.\n"); std::pair<Eigen::Vector3d, Eigen::Vector3d> plane = best_plane_from_points(p1); Eigen::Vector3d & centroid = plane.first; Eigen::Vector3d & normal = plane.second; Matrix<double> result(1, 4); for (int col = 0; col < 3; col++) result(0, col) = normal[col]; result(0, 3) = -normal.dot(centroid); // Make the normal always point "up", away from the origin, // which means that the free term must be negative if (result(0, 3) > 0) { for (int col = 0; col < 4; col++) result(0, col) *= -1.0; } return result; } }; // Given a 1x4 matrix H = (a, b, c, d) determining the plane // a * x + b * y + c * z + d = 0, find the distance to this plane // from a point xyz. template<class Vec3> double dist_to_plane(vw::Matrix<double, 1, 4> const& H, Vec3 const& xyz) { double ans = 0.0; for (unsigned col = 0; col < 3; col++) { ans += H(0, col) * xyz[col]; } ans += H(0, 3); return std::abs(ans); } // The value p2 is needed by the interface but we don't use it struct BestFitPlaneErrorMetric { template <class RelationT, class ContainerT> double operator() (RelationT const& H, ContainerT const& p1, ContainerT const& p2) const { return dist_to_plane(H, p1); } }; struct Options : vw::cartography::GdalWriteOptions { std::string shapefile, dem, bathy_plane; double outlier_threshold; int num_ransac_iterations; Options(): outlier_threshold(0.2), num_ransac_iterations(1000) {} }; void handle_arguments(int argc, char *argv[], Options& opt) { po::options_description general_options("General Options"); general_options.add_options() ("shapefile", po::value(&opt.shapefile), "The shapefile with vertices whose coordinates will be looked up in the DEM.") ("dem", po::value(&opt.dem), "The DEM to use.") ("bathy-plane", po::value(&opt.bathy_plane), "The output file storing the computed plane as four coefficients a, b, c, d, " "with the plane being a*x + b*y + c*z + d = 0.") ("outlier-threshold", po::value(&opt.outlier_threshold)->default_value(0.2), "A value, in meters, to determine the distance from a sampled point on the DEM to the " "best-fit plane to determine if it will be marked as outlier and not " "included in the calculation of that plane.") ("num-ransac-iterations", po::value(&opt.num_ransac_iterations)->default_value(1000), "Number of RANSAC iterations to use to find the best-fitting plane."); general_options.add( vw::cartography::GdalWriteOptionsDescription(opt) ); po::options_description positional(""); //positional.add_options() // ("input-files", po::value< std::vector<std::string> >(), "Input files"); po::positional_options_description positional_desc; //positional_desc.add("input-files", -1); std::string usage("[options]"); bool allow_unregistered = false; std::vector<std::string> unregistered; po::variables_map vm = asp::check_command_line(argc, argv, opt, general_options, general_options, positional, positional_desc, usage, allow_unregistered, unregistered); if (opt.shapefile == "") vw_throw( ArgumentErr() << "Missing the input shapefile.\n" << usage << general_options ); if (opt.dem == "") vw_throw( ArgumentErr() << "Missing the input dem.\n" << usage << general_options ); if (opt.bathy_plane == "") vw_throw( ArgumentErr() << "Missing the output bathy plane file.\n" << usage << general_options ); } int main( int argc, char *argv[] ) { Options opt; try { handle_arguments(argc, argv, opt); // Read the shapefile std::cout << "Reading the shapefile: " << opt.shapefile << std::endl; bool has_shape_georef; std::vector<vw::geometry::dPoly> polyVec; std::string poly_color; vw::cartography::GeoReference shape_georef; read_shapefile(opt.shapefile, poly_color, has_shape_georef, shape_georef, polyVec); if (!has_shape_georef) vw_throw( ArgumentErr() << "The input shapefile has no georeference.\n" ); // Read the DEM and its associated data // TODO(oalexan1): Think more about the interpolation method std::cout << "Reading the DEM: " << opt.dem << std::endl; vw::cartography::GeoReference dem_georef; if (!read_georeference(dem_georef, opt.dem)) vw_throw( ArgumentErr() << "The input DEM has no georeference.\n" ); double dem_nodata_val = -std::numeric_limits<float>::max(); // note we use a float nodata if (!vw::read_nodata_val(opt.dem, dem_nodata_val)) vw_throw( ArgumentErr() << "Could not read the DEM nodata value.\n"); std::cout << "Read DEM nodata value: " << dem_nodata_val << std::endl; DiskImageView<float> dem(opt.dem); std::cout << "The DEM width and height are: " << dem.cols() << ' ' << dem.rows() << std::endl; ImageViewRef< PixelMask<float> > interp_dem = interpolate(create_mask(dem, dem_nodata_val), BilinearInterpolation(), ConstantEdgeExtension()); // Find the ECEF coordinates of the shape corners std::vector<Eigen::Vector3d> xyz_vec; find_xyz_at_shape_corners(polyVec,shape_georef, dem_georef, interp_dem, xyz_vec); // Compute the water surface using RANSAC std::vector<Eigen::Vector3d> dummy_vec(xyz_vec.size()); // Required by the interface std::vector<size_t> inlier_indices; double inlier_threshold = opt.outlier_threshold; int min_num_output_inliers = std::max(xyz_vec.size()/2, size_t(3)); bool reduce_min_num_output_inliers_if_no_fit = true; vw::Matrix<double> H; try { math::RandomSampleConsensus<BestFitPlaneFunctor, BestFitPlaneErrorMetric> ransac(BestFitPlaneFunctor(), BestFitPlaneErrorMetric(), opt.num_ransac_iterations, inlier_threshold, min_num_output_inliers, reduce_min_num_output_inliers_if_no_fit); H = ransac(xyz_vec, dummy_vec); inlier_indices = ransac.inlier_indices(H, xyz_vec, dummy_vec); } catch (const vw::math::RANSACErr& e ) { vw_out() << "RANSAC Failed: " << e.what() << "\n"; } vw_out() << "Found " << inlier_indices.size() << " / " << xyz_vec.size() << " inliers.\n"; //std::cout << "Final matrix is " << H << std::endl; double max_error = - 1.0, max_inlier_error = -1.0; for (size_t it = 0; it < xyz_vec.size(); it++) max_error = std::max(max_error, dist_to_plane(H, xyz_vec[it])); // Do estimates for the mean height and angle of the plane Vector3 mean_xyz(0, 0, 0); double mean_height = 0.0; int num = 0; for (size_t it = 0; it < inlier_indices.size(); it++) { Eigen::Vector3d p = xyz_vec[inlier_indices[it]]; Vector3 xyz(p[0], p[1], p[2]); max_inlier_error = std::max(max_inlier_error, dist_to_plane(H, xyz)); Vector3 llh = dem_georef.datum().cartesian_to_geodetic(xyz); mean_height += llh[2]; mean_xyz += xyz; num++; } mean_height /= num; mean_xyz /= num; Vector3 plane_normal(H(0, 0), H(0, 1), H(0, 2)); Vector3 surface_normal = mean_xyz / norm_2(mean_xyz); // ignore the datum flattening double plane_angle = (180.0 / M_PI) * acos(dot_prod(plane_normal, surface_normal)); std::cout << "Max distance to the plane (meters): " << max_error << std::endl; std::cout << "Max inlier distance to the plane (meters): " << max_inlier_error << std::endl; std::cout << std::endl; std::cout << "Mean plane height above datum (meters): " << mean_height << std::endl; std::cout << "Plane inclination (degrees): " << plane_angle << std::endl; std::cout << "The plane inclination is defined as the angle between the plane\n" << "normal and the ray going from the Earth center to the mean of\n" << "all inlier measurements in ECEF coordinates." << std::endl; std::cout << "" << std::endl; std::cout << "Writing: " << opt.bathy_plane << std::endl; std::ofstream bp(opt.bathy_plane.c_str()); bp.precision(17); for (int col = 0; col < H.cols(); col++) { bp << H(0, col); if (col < H.cols() - 1) bp << " "; else bp << "\n"; } bp.close(); } ASP_STANDARD_CATCHES; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: lngmerge.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: nf $ $Date: 2001-04-25 10:17: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): _______________________________________ * * ************************************************************************/ #include <tools/fsys.hxx> // local includes #include "lngmerge.hxx" #include "utf8conv.hxx" // // class LngParser // /*****************************************************************************/ LngParser::LngParser( const ByteString &rLngFile, BOOL bUTF8 ) /*****************************************************************************/ : sSource( rLngFile ), nError( LNG_OK ), pLines( NULL ), bDBIsUTF8( bUTF8 ) { pLines = new LngLineList( 100, 100 ); DirEntry aEntry( String( sSource, RTL_TEXTENCODING_ASCII_US )); if ( aEntry.Exists()) { SvFileStream aStream( String( sSource, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_READ ); if ( aStream.IsOpen()) { ByteString sLine; while ( !aStream.IsEof()) { aStream.ReadLine( sLine ); pLines->Insert( new ByteString( sLine ), LIST_APPEND ); } } else nError = LNG_COULD_NOT_OPEN; } else nError = LNG_FILE_NOTFOUND; } /*****************************************************************************/ LngParser::~LngParser() /*****************************************************************************/ { for ( ULONG i = 0; i < pLines->Count(); i++ ) delete pLines->GetObject( i ); delete pLines; } /*****************************************************************************/ BOOL LngParser::CreateSDF( const ByteString &rSDFFile, const ByteString &rPrj, const ByteString &rRoot ) /*****************************************************************************/ { SvFileStream aSDFStream( String( rSDFFile, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_WRITE | STREAM_TRUNC ); if ( !aSDFStream.IsOpen()) { nError = SDF_COULD_NOT_OPEN; } nError = SDF_OK; DirEntry aEntry( String( sSource, RTL_TEXTENCODING_ASCII_US )); aEntry.ToAbs(); String sFullEntry = aEntry.GetFull(); aEntry += DirEntry( String( "..", RTL_TEXTENCODING_ASCII_US )); aEntry += DirEntry( rRoot ); ByteString sPrjEntry( aEntry.GetFull(), gsl_getSystemTextEncoding()); ByteString sActFileName( sFullEntry.Copy( sPrjEntry.Len() + 1 ), gsl_getSystemTextEncoding()); sActFileName.ToLowerAscii(); ULONG nPos = 0; BOOL bGroup = FALSE; ByteString sGroup; // seek to next group while ( nPos < pLines->Count() && !bGroup ) { ByteString sLine( *pLines->GetObject( nPos )); sLine.EraseLeadingChars( ' ' ); sLine.EraseTrailingChars( ' ' ); if (( sLine.GetChar( 0 ) == '[' ) && ( sLine.GetChar( sLine.Len() - 1 ) == ']' )) { sGroup = sLine.GetToken( 1, '[' ).GetToken( 0, ']' ); sGroup.EraseLeadingChars( ' ' ); sGroup.EraseTrailingChars( ' ' ); bGroup = TRUE; } nPos ++; } while ( nPos < pLines->Count()) { ByteString Text[ LANGUAGES ]; ByteString sID( sGroup ); // read languages bGroup = FALSE; while ( nPos < pLines->Count() && !bGroup ) { ByteString sLine( *pLines->GetObject( nPos )); sLine.EraseLeadingChars( ' ' ); sLine.EraseTrailingChars( ' ' ); if (( sLine.GetChar( 0 ) == '[' ) && ( sLine.GetChar( sLine.Len() - 1 ) == ']' )) { sGroup = sLine.GetToken( 1, '[' ).GetToken( 0, ']' ); sGroup.EraseLeadingChars( ' ' ); sGroup.EraseTrailingChars( ' ' ); bGroup = TRUE; } else if ( sLine.GetTokenCount( '=' ) > 1 ) { ByteString sLang = sLine.GetToken( 0, '=' ); sLang.EraseLeadingChars( ' ' ); sLang.EraseTrailingChars( ' ' ); if (( sLang.IsNumericAscii()) && ( MergeDataFile::GetLangIndex( sLang.ToInt32()) < LANGUAGES )) { // this is a valid text line ByteString sText = sLine.GetToken( 1, '\"' ).GetToken( 0, '\"' ); USHORT nIndex = MergeDataFile::GetLangIndex( sLang.ToInt32()); Text[ nIndex ] = sText; } } nPos ++; } BOOL bExport = Text[ GERMAN_INDEX ].Len() && ( Text[ ENGLISH_INDEX ].Len() || Text[ ENGLISH_US_INDEX ].Len()); if ( bExport ) { Time aTime; ByteString sTimeStamp( ByteString::CreateFromInt64( Date().GetDate())); sTimeStamp += " "; sTimeStamp += ByteString::CreateFromInt32( aTime.GetHour()); sTimeStamp += ":"; sTimeStamp += ByteString::CreateFromInt32( aTime.GetMin()); sTimeStamp += ":"; sTimeStamp += ByteString::CreateFromInt32( aTime.GetSec()); for ( ULONG i = 0; i < LANGUAGES; i++ ) { if ( LANGUAGE_ALLOWED( i )) { ByteString sAct = Text[ i ]; if ( !sAct.Len() && i ) sAct = Text[ GERMAN_INDEX ]; ByteString sOutput( rPrj ); sOutput += "\t"; if ( rRoot.Len()) sOutput += sActFileName; sOutput += "\t0\t"; sOutput += "LngText\t"; sOutput += sID; sOutput += "\t\t\t\t0\t"; sOutput += ByteString::CreateFromInt64( Export::LangId[ i ] ); sOutput += "\t"; sOutput += sAct; sOutput += "\t\t\t\t"; sOutput += sTimeStamp; if ( bDBIsUTF8 ) sOutput = UTF8Converter::ConvertToUTF8( sOutput, Export::GetCharSet( Export::LangId[ i ] )); aSDFStream.WriteLine( sOutput ); } } } } aSDFStream.Close(); return TRUE; } /*****************************************************************************/ BOOL LngParser::Merge( const ByteString &rSDFFile, const ByteString &rDestinationFile ) /*****************************************************************************/ { SvFileStream aDestination( String( rDestinationFile, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_WRITE | STREAM_TRUNC ); if ( !aDestination.IsOpen()) { nError = LNG_COULD_NOT_OPEN; } nError = LNG_OK; MergeDataFile aMergeDataFile( rSDFFile, FALSE, RTL_TEXTENCODING_MS_1252, bDBIsUTF8 ); ULONG nPos = 0; BOOL bGroup = FALSE; ByteString sGroup; // seek to next group while ( nPos < pLines->Count() && !bGroup ) { ByteString sLine( *pLines->GetObject( nPos )); sLine.EraseLeadingChars( ' ' ); sLine.EraseTrailingChars( ' ' ); if (( sLine.GetChar( 0 ) == '[' ) && ( sLine.GetChar( sLine.Len() - 1 ) == ']' )) { sGroup = sLine.GetToken( 1, '[' ).GetToken( 0, ']' ); sGroup.EraseLeadingChars( ' ' ); sGroup.EraseTrailingChars( ' ' ); bGroup = TRUE; } nPos ++; } while ( nPos < pLines->Count()) { ByteString Text[ LANGUAGES ]; ByteString sID( sGroup ); ULONG nLastLangPos = 0; ResData *pResData = new ResData( "", sID ); pResData->sResTyp = "lngtext"; PFormEntrys *pEntrys = aMergeDataFile.GetPFormEntrys( pResData ); // read languages bGroup = FALSE; while ( nPos < pLines->Count() && !bGroup ) { ByteString sLine( *pLines->GetObject( nPos )); sLine.EraseLeadingChars( ' ' ); sLine.EraseTrailingChars( ' ' ); if (( sLine.GetChar( 0 ) == '[' ) && ( sLine.GetChar( sLine.Len() - 1 ) == ']' )) { sGroup = sLine.GetToken( 1, '[' ).GetToken( 0, ']' ); sGroup.EraseLeadingChars( ' ' ); sGroup.EraseTrailingChars( ' ' ); bGroup = TRUE; } else if ( sLine.GetTokenCount( '=' ) > 1 ) { ByteString sLang = sLine.GetToken( 0, '=' ); sLang.EraseLeadingChars( ' ' ); sLang.EraseTrailingChars( ' ' ); if (( sLang.IsNumericAscii()) && ( MergeDataFile::GetLangIndex( sLang.ToInt32()) < LANGUAGES ) && ( pEntrys )) { // this is a valid text line USHORT nIndex = MergeDataFile::GetLangIndex( sLang.ToInt32()); ByteString sNewText; pEntrys->GetText( sNewText, STRING_TYP_TEXT, nIndex, TRUE ); if ( sNewText.Len()) { ByteString *pLine = pLines->GetObject( nPos ); if ( sLang.ToInt32() != GERMAN ) { ByteString sText( sLang ); sText += " = \""; sText += sNewText; sText += "\""; *pLine = sText; } Text[ nIndex ] = sNewText; } nLastLangPos = nPos; } } nPos ++; } if ( nLastLangPos ) { for ( USHORT i = 0; i < LANGUAGES; i++ ) { if (( i != GERMAN ) && ( !Text[ i ].Len())) { ByteString sNewText; pEntrys->GetText( sNewText, STRING_TYP_TEXT, i, TRUE ); if (( sNewText.Len()) && !(( i == COMMENT ) && ( sNewText == "-" ))) { ByteString sLine; if ( Export::LangId[ i ] < 10 ) sLine += "0"; sLine += Export::LangId[ i ]; sLine += " = \""; sLine += sNewText; sLine += "\""; nLastLangPos++; nPos++; pLines->Insert( new ByteString( sLine ), nLastLangPos ); } } } } delete pResData; } for ( ULONG i = 0; i < pLines->Count(); i++ ) aDestination.WriteLine( *pLines->GetObject( i )); aDestination.Close(); return TRUE; } <commit_msg>Fix for merging with incorrect lang ids, repairment of wrong merged files<commit_after>/************************************************************************* * * $RCSfile: lngmerge.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: nf $ $Date: 2001-05-16 13:06:14 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <tools/fsys.hxx> // local includes #include "lngmerge.hxx" #include "utf8conv.hxx" // // class LngParser // /*****************************************************************************/ LngParser::LngParser( const ByteString &rLngFile, BOOL bUTF8 ) /*****************************************************************************/ : sSource( rLngFile ), nError( LNG_OK ), pLines( NULL ), bDBIsUTF8( bUTF8 ) { pLines = new LngLineList( 100, 100 ); DirEntry aEntry( String( sSource, RTL_TEXTENCODING_ASCII_US )); if ( aEntry.Exists()) { SvFileStream aStream( String( sSource, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_READ ); if ( aStream.IsOpen()) { ByteString sLine; while ( !aStream.IsEof()) { aStream.ReadLine( sLine ); pLines->Insert( new ByteString( sLine ), LIST_APPEND ); } } else nError = LNG_COULD_NOT_OPEN; } else nError = LNG_FILE_NOTFOUND; } /*****************************************************************************/ LngParser::~LngParser() /*****************************************************************************/ { for ( ULONG i = 0; i < pLines->Count(); i++ ) delete pLines->GetObject( i ); delete pLines; } /*****************************************************************************/ BOOL LngParser::CreateSDF( const ByteString &rSDFFile, const ByteString &rPrj, const ByteString &rRoot ) /*****************************************************************************/ { SvFileStream aSDFStream( String( rSDFFile, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_WRITE | STREAM_TRUNC ); if ( !aSDFStream.IsOpen()) { nError = SDF_COULD_NOT_OPEN; } nError = SDF_OK; DirEntry aEntry( String( sSource, RTL_TEXTENCODING_ASCII_US )); aEntry.ToAbs(); String sFullEntry = aEntry.GetFull(); aEntry += DirEntry( String( "..", RTL_TEXTENCODING_ASCII_US )); aEntry += DirEntry( rRoot ); ByteString sPrjEntry( aEntry.GetFull(), gsl_getSystemTextEncoding()); ByteString sActFileName( sFullEntry.Copy( sPrjEntry.Len() + 1 ), gsl_getSystemTextEncoding()); sActFileName.ToLowerAscii(); ULONG nPos = 0; BOOL bGroup = FALSE; ByteString sGroup; // seek to next group while ( nPos < pLines->Count() && !bGroup ) { ByteString sLine( *pLines->GetObject( nPos )); sLine.EraseLeadingChars( ' ' ); sLine.EraseTrailingChars( ' ' ); if (( sLine.GetChar( 0 ) == '[' ) && ( sLine.GetChar( sLine.Len() - 1 ) == ']' )) { sGroup = sLine.GetToken( 1, '[' ).GetToken( 0, ']' ); sGroup.EraseLeadingChars( ' ' ); sGroup.EraseTrailingChars( ' ' ); bGroup = TRUE; } nPos ++; } while ( nPos < pLines->Count()) { ByteString Text[ LANGUAGES ]; ByteString sID( sGroup ); // read languages bGroup = FALSE; while ( nPos < pLines->Count() && !bGroup ) { ByteString sLine( *pLines->GetObject( nPos )); sLine.EraseLeadingChars( ' ' ); sLine.EraseTrailingChars( ' ' ); if (( sLine.GetChar( 0 ) == '[' ) && ( sLine.GetChar( sLine.Len() - 1 ) == ']' )) { sGroup = sLine.GetToken( 1, '[' ).GetToken( 0, ']' ); sGroup.EraseLeadingChars( ' ' ); sGroup.EraseTrailingChars( ' ' ); bGroup = TRUE; } else if ( sLine.GetTokenCount( '=' ) > 1 ) { ByteString sLang = sLine.GetToken( 0, '=' ); sLang.EraseLeadingChars( ' ' ); sLang.EraseTrailingChars( ' ' ); if (( sLang.IsNumericAscii()) && ( MergeDataFile::GetLangIndex( sLang.ToInt32()) < LANGUAGES )) { // this is a valid text line ByteString sText = sLine.GetToken( 1, '\"' ).GetToken( 0, '\"' ); USHORT nIndex = MergeDataFile::GetLangIndex( sLang.ToInt32()); Text[ nIndex ] = sText; } } nPos ++; } BOOL bExport = Text[ GERMAN_INDEX ].Len() && ( Text[ ENGLISH_INDEX ].Len() || Text[ ENGLISH_US_INDEX ].Len()); if ( bExport ) { Time aTime; ByteString sTimeStamp( ByteString::CreateFromInt64( Date().GetDate())); sTimeStamp += " "; sTimeStamp += ByteString::CreateFromInt32( aTime.GetHour()); sTimeStamp += ":"; sTimeStamp += ByteString::CreateFromInt32( aTime.GetMin()); sTimeStamp += ":"; sTimeStamp += ByteString::CreateFromInt32( aTime.GetSec()); for ( ULONG i = 0; i < LANGUAGES; i++ ) { if ( LANGUAGE_ALLOWED( i )) { ByteString sAct = Text[ i ]; if ( !sAct.Len() && i ) sAct = Text[ GERMAN_INDEX ]; ByteString sOutput( rPrj ); sOutput += "\t"; if ( rRoot.Len()) sOutput += sActFileName; sOutput += "\t0\t"; sOutput += "LngText\t"; sOutput += sID; sOutput += "\t\t\t\t0\t"; sOutput += ByteString::CreateFromInt64( Export::LangId[ i ] ); sOutput += "\t"; sOutput += sAct; sOutput += "\t\t\t\t"; sOutput += sTimeStamp; if ( bDBIsUTF8 ) sOutput = UTF8Converter::ConvertToUTF8( sOutput, Export::GetCharSet( Export::LangId[ i ] )); aSDFStream.WriteLine( sOutput ); } } } } aSDFStream.Close(); return TRUE; } /*****************************************************************************/ BOOL LngParser::Merge( const ByteString &rSDFFile, const ByteString &rDestinationFile ) /*****************************************************************************/ { SvFileStream aDestination( String( rDestinationFile, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_WRITE | STREAM_TRUNC ); if ( !aDestination.IsOpen()) { nError = LNG_COULD_NOT_OPEN; } nError = LNG_OK; MergeDataFile aMergeDataFile( rSDFFile, FALSE, RTL_TEXTENCODING_MS_1252, bDBIsUTF8 ); ULONG nPos = 0; BOOL bGroup = FALSE; ByteString sGroup; // seek to next group while ( nPos < pLines->Count() && !bGroup ) { ByteString sLine( *pLines->GetObject( nPos )); sLine.EraseLeadingChars( ' ' ); sLine.EraseTrailingChars( ' ' ); if (( sLine.GetChar( 0 ) == '[' ) && ( sLine.GetChar( sLine.Len() - 1 ) == ']' )) { sGroup = sLine.GetToken( 1, '[' ).GetToken( 0, ']' ); sGroup.EraseLeadingChars( ' ' ); sGroup.EraseTrailingChars( ' ' ); bGroup = TRUE; } nPos ++; } while ( nPos < pLines->Count()) { ByteString Text[ LANGUAGES ]; ByteString sID( sGroup ); ULONG nLastLangPos = 0; ResData *pResData = new ResData( "", sID ); pResData->sResTyp = "lngtext"; PFormEntrys *pEntrys = aMergeDataFile.GetPFormEntrys( pResData ); // read languages bGroup = FALSE; while ( nPos < pLines->Count() && !bGroup ) { ByteString sLine( *pLines->GetObject( nPos )); sLine.EraseLeadingChars( ' ' ); sLine.EraseTrailingChars( ' ' ); if (( sLine.GetChar( 0 ) == '[' ) && ( sLine.GetChar( sLine.Len() - 1 ) == ']' )) { sGroup = sLine.GetToken( 1, '[' ).GetToken( 0, ']' ); sGroup.EraseLeadingChars( ' ' ); sGroup.EraseTrailingChars( ' ' ); bGroup = TRUE; nPos ++; } else if ( sLine.GetTokenCount( '=' ) > 1 ) { ByteString sLang = sLine.GetToken( 0, '=' ); sLang.EraseLeadingChars( ' ' ); sLang.EraseTrailingChars( ' ' ); if ( !sLang.IsNumericAscii() || !LANGUAGE_ALLOWED( sLang.ToInt32())) { pLines->Remove( nPos ); } else if (( MergeDataFile::GetLangIndex( sLang.ToInt32()) < LANGUAGES ) && ( pEntrys )) { // this is a valid text line USHORT nIndex = MergeDataFile::GetLangIndex( sLang.ToInt32()); ByteString sNewText; pEntrys->GetText( sNewText, STRING_TYP_TEXT, nIndex, TRUE ); if ( sNewText.Len()) { ByteString *pLine = pLines->GetObject( nPos ); if ( sLang.ToInt32() != GERMAN ) { ByteString sText( sLang ); sText += " = \""; sText += sNewText; sText += "\""; *pLine = sText; } Text[ nIndex ] = sNewText; } nLastLangPos = nPos; nPos ++; } else nPos ++; } else nPos++; } if ( nLastLangPos ) { for ( USHORT i = 0; i < LANGUAGES; i++ ) { if (( i != GERMAN ) && ( !Text[ i ].Len())) { ByteString sNewText; pEntrys->GetText( sNewText, STRING_TYP_TEXT, i, TRUE ); if (( sNewText.Len()) && !(( i == COMMENT ) && ( sNewText == "-" ))) { ByteString sLine; if ( Export::LangId[ i ] < 10 ) sLine += "0"; sLine += ByteString::CreateFromInt32( Export::LangId[ i ] ); sLine += " = \""; sLine += sNewText; sLine += "\""; nLastLangPos++; nPos++; pLines->Insert( new ByteString( sLine ), nLastLangPos ); } } } } delete pResData; } for ( ULONG i = 0; i < pLines->Count(); i++ ) aDestination.WriteLine( *pLines->GetObject( i )); aDestination.Close(); return TRUE; } <|endoftext|>
<commit_before>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "spatial_resampler.h" namespace webrtc { VPMSimpleSpatialResampler::VPMSimpleSpatialResampler() : _resamplingMode(kFastRescaling), _targetWidth(0), _targetHeight(0), _interpolatorPtr(NULL) { } VPMSimpleSpatialResampler::~VPMSimpleSpatialResampler() { Release(); } WebRtc_Word32 VPMSimpleSpatialResampler::Release() { if (_interpolatorPtr != NULL) { delete _interpolatorPtr; _interpolatorPtr = NULL; } return VPM_OK; } WebRtc_Word32 VPMSimpleSpatialResampler::SetTargetFrameSize(WebRtc_UWord32 width, WebRtc_UWord32 height) { if (_resamplingMode == kNoRescaling) { return VPM_OK; } if (width < 1 || height < 1) { return VPM_PARAMETER_ERROR; } _targetWidth = width; _targetHeight = height; return VPM_OK; } void VPMSimpleSpatialResampler::SetInputFrameResampleMode(VideoFrameResampling resamplingMode) { _resamplingMode = resamplingMode; } void VPMSimpleSpatialResampler::Reset() { _resamplingMode = kFastRescaling; _targetWidth = 0; _targetHeight = 0; } WebRtc_Word32 VPMSimpleSpatialResampler::ResampleFrame(const VideoFrame& inFrame, VideoFrame& outFrame) { WebRtc_Word32 ret; if (_resamplingMode == kNoRescaling) { return outFrame.CopyFrame(inFrame); } else if (_targetWidth < 1 || _targetHeight < 1) { return VPM_PARAMETER_ERROR; } // Check if re-sampling is needed if ((inFrame.Width() == _targetWidth) && (inFrame.Height() == _targetHeight)) { return outFrame.CopyFrame(inFrame); } if (_resamplingMode == kBiLinear) { return BiLinearInterpolation(inFrame, outFrame); } outFrame.SetTimeStamp(inFrame.TimeStamp()); if (_targetWidth > inFrame.Width() && ( ExactMultiplier(inFrame.Width(), inFrame.Height()))) { // The codec might want to pad this later... adding 8 pixels const WebRtc_UWord32 requiredSize = (_targetWidth + 8) * (_targetHeight + 8) * 3 / 2; outFrame.VerifyAndAllocate(requiredSize); return UpsampleFrame(inFrame, outFrame); } else { // 1 cut/pad // 2 scale factor 2X (in both cases if required) WebRtc_UWord32 croppedWidth = inFrame.Width(); WebRtc_UWord32 croppedHeight = inFrame.Height(); //Calculates cropped dimensions CropSize(inFrame.Width(), inFrame.Height(), croppedWidth, croppedHeight); VideoFrame* targetFrame; outFrame.VerifyAndAllocate(croppedWidth * croppedHeight * 3 / 2); targetFrame = &outFrame; ConvertI420ToI420(inFrame.Buffer(), inFrame.Width(), inFrame.Height(), targetFrame->Buffer(), croppedWidth, croppedHeight); targetFrame->SetWidth(croppedWidth); targetFrame->SetHeight(croppedHeight); //We have correct aspect ratio, sub-sample with a multiple of two to get //close to the target size ret = SubsampleMultipleOf2(*targetFrame); if (ret != VPM_OK) { return ret; } } return VPM_OK; } WebRtc_Word32 VPMSimpleSpatialResampler::UpsampleFrame(const VideoFrame& inFrame, VideoFrame& outFrame) { outFrame.CopyFrame(inFrame); WebRtc_UWord32 currentLength = inFrame.Width() * inFrame.Height() * 3 / 2; float ratioWidth = _targetWidth / (float)inFrame.Width(); float ratioHeight = _targetHeight / (float)inFrame.Height(); WebRtc_UWord32 scaledWidth = 0; WebRtc_UWord32 scaledHeight = 0; if(ratioWidth > 1 || ratioHeight > 1) { // scale up if(ratioWidth <= 1.5 && ratioHeight <= 1.5) { // scale up 1.5 currentLength = ScaleI420Up3_2(inFrame.Width(), inFrame.Height(), outFrame.Buffer(), outFrame.Size(), scaledWidth, scaledHeight); } else if(ratioWidth <= 2 && ratioHeight <= 2) { // scale up 2 currentLength = ScaleI420Up2(inFrame.Width(), inFrame.Height(), outFrame.Buffer(), outFrame.Size(), scaledWidth, scaledHeight); } else if(ratioWidth <= 2.25 && ratioHeight <= 2.25) { // scale up 2.25 currentLength = ScaleI420Up3_2(inFrame.Width(), inFrame.Height(), outFrame.Buffer(), outFrame.Size(), scaledWidth, scaledHeight); currentLength = ScaleI420Up3_2(scaledWidth, scaledHeight, outFrame.Buffer(), outFrame.Size(), scaledWidth, scaledHeight); } else if(ratioWidth <= 3 && ratioHeight <= 3) { // scale up 3 currentLength = ScaleI420Up2(inFrame.Width(), inFrame.Height(), outFrame.Buffer(), outFrame.Size(), scaledWidth, scaledHeight); currentLength = ScaleI420Up3_2(scaledWidth, scaledHeight, outFrame.Buffer(), outFrame.Size(), scaledWidth, scaledHeight); } else if(ratioWidth <= 4 && ratioHeight <= 4) { // scale up 4 currentLength = ScaleI420Up2(inFrame.Width(), inFrame.Height(), outFrame.Buffer(), outFrame.Size(), scaledWidth, scaledHeight); currentLength = ScaleI420Up2(scaledWidth, scaledHeight, outFrame.Buffer(), outFrame.Size(), scaledWidth, scaledHeight); } //TODO: what if ratioWidth/Height >= 8 ? if (scaledWidth <= 0 || scaledHeight <= 0) { return VPM_GENERAL_ERROR; } if ((static_cast<WebRtc_UWord32>(scaledWidth) > _targetWidth) || (static_cast<WebRtc_UWord32>(scaledHeight) > _targetHeight)) { currentLength = CutI420Frame(outFrame.Buffer(), scaledWidth, scaledHeight, _targetWidth, _targetHeight); } } else { return VPM_GENERAL_ERROR; } outFrame.SetWidth(_targetWidth); outFrame.SetHeight(_targetHeight); outFrame.SetLength(_targetWidth * _targetHeight * 3 / 2); return VPM_OK; } WebRtc_Word32 VPMSimpleSpatialResampler::CropSize(WebRtc_UWord32 width, WebRtc_UWord32 height, WebRtc_UWord32& croppedWidth, WebRtc_UWord32& croppedHeight) const { // Crop the image to a width and height which is a // multiple of two, so that we can do a simpler scaling. croppedWidth = _targetWidth; croppedHeight = _targetHeight; if (width >= 8 * _targetWidth && height >= 8 * _targetHeight) { croppedWidth = 8 * _targetWidth; croppedHeight = 8 * _targetHeight; } else if (width >= 4 * _targetWidth && height >= 4 * _targetHeight) { croppedWidth = 4 * _targetWidth; croppedHeight = 4 * _targetHeight; } else if (width >= 2 * _targetWidth && height >= 2 * _targetHeight) { croppedWidth = 2 * _targetWidth; croppedHeight = 2 * _targetHeight; } return VPM_OK; } WebRtc_Word32 VPMSimpleSpatialResampler::SubsampleMultipleOf2(VideoFrame& frame) { WebRtc_UWord32 tempWidth = frame.Width(); WebRtc_UWord32 tempHeight = frame.Height(); while (tempWidth / _targetWidth >= 2 && tempHeight / _targetHeight >= 2) { ScaleI420FrameQuarter(tempWidth, tempHeight, frame.Buffer()); tempWidth /= 2; tempHeight /= 2; } frame.SetWidth(tempWidth); frame.SetHeight(tempHeight); frame.SetLength(frame.Width() * frame.Height() * 3 / 2); return VPM_OK; } bool VPMSimpleSpatialResampler::ExactMultiplier(WebRtc_UWord32 width, WebRtc_UWord32 height) const { bool exactMultiplier = false; if (_targetWidth % width == 0 && _targetHeight % height == 0) { // we have a multiple, is it an even multiple? WebRtc_Word32 widthMultiple = _targetWidth / width; WebRtc_Word32 heightMultiple = _targetHeight / height; if ((widthMultiple == 2 && heightMultiple == 2) || (widthMultiple == 4 && heightMultiple == 4) || (widthMultiple == 8 && heightMultiple == 8) || (widthMultiple == 1 && heightMultiple == 1)) { exactMultiplier = true; } } return exactMultiplier; } WebRtc_Word32 VPMSimpleSpatialResampler::BiLinearInterpolation(const VideoFrame& inFrame, VideoFrame& outFrame) { WebRtc_Word32 retVal; if (_interpolatorPtr == NULL) { _interpolatorPtr = new interpolator(); } // set bi-linear interpolator retVal = _interpolatorPtr->Set(inFrame.Width(), inFrame.Height(), _targetWidth, _targetHeight, kI420, kI420, kBilinear ); if (retVal < 0 ) { return retVal; } // Verify size of output buffer outFrame.VerifyAndAllocate(_targetHeight * _targetWidth * 3 >> 1); WebRtc_UWord32 outSz = outFrame.Size(); // interpolate frame retVal = _interpolatorPtr->Interpolate(inFrame.Buffer(), outFrame.Buffer(), outSz); assert(outSz <= outFrame.Size()); // returns height if (retVal < 0) { return retVal; } // Set output frame parameters outFrame.SetHeight(_targetHeight); outFrame.SetWidth(_targetWidth); outFrame.SetLength(outSz); outFrame.SetTimeStamp(inFrame.TimeStamp()); return VPM_OK; } WebRtc_UWord32 VPMSimpleSpatialResampler::TargetHeight() { return _targetHeight; } WebRtc_UWord32 VPMSimpleSpatialResampler::TargetWidth() { return _targetWidth; } } //namespace <commit_msg>Fix unused variable warning in spatial_resampler.cc<commit_after>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "spatial_resampler.h" namespace webrtc { VPMSimpleSpatialResampler::VPMSimpleSpatialResampler() : _resamplingMode(kFastRescaling), _targetWidth(0), _targetHeight(0), _interpolatorPtr(NULL) { } VPMSimpleSpatialResampler::~VPMSimpleSpatialResampler() { Release(); } WebRtc_Word32 VPMSimpleSpatialResampler::Release() { if (_interpolatorPtr != NULL) { delete _interpolatorPtr; _interpolatorPtr = NULL; } return VPM_OK; } WebRtc_Word32 VPMSimpleSpatialResampler::SetTargetFrameSize(WebRtc_UWord32 width, WebRtc_UWord32 height) { if (_resamplingMode == kNoRescaling) { return VPM_OK; } if (width < 1 || height < 1) { return VPM_PARAMETER_ERROR; } _targetWidth = width; _targetHeight = height; return VPM_OK; } void VPMSimpleSpatialResampler::SetInputFrameResampleMode(VideoFrameResampling resamplingMode) { _resamplingMode = resamplingMode; } void VPMSimpleSpatialResampler::Reset() { _resamplingMode = kFastRescaling; _targetWidth = 0; _targetHeight = 0; } WebRtc_Word32 VPMSimpleSpatialResampler::ResampleFrame(const VideoFrame& inFrame, VideoFrame& outFrame) { WebRtc_Word32 ret; if (_resamplingMode == kNoRescaling) { return outFrame.CopyFrame(inFrame); } else if (_targetWidth < 1 || _targetHeight < 1) { return VPM_PARAMETER_ERROR; } // Check if re-sampling is needed if ((inFrame.Width() == _targetWidth) && (inFrame.Height() == _targetHeight)) { return outFrame.CopyFrame(inFrame); } if (_resamplingMode == kBiLinear) { return BiLinearInterpolation(inFrame, outFrame); } outFrame.SetTimeStamp(inFrame.TimeStamp()); if (_targetWidth > inFrame.Width() && ( ExactMultiplier(inFrame.Width(), inFrame.Height()))) { // The codec might want to pad this later... adding 8 pixels const WebRtc_UWord32 requiredSize = (_targetWidth + 8) * (_targetHeight + 8) * 3 / 2; outFrame.VerifyAndAllocate(requiredSize); return UpsampleFrame(inFrame, outFrame); } else { // 1 cut/pad // 2 scale factor 2X (in both cases if required) WebRtc_UWord32 croppedWidth = inFrame.Width(); WebRtc_UWord32 croppedHeight = inFrame.Height(); //Calculates cropped dimensions CropSize(inFrame.Width(), inFrame.Height(), croppedWidth, croppedHeight); VideoFrame* targetFrame; outFrame.VerifyAndAllocate(croppedWidth * croppedHeight * 3 / 2); targetFrame = &outFrame; ConvertI420ToI420(inFrame.Buffer(), inFrame.Width(), inFrame.Height(), targetFrame->Buffer(), croppedWidth, croppedHeight); targetFrame->SetWidth(croppedWidth); targetFrame->SetHeight(croppedHeight); //We have correct aspect ratio, sub-sample with a multiple of two to get //close to the target size ret = SubsampleMultipleOf2(*targetFrame); if (ret != VPM_OK) { return ret; } } return VPM_OK; } WebRtc_Word32 VPMSimpleSpatialResampler::UpsampleFrame(const VideoFrame& inFrame, VideoFrame& outFrame) { outFrame.CopyFrame(inFrame); float ratioWidth = _targetWidth / (float)inFrame.Width(); float ratioHeight = _targetHeight / (float)inFrame.Height(); WebRtc_UWord32 scaledWidth = 0; WebRtc_UWord32 scaledHeight = 0; if(ratioWidth > 1 || ratioHeight > 1) { // scale up if(ratioWidth <= 1.5 && ratioHeight <= 1.5) { // scale up 1.5 WebRtc_Word32 ret = ScaleI420Up3_2(inFrame.Width(), inFrame.Height(), outFrame.Buffer(), outFrame.Size(), scaledWidth, scaledHeight); if (ret < 0) return VPM_GENERAL_ERROR; } else if(ratioWidth <= 2 && ratioHeight <= 2) { // scale up 2 WebRtc_Word32 ret = ScaleI420Up2(inFrame.Width(), inFrame.Height(), outFrame.Buffer(), outFrame.Size(), scaledWidth, scaledHeight); if (ret < 0) return VPM_GENERAL_ERROR; } else if(ratioWidth <= 2.25 && ratioHeight <= 2.25) { // scale up 2.25 WebRtc_Word32 ret = ScaleI420Up3_2(inFrame.Width(), inFrame.Height(), outFrame.Buffer(), outFrame.Size(), scaledWidth, scaledHeight); if (ret < 0) return VPM_GENERAL_ERROR; ret = ScaleI420Up3_2(scaledWidth, scaledHeight, outFrame.Buffer(), outFrame.Size(), scaledWidth, scaledHeight); if (ret < 0) return VPM_GENERAL_ERROR; } else if(ratioWidth <= 3 && ratioHeight <= 3) { // scale up 3 WebRtc_Word32 ret = ScaleI420Up2(inFrame.Width(), inFrame.Height(), outFrame.Buffer(), outFrame.Size(), scaledWidth, scaledHeight); if (ret < 0) return VPM_GENERAL_ERROR; ret = ScaleI420Up3_2(scaledWidth, scaledHeight, outFrame.Buffer(), outFrame.Size(), scaledWidth, scaledHeight); if (ret < 0) return VPM_GENERAL_ERROR; } else if(ratioWidth <= 4 && ratioHeight <= 4) { // scale up 4 WebRtc_Word32 ret = ScaleI420Up2(inFrame.Width(), inFrame.Height(), outFrame.Buffer(), outFrame.Size(), scaledWidth, scaledHeight); if (ret < 0) return VPM_GENERAL_ERROR; ret = ScaleI420Up2(scaledWidth, scaledHeight, outFrame.Buffer(), outFrame.Size(), scaledWidth, scaledHeight); if (ret < 0) return VPM_GENERAL_ERROR; } //TODO: what if ratioWidth/Height >= 8 ? if (scaledWidth <= 0 || scaledHeight <= 0) { return VPM_GENERAL_ERROR; } if ((static_cast<WebRtc_UWord32>(scaledWidth) > _targetWidth) || (static_cast<WebRtc_UWord32>(scaledHeight) > _targetHeight)) { WebRtc_Word32 ret = CutI420Frame(outFrame.Buffer(), scaledWidth, scaledHeight, _targetWidth, _targetHeight); if (ret < 0) return VPM_GENERAL_ERROR; } } else { return VPM_GENERAL_ERROR; } outFrame.SetWidth(_targetWidth); outFrame.SetHeight(_targetHeight); outFrame.SetLength(_targetWidth * _targetHeight * 3 / 2); return VPM_OK; } WebRtc_Word32 VPMSimpleSpatialResampler::CropSize(WebRtc_UWord32 width, WebRtc_UWord32 height, WebRtc_UWord32& croppedWidth, WebRtc_UWord32& croppedHeight) const { // Crop the image to a width and height which is a // multiple of two, so that we can do a simpler scaling. croppedWidth = _targetWidth; croppedHeight = _targetHeight; if (width >= 8 * _targetWidth && height >= 8 * _targetHeight) { croppedWidth = 8 * _targetWidth; croppedHeight = 8 * _targetHeight; } else if (width >= 4 * _targetWidth && height >= 4 * _targetHeight) { croppedWidth = 4 * _targetWidth; croppedHeight = 4 * _targetHeight; } else if (width >= 2 * _targetWidth && height >= 2 * _targetHeight) { croppedWidth = 2 * _targetWidth; croppedHeight = 2 * _targetHeight; } return VPM_OK; } WebRtc_Word32 VPMSimpleSpatialResampler::SubsampleMultipleOf2(VideoFrame& frame) { WebRtc_UWord32 tempWidth = frame.Width(); WebRtc_UWord32 tempHeight = frame.Height(); while (tempWidth / _targetWidth >= 2 && tempHeight / _targetHeight >= 2) { ScaleI420FrameQuarter(tempWidth, tempHeight, frame.Buffer()); tempWidth /= 2; tempHeight /= 2; } frame.SetWidth(tempWidth); frame.SetHeight(tempHeight); frame.SetLength(frame.Width() * frame.Height() * 3 / 2); return VPM_OK; } bool VPMSimpleSpatialResampler::ExactMultiplier(WebRtc_UWord32 width, WebRtc_UWord32 height) const { bool exactMultiplier = false; if (_targetWidth % width == 0 && _targetHeight % height == 0) { // we have a multiple, is it an even multiple? WebRtc_Word32 widthMultiple = _targetWidth / width; WebRtc_Word32 heightMultiple = _targetHeight / height; if ((widthMultiple == 2 && heightMultiple == 2) || (widthMultiple == 4 && heightMultiple == 4) || (widthMultiple == 8 && heightMultiple == 8) || (widthMultiple == 1 && heightMultiple == 1)) { exactMultiplier = true; } } return exactMultiplier; } WebRtc_Word32 VPMSimpleSpatialResampler::BiLinearInterpolation(const VideoFrame& inFrame, VideoFrame& outFrame) { WebRtc_Word32 retVal; if (_interpolatorPtr == NULL) { _interpolatorPtr = new interpolator(); } // set bi-linear interpolator retVal = _interpolatorPtr->Set(inFrame.Width(), inFrame.Height(), _targetWidth, _targetHeight, kI420, kI420, kBilinear ); if (retVal < 0 ) { return retVal; } // Verify size of output buffer outFrame.VerifyAndAllocate(_targetHeight * _targetWidth * 3 >> 1); WebRtc_UWord32 outSz = outFrame.Size(); // interpolate frame retVal = _interpolatorPtr->Interpolate(inFrame.Buffer(), outFrame.Buffer(), outSz); assert(outSz <= outFrame.Size()); // returns height if (retVal < 0) { return retVal; } // Set output frame parameters outFrame.SetHeight(_targetHeight); outFrame.SetWidth(_targetWidth); outFrame.SetLength(outSz); outFrame.SetTimeStamp(inFrame.TimeStamp()); return VPM_OK; } WebRtc_UWord32 VPMSimpleSpatialResampler::TargetHeight() { return _targetHeight; } WebRtc_UWord32 VPMSimpleSpatialResampler::TargetWidth() { return _targetWidth; } } //namespace <|endoftext|>
<commit_before>#include "LogSinks.hpp" #include "macros.hpp" #include <unistd.h> #include <iostream> #include <ctime> static const char* const ESCAPE_BOLD = "\x1B[1m"; static const char* const ESCAPE_NORMALFONT = "\x1B[0m"; static const char* const ESCAPE_BLACK_FOREGROUND = "\x1B[30m"; static const char* const ESCAPE_RED_FOREGROUND = "\x1B[31m"; static const char* const ESCAPE_GREEN_FOREGROUND = "\x1B[32m"; static const char* const ESCAPE_YELLOW_FOREGROUND = "\x1B[33m"; static const char* const ESCAPE_BLUE_FOREGROUND = "\x1B[34m"; static const char* const ESCAPE_MAGENTA_FOREGROUND = "\x1B[35m"; static const char* const ESCAPE_CYAN_FOREGROUND = "\x1B[36m"; static const char* const ESCAPE_WHITE_FOREGROUND = "\x1B[37m"; static void HOT printDateTime(uint64_t timestamp, std::ostream& stream) { //Convert timestamp to timeval struct timeval tv; tv.tv_sec = timestamp / 1000; tv.tv_usec = (timestamp % 1000) * 1000; //Format the tm data char dateBuffer[32]; size_t formattedLength = strftime(dateBuffer, 32, "%F %T", localtime(&(tv.tv_sec))); assert(formattedLength > 0); //Format the subsecond part snprintf(dateBuffer + formattedLength, 32 - formattedLength, ".%03lu", (unsigned long) (tv.tv_usec / 1000)); stream << '[' << dateBuffer << ']'; } std::string logLevelToString(LogLevel logLevel) { switch (logLevel) { case LogLevel::Critical: { return "[Critical]"; } case LogLevel::Error: { return "[Error]"; } case LogLevel::Warn: { return "[Warn]"; } case LogLevel::Info: { return "[Info]"; } case LogLevel::Debug: { return "[Debug]"; } case LogLevel::Trace: { return "[Trace]"; } default: { return "[Unknown]"; } } } LogSink::~LogSink() { } StderrLogSink::StderrLogSink() : coloredLogging(isatty(fileno(stderr))) { } void StderrLogSink::setColoredLogging(bool value) { this->coloredLogging = value; } void HOT StderrLogSink::log(LogLevel logLevel, uint64_t timestamp, const std::string& senderName, const std::string& logMessage) { switch (logLevel) { case LogLevel::Critical: { if(coloredLogging) { std::cerr << ESCAPE_BOLD << ESCAPE_RED_FOREGROUND; } printDateTime(timestamp, std::cerr); std::cerr << "[Error] " << senderName << " - " << logMessage; if(coloredLogging) { std::cerr << ESCAPE_NORMALFONT << ESCAPE_BLACK_FOREGROUND; } std::cerr << std::endl; break; } case LogLevel::Error: { if(coloredLogging) { std::cerr << ESCAPE_RED_FOREGROUND; } printDateTime(timestamp, std::cerr); std::cerr << "[Error] " << senderName << " - "; if(coloredLogging) { std::cerr << ESCAPE_BLACK_FOREGROUND << std::endl; } std::cerr << logMessage << std::endl; break; } case LogLevel::Warn: { if(coloredLogging) { std::cerr << ESCAPE_YELLOW_FOREGROUND; } printDateTime(timestamp, std::cerr); std::cerr << "[Warning] " << senderName << " - "; if(coloredLogging) { std::cerr << ESCAPE_BLACK_FOREGROUND; } std::cerr << logMessage << std::endl; break; } case LogLevel::Info: { if(coloredLogging) { std::cerr << ESCAPE_GREEN_FOREGROUND; } printDateTime(timestamp, std::cerr); std::cerr << "[Info] " << senderName << " - "; if(coloredLogging) { std::cerr << ESCAPE_BLACK_FOREGROUND; } std::cerr << logMessage << std::endl; break; } case LogLevel::Debug: { if(coloredLogging) { std::cerr << ESCAPE_BLUE_FOREGROUND; } printDateTime(timestamp, std::cerr); std::cerr << "[Debug] " << senderName << " - "; if(coloredLogging) { std::cerr << ESCAPE_BLACK_FOREGROUND; } std::cerr << logMessage << std::endl; break; } case LogLevel::Trace: { if(coloredLogging) { std::cerr << ESCAPE_CYAN_FOREGROUND; } printDateTime(timestamp, std::cerr); std::cerr << "[Trace] " << senderName << " - "; if(coloredLogging) { std::cerr << ESCAPE_BLACK_FOREGROUND; } std::cerr << logMessage << std::endl; break; } default: { printDateTime(timestamp, std::cerr); std::cerr << "[Unknown] " << senderName << " - " << logMessage << std::endl; break; } } } FileLogSink::FileLogSink(const std::string& filename) : fout(filename.c_str()), filename(filename) { } FileLogSink::~FileLogSink() { fout.close(); } void FileLogSink::log(LogLevel logLevel, uint64_t timestamp, const std::string& senderName, const std::string& logMessage) { printDateTime(timestamp, fout); fout << logLevelToString(logLevel) << senderName << " - " << logMessage << std::endl; } <commit_msg>Fix file logging format<commit_after>#include "LogSinks.hpp" #include "macros.hpp" #include <unistd.h> #include <iostream> #include <ctime> static const char* const ESCAPE_BOLD = "\x1B[1m"; static const char* const ESCAPE_NORMALFONT = "\x1B[0m"; static const char* const ESCAPE_BLACK_FOREGROUND = "\x1B[30m"; static const char* const ESCAPE_RED_FOREGROUND = "\x1B[31m"; static const char* const ESCAPE_GREEN_FOREGROUND = "\x1B[32m"; static const char* const ESCAPE_YELLOW_FOREGROUND = "\x1B[33m"; static const char* const ESCAPE_BLUE_FOREGROUND = "\x1B[34m"; static const char* const ESCAPE_MAGENTA_FOREGROUND = "\x1B[35m"; static const char* const ESCAPE_CYAN_FOREGROUND = "\x1B[36m"; static const char* const ESCAPE_WHITE_FOREGROUND = "\x1B[37m"; static void HOT printDateTime(uint64_t timestamp, std::ostream& stream) { //Convert timestamp to timeval struct timeval tv; tv.tv_sec = timestamp / 1000; tv.tv_usec = (timestamp % 1000) * 1000; //Format the tm data char dateBuffer[32]; size_t formattedLength = strftime(dateBuffer, 32, "%F %T", localtime(&(tv.tv_sec))); assert(formattedLength > 0); //Format the subsecond part snprintf(dateBuffer + formattedLength, 32 - formattedLength, ".%03lu", (unsigned long) (tv.tv_usec / 1000)); stream << '[' << dateBuffer << ']'; } std::string logLevelToString(LogLevel logLevel) { switch (logLevel) { case LogLevel::Critical: { return "[Critical]"; } case LogLevel::Error: { return "[Error]"; } case LogLevel::Warn: { return "[Warn]"; } case LogLevel::Info: { return "[Info]"; } case LogLevel::Debug: { return "[Debug]"; } case LogLevel::Trace: { return "[Trace]"; } default: { return "[Unknown]"; } } } LogSink::~LogSink() { } StderrLogSink::StderrLogSink() : coloredLogging(isatty(fileno(stderr))) { } void StderrLogSink::setColoredLogging(bool value) { this->coloredLogging = value; } void HOT StderrLogSink::log(LogLevel logLevel, uint64_t timestamp, const std::string& senderName, const std::string& logMessage) { switch (logLevel) { case LogLevel::Critical: { if(coloredLogging) { std::cerr << ESCAPE_BOLD << ESCAPE_RED_FOREGROUND; } printDateTime(timestamp, std::cerr); std::cerr << "[Error] " << senderName << " - " << logMessage; if(coloredLogging) { std::cerr << ESCAPE_NORMALFONT << ESCAPE_BLACK_FOREGROUND; } std::cerr << std::endl; break; } case LogLevel::Error: { if(coloredLogging) { std::cerr << ESCAPE_RED_FOREGROUND; } printDateTime(timestamp, std::cerr); std::cerr << "[Error] " << senderName << " - "; if(coloredLogging) { std::cerr << ESCAPE_BLACK_FOREGROUND << std::endl; } std::cerr << logMessage << std::endl; break; } case LogLevel::Warn: { if(coloredLogging) { std::cerr << ESCAPE_YELLOW_FOREGROUND; } printDateTime(timestamp, std::cerr); std::cerr << "[Warning] " << senderName << " - "; if(coloredLogging) { std::cerr << ESCAPE_BLACK_FOREGROUND; } std::cerr << logMessage << std::endl; break; } case LogLevel::Info: { if(coloredLogging) { std::cerr << ESCAPE_GREEN_FOREGROUND; } printDateTime(timestamp, std::cerr); std::cerr << "[Info] " << senderName << " - "; if(coloredLogging) { std::cerr << ESCAPE_BLACK_FOREGROUND; } std::cerr << logMessage << std::endl; break; } case LogLevel::Debug: { if(coloredLogging) { std::cerr << ESCAPE_BLUE_FOREGROUND; } printDateTime(timestamp, std::cerr); std::cerr << "[Debug] " << senderName << " - "; if(coloredLogging) { std::cerr << ESCAPE_BLACK_FOREGROUND; } std::cerr << logMessage << std::endl; break; } case LogLevel::Trace: { if(coloredLogging) { std::cerr << ESCAPE_CYAN_FOREGROUND; } printDateTime(timestamp, std::cerr); std::cerr << "[Trace] " << senderName << " - "; if(coloredLogging) { std::cerr << ESCAPE_BLACK_FOREGROUND; } std::cerr << logMessage << std::endl; break; } default: { printDateTime(timestamp, std::cerr); std::cerr << "[Unknown] " << senderName << " - " << logMessage << std::endl; break; } } } FileLogSink::FileLogSink(const std::string& filename) : fout(filename.c_str()), filename(filename) { } FileLogSink::~FileLogSink() { fout.close(); } void FileLogSink::log(LogLevel logLevel, uint64_t timestamp, const std::string& senderName, const std::string& logMessage) { printDateTime(timestamp, fout); fout << logLevelToString(logLevel) << ' ' << senderName << " - " << logMessage << std::endl; } <|endoftext|>
<commit_before>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE Main #include <boost/test/unit_test.hpp> #include <time_ordered_set.h> #include <bucket.h> class Moc_Storage :public memseries::storage::AbstractStorage { public: size_t writed_count; std::vector<memseries::Meas> meases; memseries::append_result append(const memseries::Meas::PMeas begin, const size_t size) { writed_count+=size; return memseries::append_result(size,0); } memseries::append_result append(const memseries::Meas &value) { meases.push_back(value); writed_count += 1; return memseries::append_result(1,0); } memseries::storage::Reader_ptr readInterval(const memseries::IdArray &ids, memseries::Flag flag, memseries::Time from, memseries::Time to) { return nullptr; } memseries::storage::Reader_ptr readInTimePoint(const memseries::IdArray &ids, memseries::Flag flag, memseries::Time time_point) { return nullptr; } memseries::Time minTime() { return 0; } /// max time of writed meas memseries::Time maxTime() { return 0; } }; BOOST_AUTO_TEST_CASE(TimeOrderedSetTest) { const size_t max_size = 10; auto base = memseries::storage::TimeOrderedSet{ max_size }; //with move ctor check memseries::storage::TimeOrderedSet tos(std::move(base)); auto e = memseries::Meas::empty(); for (size_t i = 0; i < max_size; i++) { e.time = max_size - i; BOOST_CHECK(!tos.is_full()); BOOST_CHECK(tos.append(e)); } e.time = max_size; BOOST_CHECK(!tos.append(e)); //is_full BOOST_CHECK(tos.is_full()); {//check copy ctor and operator= memseries::storage::TimeOrderedSet copy_tos{ tos }; BOOST_CHECK_EQUAL(copy_tos.size(), max_size); memseries::storage::TimeOrderedSet copy_assign{}; copy_assign = copy_tos; auto a = copy_assign.as_array(); BOOST_CHECK_EQUAL(a.size(), max_size); for (size_t i = 1; i <= max_size; i++) { auto e = a[i - 1]; BOOST_CHECK_EQUAL(e.time, i); } BOOST_CHECK_EQUAL(copy_assign.minTime(), memseries::Time(1)); BOOST_CHECK_EQUAL(copy_assign.maxTime(), memseries::Time(max_size)); } BOOST_CHECK(tos.is_full()); e.time=max_size+1; BOOST_CHECK(tos.append(e,true)); BOOST_CHECK_EQUAL(tos.size(),max_size+1); } BOOST_AUTO_TEST_CASE(BucketTest) { std::shared_ptr<Moc_Storage> stor(new Moc_Storage); stor->writed_count = 0; const size_t max_size = 10; const size_t max_count = 10; auto base = memseries::storage::Bucket{ max_size, max_count,stor}; //with move ctor check memseries::storage::Bucket mbucket(std::move(base)); BOOST_CHECK_EQUAL(mbucket.max_size(),max_count); auto e = memseries::Meas::empty(); //max time always memseries::Time t=100; for (size_t i = 0; i < max_size; i++) { e.time = t; t += 1; BOOST_CHECK(mbucket.append(e)); } t = 50; for (size_t i = 0; i < max_size; i++) { e.time = t; t += 1; BOOST_CHECK(mbucket.append(e)); } t = 10; for (size_t i = 0; i < max_size; i++) { e.time = t; t += 1; BOOST_CHECK(mbucket.append(e)); } t = 70; for (size_t i = 0; i < max_size; i++) { e.time = t; t += 1; BOOST_CHECK(mbucket.append(e)); } //buckets count; BOOST_CHECK_EQUAL(mbucket.size(), 4); //now bucket is full //TODO remove this //BOOST_CHECK(!mbucket.append(e)); //insert in exists time e.time = 12; BOOST_CHECK(mbucket.append(e)); e.time = 13; BOOST_CHECK(mbucket.append(e)); e.time = 14; BOOST_CHECK(mbucket.append(e)); BOOST_CHECK_EQUAL(mbucket.size(), 2); // fill storage to initiate flush to storage auto wr = mbucket.writed_count(); auto end = max_size*max_count - wr; for (size_t i = 0; i <end; i++) { t ++; BOOST_CHECK(mbucket.append(e)); } //bucket must be full; BOOST_CHECK(mbucket.is_full()); auto wcount = mbucket.writed_count(); //drop part of data to storage; e.time++; BOOST_CHECK(mbucket.append(e)); BOOST_CHECK(!mbucket.is_full()); BOOST_CHECK_EQUAL(stor->writed_count+mbucket.writed_count(),wcount+1);// one appended when drop to storage. //time should be increased for (size_t i = 0; i < stor->meases.size() - 1; i++) { BOOST_CHECK(stor->meases[i].time<stor->meases[i+1].time); } stor->meases.clear(); stor->writed_count = 0; mbucket.flush(); for (size_t i = 0; i < stor->meases.size() - 1; i++) { BOOST_CHECK(stor->meases[i].time<=stor->meases[i + 1].time); } } <commit_msg>gcc build<commit_after>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE Main #include <boost/test/unit_test.hpp> #include <time_ordered_set.h> #include <bucket.h> class Moc_Storage :public memseries::storage::AbstractStorage { public: size_t writed_count; std::vector<memseries::Meas> meases; memseries::append_result append(const memseries::Meas::PMeas begin, const size_t size) { writed_count+=size; return memseries::append_result(size,0); } memseries::append_result append(const memseries::Meas &value) { meases.push_back(value); writed_count += 1; return memseries::append_result(1,0); } memseries::storage::Reader_ptr readInterval(const memseries::IdArray &ids, memseries::Flag flag, memseries::Time from, memseries::Time to) { return nullptr; } memseries::storage::Reader_ptr readInTimePoint(const memseries::IdArray &ids, memseries::Flag flag, memseries::Time time_point) { return nullptr; } memseries::Time minTime() { return 0; } /// max time of writed meas memseries::Time maxTime() { return 0; } }; BOOST_AUTO_TEST_CASE(TimeOrderedSetTest) { const size_t max_size = 10; auto base = memseries::storage::TimeOrderedSet{ max_size }; //with move ctor check memseries::storage::TimeOrderedSet tos(std::move(base)); auto e = memseries::Meas::empty(); for (size_t i = 0; i < max_size; i++) { e.time = max_size - i; BOOST_CHECK(!tos.is_full()); BOOST_CHECK(tos.append(e)); } e.time = max_size; BOOST_CHECK(!tos.append(e)); //is_full BOOST_CHECK(tos.is_full()); {//check copy ctor and operator= memseries::storage::TimeOrderedSet copy_tos{ tos }; BOOST_CHECK_EQUAL(copy_tos.size(), max_size); memseries::storage::TimeOrderedSet copy_assign{}; copy_assign = copy_tos; auto a = copy_assign.as_array(); BOOST_CHECK_EQUAL(a.size(), max_size); for (size_t i = 1; i <= max_size; i++) { auto e = a[i - 1]; BOOST_CHECK_EQUAL(e.time, i); } BOOST_CHECK_EQUAL(copy_assign.minTime(), memseries::Time(1)); BOOST_CHECK_EQUAL(copy_assign.maxTime(), memseries::Time(max_size)); } BOOST_CHECK(tos.is_full()); e.time=max_size+1; BOOST_CHECK(tos.append(e,true)); BOOST_CHECK_EQUAL(tos.size(),max_size+1); } BOOST_AUTO_TEST_CASE(BucketTest) { std::shared_ptr<Moc_Storage> stor(new Moc_Storage); stor->writed_count = 0; const size_t max_size = 10; const size_t max_count = 10; auto base = memseries::storage::Bucket{ max_size, max_count,stor}; //with move ctor check memseries::storage::Bucket mbucket(std::move(base)); BOOST_CHECK_EQUAL(mbucket.max_size(),max_count); auto e = memseries::Meas::empty(); //max time always memseries::Time t=100; for (size_t i = 0; i < max_size; i++) { e.time = t; t += 1; BOOST_CHECK(mbucket.append(e)); } t = 50; for (size_t i = 0; i < max_size; i++) { e.time = t; t += 1; BOOST_CHECK(mbucket.append(e)); } t = 10; for (size_t i = 0; i < max_size; i++) { e.time = t; t += 1; BOOST_CHECK(mbucket.append(e)); } t = 70; for (size_t i = 0; i < max_size; i++) { e.time = t; t += 1; BOOST_CHECK(mbucket.append(e)); } //buckets count; BOOST_CHECK_EQUAL(mbucket.size(), size_t(4)); //now bucket is full //TODO remove this //BOOST_CHECK(!mbucket.append(e)); //insert in exists time e.time = 12; BOOST_CHECK(mbucket.append(e)); e.time = 13; BOOST_CHECK(mbucket.append(e)); e.time = 14; BOOST_CHECK(mbucket.append(e)); BOOST_CHECK_EQUAL(mbucket.size(), size_t(2)); // fill storage to initiate flush to storage auto wr = mbucket.writed_count(); auto end = max_size*max_count - wr; for (size_t i = 0; i <end; i++) { t ++; BOOST_CHECK(mbucket.append(e)); } //bucket must be full; BOOST_CHECK(mbucket.is_full()); auto wcount = mbucket.writed_count(); //drop part of data to storage; e.time++; BOOST_CHECK(mbucket.append(e)); BOOST_CHECK(!mbucket.is_full()); BOOST_CHECK_EQUAL(stor->writed_count+mbucket.writed_count(),wcount+1);// one appended when drop to storage. //time should be increased for (size_t i = 0; i < stor->meases.size() - 1; i++) { BOOST_CHECK(stor->meases[i].time<stor->meases[i+1].time); } stor->meases.clear(); stor->writed_count = 0; mbucket.flush(); for (size_t i = 0; i < stor->meases.size() - 1; i++) { BOOST_CHECK(stor->meases[i].time<=stor->meases[i + 1].time); } } <|endoftext|>
<commit_before>// Given a stream of integers and a window size, calculate the moving average of // all integers in the sliding window. // For example, // MovingAverage m = new MovingAverage(3); // m.next(1) = 1 // m.next(10) = (1 + 10) / 2 // m.next(3) = (1 + 10 + 3) / 3 // m.next(5) = (10 + 3 + 5) / 3 class MovingAverage { public: /** Initialize your data structure here. */ MovingAverage(int size) : sz(size) {} double next(int val) { if (cnt < sz) ++cnt; else { sum -= vals.front(); vals.pop_front(); } sum += val; vals.push_back(val); // return cnt ? static_cast<double>(sum) / cnt : DBL_MAX; return static_cast<double>(sum) / cnt; } private: int sz = 0, cnt = 0, sum = 0; deque<int> vals; }; /** * Your MovingAverage object will be instantiated and called as such: * MovingAverage obj = new MovingAverage(size); * double param_1 = obj.next(val); */<commit_msg>update 346<commit_after>// Given a stream of integers and a window size, calculate the moving average of // all integers in the sliding window. // For example, // MovingAverage m = new MovingAverage(3); // m.next(1) = 1 // m.next(10) = (1 + 10) / 2 // m.next(3) = (1 + 10 + 3) / 3 // m.next(5) = (10 + 3 + 5) / 3 class MovingAverage { public: /** Initialize your data structure here. */ MovingAverage(int size) : sz(size) {} double next(int val) { sum += val; vals.push(val); if (vals.size() > sz) { sum -= vals.front(); vals.pop(); } // return cnt ? static_cast<double>(sum) / cnt : DBL_MAX; return sum / vals.size(); } private: int sz = 0; double sum = 0; queue<int> vals; }; /** * Your MovingAverage object will be instantiated and called as such: * MovingAverage obj = new MovingAverage(size); * double param_1 = obj.next(val); */<|endoftext|>
<commit_before>// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __STOUT_DURATION_HPP__ #define __STOUT_DURATION_HPP__ #include <ctype.h> // For 'isdigit'. // For 'timeval'. #ifndef __WINDOWS__ #include <sys/time.h> #endif // __WINDOWS__ #include <iomanip> #include <iostream> #include <limits> #include <string> #include "error.hpp" #include "numify.hpp" #include "try.hpp" class Duration { public: static Try<Duration> parse(const std::string& s) { // TODO(benh): Support negative durations (i.e., starts with '-'). size_t index = 0; while (index < s.size()) { if (isdigit(s[index]) || s[index] == '.') { index++; continue; } Try<double> value = numify<double>(s.substr(0, index)); if (value.isError()) { return Error(value.error()); } const std::string unit = s.substr(index); if (unit == "ns") { return Duration(value.get(), NANOSECONDS); } else if (unit == "us") { return Duration(value.get(), MICROSECONDS); } else if (unit == "ms") { return Duration(value.get(), MILLISECONDS); } else if (unit == "secs") { return Duration(value.get(), SECONDS); } else if (unit == "mins") { return Duration(value.get(), MINUTES); } else if (unit == "hrs") { return Duration(value.get(), HOURS); } else if (unit == "days") { return Duration(value.get(), DAYS); } else if (unit == "weeks") { return Duration(value.get(), WEEKS); } else { return Error( "Unknown duration unit '" + unit + "'; supported units are" " 'ns', 'us', 'ms', 'secs', 'mins', 'hrs', 'days', and 'weeks'"); } } return Error("Invalid duration '" + s + "'"); } static Try<Duration> create(double seconds); constexpr Duration() : nanos(0) {} explicit Duration(const timeval& t) { nanos = t.tv_sec * SECONDS + t.tv_usec * MICROSECONDS; } int64_t ns() const { return nanos; } double us() const { return static_cast<double>(nanos) / MICROSECONDS; } double ms() const { return static_cast<double>(nanos) / MILLISECONDS; } double secs() const { return static_cast<double>(nanos) / SECONDS; } double mins() const { return static_cast<double>(nanos) / MINUTES; } double hrs() const { return static_cast<double>(nanos) / HOURS; } double days() const { return static_cast<double>(nanos) / DAYS; } double weeks() const { return static_cast<double>(nanos) / WEEKS; } struct timeval timeval() const { struct timeval t; t.tv_sec = secs(); t.tv_usec = us() - (t.tv_sec * MILLISECONDS); return t; } bool operator<(const Duration& d) const { return nanos < d.nanos; } bool operator<=(const Duration& d) const { return nanos <= d.nanos; } bool operator>(const Duration& d) const { return nanos > d.nanos; } bool operator>=(const Duration& d) const { return nanos >= d.nanos; } bool operator==(const Duration& d) const { return nanos == d.nanos; } bool operator!=(const Duration& d) const { return nanos != d.nanos; } Duration& operator+=(const Duration& that) { nanos += that.nanos; return *this; } Duration& operator-=(const Duration& that) { nanos -= that.nanos; return *this; } Duration& operator*=(double multiplier) { nanos = static_cast<int64_t>(nanos * multiplier); return *this; } Duration& operator/=(double divisor) { nanos = static_cast<int64_t>(nanos / divisor); return *this; } Duration operator+(const Duration& that) const { Duration sum = *this; sum += that; return sum; } Duration operator-(const Duration& that) const { Duration diff = *this; diff -= that; return diff; } Duration operator*(double multiplier) const { Duration product = *this; product *= multiplier; return product; } Duration operator/(double divisor) const { Duration quotient = *this; quotient /= divisor; return quotient; } // A constant holding the maximum value a Duration can have. static constexpr Duration max(); // A constant holding the minimum (negative) value a Duration can // have. static constexpr Duration min(); // A constant holding a Duration of a "zero" value. static constexpr Duration zero() { return Duration(); } protected: static constexpr int64_t NANOSECONDS = 1; static constexpr int64_t MICROSECONDS = 1000 * NANOSECONDS; static constexpr int64_t MILLISECONDS = 1000 * MICROSECONDS; static constexpr int64_t SECONDS = 1000 * MILLISECONDS; static constexpr int64_t MINUTES = 60 * SECONDS; static constexpr int64_t HOURS = 60 * MINUTES; static constexpr int64_t DAYS = 24 * HOURS; static constexpr int64_t WEEKS = 7 * DAYS; // Construct from a (value, unit) pair. constexpr Duration(int64_t value, int64_t unit) : nanos(value * unit) {} private: // Used only by "parse". constexpr Duration(double value, int64_t unit) : nanos(static_cast<int64_t>(value * unit)) {} int64_t nanos; friend std::ostream& operator<<( std::ostream& stream, const Duration& duration); }; class Nanoseconds : public Duration { public: explicit constexpr Nanoseconds(int64_t nanoseconds) : Duration(nanoseconds, NANOSECONDS) {} constexpr Nanoseconds(const Duration& d) : Duration(d) {} double value() const { return static_cast<double>(this->ns()); } static std::string units() { return "ns"; } }; class Microseconds : public Duration { public: explicit constexpr Microseconds(int64_t microseconds) : Duration(microseconds, MICROSECONDS) {} constexpr Microseconds(const Duration& d) : Duration(d) {} double value() const { return this->us(); } static std::string units() { return "us"; } }; class Milliseconds : public Duration { public: explicit constexpr Milliseconds(int64_t milliseconds) : Duration(milliseconds, MILLISECONDS) {} constexpr Milliseconds(const Duration& d) : Duration(d) {} double value() const { return this->ms(); } static std::string units() { return "ms"; } }; class Seconds : public Duration { public: explicit constexpr Seconds(int64_t seconds) : Duration(seconds, SECONDS) {} constexpr Seconds(const Duration& d) : Duration(d) {} double value() const { return this->secs(); } static std::string units() { return "secs"; } }; class Minutes : public Duration { public: explicit constexpr Minutes(int64_t minutes) : Duration(minutes, MINUTES) {} constexpr Minutes(const Duration& d) : Duration(d) {} double value() const { return this->mins(); } static std::string units() { return "mins"; } }; class Hours : public Duration { public: explicit constexpr Hours(int64_t hours) : Duration(hours, HOURS) {} constexpr Hours(const Duration& d) : Duration(d) {} double value() const { return this->hrs(); } static std::string units() { return "hrs"; } }; class Days : public Duration { public: explicit Days(int64_t days) : Duration(days, DAYS) {} Days(const Duration& d) : Duration(d) {} double value() const { return this->days(); } static std::string units() { return "days"; } }; class Weeks : public Duration { public: explicit constexpr Weeks(int64_t value) : Duration(value, WEEKS) {} constexpr Weeks(const Duration& d) : Duration(d) {} double value() const { return this->weeks(); } static std::string units() { return "weeks"; } }; inline std::ostream& operator<<(std::ostream& stream, const Duration& duration_) { long precision = stream.precision(); // Output the duration in full double precision. stream.precision(std::numeric_limits<double>::digits10); // Parse the duration as the sign and the absolute value. Duration duration = duration_; if (duration_ < Duration::zero()) { stream << "-"; // Duration::min() may not be representable as a positive Duration. if (duration_ == Duration::min()) { duration = Duration::max(); } else { duration = duration_ * -1; } } // First determine which bucket of time unit the duration falls into // then check whether the duration can be represented as a whole // number with this time unit or a smaller one. // e.g. 1.42857142857143weeks falls into the 'Weeks' bucket but // reads better with a smaller unit: '10days'. So we use 'days' // instead of 'weeks' to output the duration. int64_t nanoseconds = duration.ns(); if (duration < Microseconds(1)) { stream << duration.ns() << Nanoseconds::units(); } else if (duration < Milliseconds(1)) { if (nanoseconds % Duration::MICROSECONDS != 0) { // We can't get a whole number using this unit but we can at // one level down. stream << duration.ns() << Nanoseconds::units(); } else { stream << duration.us() << Microseconds::units(); } } else if (duration < Seconds(1)) { if (nanoseconds % Duration::MILLISECONDS != 0 && nanoseconds % Duration::MICROSECONDS == 0) { stream << duration.us() << Microseconds::units(); } else { stream << duration.ms() << Milliseconds::units(); } } else if (duration < Minutes(1)) { if (nanoseconds % Duration::SECONDS != 0 && nanoseconds % Duration::MILLISECONDS == 0) { stream << duration.ms() << Milliseconds::units(); } else { stream << duration.secs() << Seconds::units(); } } else if (duration < Hours(1)) { if (nanoseconds % Duration::MINUTES != 0 && nanoseconds % Duration::SECONDS == 0) { stream << duration.secs() << Seconds::units(); } else { stream << duration.mins() << Minutes::units(); } } else if (duration < Days(1)) { if (nanoseconds % Duration::HOURS != 0 && nanoseconds % Duration::MINUTES == 0) { stream << duration.mins() << Minutes::units(); } else { stream << duration.hrs() << Hours::units(); } } else if (duration < Weeks(1)) { if (nanoseconds % Duration::DAYS != 0 && nanoseconds % Duration::HOURS == 0) { stream << duration.hrs() << Hours::units(); } else { stream << duration.days() << Days::units(); } } else { if (nanoseconds % Duration::WEEKS != 0 && nanoseconds % Duration::DAYS == 0) { stream << duration.days() << Days::units(); } else { stream << duration.weeks() << Weeks::units(); } } // Return the stream to original formatting state. stream.precision(precision); return stream; } inline Try<Duration> Duration::create(double seconds) { if (seconds * SECONDS > std::numeric_limits<int64_t>::max() || seconds * SECONDS < std::numeric_limits<int64_t>::min()) { return Error("Argument out of the range that a Duration can represent due " "to int64_t's size limit"); } return Nanoseconds(static_cast<int64_t>(seconds * SECONDS)); } inline constexpr Duration Duration::max() { return Nanoseconds(std::numeric_limits<int64_t>::max()); } inline constexpr Duration Duration::min() { return Nanoseconds(std::numeric_limits<int64_t>::min()); } #endif // __STOUT_DURATION_HPP__ <commit_msg>Removed an unnecessary call to stream.precision() in Duration.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __STOUT_DURATION_HPP__ #define __STOUT_DURATION_HPP__ #include <ctype.h> // For 'isdigit'. // For 'timeval'. #ifndef __WINDOWS__ #include <sys/time.h> #endif // __WINDOWS__ #include <iomanip> #include <iostream> #include <limits> #include <string> #include "error.hpp" #include "numify.hpp" #include "try.hpp" class Duration { public: static Try<Duration> parse(const std::string& s) { // TODO(benh): Support negative durations (i.e., starts with '-'). size_t index = 0; while (index < s.size()) { if (isdigit(s[index]) || s[index] == '.') { index++; continue; } Try<double> value = numify<double>(s.substr(0, index)); if (value.isError()) { return Error(value.error()); } const std::string unit = s.substr(index); if (unit == "ns") { return Duration(value.get(), NANOSECONDS); } else if (unit == "us") { return Duration(value.get(), MICROSECONDS); } else if (unit == "ms") { return Duration(value.get(), MILLISECONDS); } else if (unit == "secs") { return Duration(value.get(), SECONDS); } else if (unit == "mins") { return Duration(value.get(), MINUTES); } else if (unit == "hrs") { return Duration(value.get(), HOURS); } else if (unit == "days") { return Duration(value.get(), DAYS); } else if (unit == "weeks") { return Duration(value.get(), WEEKS); } else { return Error( "Unknown duration unit '" + unit + "'; supported units are" " 'ns', 'us', 'ms', 'secs', 'mins', 'hrs', 'days', and 'weeks'"); } } return Error("Invalid duration '" + s + "'"); } static Try<Duration> create(double seconds); constexpr Duration() : nanos(0) {} explicit Duration(const timeval& t) { nanos = t.tv_sec * SECONDS + t.tv_usec * MICROSECONDS; } int64_t ns() const { return nanos; } double us() const { return static_cast<double>(nanos) / MICROSECONDS; } double ms() const { return static_cast<double>(nanos) / MILLISECONDS; } double secs() const { return static_cast<double>(nanos) / SECONDS; } double mins() const { return static_cast<double>(nanos) / MINUTES; } double hrs() const { return static_cast<double>(nanos) / HOURS; } double days() const { return static_cast<double>(nanos) / DAYS; } double weeks() const { return static_cast<double>(nanos) / WEEKS; } struct timeval timeval() const { struct timeval t; t.tv_sec = secs(); t.tv_usec = us() - (t.tv_sec * MILLISECONDS); return t; } bool operator<(const Duration& d) const { return nanos < d.nanos; } bool operator<=(const Duration& d) const { return nanos <= d.nanos; } bool operator>(const Duration& d) const { return nanos > d.nanos; } bool operator>=(const Duration& d) const { return nanos >= d.nanos; } bool operator==(const Duration& d) const { return nanos == d.nanos; } bool operator!=(const Duration& d) const { return nanos != d.nanos; } Duration& operator+=(const Duration& that) { nanos += that.nanos; return *this; } Duration& operator-=(const Duration& that) { nanos -= that.nanos; return *this; } Duration& operator*=(double multiplier) { nanos = static_cast<int64_t>(nanos * multiplier); return *this; } Duration& operator/=(double divisor) { nanos = static_cast<int64_t>(nanos / divisor); return *this; } Duration operator+(const Duration& that) const { Duration sum = *this; sum += that; return sum; } Duration operator-(const Duration& that) const { Duration diff = *this; diff -= that; return diff; } Duration operator*(double multiplier) const { Duration product = *this; product *= multiplier; return product; } Duration operator/(double divisor) const { Duration quotient = *this; quotient /= divisor; return quotient; } // A constant holding the maximum value a Duration can have. static constexpr Duration max(); // A constant holding the minimum (negative) value a Duration can // have. static constexpr Duration min(); // A constant holding a Duration of a "zero" value. static constexpr Duration zero() { return Duration(); } protected: static constexpr int64_t NANOSECONDS = 1; static constexpr int64_t MICROSECONDS = 1000 * NANOSECONDS; static constexpr int64_t MILLISECONDS = 1000 * MICROSECONDS; static constexpr int64_t SECONDS = 1000 * MILLISECONDS; static constexpr int64_t MINUTES = 60 * SECONDS; static constexpr int64_t HOURS = 60 * MINUTES; static constexpr int64_t DAYS = 24 * HOURS; static constexpr int64_t WEEKS = 7 * DAYS; // Construct from a (value, unit) pair. constexpr Duration(int64_t value, int64_t unit) : nanos(value * unit) {} private: // Used only by "parse". constexpr Duration(double value, int64_t unit) : nanos(static_cast<int64_t>(value * unit)) {} int64_t nanos; friend std::ostream& operator<<( std::ostream& stream, const Duration& duration); }; class Nanoseconds : public Duration { public: explicit constexpr Nanoseconds(int64_t nanoseconds) : Duration(nanoseconds, NANOSECONDS) {} constexpr Nanoseconds(const Duration& d) : Duration(d) {} double value() const { return static_cast<double>(this->ns()); } static std::string units() { return "ns"; } }; class Microseconds : public Duration { public: explicit constexpr Microseconds(int64_t microseconds) : Duration(microseconds, MICROSECONDS) {} constexpr Microseconds(const Duration& d) : Duration(d) {} double value() const { return this->us(); } static std::string units() { return "us"; } }; class Milliseconds : public Duration { public: explicit constexpr Milliseconds(int64_t milliseconds) : Duration(milliseconds, MILLISECONDS) {} constexpr Milliseconds(const Duration& d) : Duration(d) {} double value() const { return this->ms(); } static std::string units() { return "ms"; } }; class Seconds : public Duration { public: explicit constexpr Seconds(int64_t seconds) : Duration(seconds, SECONDS) {} constexpr Seconds(const Duration& d) : Duration(d) {} double value() const { return this->secs(); } static std::string units() { return "secs"; } }; class Minutes : public Duration { public: explicit constexpr Minutes(int64_t minutes) : Duration(minutes, MINUTES) {} constexpr Minutes(const Duration& d) : Duration(d) {} double value() const { return this->mins(); } static std::string units() { return "mins"; } }; class Hours : public Duration { public: explicit constexpr Hours(int64_t hours) : Duration(hours, HOURS) {} constexpr Hours(const Duration& d) : Duration(d) {} double value() const { return this->hrs(); } static std::string units() { return "hrs"; } }; class Days : public Duration { public: explicit Days(int64_t days) : Duration(days, DAYS) {} Days(const Duration& d) : Duration(d) {} double value() const { return this->days(); } static std::string units() { return "days"; } }; class Weeks : public Duration { public: explicit constexpr Weeks(int64_t value) : Duration(value, WEEKS) {} constexpr Weeks(const Duration& d) : Duration(d) {} double value() const { return this->weeks(); } static std::string units() { return "weeks"; } }; inline std::ostream& operator<<(std::ostream& stream, const Duration& duration_) { // Output the duration in full double precision and save the old precision. long precision = stream.precision(std::numeric_limits<double>::digits10); // Parse the duration as the sign and the absolute value. Duration duration = duration_; if (duration_ < Duration::zero()) { stream << "-"; // Duration::min() may not be representable as a positive Duration. if (duration_ == Duration::min()) { duration = Duration::max(); } else { duration = duration_ * -1; } } // First determine which bucket of time unit the duration falls into // then check whether the duration can be represented as a whole // number with this time unit or a smaller one. // e.g. 1.42857142857143weeks falls into the 'Weeks' bucket but // reads better with a smaller unit: '10days'. So we use 'days' // instead of 'weeks' to output the duration. int64_t nanoseconds = duration.ns(); if (duration < Microseconds(1)) { stream << duration.ns() << Nanoseconds::units(); } else if (duration < Milliseconds(1)) { if (nanoseconds % Duration::MICROSECONDS != 0) { // We can't get a whole number using this unit but we can at // one level down. stream << duration.ns() << Nanoseconds::units(); } else { stream << duration.us() << Microseconds::units(); } } else if (duration < Seconds(1)) { if (nanoseconds % Duration::MILLISECONDS != 0 && nanoseconds % Duration::MICROSECONDS == 0) { stream << duration.us() << Microseconds::units(); } else { stream << duration.ms() << Milliseconds::units(); } } else if (duration < Minutes(1)) { if (nanoseconds % Duration::SECONDS != 0 && nanoseconds % Duration::MILLISECONDS == 0) { stream << duration.ms() << Milliseconds::units(); } else { stream << duration.secs() << Seconds::units(); } } else if (duration < Hours(1)) { if (nanoseconds % Duration::MINUTES != 0 && nanoseconds % Duration::SECONDS == 0) { stream << duration.secs() << Seconds::units(); } else { stream << duration.mins() << Minutes::units(); } } else if (duration < Days(1)) { if (nanoseconds % Duration::HOURS != 0 && nanoseconds % Duration::MINUTES == 0) { stream << duration.mins() << Minutes::units(); } else { stream << duration.hrs() << Hours::units(); } } else if (duration < Weeks(1)) { if (nanoseconds % Duration::DAYS != 0 && nanoseconds % Duration::HOURS == 0) { stream << duration.hrs() << Hours::units(); } else { stream << duration.days() << Days::units(); } } else { if (nanoseconds % Duration::WEEKS != 0 && nanoseconds % Duration::DAYS == 0) { stream << duration.days() << Days::units(); } else { stream << duration.weeks() << Weeks::units(); } } // Return the stream to original formatting state. stream.precision(precision); return stream; } inline Try<Duration> Duration::create(double seconds) { if (seconds * SECONDS > std::numeric_limits<int64_t>::max() || seconds * SECONDS < std::numeric_limits<int64_t>::min()) { return Error("Argument out of the range that a Duration can represent due " "to int64_t's size limit"); } return Nanoseconds(static_cast<int64_t>(seconds * SECONDS)); } inline constexpr Duration Duration::max() { return Nanoseconds(std::numeric_limits<int64_t>::max()); } inline constexpr Duration Duration::min() { return Nanoseconds(std::numeric_limits<int64_t>::min()); } #endif // __STOUT_DURATION_HPP__ <|endoftext|>
<commit_before>/* OpenSceneGraph example, osgdepthpartion. * * 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. */ #include "DistanceAccumulator.h" #include <osg/Geode> #include <osg/Transform> #include <osg/Projection> #include <algorithm> #include <math.h> /** Function that sees whether one DistancePair should come before another in an sorted list. Used to sort the vector of DistancePairs. */ bool precedes(const DistanceAccumulator::DistancePair &a, const DistanceAccumulator::DistancePair &b) { // This results in sorting in order of descending far distances if(a.second > b.second) return true; else return false; } /** Computes distance betwen a point and the viewpoint of a matrix */ double distance(const osg::Vec3 &coord, const osg::Matrix& matrix) { return -( coord[0]*matrix(0,2) + coord[1]*matrix(1,2) + coord[2]*matrix(2,2) + matrix(3,2) ); } #define CURRENT_CLASS DistanceAccumulator CURRENT_CLASS::CURRENT_CLASS() : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN), _nearFarRatio(0.0005), _maxDepth(UINT_MAX) { setMatrices(osg::Matrix::identity(), osg::Matrix::identity()); reset(); } CURRENT_CLASS::~CURRENT_CLASS() {} void CURRENT_CLASS::pushLocalFrustum() { osg::Matrix& currMatrix = _viewMatrices.back(); // Compute the frustum in local space osg::Polytope localFrustum; localFrustum.setToUnitFrustum(false, false); localFrustum.transformProvidingInverse(currMatrix*_projectionMatrices.back()); _localFrusta.push_back(localFrustum); // Compute new bounding box corners bbCornerPair corner; corner.second = (currMatrix(0,2)<=0?1:0) | (currMatrix(1,2)<=0?2:0) | (currMatrix(2,2)<=0?4:0); corner.first = (~corner.second)&7; _bbCorners.push_back(corner); } void CURRENT_CLASS::pushDistancePair(double zNear, double zFar) { if(zFar > 0.0) // Make sure some of drawable is visible { // Make sure near plane is in front of viewpoint. if(zNear <= 0.0) { zNear = zFar*_nearFarRatio; if(zNear >= 1.0) zNear = 1.0; // 1.0 limit chosen arbitrarily! } // Add distance pair for current drawable _distancePairs.push_back(DistancePair(zNear, zFar)); // Override the current nearest/farthest planes if necessary if(zNear < _limits.first) _limits.first = zNear; if(zFar > _limits.second) _limits.second = zFar; } } /** Return true if the node should be traversed, and false if the bounding sphere of the node is small enough to be rendered by one Camera. If the latter is true, then store the node's near & far plane distances. */ bool CURRENT_CLASS::shouldContinueTraversal(osg::Node &node) { // Allow traversal to continue if we haven't reached maximum depth. bool keepTraversing = (_currentDepth < _maxDepth); const osg::BoundingSphere &bs = node.getBound(); double zNear = 0.0, zFar = 0.0; // Make sure bounding sphere is valid and within viewing volume if(bs.valid()) { if(!_localFrusta.back().contains(bs)) keepTraversing = false; else { // Compute near and far planes for this node zNear = distance(bs._center, _viewMatrices.back()); zFar = zNear + bs._radius; zNear -= bs._radius; // If near/far ratio is big enough, then we don't need to keep // traversing children of this node. if(zNear >= zFar*_nearFarRatio) keepTraversing = false; } } // If traversal should stop, then store this node's (near,far) pair if(!keepTraversing) pushDistancePair(zNear, zFar); return keepTraversing; } void CURRENT_CLASS::apply(osg::Node &node) { if(shouldContinueTraversal(node)) { // Traverse this node _currentDepth++; traverse(node); _currentDepth--; } } void CURRENT_CLASS::apply(osg::Projection &proj) { if(shouldContinueTraversal(proj)) { // Push the new projection matrix view frustum _projectionMatrices.push_back(proj.getMatrix()); pushLocalFrustum(); // Traverse the group _currentDepth++; traverse(proj); _currentDepth--; // Reload original matrix and frustum _localFrusta.pop_back(); _bbCorners.pop_back(); _projectionMatrices.pop_back(); } } void CURRENT_CLASS::apply(osg::Transform &transform) { if(shouldContinueTraversal(transform)) { // Compute transform for current node osg::Matrix currMatrix = _viewMatrices.back(); bool pushMatrix = transform.computeLocalToWorldMatrix(currMatrix, this); if(pushMatrix) { // Store the new modelview matrix and view frustum _viewMatrices.push_back(currMatrix); pushLocalFrustum(); } _currentDepth++; traverse(transform); _currentDepth--; if(pushMatrix) { // Restore the old modelview matrix and view frustum _localFrusta.pop_back(); _bbCorners.pop_back(); _viewMatrices.pop_back(); } } } void CURRENT_CLASS::apply(osg::Geode &geode) { // Contained drawables will only be individually considered if we are // allowed to continue traversing. if(shouldContinueTraversal(geode)) { osg::Drawable *drawable; double zNear, zFar; // Handle each drawable in this geode for(unsigned int i = 0; i < geode.getNumDrawables(); i++) { drawable = geode.getDrawable(i); const osg::BoundingBox &bb = drawable->getBound(); if(bb.valid()) { // Make sure drawable will be visible in the scene if(!_localFrusta.back().contains(bb)) continue; // Compute near/far distances for current drawable zNear = distance(bb.corner(_bbCorners.back().first), _viewMatrices.back()); zFar = distance(bb.corner(_bbCorners.back().second), _viewMatrices.back()); if(zNear > zFar) std::swap(zNear, zFar); pushDistancePair(zNear, zFar); } } } } void CURRENT_CLASS::setMatrices(const osg::Matrix &modelview, const osg::Matrix &projection) { _modelview = modelview; _projection = projection; } void CURRENT_CLASS::reset() { // Clear vectors & values _distancePairs.clear(); _cameraPairs.clear(); _limits.first = DBL_MAX; _limits.second = 0.0; _currentDepth = 0; // Initial transform matrix is the modelview matrix _viewMatrices.clear(); _viewMatrices.push_back(_modelview); // Set the initial projection matrix _projectionMatrices.clear(); _projectionMatrices.push_back(_projection); // Create a frustum without near/far planes, for cull computations _localFrusta.clear(); _bbCorners.clear(); pushLocalFrustum(); } void CURRENT_CLASS::computeCameraPairs() { // Nothing in the scene, so no cameras needed if(_distancePairs.empty()) return; // Entire scene can be handled by just one camera if(_limits.first >= _limits.second*_nearFarRatio) { _cameraPairs.push_back(_limits); return; } PairList::iterator i,j; // Sort the list of distance pairs by descending far distance std::sort(_distancePairs.begin(), _distancePairs.end(), precedes); // Combine overlapping distance pairs. The resulting set of distance // pairs (called combined pairs) will not overlap. PairList combinedPairs; DistancePair currPair = _distancePairs.front(); for(i = _distancePairs.begin(); i != _distancePairs.end(); i++) { // Current distance pair does not overlap current combined pair, so // save the current combined pair and start a new one. if(i->second < 0.99*currPair.first) { combinedPairs.push_back(currPair); currPair = *i; } // Current distance pair overlaps current combined pair, so expand // current combined pair to encompass distance pair. else currPair.first = std::min(i->first, currPair.first); } combinedPairs.push_back(currPair); // Add last pair // Compute the (near,far) distance pairs for each camera. // Each of these distance pairs is called a "view segment". double currNearLimit, numSegs, new_ratio; double ratio_invlog = 1.0/log(_nearFarRatio); unsigned int temp; for(i = combinedPairs.begin(); i != combinedPairs.end(); i++) { currPair = *i; // Save current view segment // Compute the fractional number of view segments needed to span // the current combined distance pair. currNearLimit = currPair.second*_nearFarRatio; if(currPair.first >= currNearLimit) numSegs = 1.0; else { numSegs = log(currPair.first/currPair.second)*ratio_invlog; // Compute the near plane of the last view segment //currNearLimit *= pow(_nearFarRatio, -floor(-numSegs) - 1); for(temp = (unsigned int)(-floor(-numSegs)); temp > 1; temp--) { currNearLimit *= _nearFarRatio; } } // See if the closest view segment can absorb other combined pairs for(j = i+1; j != combinedPairs.end(); j++) { // No other distance pairs can be included if(j->first < currNearLimit) break; } // If we did absorb another combined distance pair, recompute the // number of required view segments. if(i != j-1) { i = j-1; currPair.first = i->first; if(currPair.first >= currPair.second*_nearFarRatio) numSegs = 1.0; else numSegs = log(currPair.first/currPair.second)*ratio_invlog; } /* Compute an integer number of segments by rounding the fractional number of segments according to how many segments there are. In general, the more segments there are, the more likely that the integer number of segments will be rounded down. The purpose of this is to try to minimize the number of view segments that are used to render any section of the scene without violating the specified _nearFarRatio by too much. */ if(numSegs < 10.0) numSegs = floor(numSegs + 1.0 - 0.1*floor(numSegs)); else numSegs = floor(numSegs); // Compute the near/far ratio that will be used for each view segment // in this section of the scene. new_ratio = pow(currPair.first/currPair.second, 1.0/numSegs); // Add numSegs new view segments to the camera pairs list for(temp = (unsigned int)numSegs; temp > 0; temp--) { currPair.first = currPair.second*new_ratio; _cameraPairs.push_back(currPair); currPair.second = currPair.first; } } } void CURRENT_CLASS::setNearFarRatio(double ratio) { if(ratio <= 0.0 || ratio >= 1.0) return; _nearFarRatio = ratio; } #undef CURRENT_CLASS <commit_msg>From Tim Moore, compile fix for gcc 4.3<commit_after>/* OpenSceneGraph example, osgdepthpartion. * * 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. */ #include "DistanceAccumulator.h" #include <osg/Geode> #include <osg/Transform> #include <osg/Projection> #include <algorithm> #include <math.h> #include <limits.h> /** Function that sees whether one DistancePair should come before another in an sorted list. Used to sort the vector of DistancePairs. */ bool precedes(const DistanceAccumulator::DistancePair &a, const DistanceAccumulator::DistancePair &b) { // This results in sorting in order of descending far distances if(a.second > b.second) return true; else return false; } /** Computes distance betwen a point and the viewpoint of a matrix */ double distance(const osg::Vec3 &coord, const osg::Matrix& matrix) { return -( coord[0]*matrix(0,2) + coord[1]*matrix(1,2) + coord[2]*matrix(2,2) + matrix(3,2) ); } #define CURRENT_CLASS DistanceAccumulator CURRENT_CLASS::CURRENT_CLASS() : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN), _nearFarRatio(0.0005), _maxDepth(UINT_MAX) { setMatrices(osg::Matrix::identity(), osg::Matrix::identity()); reset(); } CURRENT_CLASS::~CURRENT_CLASS() {} void CURRENT_CLASS::pushLocalFrustum() { osg::Matrix& currMatrix = _viewMatrices.back(); // Compute the frustum in local space osg::Polytope localFrustum; localFrustum.setToUnitFrustum(false, false); localFrustum.transformProvidingInverse(currMatrix*_projectionMatrices.back()); _localFrusta.push_back(localFrustum); // Compute new bounding box corners bbCornerPair corner; corner.second = (currMatrix(0,2)<=0?1:0) | (currMatrix(1,2)<=0?2:0) | (currMatrix(2,2)<=0?4:0); corner.first = (~corner.second)&7; _bbCorners.push_back(corner); } void CURRENT_CLASS::pushDistancePair(double zNear, double zFar) { if(zFar > 0.0) // Make sure some of drawable is visible { // Make sure near plane is in front of viewpoint. if(zNear <= 0.0) { zNear = zFar*_nearFarRatio; if(zNear >= 1.0) zNear = 1.0; // 1.0 limit chosen arbitrarily! } // Add distance pair for current drawable _distancePairs.push_back(DistancePair(zNear, zFar)); // Override the current nearest/farthest planes if necessary if(zNear < _limits.first) _limits.first = zNear; if(zFar > _limits.second) _limits.second = zFar; } } /** Return true if the node should be traversed, and false if the bounding sphere of the node is small enough to be rendered by one Camera. If the latter is true, then store the node's near & far plane distances. */ bool CURRENT_CLASS::shouldContinueTraversal(osg::Node &node) { // Allow traversal to continue if we haven't reached maximum depth. bool keepTraversing = (_currentDepth < _maxDepth); const osg::BoundingSphere &bs = node.getBound(); double zNear = 0.0, zFar = 0.0; // Make sure bounding sphere is valid and within viewing volume if(bs.valid()) { if(!_localFrusta.back().contains(bs)) keepTraversing = false; else { // Compute near and far planes for this node zNear = distance(bs._center, _viewMatrices.back()); zFar = zNear + bs._radius; zNear -= bs._radius; // If near/far ratio is big enough, then we don't need to keep // traversing children of this node. if(zNear >= zFar*_nearFarRatio) keepTraversing = false; } } // If traversal should stop, then store this node's (near,far) pair if(!keepTraversing) pushDistancePair(zNear, zFar); return keepTraversing; } void CURRENT_CLASS::apply(osg::Node &node) { if(shouldContinueTraversal(node)) { // Traverse this node _currentDepth++; traverse(node); _currentDepth--; } } void CURRENT_CLASS::apply(osg::Projection &proj) { if(shouldContinueTraversal(proj)) { // Push the new projection matrix view frustum _projectionMatrices.push_back(proj.getMatrix()); pushLocalFrustum(); // Traverse the group _currentDepth++; traverse(proj); _currentDepth--; // Reload original matrix and frustum _localFrusta.pop_back(); _bbCorners.pop_back(); _projectionMatrices.pop_back(); } } void CURRENT_CLASS::apply(osg::Transform &transform) { if(shouldContinueTraversal(transform)) { // Compute transform for current node osg::Matrix currMatrix = _viewMatrices.back(); bool pushMatrix = transform.computeLocalToWorldMatrix(currMatrix, this); if(pushMatrix) { // Store the new modelview matrix and view frustum _viewMatrices.push_back(currMatrix); pushLocalFrustum(); } _currentDepth++; traverse(transform); _currentDepth--; if(pushMatrix) { // Restore the old modelview matrix and view frustum _localFrusta.pop_back(); _bbCorners.pop_back(); _viewMatrices.pop_back(); } } } void CURRENT_CLASS::apply(osg::Geode &geode) { // Contained drawables will only be individually considered if we are // allowed to continue traversing. if(shouldContinueTraversal(geode)) { osg::Drawable *drawable; double zNear, zFar; // Handle each drawable in this geode for(unsigned int i = 0; i < geode.getNumDrawables(); i++) { drawable = geode.getDrawable(i); const osg::BoundingBox &bb = drawable->getBound(); if(bb.valid()) { // Make sure drawable will be visible in the scene if(!_localFrusta.back().contains(bb)) continue; // Compute near/far distances for current drawable zNear = distance(bb.corner(_bbCorners.back().first), _viewMatrices.back()); zFar = distance(bb.corner(_bbCorners.back().second), _viewMatrices.back()); if(zNear > zFar) std::swap(zNear, zFar); pushDistancePair(zNear, zFar); } } } } void CURRENT_CLASS::setMatrices(const osg::Matrix &modelview, const osg::Matrix &projection) { _modelview = modelview; _projection = projection; } void CURRENT_CLASS::reset() { // Clear vectors & values _distancePairs.clear(); _cameraPairs.clear(); _limits.first = DBL_MAX; _limits.second = 0.0; _currentDepth = 0; // Initial transform matrix is the modelview matrix _viewMatrices.clear(); _viewMatrices.push_back(_modelview); // Set the initial projection matrix _projectionMatrices.clear(); _projectionMatrices.push_back(_projection); // Create a frustum without near/far planes, for cull computations _localFrusta.clear(); _bbCorners.clear(); pushLocalFrustum(); } void CURRENT_CLASS::computeCameraPairs() { // Nothing in the scene, so no cameras needed if(_distancePairs.empty()) return; // Entire scene can be handled by just one camera if(_limits.first >= _limits.second*_nearFarRatio) { _cameraPairs.push_back(_limits); return; } PairList::iterator i,j; // Sort the list of distance pairs by descending far distance std::sort(_distancePairs.begin(), _distancePairs.end(), precedes); // Combine overlapping distance pairs. The resulting set of distance // pairs (called combined pairs) will not overlap. PairList combinedPairs; DistancePair currPair = _distancePairs.front(); for(i = _distancePairs.begin(); i != _distancePairs.end(); i++) { // Current distance pair does not overlap current combined pair, so // save the current combined pair and start a new one. if(i->second < 0.99*currPair.first) { combinedPairs.push_back(currPair); currPair = *i; } // Current distance pair overlaps current combined pair, so expand // current combined pair to encompass distance pair. else currPair.first = std::min(i->first, currPair.first); } combinedPairs.push_back(currPair); // Add last pair // Compute the (near,far) distance pairs for each camera. // Each of these distance pairs is called a "view segment". double currNearLimit, numSegs, new_ratio; double ratio_invlog = 1.0/log(_nearFarRatio); unsigned int temp; for(i = combinedPairs.begin(); i != combinedPairs.end(); i++) { currPair = *i; // Save current view segment // Compute the fractional number of view segments needed to span // the current combined distance pair. currNearLimit = currPair.second*_nearFarRatio; if(currPair.first >= currNearLimit) numSegs = 1.0; else { numSegs = log(currPair.first/currPair.second)*ratio_invlog; // Compute the near plane of the last view segment //currNearLimit *= pow(_nearFarRatio, -floor(-numSegs) - 1); for(temp = (unsigned int)(-floor(-numSegs)); temp > 1; temp--) { currNearLimit *= _nearFarRatio; } } // See if the closest view segment can absorb other combined pairs for(j = i+1; j != combinedPairs.end(); j++) { // No other distance pairs can be included if(j->first < currNearLimit) break; } // If we did absorb another combined distance pair, recompute the // number of required view segments. if(i != j-1) { i = j-1; currPair.first = i->first; if(currPair.first >= currPair.second*_nearFarRatio) numSegs = 1.0; else numSegs = log(currPair.first/currPair.second)*ratio_invlog; } /* Compute an integer number of segments by rounding the fractional number of segments according to how many segments there are. In general, the more segments there are, the more likely that the integer number of segments will be rounded down. The purpose of this is to try to minimize the number of view segments that are used to render any section of the scene without violating the specified _nearFarRatio by too much. */ if(numSegs < 10.0) numSegs = floor(numSegs + 1.0 - 0.1*floor(numSegs)); else numSegs = floor(numSegs); // Compute the near/far ratio that will be used for each view segment // in this section of the scene. new_ratio = pow(currPair.first/currPair.second, 1.0/numSegs); // Add numSegs new view segments to the camera pairs list for(temp = (unsigned int)numSegs; temp > 0; temp--) { currPair.first = currPair.second*new_ratio; _cameraPairs.push_back(currPair); currPair.second = currPair.first; } } } void CURRENT_CLASS::setNearFarRatio(double ratio) { if(ratio <= 0.0 || ratio >= 1.0) return; _nearFarRatio = ratio; } #undef CURRENT_CLASS <|endoftext|>
<commit_before>// ThreadedAudioDevice.cpp // // Base class for all classes which spawn thread to run loop. // #include "ThreadedAudioDevice.h" #include <sys/time.h> #include <sys/resource.h> // setpriority() #include <sys/select.h> #include <string.h> // memset() #include <stdio.h> #include <assert.h> #include <errno.h> #define DEBUG 0 #if DEBUG > 1 #define PRINT0 if (1) printf #define PRINT1 if (1) printf #elif DEBUG > 0 #define PRINT0 if (1) printf #define PRINT1 if (0) printf #else #define PRINT0 if (0) printf #define PRINT1 if (0) printf #endif // Uncomment this to make it possible to profile RTcmix code w/ gprof //#define PROFILE #ifdef PROFILE static struct itimerval globalTimerVal; #endif ThreadedAudioDevice::ThreadedAudioDevice() : _device(-1), _thread(0), _frameCount(0), _starting(false), _paused(false), _stopping(false), _closing(false) { } ThreadedAudioDevice::~ThreadedAudioDevice() { // This code handles the rare case where the child thread is starting // at the same instant that the device is being destroyed. PRINT1("~ThreadedAudioDevice\n"); if (starting() && _thread != 0) { waitForThread(); starting(false); } } int ThreadedAudioDevice::startThread() { stopping(false); // Reset. if (isPassive()) // Nothing else to do here if passive mode. return 0; starting(true); #ifdef PROFILE getitimer(ITIMER_PROF, &globalTimerVal); #endif PRINT1("\tThreadedAudioDevice::startThread: starting thread\n"); int status = pthread_create(&_thread, NULL, _runProcess, this); if (status < 0) { error("Failed to create thread"); } return status; } int ThreadedAudioDevice::doStop() { if (!stopping()) { PRINT1("\tThreadedAudioDevice::doStop\n"); stopping(true); // signals play thread paused(false); waitForThread(); starting(false); } return 0; } int ThreadedAudioDevice::doGetFrameCount() const { return frameCount(); } // Local method definitions void ThreadedAudioDevice::waitForThread(int waitMs) { if (!isPassive()) { assert(_thread != 0); // should not get called again! PRINT1("ThreadedAudioDevice::waitForThread: waiting for thread to finish\n"); if (pthread_join(_thread, NULL) == -1) { PRINT0("ThreadedAudioDevice::doStop: terminating thread!\n"); pthread_cancel(_thread); _thread = 0; } PRINT1("\tThreadedAudioDevice::waitForThread: thread done\n"); } } inline void ThreadedAudioDevice::setFDSet() { fd_set *thisSet = NULL; #ifdef PREFER_SELECT_ON_WRITE if (isRecording() && !isPlaying()) // Use read fd_set for half-duplex record only. thisSet = &_rfdset; else if (isPlaying()) // Use write fd_set for full-duplex and half-duplex play. thisSet = &_wfdset; #else if (isRecording()) // Use read fd_set for for full-duplex and half-duplex record. thisSet = &_rfdset; else if (isPlaying() && !isRecording()) // Use write fd_set for half-duplex play only. thisSet = &_wfdset; #endif FD_SET(_device, thisSet); } void ThreadedAudioDevice::setDevice(int dev) { _device = dev; if (_device > 0) { FD_ZERO(&_rfdset); FD_ZERO(&_wfdset); setFDSet(); } } int ThreadedAudioDevice::waitForDevice(unsigned int wTime) { int ret; unsigned waitSecs = int(wTime / 1000.0); unsigned waitUsecs = 1000 * (wTime - unsigned(waitSecs * 1000)); // Wait wTime msecs for select to return, then bail. if (!stopping()) { int nfds = _device + 1; struct timeval tv; tv.tv_sec = waitSecs; tv.tv_usec = waitUsecs; // If wTime == 0, wait forever by passing NULL as the final arg. // if (!isPlaying()) // printf("select(%d, 0x%x, 0x%x, NULL, 0x%x)...\n", // nfds, &_rfdset, &_wfdset, wTime == 0 ? NULL : &tv); int selret = ::select(nfds, &_rfdset, &_wfdset, NULL, wTime == 0 ? NULL : &tv); if (selret <= 0) { if (errno != EINTR) fprintf(stderr, "ThreadedAudioDevice::waitForDevice: select %s\n", (selret == 0) ? "timed out" : "returned error"); ret = -1; } else { setFDSet(); ret = 0; } } else { PRINT1("ThreadedAudioDevice::waitForDevice: stopping == true\n"); ret = 1; } return ret; } void *ThreadedAudioDevice::_runProcess(void *context) { #ifdef PROFILE setitimer(ITIMER_PROF, &globalTimerVal, NULL); getitimer(ITIMER_PROF, &globalTimerVal); #endif ThreadedAudioDevice *device = (ThreadedAudioDevice *) context; pthread_attr_t attr; pthread_attr_init(&attr); int status = pthread_attr_setschedpolicy(&attr, SCHED_RR); pthread_attr_destroy(&attr); if (status != 0) { device->error("Failed to set scheduling policy of thread"); return NULL; } if (setpriority(PRIO_PROCESS, 0, -20) != 0) { // perror("ThreadedAudioDevice::startThread: Failed to set priority of thread."); } device->starting(false); // Signal that the thread is now running device->run(); return NULL; } <commit_msg>Fixed so we actually set the threads scheduling policy.<commit_after>// ThreadedAudioDevice.cpp // // Base class for all classes which spawn thread to run loop. // #include "ThreadedAudioDevice.h" #include <sys/time.h> #include <sys/resource.h> // setpriority() #include <sys/select.h> #include <string.h> // memset() #include <stdio.h> #include <assert.h> #include <errno.h> #define DEBUG 0 #if DEBUG > 1 #define PRINT0 if (1) printf #define PRINT1 if (1) printf #elif DEBUG > 0 #define PRINT0 if (1) printf #define PRINT1 if (0) printf #else #define PRINT0 if (0) printf #define PRINT1 if (0) printf #endif // Uncomment this to make it possible to profile RTcmix code w/ gprof //#define PROFILE #ifdef PROFILE static struct itimerval globalTimerVal; #endif ThreadedAudioDevice::ThreadedAudioDevice() : _device(-1), _thread(0), _frameCount(0), _starting(false), _paused(false), _stopping(false), _closing(false) { } ThreadedAudioDevice::~ThreadedAudioDevice() { // This code handles the rare case where the child thread is starting // at the same instant that the device is being destroyed. PRINT1("~ThreadedAudioDevice\n"); if (starting() && _thread != 0) { waitForThread(); starting(false); } } int ThreadedAudioDevice::startThread() { stopping(false); // Reset. if (isPassive()) // Nothing else to do here if passive mode. return 0; starting(true); #ifdef PROFILE getitimer(ITIMER_PROF, &globalTimerVal); #endif PRINT1("\tThreadedAudioDevice::startThread: starting thread\n"); pthread_attr_t attr; pthread_attr_init(&attr); int status = pthread_attr_setschedpolicy(&attr, SCHED_RR); if (status != 0) { fprintf(stderr, "startThread: Failed to set scheduling policy\n"); } status = pthread_create(&_thread, &attr, _runProcess, this); pthread_attr_destroy(&attr); if (status < 0) { error("Failed to create thread"); } return status; } int ThreadedAudioDevice::doStop() { if (!stopping()) { PRINT1("\tThreadedAudioDevice::doStop\n"); stopping(true); // signals play thread paused(false); waitForThread(); starting(false); } return 0; } int ThreadedAudioDevice::doGetFrameCount() const { return frameCount(); } // Local method definitions void ThreadedAudioDevice::waitForThread(int waitMs) { if (!isPassive()) { assert(_thread != 0); // should not get called again! PRINT1("ThreadedAudioDevice::waitForThread: waiting for thread to finish\n"); if (pthread_join(_thread, NULL) == -1) { PRINT0("ThreadedAudioDevice::doStop: terminating thread!\n"); pthread_cancel(_thread); _thread = 0; } PRINT1("\tThreadedAudioDevice::waitForThread: thread done\n"); } } inline void ThreadedAudioDevice::setFDSet() { fd_set *thisSet = NULL; #ifdef PREFER_SELECT_ON_WRITE if (isRecording() && !isPlaying()) // Use read fd_set for half-duplex record only. thisSet = &_rfdset; else if (isPlaying()) // Use write fd_set for full-duplex and half-duplex play. thisSet = &_wfdset; #else if (isRecording()) // Use read fd_set for for full-duplex and half-duplex record. thisSet = &_rfdset; else if (isPlaying() && !isRecording()) // Use write fd_set for half-duplex play only. thisSet = &_wfdset; #endif FD_SET(_device, thisSet); } void ThreadedAudioDevice::setDevice(int dev) { _device = dev; if (_device > 0) { FD_ZERO(&_rfdset); FD_ZERO(&_wfdset); setFDSet(); } } int ThreadedAudioDevice::waitForDevice(unsigned int wTime) { int ret; unsigned waitSecs = int(wTime / 1000.0); unsigned waitUsecs = 1000 * (wTime - unsigned(waitSecs * 1000)); // Wait wTime msecs for select to return, then bail. if (!stopping()) { int nfds = _device + 1; struct timeval tv; tv.tv_sec = waitSecs; tv.tv_usec = waitUsecs; // If wTime == 0, wait forever by passing NULL as the final arg. // if (!isPlaying()) // printf("select(%d, 0x%x, 0x%x, NULL, 0x%x)...\n", // nfds, &_rfdset, &_wfdset, wTime == 0 ? NULL : &tv); int selret = ::select(nfds, &_rfdset, &_wfdset, NULL, wTime == 0 ? NULL : &tv); if (selret <= 0) { if (errno != EINTR) fprintf(stderr, "ThreadedAudioDevice::waitForDevice: select %s\n", (selret == 0) ? "timed out" : "returned error"); ret = -1; } else { setFDSet(); ret = 0; } } else { PRINT1("ThreadedAudioDevice::waitForDevice: stopping == true\n"); ret = 1; } return ret; } void *ThreadedAudioDevice::_runProcess(void *context) { #ifdef PROFILE setitimer(ITIMER_PROF, &globalTimerVal, NULL); getitimer(ITIMER_PROF, &globalTimerVal); #endif ThreadedAudioDevice *device = (ThreadedAudioDevice *) context; if (setpriority(PRIO_PROCESS, 0, -20) != 0) { // perror("ThreadedAudioDevice::startThread: Failed to set priority of thread."); } device->starting(false); // Signal that the thread is now running device->run(); return NULL; } <|endoftext|>
<commit_before>// Copyright (C) 1999-2017 // Smithsonian Astrophysical Observatory, Cambridge, MA, USA // For conditions of distribution and use, see copyright notice in "copyright" #include <tk.h> #include "boxannulus.h" #include "fitsimage.h" BoxAnnulus::BoxAnnulus(Base* p, const Vector& ctr, const Vector& s, double ang, const char* clr, int* dsh, int wth, const char* fnt, const char* txt, unsigned short prop, const char* cmt, const List<Tag>& tg, const List<CallBack>& cb) : BaseBox(p, ctr, ang, clr, dsh, wth, fnt, txt, prop, cmt, tg, cb) { numAnnuli_ = 1; annuli_ = new Vector[1]; annuli_[0] = s; strcpy(type_,"boxannulus"); numHandle = 4; updateBBox(); } BoxAnnulus::BoxAnnulus(Base* p, const Vector& ctr, const Vector& inner, const Vector& outer, int num, double ang) : BaseBox(p, ctr, ang) { numAnnuli_ = num+1; annuli_ = new Vector[numAnnuli_]; for (int i=0; i<numAnnuli_; i++) annuli_[i] = ((outer-inner)/num)*i+inner; strcpy(type_,"boxannulus"); numHandle = 4 + numAnnuli_; updateBBox(); } BoxAnnulus::BoxAnnulus(Base* p, const Vector& ctr, const Vector& inner, const Vector& outer, int num, double ang, const char* clr, int* dsh, int wth, const char* fnt, const char* txt, unsigned short prop, const char* cmt, const List<Tag>& tg, const List<CallBack>& cb) : BaseBox(p, ctr, ang, clr, dsh, wth, fnt, txt, prop, cmt, tg, cb) { numAnnuli_ = num+1; annuli_ = new Vector[numAnnuli_]; for (int i=0; i<numAnnuli_; i++) annuli_[i] = ((outer-inner)/num)*i+inner; strcpy(type_,"boxannulus"); numHandle = 4 + numAnnuli_; updateBBox(); } BoxAnnulus::BoxAnnulus(Base* p, const Vector& ctr, int an, Vector* s, double ang, const char* clr, int* dsh, int wth, const char* fnt, const char* txt, unsigned short prop, const char* cmt, const List<Tag>& tg, const List<CallBack>& cb) : BaseBox(p, ctr, ang, clr, dsh, wth, fnt, txt, prop, cmt, tg, cb) { numAnnuli_ = an; annuli_ = new Vector[numAnnuli_]; for (int i=0; i<numAnnuli_; i++) annuli_[i] = s[i]; sortAnnuli(); strcpy(type_, "boxannulus"); numHandle = 4 + numAnnuli_; updateBBox(); doCallBack(CallBack::EDITCB); } BoxAnnulus::BoxAnnulus(const BoxAnnulus& a) : BaseBox(a) {} void BoxAnnulus::editBegin(int h) { if (h<5) { switch (h) { case 1: return; case 2: annuli_[numAnnuli_-1] = Vector(-annuli_[numAnnuli_-1][0],annuli_[numAnnuli_-1][1]); return; case 3: annuli_[numAnnuli_-1] = -annuli_[numAnnuli_-1]; return; case 4: annuli_[numAnnuli_-1] = Vector(annuli_[numAnnuli_-1][0],-annuli_[numAnnuli_-1][1]); return; } } doCallBack(CallBack::EDITBEGINCB); } void BoxAnnulus::edit(const Vector& v, int h) { Matrix mm = bckMatrix(); Matrix nn = mm.invert(); // This sizes about the opposite node if (h<5) { Vector o = annuli_[numAnnuli_-1]; Vector n = (annuli_[numAnnuli_-1]/2) - (v*mm); // don't go thru opposite node if (n[0]!=0 && n[1]!=0) { Vector ov = annuli_[numAnnuli_-1]/2 * nn; annuli_[numAnnuli_-1] = n; Vector nv = annuli_[numAnnuli_-1]/2 * nn; center -= nv-ov; for (int i=0; i<numAnnuli_-1; i++) { annuli_[i][0] *= fabs(n[0]/o[0]); annuli_[i][1] *= fabs(n[1]/o[1]); } } } else { // we must have some length double l = (v * mm * 2).length(); annuli_[h-5] = annuli_[numAnnuli_-1] * l/annuli_[numAnnuli_-1][0]; } updateBBox(); doCallBack(CallBack::EDITCB); doCallBack(CallBack::MOVECB); } void BoxAnnulus::editEnd() { for (int i=1; i<numAnnuli_; i++) annuli_[i] = annuli_[i].abs(); sortAnnuli(); updateBBox(); doCallBack(CallBack::EDITENDCB); } int BoxAnnulus::addAnnuli(const Vector& v) { Matrix mm = bckMatrix(); double l = (v * mm * 2).length(); Vector rr = annuli_[numAnnuli_-1] * l/annuli_[numAnnuli_-1][0]; return insertAnnuli(rr); } void BoxAnnulus::analysis(AnalysisTask mm, int which) { switch (mm) { case RADIAL: if (!analysisRadial_ && which) { addCallBack(CallBack::MOVECB, analysisRadialCB_[0], parent->options->cmdName); addCallBack(CallBack::EDITCB, analysisRadialCB_[0], parent->options->cmdName); addCallBack(CallBack::EDITENDCB, analysisRadialCB_[0], parent->options->cmdName); addCallBack(CallBack::ROTATECB, analysisRadialCB_[0], parent->options->cmdName); addCallBack(CallBack::UPDATECB, analysisRadialCB_[0], parent->options->cmdName); addCallBack(CallBack::DELETECB, analysisRadialCB_[1], parent->options->cmdName); } if (analysisRadial_ && !which) { deleteCallBack(CallBack::MOVECB, analysisRadialCB_[0]); deleteCallBack(CallBack::EDITCB, analysisRadialCB_[0]); deleteCallBack(CallBack::EDITENDCB, analysisRadialCB_[0]); deleteCallBack(CallBack::ROTATECB, analysisRadialCB_[0]); deleteCallBack(CallBack::UPDATECB, analysisRadialCB_[0]); deleteCallBack(CallBack::DELETECB, analysisRadialCB_[1]); } analysisRadial_ = which; break; case STATS: if (!analysisStats_ && which) { addCallBack(CallBack::MOVECB, analysisStatsCB_[0], parent->options->cmdName); addCallBack(CallBack::EDITCB, analysisStatsCB_[0], parent->options->cmdName); addCallBack(CallBack::EDITENDCB, analysisStatsCB_[0], parent->options->cmdName); addCallBack(CallBack::ROTATECB, analysisStatsCB_[0], parent->options->cmdName); addCallBack(CallBack::UPDATECB, analysisStatsCB_[0], parent->options->cmdName); addCallBack(CallBack::DELETECB, analysisStatsCB_[1], parent->options->cmdName); } if (analysisStats_ && !which) { deleteCallBack(CallBack::MOVECB, analysisStatsCB_[0]); deleteCallBack(CallBack::EDITCB, analysisStatsCB_[0]); deleteCallBack(CallBack::EDITENDCB, analysisStatsCB_[0]); deleteCallBack(CallBack::ROTATECB, analysisStatsCB_[0]); deleteCallBack(CallBack::UPDATECB, analysisStatsCB_[0]); deleteCallBack(CallBack::DELETECB, analysisStatsCB_[1]); } analysisStats_ = which; break; default: // na break; } } void BoxAnnulus::analysisRadial(char* xname, char* yname, char* ename, Coord::CoordSystem sys) { double* xx; double* yy; double* ee; BBox* bb = new BBox[numAnnuli_]; Matrix mm = Rotate(angle) * Translate(center); for (int ii=0; ii<numAnnuli_; ii++) { // during resize, annuli_ can be negative Vector vv = annuli_[ii].abs(); bb[ii] = BBox(-vv * mm); bb[ii].bound( vv * mm); bb[ii].bound(Vector( vv[0],-vv[1]) * mm); bb[ii].bound(Vector(-vv[0], vv[1]) * mm); } int num = parent->markerAnalysisRadial(this, &xx, &yy, &ee, numAnnuli_-1, annuli_, bb, sys); analysisXYEResult(xname, yname, ename, xx, yy, ee, num); } void BoxAnnulus::analysisStats(Coord::CoordSystem sys, Coord::SkyFrame sky) { ostringstream str; BBox* bb = new BBox[numAnnuli_]; Matrix mm = Rotate(angle) * Translate(center); for (int ii=0; ii<numAnnuli_; ii++) { // during resize, annuli_ can be negative Vector vv = annuli_[ii].abs(); bb[ii] = BBox(-vv * mm); bb[ii].bound( vv * mm); bb[ii].bound(Vector( vv[0],-vv[1]) * mm); bb[ii].bound(Vector(-vv[0], vv[1]) * mm); } parent->markerAnalysisStats(this, str, numAnnuli_-1, bb, sys, sky); str << ends; Tcl_AppendResult(parent->interp, str.str().c_str(), NULL); } // list void BoxAnnulus::list(ostream& str, Coord::CoordSystem sys, Coord::SkyFrame sky, Coord::SkyFormat format, int conj, int strip) { FitsImage* ptr = parent->findFits(sys,center); listPre(str, sys, sky, ptr, strip, 0); switch (sys) { case Coord::IMAGE: case Coord::PHYSICAL: case Coord::DETECTOR: case Coord::AMPLIFIER: listNonCel(ptr, str, sys); break; default: if (ptr->hasWCSCel(sys)) { listRADEC(ptr,center,sys,sky,format); double aa = parent->mapAngleFromRef(angle,sys,sky); str << "box(" << ra << ',' << dec << setprecision(3) << fixed; for (int ii=0; ii<numAnnuli_; ii++) { Vector rr = ptr->mapLenFromRef(annuli_[ii],sys,Coord::ARCSEC); str << ',' << setunit('"') << rr; } str.unsetf(ios_base::floatfield); str << setprecision(8) << ',' << radToDeg(aa) << ')'; } else listNonCel(ptr, str, sys); } listPost(str, conj, strip); } void BoxAnnulus::listNonCel(FitsImage* ptr, ostream& str, Coord::CoordSystem sys) { Vector vv = ptr->mapFromRef(center,sys); double aa = parent->mapAngleFromRef(angle,sys); str << "box(" << setprecision(8) << vv; for (int ii=0; ii<numAnnuli_; ii++) { Vector rr = ptr->mapLenFromRef(annuli_[ii],sys); str << ',' << rr; } str << ',' << radToDeg(aa) << ')'; } void BoxAnnulus::listXML(ostream& str, Coord::CoordSystem sys, Coord::SkyFrame sky, Coord::SkyFormat format) { FitsImage* ptr = parent->findFits(sys,center); XMLRowInit(); XMLRow(XMLSHAPE,type_); XMLRowCenter(ptr,sys,sky,format); XMLRowRadius(ptr,sys,annuli_,numAnnuli_); XMLRowAng(sys,sky); XMLRowProps(ptr,sys); XMLRowEnd(str); } void BoxAnnulus::listPros(ostream& str, Coord::CoordSystem sys, Coord::SkyFrame sky, Coord::SkyFormat format, int strip) { FitsImage* ptr = parent->findFits(); switch (sys) { case Coord::IMAGE: case Coord::DETECTOR: case Coord::AMPLIFIER: sys = Coord::IMAGE; case Coord::PHYSICAL: { Vector vv = ptr->mapFromRef(center,sys); for (int ii=0; ii<numAnnuli_; ii++) { coord.listProsCoordSystem(str,sys,sky); str << "; "; Vector rr = ptr->mapLenFromRef(annuli_[ii],Coord::IMAGE); str << "box " << setprecision(8) << vv << ' ' << rr << ' ' << radToDeg(angle); if (ii!=0) { Vector r1 = ptr->mapLenFromRef(annuli_[ii-1],Coord::IMAGE); str << " & !box " << vv << ' ' << r1 << ' ' << radToDeg(angle); } listProsPost(str, strip); } } break; default: if (ptr->hasWCSCel(sys)) { listRADECPros(ptr,center,sys,sky,format); switch (format) { case Coord::DEGREES: for (int ii=0; ii<numAnnuli_; ii++) { coord.listProsCoordSystem(str,sys,sky); str << "; "; Vector rr = ptr->mapLenFromRef(annuli_[ii],sys,Coord::ARCSEC); str << "box " << ra << 'd' << ' ' << dec << 'd' << ' ' << setprecision(3) << setunit('"') << fixed << rr << ' '; str.unsetf(ios_base::floatfield); str << setprecision(8) << radToDeg(angle); if (ii!=0) { Vector r1 = ptr->mapLenFromRef(annuli_[ii-1],sys,Coord::ARCSEC); str << " & !box " << ra << 'd' << ' ' << dec << 'd' << ' ' << setprecision(3) << setunit('"') << fixed << r1 << ' '; str.unsetf(ios_base::floatfield); str << setprecision(8) << radToDeg(angle); } listProsPost(str, strip); } break; case Coord::SEXAGESIMAL: for (int ii=0; ii<numAnnuli_; ii++) { coord.listProsCoordSystem(str,sys,sky); str << "; "; Vector rr = ptr->mapLenFromRef(annuli_[ii],sys,Coord::ARCSEC); str << "box " << ra << ' ' << dec << ' ' << setprecision(3) << setunit('"') << fixed << rr << ' '; str.unsetf(ios_base::floatfield); str << setprecision(8) << radToDeg(angle); if (ii!=0) { Vector r1 = ptr->mapLenFromRef(annuli_[ii-1],sys,Coord::ARCSEC); str << " & !box " << ra << ' ' << dec << ' ' << setprecision(3) << setunit('"') << fixed << r1 << ' '; str.unsetf(ios_base::floatfield); str << setprecision(8) << radToDeg(angle); } listProsPost(str, strip); } break; } } } } void BoxAnnulus::listSAOimage(ostream& str, int strip) { FitsImage* ptr = parent->findFits(); listSAOimagePre(str); for (int ii=0; ii<numAnnuli_; ii++) { Vector vv = ptr->mapFromRef(center,Coord::IMAGE); str << "box(" << setprecision(8) << vv << ',' << annuli_[ii] << ',' << radToDeg(angle) << ')'; if (ii!=0) str << " & !box(" << setprecision(8) << vv << ',' << annuli_[ii-1] << ',' << radToDeg(angle) << ')'; listSAOimagePost(str, strip); } } <commit_msg>clean up marker code<commit_after>// Copyright (C) 1999-2017 // Smithsonian Astrophysical Observatory, Cambridge, MA, USA // For conditions of distribution and use, see copyright notice in "copyright" #include <tk.h> #include "boxannulus.h" #include "fitsimage.h" BoxAnnulus::BoxAnnulus(Base* p, const Vector& ctr, const Vector& s, double ang, const char* clr, int* dsh, int wth, const char* fnt, const char* txt, unsigned short prop, const char* cmt, const List<Tag>& tg, const List<CallBack>& cb) : BaseBox(p, ctr, ang, clr, dsh, wth, fnt, txt, prop, cmt, tg, cb) { numAnnuli_ = 1; annuli_ = new Vector[1]; annuli_[0] = s; strcpy(type_,"boxannulus"); numHandle = 4; updateBBox(); } BoxAnnulus::BoxAnnulus(Base* p, const Vector& ctr, const Vector& inner, const Vector& outer, int num, double ang) : BaseBox(p, ctr, ang) { numAnnuli_ = num+1; annuli_ = new Vector[numAnnuli_]; for (int i=0; i<numAnnuli_; i++) annuli_[i] = ((outer-inner)/num)*i+inner; strcpy(type_,"boxannulus"); numHandle = 4 + numAnnuli_; updateBBox(); } BoxAnnulus::BoxAnnulus(Base* p, const Vector& ctr, const Vector& inner, const Vector& outer, int num, double ang, const char* clr, int* dsh, int wth, const char* fnt, const char* txt, unsigned short prop, const char* cmt, const List<Tag>& tg, const List<CallBack>& cb) : BaseBox(p, ctr, ang, clr, dsh, wth, fnt, txt, prop, cmt, tg, cb) { numAnnuli_ = num+1; annuli_ = new Vector[numAnnuli_]; for (int i=0; i<numAnnuli_; i++) annuli_[i] = ((outer-inner)/num)*i+inner; strcpy(type_,"boxannulus"); numHandle = 4 + numAnnuli_; updateBBox(); } BoxAnnulus::BoxAnnulus(Base* p, const Vector& ctr, int an, Vector* s, double ang, const char* clr, int* dsh, int wth, const char* fnt, const char* txt, unsigned short prop, const char* cmt, const List<Tag>& tg, const List<CallBack>& cb) : BaseBox(p, ctr, ang, clr, dsh, wth, fnt, txt, prop, cmt, tg, cb) { numAnnuli_ = an; annuli_ = new Vector[numAnnuli_]; for (int i=0; i<numAnnuli_; i++) annuli_[i] = s[i]; sortAnnuli(); strcpy(type_, "boxannulus"); numHandle = 4 + numAnnuli_; updateBBox(); doCallBack(CallBack::EDITCB); } BoxAnnulus::BoxAnnulus(const BoxAnnulus& a) : BaseBox(a) {} void BoxAnnulus::editBegin(int h) { if (h<5) { switch (h) { case 1: return; case 2: annuli_[numAnnuli_-1] = Vector(-annuli_[numAnnuli_-1][0],annuli_[numAnnuli_-1][1]); return; case 3: annuli_[numAnnuli_-1] = -annuli_[numAnnuli_-1]; return; case 4: annuli_[numAnnuli_-1] = Vector(annuli_[numAnnuli_-1][0],-annuli_[numAnnuli_-1][1]); return; } } doCallBack(CallBack::EDITBEGINCB); } void BoxAnnulus::edit(const Vector& v, int h) { Matrix mm = bckMatrix(); Matrix nn = mm.invert(); // This sizes about the opposite node if (h<5) { Vector o = annuli_[numAnnuli_-1]; Vector n = (annuli_[numAnnuli_-1]/2) - (v*mm); // don't go thru opposite node if (n[0]!=0 && n[1]!=0) { Vector ov = annuli_[numAnnuli_-1]/2 * nn; annuli_[numAnnuli_-1] = n; Vector nv = annuli_[numAnnuli_-1]/2 * nn; center -= nv-ov; for (int i=0; i<numAnnuli_-1; i++) { annuli_[i][0] *= fabs(n[0]/o[0]); annuli_[i][1] *= fabs(n[1]/o[1]); } } } else { // we must have some length double l = (v * mm * 2).length(); annuli_[h-5] = annuli_[numAnnuli_-1] * l/annuli_[numAnnuli_-1][0]; } updateBBox(); doCallBack(CallBack::EDITCB); doCallBack(CallBack::MOVECB); } void BoxAnnulus::editEnd() { for (int i=1; i<numAnnuli_; i++) annuli_[i] = annuli_[i].abs(); sortAnnuli(); updateBBox(); doCallBack(CallBack::EDITENDCB); } int BoxAnnulus::addAnnuli(const Vector& v) { Matrix mm = bckMatrix(); double l = (v * mm * 2).length(); Vector rr = annuli_[numAnnuli_-1] * l/annuli_[numAnnuli_-1][0]; return insertAnnuli(rr); } void BoxAnnulus::analysis(AnalysisTask mm, int which) { switch (mm) { case RADIAL: if (!analysisRadial_ && which) { addCallBack(CallBack::MOVECB, analysisRadialCB_[0], parent->options->cmdName); addCallBack(CallBack::EDITCB, analysisRadialCB_[0], parent->options->cmdName); addCallBack(CallBack::EDITENDCB, analysisRadialCB_[0], parent->options->cmdName); addCallBack(CallBack::ROTATECB, analysisRadialCB_[0], parent->options->cmdName); addCallBack(CallBack::UPDATECB, analysisRadialCB_[0], parent->options->cmdName); addCallBack(CallBack::DELETECB, analysisRadialCB_[1], parent->options->cmdName); } if (analysisRadial_ && !which) { deleteCallBack(CallBack::MOVECB, analysisRadialCB_[0]); deleteCallBack(CallBack::EDITCB, analysisRadialCB_[0]); deleteCallBack(CallBack::EDITENDCB, analysisRadialCB_[0]); deleteCallBack(CallBack::ROTATECB, analysisRadialCB_[0]); deleteCallBack(CallBack::UPDATECB, analysisRadialCB_[0]); deleteCallBack(CallBack::DELETECB, analysisRadialCB_[1]); } analysisRadial_ = which; break; case STATS: if (!analysisStats_ && which) { addCallBack(CallBack::MOVECB, analysisStatsCB_[0], parent->options->cmdName); addCallBack(CallBack::EDITCB, analysisStatsCB_[0], parent->options->cmdName); addCallBack(CallBack::EDITENDCB, analysisStatsCB_[0], parent->options->cmdName); addCallBack(CallBack::ROTATECB, analysisStatsCB_[0], parent->options->cmdName); addCallBack(CallBack::UPDATECB, analysisStatsCB_[0], parent->options->cmdName); addCallBack(CallBack::DELETECB, analysisStatsCB_[1], parent->options->cmdName); } if (analysisStats_ && !which) { deleteCallBack(CallBack::MOVECB, analysisStatsCB_[0]); deleteCallBack(CallBack::EDITCB, analysisStatsCB_[0]); deleteCallBack(CallBack::EDITENDCB, analysisStatsCB_[0]); deleteCallBack(CallBack::ROTATECB, analysisStatsCB_[0]); deleteCallBack(CallBack::UPDATECB, analysisStatsCB_[0]); deleteCallBack(CallBack::DELETECB, analysisStatsCB_[1]); } analysisStats_ = which; break; default: // na break; } } void BoxAnnulus::analysisRadial(char* xname, char* yname, char* ename, Coord::CoordSystem sys) { double* xx; double* yy; double* ee; BBox* bb = new BBox[numAnnuli_]; Matrix mm = Rotate(angle) * Translate(center); for (int ii=0; ii<numAnnuli_; ii++) { // during resize, annuli_ can be negative Vector vv = annuli_[ii].abs(); bb[ii] = BBox(-vv * mm); bb[ii].bound( vv * mm); bb[ii].bound(Vector( vv[0],-vv[1]) * mm); bb[ii].bound(Vector(-vv[0], vv[1]) * mm); } int num = parent->markerAnalysisRadial(this, &xx, &yy, &ee, numAnnuli_-1, annuli_, bb, sys); analysisXYEResult(xname, yname, ename, xx, yy, ee, num); } void BoxAnnulus::analysisStats(Coord::CoordSystem sys, Coord::SkyFrame sky) { ostringstream str; BBox* bb = new BBox[numAnnuli_]; Matrix mm = Rotate(angle) * Translate(center); for (int ii=0; ii<numAnnuli_; ii++) { // during resize, annuli_ can be negative Vector vv = annuli_[ii].abs(); bb[ii] = BBox(-vv * mm); bb[ii].bound( vv * mm); bb[ii].bound(Vector( vv[0],-vv[1]) * mm); bb[ii].bound(Vector(-vv[0], vv[1]) * mm); } parent->markerAnalysisStats(this, str, numAnnuli_-1, bb, sys, sky); str << ends; Tcl_AppendResult(parent->interp, str.str().c_str(), NULL); } // list void BoxAnnulus::list(ostream& str, Coord::CoordSystem sys, Coord::SkyFrame sky, Coord::SkyFormat format, int conj, int strip) { FitsImage* ptr = parent->findFits(sys,center); listPre(str, sys, sky, ptr, strip, 0); switch (sys) { case Coord::IMAGE: case Coord::PHYSICAL: case Coord::DETECTOR: case Coord::AMPLIFIER: listNonCel(ptr, str, sys); break; default: if (ptr->hasWCSCel(sys)) { listRADEC(ptr,center,sys,sky,format); double aa = parent->mapAngleFromRef(angle,sys,sky); str << "box(" << ra << ',' << dec << setprecision(3) << fixed; for (int ii=0; ii<numAnnuli_; ii++) { Vector rr = ptr->mapLenFromRef(annuli_[ii],sys,Coord::ARCSEC); str << ',' << setunit('"') << rr; } str.unsetf(ios_base::floatfield); str << setprecision(8) << ',' << radToDeg(aa) << ')'; } else listNonCel(ptr, str, sys); } listPost(str, conj, strip); } void BoxAnnulus::listNonCel(FitsImage* ptr, ostream& str, Coord::CoordSystem sys) { Vector vv = ptr->mapFromRef(center,sys); double aa = parent->mapAngleFromRef(angle,sys); str << "box(" << setprecision(8) << vv; for (int ii=0; ii<numAnnuli_; ii++) { Vector rr = ptr->mapLenFromRef(annuli_[ii],sys); str << ',' << rr; } str << ',' << radToDeg(aa) << ')'; } void BoxAnnulus::listXML(ostream& str, Coord::CoordSystem sys, Coord::SkyFrame sky, Coord::SkyFormat format) { FitsImage* ptr = parent->findFits(sys,center); XMLRowInit(); XMLRow(XMLSHAPE,type_); XMLRowCenter(ptr,sys,sky,format); XMLRowRadius(ptr,sys,annuli_,numAnnuli_); XMLRowAng(sys,sky); XMLRowProps(ptr,sys); XMLRowEnd(str); } void BoxAnnulus::listPros(ostream& str, Coord::CoordSystem sys, Coord::SkyFrame sky, Coord::SkyFormat format, int strip) { FitsImage* ptr = parent->findFits(); switch (sys) { case Coord::IMAGE: case Coord::DETECTOR: case Coord::AMPLIFIER: sys = Coord::IMAGE; case Coord::PHYSICAL: { Vector vv = ptr->mapFromRef(center,sys); for (int ii=0; ii<numAnnuli_; ii++) { coord.listProsCoordSystem(str,sys,sky); str << "; "; Vector rr = ptr->mapLenFromRef(annuli_[ii],Coord::IMAGE); str << "box " << setprecision(8) << vv << ' ' << rr << ' ' << radToDeg(angle); if (ii!=0) { Vector r1 = ptr->mapLenFromRef(annuli_[ii-1],Coord::IMAGE); str << " & !box " << vv << ' ' << r1 << ' ' << radToDeg(angle); } listProsPost(str, strip); } } break; default: if (ptr->hasWCSCel(sys)) { listRADECPros(ptr,center,sys,sky,format); for (int ii=0; ii<numAnnuli_; ii++) { coord.listProsCoordSystem(str,sys,sky); str << "; "; Vector rr = ptr->mapLenFromRef(annuli_[ii],sys,Coord::ARCSEC); str << "box "; switch (format) { case Coord::DEGREES: str << ra << 'd' << ' ' << dec << 'd' << ' '; break; case Coord::SEXAGESIMAL: str << ra << ' ' << dec << ' '; break; } str << setprecision(3) << setunit('"') << fixed << rr << ' '; str.unsetf(ios_base::floatfield); str << setprecision(8) << radToDeg(angle); if (ii!=0) { Vector r1 = ptr->mapLenFromRef(annuli_[ii-1],sys,Coord::ARCSEC); str << " & !box "; switch (format) { case Coord::DEGREES: str << ra << 'd' << ' ' << dec << 'd' << ' '; break; case Coord::SEXAGESIMAL: str << ra << ' ' << dec << ' '; break; } str << setprecision(3) << setunit('"') << fixed << r1 << ' '; str.unsetf(ios_base::floatfield); str << setprecision(8) << radToDeg(angle); } listProsPost(str, strip); } } } } void BoxAnnulus::listSAOimage(ostream& str, int strip) { FitsImage* ptr = parent->findFits(); listSAOimagePre(str); for (int ii=0; ii<numAnnuli_; ii++) { Vector vv = ptr->mapFromRef(center,Coord::IMAGE); str << "box(" << setprecision(8) << vv << ',' << annuli_[ii] << ',' << radToDeg(angle) << ')'; if (ii!=0) str << " & !box(" << setprecision(8) << vv << ',' << annuli_[ii-1] << ',' << radToDeg(angle) << ')'; listSAOimagePost(str, strip); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/> * @author Andre Moreira Magalhaes <[email protected]> * * 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 "tls-cert-verifier-op.h" #include <TelepathyQt/PendingVariantMap> #include <KMessageBox> #include <KLocalizedString> #include <KDebug> #include <QSslCertificate> TlsCertVerifierOp::TlsCertVerifierOp(const Tp::AccountPtr &account, const Tp::ConnectionPtr &connection, const Tp::ChannelPtr &channel) : Tp::PendingOperation(channel), m_account(account), m_connection(connection), m_channel(channel) { QDBusObjectPath certificatePath = qdbus_cast<QDBusObjectPath>(channel->immutableProperties().value( TP_QT_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + QLatin1String(".ServerCertificate"))); m_hostname = qdbus_cast<QString>(channel->immutableProperties().value( TP_QT_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + QLatin1String(".Hostname"))); m_referenceIdentities = qdbus_cast<QStringList>(channel->immutableProperties().value( TP_QT_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + QLatin1String(".ReferenceIdentities"))); m_authTLSCertificateIface = new Tp::Client::AuthenticationTLSCertificateInterface( channel->dbusConnection(), channel->busName(), certificatePath.path()); connect(m_authTLSCertificateIface->requestAllProperties(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(gotProperties(Tp::PendingOperation*))); } TlsCertVerifierOp::~TlsCertVerifierOp() { } void TlsCertVerifierOp::gotProperties(Tp::PendingOperation *op) { if (op->isError()) { kWarning() << "Unable to retrieve properties from AuthenticationTLSCertificate object at" << m_authTLSCertificateIface->path(); m_channel->requestClose(); setFinishedWithError(op->errorName(), op->errorMessage()); return; } // everything ok, we can return from handleChannels now Q_EMIT ready(this); Tp::PendingVariantMap *pvm = qobject_cast<Tp::PendingVariantMap*>(op); QVariantMap props = qdbus_cast<QVariantMap>(pvm->result()); m_certType = qdbus_cast<QString>(props.value(QLatin1String("CertificateType"))); m_certData = qdbus_cast<CertificateDataList>(props.value(QLatin1String("CertificateChainData"))); if(m_certType.compare(QLatin1String("x509"), Qt::CaseInsensitive)) { kWarning() << "This is not an x509 certificate"; } Q_FOREACH (const QByteArray &data, m_certData) { // FIXME How to chech if it is QSsl::Pem or QSsl::Der? QSsl::Der works for kdetalk QList<QSslCertificate> certs = QSslCertificate::fromData(data, QSsl::Der); Q_FOREACH (const QSslCertificate &cert, certs) { kDebug() << cert; kDebug() << "Issuer Organization:" << cert.issuerInfo(QSslCertificate::Organization); kDebug() << "Issuer Common Name:" << cert.issuerInfo(QSslCertificate::CommonName); kDebug() << "Issuer Locality Name:" << cert.issuerInfo(QSslCertificate::LocalityName); kDebug() << "Issuer Organizational Unit Name:" << cert.issuerInfo(QSslCertificate::OrganizationalUnitName); kDebug() << "Issuer Country Name:" << cert.issuerInfo(QSslCertificate::CountryName); kDebug() << "Issuer State or Province Name:" << cert.issuerInfo(QSslCertificate::StateOrProvinceName); kDebug() << "Subject Organization:" << cert.subjectInfo(QSslCertificate::Organization); kDebug() << "Subject Common Name:" << cert.subjectInfo(QSslCertificate::CommonName); kDebug() << "Subject Locality Name:" << cert.subjectInfo(QSslCertificate::LocalityName); kDebug() << "Subject Organizational Unit Name:" << cert.subjectInfo(QSslCertificate::OrganizationalUnitName); kDebug() << "Subject Country Name:" << cert.subjectInfo(QSslCertificate::CountryName); kDebug() << "Subject State Or Province Name:" << cert.subjectInfo(QSslCertificate::StateOrProvinceName); kDebug() << "Effective Date:" << cert.effectiveDate(); kDebug() << "Expiry Date:" << cert.expiryDate(); kDebug() << "Public Key:" << cert.publicKey(); kDebug() << "Serial Number:" << cert.serialNumber(); kDebug() << "Version" << cert.version(); kDebug() << "Is Valid?" << cert.isValid(); } } //TODO Show a nice dialog if (KMessageBox::questionYesNo(0, i18n("Accept this certificate from <b>%1?</b><br />%2<br />").arg(m_hostname).arg(QString::fromLatin1(m_certData.first().toHex())), i18n("Untrusted certificate")) == KMessageBox::Yes) { // TODO Remember value m_authTLSCertificateIface->Accept().waitForFinished(); setFinished(); } else { Tp::TLSCertificateRejectionList rejections; // TODO Add reason m_authTLSCertificateIface->Reject(rejections); m_channel->requestClose(); setFinishedWithError(QLatin1String("Cert.Untrusted"), QLatin1String("Certificate rejected by the user")); } } #include "tls-cert-verifier-op.moc" <commit_msg>Add missing include<commit_after>/* * Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/> * @author Andre Moreira Magalhaes <[email protected]> * * 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 "tls-cert-verifier-op.h" #include <TelepathyQt/PendingVariantMap> #include <KMessageBox> #include <KLocalizedString> #include <KDebug> #include <QSslCertificate> #include <QSslKey> TlsCertVerifierOp::TlsCertVerifierOp(const Tp::AccountPtr &account, const Tp::ConnectionPtr &connection, const Tp::ChannelPtr &channel) : Tp::PendingOperation(channel), m_account(account), m_connection(connection), m_channel(channel) { QDBusObjectPath certificatePath = qdbus_cast<QDBusObjectPath>(channel->immutableProperties().value( TP_QT_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + QLatin1String(".ServerCertificate"))); m_hostname = qdbus_cast<QString>(channel->immutableProperties().value( TP_QT_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + QLatin1String(".Hostname"))); m_referenceIdentities = qdbus_cast<QStringList>(channel->immutableProperties().value( TP_QT_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + QLatin1String(".ReferenceIdentities"))); m_authTLSCertificateIface = new Tp::Client::AuthenticationTLSCertificateInterface( channel->dbusConnection(), channel->busName(), certificatePath.path()); connect(m_authTLSCertificateIface->requestAllProperties(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(gotProperties(Tp::PendingOperation*))); } TlsCertVerifierOp::~TlsCertVerifierOp() { } void TlsCertVerifierOp::gotProperties(Tp::PendingOperation *op) { if (op->isError()) { kWarning() << "Unable to retrieve properties from AuthenticationTLSCertificate object at" << m_authTLSCertificateIface->path(); m_channel->requestClose(); setFinishedWithError(op->errorName(), op->errorMessage()); return; } // everything ok, we can return from handleChannels now Q_EMIT ready(this); Tp::PendingVariantMap *pvm = qobject_cast<Tp::PendingVariantMap*>(op); QVariantMap props = qdbus_cast<QVariantMap>(pvm->result()); m_certType = qdbus_cast<QString>(props.value(QLatin1String("CertificateType"))); m_certData = qdbus_cast<CertificateDataList>(props.value(QLatin1String("CertificateChainData"))); if(m_certType.compare(QLatin1String("x509"), Qt::CaseInsensitive)) { kWarning() << "This is not an x509 certificate"; } Q_FOREACH (const QByteArray &data, m_certData) { // FIXME How to chech if it is QSsl::Pem or QSsl::Der? QSsl::Der works for kdetalk QList<QSslCertificate> certs = QSslCertificate::fromData(data, QSsl::Der); Q_FOREACH (const QSslCertificate &cert, certs) { kDebug() << cert; kDebug() << "Issuer Organization:" << cert.issuerInfo(QSslCertificate::Organization); kDebug() << "Issuer Common Name:" << cert.issuerInfo(QSslCertificate::CommonName); kDebug() << "Issuer Locality Name:" << cert.issuerInfo(QSslCertificate::LocalityName); kDebug() << "Issuer Organizational Unit Name:" << cert.issuerInfo(QSslCertificate::OrganizationalUnitName); kDebug() << "Issuer Country Name:" << cert.issuerInfo(QSslCertificate::CountryName); kDebug() << "Issuer State or Province Name:" << cert.issuerInfo(QSslCertificate::StateOrProvinceName); kDebug() << "Subject Organization:" << cert.subjectInfo(QSslCertificate::Organization); kDebug() << "Subject Common Name:" << cert.subjectInfo(QSslCertificate::CommonName); kDebug() << "Subject Locality Name:" << cert.subjectInfo(QSslCertificate::LocalityName); kDebug() << "Subject Organizational Unit Name:" << cert.subjectInfo(QSslCertificate::OrganizationalUnitName); kDebug() << "Subject Country Name:" << cert.subjectInfo(QSslCertificate::CountryName); kDebug() << "Subject State Or Province Name:" << cert.subjectInfo(QSslCertificate::StateOrProvinceName); kDebug() << "Effective Date:" << cert.effectiveDate(); kDebug() << "Expiry Date:" << cert.expiryDate(); kDebug() << "Public Key:" << cert.publicKey(); kDebug() << "Serial Number:" << cert.serialNumber(); kDebug() << "Version" << cert.version(); kDebug() << "Is Valid?" << cert.isValid(); } } //TODO Show a nice dialog if (KMessageBox::questionYesNo(0, i18n("Accept this certificate from <b>%1?</b><br />%2<br />").arg(m_hostname).arg(QString::fromLatin1(m_certData.first().toHex())), i18n("Untrusted certificate")) == KMessageBox::Yes) { // TODO Remember value m_authTLSCertificateIface->Accept().waitForFinished(); setFinished(); } else { Tp::TLSCertificateRejectionList rejections; // TODO Add reason m_authTLSCertificateIface->Reject(rejections); m_channel->requestClose(); setFinishedWithError(QLatin1String("Cert.Untrusted"), QLatin1String("Certificate rejected by the user")); } } #include "tls-cert-verifier-op.moc" <|endoftext|>
<commit_before>/* Copyright 2015 Nervana Systems Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <time.h> #include <iostream> #include <fstream> #include <string> #include <vector> #include <memory> #include <algorithm> #include <cassert> #include <cstring> #include <sstream> #include "streams.hpp" #include "buffer.hpp" #define FORMAT_VERSION 1 #define WRITER_VERSION 1 #define MAGIC_STRING "MACR" #define CPIO_FOOTER "TRAILER!!!" typedef std::vector<std::string> LineList; typedef std::vector<char> ByteVect; typedef std::pair<std::shared_ptr<ByteVect>,std::shared_ptr<ByteVect>> DataPair; static_assert(sizeof(int) == 4, "int is not 4 bytes"); static_assert(sizeof(uint) == 4, "uint is not 4 bytes"); static_assert(sizeof(short) == 2, "short is not 2 bytes"); /* The data is stored as a cpio archive and may be unpacked using the GNU cpio utility. https://www.gnu.org/software/cpio/ Individual items are packed into a macrobatch file as follows: - header - datum 1 - target 1 - datum 2 - target 2 ... - trailer Each of these items comprises of a cpio header record followed by data. */ class RecordHeader { public: RecordHeader(); void loadDoubleShort(uint* dst, ushort src[2]); void saveDoubleShort(ushort* dst, uint src); void read(IfStream& ifs, uint* fileSize); void write(OfStream& ofs, uint fileSize, const char* fileName); public: ushort _magic; ushort _dev; ushort _ino; ushort _mode; ushort _uid; ushort _gid; ushort _nlink; ushort _rdev; ushort _mtime[2]; ushort _namesize; ushort _filesize[2]; }; class BatchFileHeader { friend class BatchFileReader; friend class BatchFileWriter; public: BatchFileHeader(); void read(IfStream& ifs); void write(OfStream& ofs); private: #pragma pack(1) char _magic[4]; uint _formatVersion; uint _writerVersion; char _dataType[8]; uint _itemCount; uint _maxDatumSize; uint _maxTargetSize; uint _totalDataSize; uint _totalTargetsSize; char _unused[24]; #pragma pack() }; class BatchFileTrailer { public: BatchFileTrailer() ; void write(OfStream& ofs); void read(IfStream& ifs); private: uint _unused[4]; }; class BatchFileReader { public: BatchFileReader(); BatchFileReader(const std::string& fileName); ~BatchFileReader() ; bool open(const std::string& fileName); void close(); void readToBuffer(Buffer& dest); // TODO: still need this read? std::shared_ptr<ByteVect> read(); int itemCount() ; int totalDataSize() ; int totalTargetsSize(); int maxDatumSize() ; int maxTargetSize(); private: IfStream _ifs; BatchFileHeader _fileHeader; BatchFileTrailer _fileTrailer; RecordHeader _recordHeader; std::string _fileName; std::string _tempName; }; class BatchFileWriter { public: ~BatchFileWriter(); void open(const std::string& fileName, const std::string& dataType = ""); void close(); void writeItem(char* datum, char* target, uint datumSize, uint targetSize); void writeItem(ByteVect &datum, ByteVect &target); private: OfStream _ofs; BatchFileHeader _fileHeader; BatchFileTrailer _fileTrailer; RecordHeader _recordHeader; int _fileHeaderOffset; std::string _fileName; std::string _tempName; }; extern int readFileLines(const std::string &filn, LineList &ll); extern int readFileBytes(const std::string &filn, ByteVect &b); <commit_msg>remove unused method BatchFileReader::read<commit_after>/* Copyright 2015 Nervana Systems Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <time.h> #include <iostream> #include <fstream> #include <string> #include <vector> #include <memory> #include <algorithm> #include <cassert> #include <cstring> #include <sstream> #include "streams.hpp" #include "buffer.hpp" #define FORMAT_VERSION 1 #define WRITER_VERSION 1 #define MAGIC_STRING "MACR" #define CPIO_FOOTER "TRAILER!!!" typedef std::vector<std::string> LineList; typedef std::vector<char> ByteVect; typedef std::pair<std::shared_ptr<ByteVect>,std::shared_ptr<ByteVect>> DataPair; static_assert(sizeof(int) == 4, "int is not 4 bytes"); static_assert(sizeof(uint) == 4, "uint is not 4 bytes"); static_assert(sizeof(short) == 2, "short is not 2 bytes"); /* The data is stored as a cpio archive and may be unpacked using the GNU cpio utility. https://www.gnu.org/software/cpio/ Individual items are packed into a macrobatch file as follows: - header - datum 1 - target 1 - datum 2 - target 2 ... - trailer Each of these items comprises of a cpio header record followed by data. */ class RecordHeader { public: RecordHeader(); void loadDoubleShort(uint* dst, ushort src[2]); void saveDoubleShort(ushort* dst, uint src); void read(IfStream& ifs, uint* fileSize); void write(OfStream& ofs, uint fileSize, const char* fileName); public: ushort _magic; ushort _dev; ushort _ino; ushort _mode; ushort _uid; ushort _gid; ushort _nlink; ushort _rdev; ushort _mtime[2]; ushort _namesize; ushort _filesize[2]; }; class BatchFileHeader { friend class BatchFileReader; friend class BatchFileWriter; public: BatchFileHeader(); void read(IfStream& ifs); void write(OfStream& ofs); private: #pragma pack(1) char _magic[4]; uint _formatVersion; uint _writerVersion; char _dataType[8]; uint _itemCount; uint _maxDatumSize; uint _maxTargetSize; uint _totalDataSize; uint _totalTargetsSize; char _unused[24]; #pragma pack() }; class BatchFileTrailer { public: BatchFileTrailer() ; void write(OfStream& ofs); void read(IfStream& ifs); private: uint _unused[4]; }; class BatchFileReader { public: BatchFileReader(); BatchFileReader(const std::string& fileName); ~BatchFileReader() ; bool open(const std::string& fileName); void close(); void readToBuffer(Buffer& dest); int itemCount() ; int totalDataSize() ; int totalTargetsSize(); int maxDatumSize() ; int maxTargetSize(); private: IfStream _ifs; BatchFileHeader _fileHeader; BatchFileTrailer _fileTrailer; RecordHeader _recordHeader; std::string _fileName; std::string _tempName; }; class BatchFileWriter { public: ~BatchFileWriter(); void open(const std::string& fileName, const std::string& dataType = ""); void close(); void writeItem(char* datum, char* target, uint datumSize, uint targetSize); void writeItem(ByteVect &datum, ByteVect &target); private: OfStream _ofs; BatchFileHeader _fileHeader; BatchFileTrailer _fileTrailer; RecordHeader _recordHeader; int _fileHeaderOffset; std::string _fileName; std::string _tempName; }; extern int readFileLines(const std::string &filn, LineList &ll); extern int readFileBytes(const std::string &filn, ByteVect &b); <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: wrdtrans.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2003-04-28 16:31:08 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "wrdtrans.hxx" // NOT FULLY DECLARED SERVICES #include <vector> #include <vos/macros.hxx> #include <tools/stream.hxx> #include "wtratree.hxx" #include <tools/string.hxx> //************** Declaration WordTrans_ErrorList ******************// typedef NAMESPACE_STD(vector)<ByteString> Stl_ByteStringList; class WordTrans_ErrorList { public: // OPERATIONS void AddError( WordTransformer::E_Error i_eType, const char * i_sErrorDescription ); void Clear(); /// Empties the list. // INQUIRY USHORT NrOfErrors() const; WordTransformer::E_Error GetError( USHORT i_nNr, /// [0 .. NrOfErrors()-1], other values return an empty error. ByteString * o_pErrorText ) const; /// If o_pErrorText != 0, the String is filled with the description of the error. private: // DATA Stl_ByteStringList aErrors; }; //************** Implementation WordTransformer ******************// WordTransformer::WordTransformer() : dpTransformer(0), dpErrors(new WordTrans_ErrorList) { } WordTransformer::~WordTransformer() { if (dpTransformer != 0) delete dpTransformer; delete dpErrors; } BOOL WordTransformer::LoadWordlist( const ByteString & i_sWordlist_Filepath, CharSet i_nWorkingCharSet, CharSet i_nFileCharSet ) { if (dpTransformer != 0) return FALSE; SvFileStream aFile(String(i_sWordlist_Filepath,RTL_TEXTENCODING_ASCII_US),STREAM_STD_READ); if (! aFile.IsOpen()) return FALSE; aFile.SetStreamCharSet( i_nFileCharSet ) ; // aFile.SetTargetCharSet( i_nWorkingCharSet ); dpTransformer = new WordTransTree; ByteString sTrans; while ( aFile.ReadLine(sTrans) ) { dpTransformer->AddWordPair(sTrans.GetToken(0,';'),sTrans.GetToken(1,';')); } aFile.Close(); return TRUE; } USHORT WordTransformer::Transform(ByteString & io_sText) { // Initialization and precondition testing: dpErrors->Clear(); if (dpTransformer == 0) { dpErrors->AddError(ERROR_NO_WORDLIST,"Error: No wordlist was loaded."); return dpErrors->NrOfErrors(); } else if (io_sText.Len() > 63 * 1024) { dpErrors->AddError(ERROR_OUTPUTSTRING_TOO_LONG,"Error: Inputstring was too long (bigger than 63 KB)."); return dpErrors->NrOfErrors(); } else if (io_sText.Len() == 0) { return 0; } // Transform: dpTransformer->InitTransformation( io_sText.GetBuffer(), io_sText.Len() ); for ( ; !dpTransformer->TextEndReached(); ) { if (dpTransformer->TransformNextToken() != WordTransTree::OK) { CreateError(); } } io_sText = dpTransformer->Output(); return dpErrors->NrOfErrors(); } USHORT WordTransformer::NrOfErrors() const { return dpErrors->NrOfErrors(); } WordTransformer::E_Error WordTransformer::GetError( USHORT i_nNr, ByteString * o_pErrorText) const { return dpErrors->GetError(i_nNr,o_pErrorText); } void WordTransformer::CreateError() { ByteString sErr; switch (dpTransformer->CurResult()) { case WordTransTree::OK: break; case WordTransTree::HOTKEY_LOST: sErr = ByteString("Error: By replacement of string "); sErr += dpTransformer->CurReplacedString(); sErr += " by "; sErr += dpTransformer->CurReplacingString(); sErr += "the hotkey at char '"; sErr += dpTransformer->CurHotkey(); sErr += "' was lost."; dpErrors->AddError( ERROR_HOTKEY,sErr.GetBufferAccess()); sErr.ReleaseBufferAccess(); break; case WordTransTree::OUTPUT_OVERFLOW: dpErrors->AddError(ERROR_OUTPUTSTRING_TOO_LONG,"Error: Output buffer overflow."); break; default: dpErrors->AddError(OTHER_ERROR,"Error: Unknown error."); } } //************** Implementation WordTrans_ErrorList ******************// void WordTrans_ErrorList::AddError( WordTransformer::E_Error i_eType, const char * i_sErrorDescription ) { ByteString sErrorType = "xxx"; char * pErrorChars = sErrorType.GetBufferAccess(); pErrorChars[0] = char(i_eType / 100 + '0'); pErrorChars[1] = char( (i_eType % 100) / 10 + '0'); pErrorChars[2] = char(i_eType % 10 + '0'); sErrorType += i_sErrorDescription; aErrors.push_back(sErrorType); sErrorType.ReleaseBufferAccess(); } void WordTrans_ErrorList::Clear() { aErrors.erase(aErrors.begin(),aErrors.end()); } USHORT WordTrans_ErrorList::NrOfErrors() const { return aErrors.size(); } WordTransformer::E_Error WordTrans_ErrorList::GetError( USHORT i_nNr, ByteString * o_pErrorText ) const { if (0 <= i_nNr && i_nNr < aErrors.size() ) { const ByteString & rError = aErrors[i_nNr]; const char * pErrorChars = rError.GetBuffer(); USHORT nError = USHORT( (pErrorChars[0] - '0') ) * 100 + (pErrorChars[1] - '0') * 10 + pErrorChars[2] - '0'; if (o_pErrorText != 0) *o_pErrorText = pErrorChars+3; return WordTransformer::E_Error(nError); } else { if (o_pErrorText != 0) *o_pErrorText = ""; return WordTransformer::OK; } } <commit_msg>INTEGRATION: CWS rcmerge (1.2.6); FILE MERGED 2003/06/11 09:57:38 nf 1.2.6.1: #i13369# removed warnings<commit_after>/************************************************************************* * * $RCSfile: wrdtrans.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2003-06-13 11:40: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): _______________________________________ * * ************************************************************************/ #include "wrdtrans.hxx" // NOT FULLY DECLARED SERVICES #include <vector> #include <vos/macros.hxx> #include <tools/stream.hxx> #include "wtratree.hxx" #include <tools/string.hxx> //************** Declaration WordTrans_ErrorList ******************// typedef NAMESPACE_STD(vector)<ByteString> Stl_ByteStringList; class WordTrans_ErrorList { public: // OPERATIONS void AddError( WordTransformer::E_Error i_eType, const char * i_sErrorDescription ); void Clear(); /// Empties the list. // INQUIRY USHORT NrOfErrors() const; WordTransformer::E_Error GetError( USHORT i_nNr, /// [0 .. NrOfErrors()-1], other values return an empty error. ByteString * o_pErrorText ) const; /// If o_pErrorText != 0, the String is filled with the description of the error. private: // DATA Stl_ByteStringList aErrors; }; //************** Implementation WordTransformer ******************// WordTransformer::WordTransformer() : dpTransformer(0), dpErrors(new WordTrans_ErrorList) { } WordTransformer::~WordTransformer() { if (dpTransformer != 0) delete dpTransformer; delete dpErrors; } BOOL WordTransformer::LoadWordlist( const ByteString & i_sWordlist_Filepath, CharSet i_nWorkingCharSet, CharSet i_nFileCharSet ) { if (dpTransformer != 0) return FALSE; SvFileStream aFile(String(i_sWordlist_Filepath,RTL_TEXTENCODING_ASCII_US),STREAM_STD_READ); if (! aFile.IsOpen()) return FALSE; aFile.SetStreamCharSet( i_nFileCharSet ) ; // aFile.SetTargetCharSet( i_nWorkingCharSet ); dpTransformer = new WordTransTree; ByteString sTrans; while ( aFile.ReadLine(sTrans) ) { dpTransformer->AddWordPair(sTrans.GetToken(0,';'),sTrans.GetToken(1,';')); } aFile.Close(); return TRUE; } USHORT WordTransformer::Transform(ByteString & io_sText) { // Initialization and precondition testing: dpErrors->Clear(); if (dpTransformer == 0) { dpErrors->AddError(ERROR_NO_WORDLIST,"Error: No wordlist was loaded."); return dpErrors->NrOfErrors(); } else if (io_sText.Len() > 63 * 1024) { dpErrors->AddError(ERROR_OUTPUTSTRING_TOO_LONG,"Error: Inputstring was too long (bigger than 63 KB)."); return dpErrors->NrOfErrors(); } else if (io_sText.Len() == 0) { return 0; } // Transform: dpTransformer->InitTransformation( io_sText.GetBuffer(), io_sText.Len() ); for ( ; !dpTransformer->TextEndReached(); ) { if (dpTransformer->TransformNextToken() != WordTransTree::OK) { CreateError(); } } io_sText = dpTransformer->Output(); return dpErrors->NrOfErrors(); } USHORT WordTransformer::NrOfErrors() const { return dpErrors->NrOfErrors(); } WordTransformer::E_Error WordTransformer::GetError( USHORT i_nNr, ByteString * o_pErrorText) const { return dpErrors->GetError(i_nNr,o_pErrorText); } void WordTransformer::CreateError() { ByteString sErr; switch (dpTransformer->CurResult()) { case WordTransTree::OK: break; case WordTransTree::HOTKEY_LOST: sErr = ByteString("Error: By replacement of string "); sErr += dpTransformer->CurReplacedString(); sErr += " by "; sErr += dpTransformer->CurReplacingString(); sErr += "the hotkey at char '"; sErr += dpTransformer->CurHotkey(); sErr += "' was lost."; dpErrors->AddError( ERROR_HOTKEY,sErr.GetBufferAccess()); sErr.ReleaseBufferAccess(); break; case WordTransTree::OUTPUT_OVERFLOW: dpErrors->AddError(ERROR_OUTPUTSTRING_TOO_LONG,"Error: Output buffer overflow."); break; default: dpErrors->AddError(OTHER_ERROR,"Error: Unknown error."); } } //************** Implementation WordTrans_ErrorList ******************// void WordTrans_ErrorList::AddError( WordTransformer::E_Error i_eType, const char * i_sErrorDescription ) { ByteString sErrorType = "xxx"; char * pErrorChars = sErrorType.GetBufferAccess(); pErrorChars[0] = char(i_eType / 100 + '0'); pErrorChars[1] = char( (i_eType % 100) / 10 + '0'); pErrorChars[2] = char(i_eType % 10 + '0'); sErrorType += i_sErrorDescription; aErrors.push_back(sErrorType); sErrorType.ReleaseBufferAccess(); } void WordTrans_ErrorList::Clear() { aErrors.erase(aErrors.begin(),aErrors.end()); } USHORT WordTrans_ErrorList::NrOfErrors() const { return aErrors.size(); } WordTransformer::E_Error WordTrans_ErrorList::GetError( USHORT i_nNr, ByteString * o_pErrorText ) const { if ( i_nNr < aErrors.size() ) { const ByteString & rError = aErrors[i_nNr]; const char * pErrorChars = rError.GetBuffer(); USHORT nError = USHORT( (pErrorChars[0] - '0') ) * 100 + (pErrorChars[1] - '0') * 10 + pErrorChars[2] - '0'; if (o_pErrorText != 0) *o_pErrorText = pErrorChars+3; return WordTransformer::E_Error(nError); } else { if (o_pErrorText != 0) *o_pErrorText = ""; return WordTransformer::OK; } } <|endoftext|>
<commit_before>Bool_t gIsAnalysisLoaded = kFALSE ; //______________________________________________________________________ Bool_t LoadLib( const char* pararchivename) { // Loads the AliRoot required libraries from a tar file Bool_t rv = kTRUE ; char cdir[1024] ; sprintf(cdir, "%s", gSystem->WorkingDirectory() ) ; // Setup par File if (pararchivename) { char processline[1024]; sprintf(processline,".! tar xvzf %s.par",pararchivename); gROOT->ProcessLine(processline); gSystem->ChangeDirectory(pararchivename); // check for BUILD.sh and execute if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) { printf("*** Building PAR archive %s ***\n", pararchivename); if (gSystem->Exec("PROOF-INF/BUILD.sh")) { AliError(Form("Cannot Build the PAR Archive %s! - Abort!", pararchivename) ); return kFALSE ; } } // check for SETUP.C and execute if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) { printf("*** Setup PAR archive %s ***\n", pararchivename); gROOT->Macro("PROOF-INF/SETUP.C"); } } if ( strstr(pararchivename, "ESD") ) { //gSystem->Load("libVMC.so"); //gSystem->Load("libRAliEn.so"); gSystem->Load("libESD.so") ; //gSystem->Load("libProof.so") ; } if ( strstr(pararchivename, "AnalysisCheck") ) { gSystem->Load("libSpectrum.so"); } printf("lib%s done\n", pararchivename); gSystem->ChangeDirectory(cdir); gIsAnalysisLoaded = kTRUE ; return rv ; } //______________________________________________________________________ void ana() { if (! gIsAnalysisLoaded ) { LoadLib("ESD") ; LoadLib("ANALYSIS") ; LoadLib("AnalysisCheck") ; } // create the analysis goodies object AliAnalysisGoodies * ag = new AliAnalysisGoodies() ; // definition of analysis tasks const Int_t knumberOfTasks = 10 ; AliAnalysisTask * taskList[knumberOfTasks] ; TClass * taskInputList[knumberOfTasks] ; TClass * taskOutputList[knumberOfTasks] ; taskList[0] = new AliPHOSQATask("PHOS") ; taskInputList[0] = TChain::Class() ; taskOutputList[0] = TObjArray::Class() ; taskList[1] = new AliEMCALQATask("EMCal") ; taskInputList[1] = taskInputList[0] ; // only one top input container allowed taskOutputList[1] = TObjArray::Class() ; taskList[2] = new AliPMDQATask("PMD") ; taskInputList[2] = taskInputList[0] ; // only one top input container allowed taskOutputList[2] = TObjArray::Class() ; taskList[3] = new AliAnalysisTaskPt("Pt") ; taskInputList[3] = taskInputList[0] ; // only one top input container allowed taskOutputList[3] = TObjArray::Class() ; taskList[4] = new AliHMPIDQATask("HMPID") ; taskInputList[4] = taskInputList[0] ; // only one top input container allowed taskOutputList[4] = TObjArray::Class() ; taskList[5] = new AliT0QATask("T0") ; taskInputList[5] = taskInputList[0] ; // only one top input container allowed taskOutputList[5] = TObjArray::Class() ; taskList[6] = new AliMUONQATask("MUON") ; taskInputList[6] = taskInputList[0] ; // only one top input container allowed taskOutputList[6] = TObjArray::Class() ; taskList[7] = new AliTRDQATask("TRD") ; taskInputList[7] = taskInputList[0] ; // only one top input container allowed taskOutputList[7] = TObjArray::Class() ; taskList[8] = new AliTOFQATask("TOF") ; taskInputList[8] = taskInputList[0] ; // only one top input container allowed taskOutputList[8] = TObjArray::Class() ; taskList[9] = new AliVZEROQATask("VZERO") ; taskInputList[9] = taskInputList[0] ; // only one top input container allowed taskOutputList[9] = TObjArray::Class() ; // taskList[8] = new AliFMDQATask("FMD") ; // taskInputList[8] = taskInputList[0] ; // only one top input container allowed // taskOutputList[8] = TObjArray::Class() ; ag->SetTasks(knumberOfTasks, taskList, taskInputList, taskOutputList) ; // get the data to analyze // definition of Tag cuts const char * runCuts = 0x0 ; const char * evtCuts = 0x0 ; const char * lhcCuts = 0x0 ; const char * detCuts = 0x0 ; //"fEventTag.fNPHOSClustersMin == 1 && fEventTag.fNEMCALClustersMin == 1" ; TString input = gSystem->Getenv("ANA_INPUT") ; if ( input != "") { char argument[1024] ; if ( input.Contains("tag?") ) { //create the ESD collection from the tag collection input.ReplaceAll("tag?", "") ; const char * collESD = "esdCollection.xml" ; ag->MakeEsdCollectionFromTagCollection(runCuts, lhcCuts, detCuts, evtCuts, input.Data(), collESD) ; sprintf(argument, "esd?%s", collESD) ; } else if ( input.Contains("esd?") ) sprintf(argument, "%s", input.Data()) ; ag->Process(argument) ; } else { TChain* analysisChain = new TChain("esdTree") ; // input = "alien:///alice/cern.ch/user/a/aliprod/prod2006_2/output_pp/105/411/AliESDs.root" ; // analysisChain->AddFile(input); input = "AliESDs.root" ; analysisChain->AddFile(input); ag->Process(analysisChain) ; } return ; } //______________________________________________________________________ void Merge(const char * xml, const char * sub, const char * out) { if (! gIsAnalysisLoaded ) LoadLib("ESD") ; AliAnalysisGoodies * ag = new AliAnalysisGoodies() ; ag->Merge(xml, sub, out) ; } <commit_msg>Adding reation of par file (Yves)<commit_after>Bool_t gIsAnalysisLoaded = kFALSE ; //______________________________________________________________________ Bool_t LoadLib( const char* pararchivename) { // Loads the AliRoot required libraries from a tar file Bool_t rv = kTRUE ; char cdir[1024] ; sprintf(cdir, "%s", gSystem->WorkingDirectory() ) ; // Setup par File if (pararchivename) { char parpar[80] ; sprintf(parpar, "%s.par", pararchivename) ; if ( gSystem->AccessPathName(parpar) ) { gSystem->ChangeDirectory(gSystem->Getenv("ALICE_ROOT")) ; char processline[1024]; sprintf(processline, ".! make %s", parpar) ; cout << processline << endl ; gROOT->ProcessLine(processline) ; gSystem->ChangeDirectory(cdir) ; sprintf(processline, ".! mv %s/%s .", gSystem->Getenv("ALICE_ROOT"), parpar) ; gROOT->ProcessLine(processline) ; sprintf(processline,".! tar xvzf %s",parpar); gROOT->ProcessLine(processline); } gSystem->ChangeDirectory(pararchivename); // check for BUILD.sh and execute if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) { printf("*** Building PAR archive %s ***\n", pararchivename); if (gSystem->Exec("PROOF-INF/BUILD.sh")) { AliError(Form("Cannot Build the PAR Archive %s! - Abort!", pararchivename) ); return kFALSE ; } } // check for SETUP.C and execute if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) { printf("*** Setup PAR archive %s ***\n", pararchivename); gROOT->Macro("PROOF-INF/SETUP.C"); } } if ( strstr(pararchivename, "ESD") ) { //gSystem->Load("libVMC.so"); //gSystem->Load("libRAliEn.so"); gSystem->Load("libESD.so") ; //gSystem->Load("libProof.so") ; } if ( strstr(pararchivename, "AnalysisCheck") ) { gSystem->Load("libSpectrum.so"); } printf("lib%s done\n", pararchivename); gSystem->ChangeDirectory(cdir); gIsAnalysisLoaded = kTRUE ; return rv ; } //______________________________________________________________________ void ana(const Int_t kEvent=100) { if (! gIsAnalysisLoaded ) { LoadLib("ESD") ; LoadLib("ANALYSIS") ; LoadLib("AnalysisCheck") ; } // create the analysis goodies object AliAnalysisGoodies * ag = new AliAnalysisGoodies() ; // definition of analysis tasks const Int_t knumberOfTasks = 10 ; AliAnalysisTask * taskList[knumberOfTasks] ; TClass * taskInputList[knumberOfTasks] ; TClass * taskOutputList[knumberOfTasks] ; taskList[0] = new AliPHOSQATask("PHOS") ; taskInputList[0] = TChain::Class() ; taskOutputList[0] = TObjArray::Class() ; taskList[1] = new AliEMCALQATask("EMCal") ; taskInputList[1] = taskInputList[0] ; // only one top input container allowed taskOutputList[1] = TObjArray::Class() ; taskList[2] = new AliPMDQATask("PMD") ; taskInputList[2] = taskInputList[0] ; // only one top input container allowed taskOutputList[2] = TObjArray::Class() ; taskList[3] = new AliAnalysisTaskPt("Pt") ; taskInputList[3] = taskInputList[0] ; // only one top input container allowed taskOutputList[3] = TObjArray::Class() ; taskList[4] = new AliHMPIDQATask("HMPID") ; taskInputList[4] = taskInputList[0] ; // only one top input container allowed taskOutputList[4] = TObjArray::Class() ; taskList[5] = new AliT0QATask("T0") ; taskInputList[5] = taskInputList[0] ; // only one top input container allowed taskOutputList[5] = TObjArray::Class() ; taskList[6] = new AliMUONQATask("MUON") ; taskInputList[6] = taskInputList[0] ; // only one top input container allowed taskOutputList[6] = TObjArray::Class() ; taskList[7] = new AliTRDQATask("TRD") ; taskInputList[7] = taskInputList[0] ; // only one top input container allowed taskOutputList[7] = TObjArray::Class() ; taskList[8] = new AliTOFQATask("TOF") ; taskInputList[8] = taskInputList[0] ; // only one top input container allowed taskOutputList[8] = TObjArray::Class() ; taskList[9] = new AliVZEROQATask("VZERO") ; taskInputList[9] = taskInputList[0] ; // only one top input container allowed taskOutputList[9] = TObjArray::Class() ; // taskList[8] = new AliFMDQATask("FMD") ; // taskInputList[8] = taskInputList[0] ; // only one top input container allowed // taskOutputList[8] = TObjArray::Class() ; ag->SetTasks(knumberOfTasks, taskList, taskInputList, taskOutputList) ; // get the data to analyze // definition of Tag cuts const char * runCuts = 0x0 ; const char * evtCuts = 0x0 ; const char * lhcCuts = 0x0 ; const char * detCuts = 0x0 ; //"fEventTag.fNPHOSClustersMin == 1 && fEventTag.fNEMCALClustersMin == 1" ; TString input = gSystem->Getenv("ANA_INPUT") ; if ( input != "") { char argument[1024] ; if ( input.Contains("tag?") ) { //create the ESD collection from the tag collection input.ReplaceAll("tag?", "") ; const char * collESD = "esdCollection.xml" ; ag->MakeEsdCollectionFromTagCollection(runCuts, lhcCuts, detCuts, evtCuts, input.Data(), collESD) ; sprintf(argument, "esd?%s", collESD) ; } else if ( input.Contains("esd?") ) sprintf(argument, "%s", input.Data()) ; ag->Process(argument) ; } else { TChain* analysisChain = new TChain("esdTree") ; // input = "alien:///alice/cern.ch/user/a/aliprod/prod2006_2/output_pp/105/411/AliESDs.root" ; // analysisChain->AddFile(input); input = "AliESDs.root" ; const char * kInDir = gSystem->Getenv("OUTDIR") ; if ( kInDir ) { if ( ! gSystem->cd(kInDir) ) { printf("%s does not exist\n", kInDir) ; return ; } Int_t event, skipped=0 ; char file[120] ; for (event = 0 ; event < kEvent ; event++) { sprintf(file, "%s/%d/AliESDs.root", kInDir,event) ; TFile * fESD = 0 ; if ( fESD = TFile::Open(file)) if ( fESD->Get("esdTree") ) { printf("++++ Adding %s\n", file) ; analysisChain->AddFile(file); } else { printf("---- Skipping %s\n", file) ; skipped++ ; } } printf("number of entries # %lld, skipped %d\n", analysisChain->GetEntries(), skipped*100) ; } else analysisChain->AddFile(input); ag->Process(analysisChain) ; } return ; } //______________________________________________________________________ void Merge(const char * xml, const char * sub, const char * out) { if (! gIsAnalysisLoaded ) LoadLib("ESD") ; AliAnalysisGoodies * ag = new AliAnalysisGoodies() ; ag->Merge(xml, sub, out) ; } <|endoftext|>
<commit_before>#include "ESP8266_AT.h" ESP8266_AT::ESP8266_AT(uint32_t rxPin, uint32_t txPin, uint32_t baud) : m_rxPin(rxPin), m_txPin(txPin) { SoftwareSerial *serial = new SoftwareSerial(rxPin, txPin); serial->begin(baud); m_serial = serial; } ESP8266_AT::ESP8266_AT(SoftwareSerial &serial) : m_rxPin(0), m_txPin(0), m_serial(&serial) { } ESP8266_AT::ESP8266_AT(HardwareSerial &serial) : m_rxPin(0), m_txPin(0), m_serial(&serial) { } ESP8266_AT::~ESP8266_AT() { disconnect(); if(m_rxPin != 0 && m_txPin !=0) delete m_serial; } void ESP8266_AT::rxClear() { while(m_serial->available() > 0) m_serial->read(); } bool ESP8266_AT::checkATResponse(String *buf, String target, uint32_t timeout) { *buf = ""; char c; unsigned long start = millis(); while (millis() - start < timeout) { while(m_serial->available() > 0) { c = m_serial->read(); // 1 byte if(c == '\0') continue; *buf += c; } if (buf->indexOf(target) != -1) return true; } return false; } bool ESP8266_AT::checkATResponse(String target, uint32_t timeout) { String buf; return checkATResponse(&buf, target, timeout); } bool ESP8266_AT::statusAT() { rxClear(); m_serial->println("AT"); return checkATResponse(); } bool ESP8266_AT::restart() { rxClear(); m_serial->println("AT+RST"); if(!checkATResponse()) return false; delay(2000); unsigned long start = millis(); while(millis() - start < 3000) { if(statusAT()) { delay(1500); return true; } delay(100); } return false; } bool ESP8266_AT::connect(String ssid, String password) { rxClear(); m_serial->println("AT+CWMODE_DEF=1"); // 1: station(client) mode, 2: softAP(server) mode, 3: 1&2 if(!(checkATResponse() && restart())) return false; // change "DEF"ault cwMode and restart // Connect to an AP rxClear(); m_serial->print("AT+CWJAP_DEF=\""); m_serial->print(ssid); m_serial->print("\",\""); m_serial->print(password); m_serial->println("\""); return checkATResponse("OK", 10000); } bool ESP8266_AT::disconnect() { rxClear(); m_serial->println("AT+CWQAP"); return checkATResponse(); } bool ESP8266_AT::statusWiFi() { String buf; rxClear(); m_serial->println("AT+CIPSTATUS"); checkATResponse(&buf, "S:", 10000); uint32_t index = buf.indexOf(":"); uint8_t stat = buf.substring(index + 1, index + 2).toInt(); return (stat != 5); // 5: ESP8266 station is NOT connected to an AP } int ESP8266_AT::connect(const char *host, uint16_t port) { if(connected()) stop(); String buf; uint8_t retry = 10; while(retry--) { rxClear(); m_serial->print("AT+CIPSTART=\"TCP\",\""); m_serial->print(host); m_serial->print("\","); m_serial->println(port); checkATResponse(&buf, "OK", 2000); if(buf.indexOf("OK") != -1 || buf.indexOf("ALREADY") != -1) { return 1; // SUCCESS } delay(500); } return -1; // TIMED_OUT } int ESP8266_AT::connect(IPAddress ip, uint16_t port) { String host = ""; for(uint8_t i = 0; i < 4;) { host += String(ip[i]); if(++i < 4) host += "."; } return connect(host.c_str(), port); } void ESP8266_AT::stop() { // TODO } uint8_t ESP8266_AT::connected() { return 1; // TODO } size_t ESP8266_AT::write(const uint8_t *buf, size_t size) { return 0; // TODO } size_t ESP8266_AT::write(uint8_t) { return 0; // TODO } int ESP8266_AT::available() { return 0; // TODO } int ESP8266_AT::read() { return 0; // TODO } int ESP8266_AT::read(uint8_t *buf, size_t size) { return 0; // TODO } int ESP8266_AT::peek() { return 0; // TODO } void ESP8266_AT::flush() { // TODO } ESP8266_AT::operator bool() { // TODO } <commit_msg>Implemented ESP8266_AT::stop<commit_after>#include "ESP8266_AT.h" ESP8266_AT::ESP8266_AT(uint32_t rxPin, uint32_t txPin, uint32_t baud) : m_rxPin(rxPin), m_txPin(txPin) { SoftwareSerial *serial = new SoftwareSerial(rxPin, txPin); serial->begin(baud); m_serial = serial; } ESP8266_AT::ESP8266_AT(SoftwareSerial &serial) : m_rxPin(0), m_txPin(0), m_serial(&serial) { } ESP8266_AT::ESP8266_AT(HardwareSerial &serial) : m_rxPin(0), m_txPin(0), m_serial(&serial) { } ESP8266_AT::~ESP8266_AT() { disconnect(); if(m_rxPin != 0 && m_txPin !=0) delete m_serial; } void ESP8266_AT::rxClear() { while(m_serial->available() > 0) m_serial->read(); } bool ESP8266_AT::checkATResponse(String *buf, String target, uint32_t timeout) { *buf = ""; char c; unsigned long start = millis(); while (millis() - start < timeout) { while(m_serial->available() > 0) { c = m_serial->read(); // 1 byte if(c == '\0') continue; *buf += c; } if (buf->indexOf(target) != -1) return true; } return false; } bool ESP8266_AT::checkATResponse(String target, uint32_t timeout) { String buf; return checkATResponse(&buf, target, timeout); } bool ESP8266_AT::statusAT() { rxClear(); m_serial->println("AT"); return checkATResponse(); } bool ESP8266_AT::restart() { rxClear(); m_serial->println("AT+RST"); if(!checkATResponse()) return false; delay(2000); unsigned long start = millis(); while(millis() - start < 3000) { if(statusAT()) { delay(1500); return true; } delay(100); } return false; } bool ESP8266_AT::connect(String ssid, String password) { rxClear(); m_serial->println("AT+CWMODE_DEF=1"); // 1: station(client) mode, 2: softAP(server) mode, 3: 1&2 if(!(checkATResponse() && restart())) return false; // change "DEF"ault cwMode and restart // Connect to an AP rxClear(); m_serial->print("AT+CWJAP_DEF=\""); m_serial->print(ssid); m_serial->print("\",\""); m_serial->print(password); m_serial->println("\""); return checkATResponse("OK", 10000); } bool ESP8266_AT::disconnect() { rxClear(); m_serial->println("AT+CWQAP"); return checkATResponse(); } bool ESP8266_AT::statusWiFi() { String buf; rxClear(); m_serial->println("AT+CIPSTATUS"); checkATResponse(&buf, "S:", 10000); uint32_t index = buf.indexOf(":"); uint8_t stat = buf.substring(index + 1, index + 2).toInt(); return (stat != 5); // 5: ESP8266 station is NOT connected to an AP } int ESP8266_AT::connect(const char *host, uint16_t port) { if(connected()) stop(); String buf; uint8_t retry = 10; while(retry--) { rxClear(); m_serial->print("AT+CIPSTART=\"TCP\",\""); m_serial->print(host); m_serial->print("\","); m_serial->println(port); checkATResponse(&buf, "OK", 2000); if(buf.indexOf("OK") != -1 || buf.indexOf("ALREADY") != -1) { return 1; // SUCCESS } delay(500); } return -1; // TIMED_OUT } int ESP8266_AT::connect(IPAddress ip, uint16_t port) { String host = ""; for(uint8_t i = 0; i < 4;) { host += String(ip[i]); if(++i < 4) host += "."; } return connect(host.c_str(), port); } void ESP8266_AT::stop() { rxClear(); m_serial->println("AT+CIPCLOSE"); checkATResponse("OK", 5000); } uint8_t ESP8266_AT::connected() { return 1; // TODO } size_t ESP8266_AT::write(const uint8_t *buf, size_t size) { return 0; // TODO } size_t ESP8266_AT::write(uint8_t) { return 0; // TODO } int ESP8266_AT::available() { return 0; // TODO } int ESP8266_AT::read() { return 0; // TODO } int ESP8266_AT::read(uint8_t *buf, size_t size) { return 0; // TODO } int ESP8266_AT::peek() { return 0; // TODO } void ESP8266_AT::flush() { // TODO } ESP8266_AT::operator bool() { // TODO } <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file Client.cpp * @author Gav Wood <[email protected]> * @date 2014 */ #include "Client.h" #include <chrono> #include <thread> #include "Common.h" #include "Defaults.h" using namespace std; using namespace eth; Client::Client(std::string const& _clientVersion, Address _us, std::string const& _dbPath): m_clientVersion(_clientVersion), m_bc(_dbPath), m_stateDB(State::openDB(_dbPath)), m_s(_us, m_stateDB), m_mined(_us, m_stateDB) { Defaults::setDBPath(_dbPath); // Synchronise the state according to the block chain - i.e. replay all transactions in block chain, in order. // In practise this won't need to be done since the State DB will contain the keys for the tries for most recent (and many old) blocks. // TODO: currently it contains keys for *all* blocks. Make it remove old ones. m_s.sync(m_bc); m_s.sync(m_tq); m_mined = m_s; m_changed = true; static const char* c_threadName = "eth"; m_work = new thread([&](){ setThreadName(c_threadName); while (m_workState != Deleting) work(); m_workState = Deleted; }); } Client::~Client() { if (m_workState == Active) m_workState = Deleting; while (m_workState != Deleted) this_thread::sleep_for(chrono::milliseconds(10)); } void Client::startNetwork(short _listenPort, std::string const& _seedHost, short _port, NodeMode _mode, unsigned _peers, string const& _publicIP, bool _upnp) { if (m_net) return; m_net = new PeerServer(m_clientVersion, m_bc, 0, _listenPort, _mode, _publicIP, _upnp); m_net->setIdealPeerCount(_peers); if (_seedHost.size()) connect(_seedHost, _port); } void Client::connect(std::string const& _seedHost, short _port) { if (!m_net) return; m_net->connect(_seedHost, _port); } void Client::stopNetwork() { delete m_net; m_net = nullptr; } void Client::startMining() { m_doMine = true; m_miningStarted = true; } void Client::stopMining() { m_doMine = false; } void Client::transact(Secret _secret, Address _dest, u256 _amount, u256s _data) { lock_guard<mutex> l(m_lock); Transaction t; t.nonce = m_mined.transactionsFrom(toAddress(_secret)); t.receiveAddress = _dest; t.value = _amount; t.data = _data; t.sign(_secret); cnote << "New transaction " << t; m_tq.attemptImport(t.rlp()); m_changed = true; } void Client::work() { bool changed = false; // Process network events. // Synchronise block chain with network. // Will broadcast any of our (new) transactions and blocks, and collect & add any of their (new) transactions and blocks. if (m_net) { m_net->process(); lock_guard<mutex> l(m_lock); if (m_net->sync(m_bc, m_tq, m_stateDB)) changed = true; } // Synchronise state to block chain. // This should remove any transactions on our queue that are included within our state. // It also guarantees that the state reflects the longest (valid!) chain on the block chain. // This might mean reverting to an earlier state and replaying some blocks, or, (worst-case: // if there are no checkpoints before our fork) reverting to the genesis block and replaying // all blocks. // Resynchronise state with block chain & trans { lock_guard<mutex> l(m_lock); if (m_s.sync(m_bc)) { cnote << "Externally mined block: Restarting mining operation."; changed = true; m_miningStarted = true; // need to re-commit to mine. m_mined = m_s; } if (m_mined.sync(m_tq)) { cnote << "Additional transaction ready: Restarting mining operation."; changed = true; m_miningStarted = true; } } if (m_doMine) { if (m_miningStarted) { lock_guard<mutex> l(m_lock); m_mined.commitToMine(m_bc); } m_miningStarted = false; // Mine for a while. MineInfo mineInfo = m_mined.mine(100); m_mineProgress.best = max(m_mineProgress.best, mineInfo.best); m_mineProgress.current = mineInfo.best; m_mineProgress.requirement = mineInfo.requirement; if (mineInfo.completed) { // Import block. lock_guard<mutex> l(m_lock); m_bc.attemptImport(m_mined.blockData(), m_stateDB); m_mineProgress.best = 0; m_changed = true; m_miningStarted = true; // need to re-commit to mine. } } else this_thread::sleep_for(chrono::milliseconds(100)); m_changed = m_changed || changed; } void Client::lock() { m_lock.lock(); } void Client::unlock() { m_lock.unlock(); } <commit_msg>Avoid unnecessesasry mining messages.<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file Client.cpp * @author Gav Wood <[email protected]> * @date 2014 */ #include "Client.h" #include <chrono> #include <thread> #include "Common.h" #include "Defaults.h" using namespace std; using namespace eth; Client::Client(std::string const& _clientVersion, Address _us, std::string const& _dbPath): m_clientVersion(_clientVersion), m_bc(_dbPath), m_stateDB(State::openDB(_dbPath)), m_s(_us, m_stateDB), m_mined(_us, m_stateDB) { Defaults::setDBPath(_dbPath); // Synchronise the state according to the block chain - i.e. replay all transactions in block chain, in order. // In practise this won't need to be done since the State DB will contain the keys for the tries for most recent (and many old) blocks. // TODO: currently it contains keys for *all* blocks. Make it remove old ones. m_s.sync(m_bc); m_s.sync(m_tq); m_mined = m_s; m_changed = true; static const char* c_threadName = "eth"; m_work = new thread([&](){ setThreadName(c_threadName); while (m_workState != Deleting) work(); m_workState = Deleted; }); } Client::~Client() { if (m_workState == Active) m_workState = Deleting; while (m_workState != Deleted) this_thread::sleep_for(chrono::milliseconds(10)); } void Client::startNetwork(short _listenPort, std::string const& _seedHost, short _port, NodeMode _mode, unsigned _peers, string const& _publicIP, bool _upnp) { if (m_net) return; m_net = new PeerServer(m_clientVersion, m_bc, 0, _listenPort, _mode, _publicIP, _upnp); m_net->setIdealPeerCount(_peers); if (_seedHost.size()) connect(_seedHost, _port); } void Client::connect(std::string const& _seedHost, short _port) { if (!m_net) return; m_net->connect(_seedHost, _port); } void Client::stopNetwork() { delete m_net; m_net = nullptr; } void Client::startMining() { m_doMine = true; m_miningStarted = true; } void Client::stopMining() { m_doMine = false; } void Client::transact(Secret _secret, Address _dest, u256 _amount, u256s _data) { lock_guard<mutex> l(m_lock); Transaction t; t.nonce = m_mined.transactionsFrom(toAddress(_secret)); t.receiveAddress = _dest; t.value = _amount; t.data = _data; t.sign(_secret); cnote << "New transaction " << t; m_tq.attemptImport(t.rlp()); m_changed = true; } void Client::work() { bool changed = false; // Process network events. // Synchronise block chain with network. // Will broadcast any of our (new) transactions and blocks, and collect & add any of their (new) transactions and blocks. if (m_net) { m_net->process(); lock_guard<mutex> l(m_lock); if (m_net->sync(m_bc, m_tq, m_stateDB)) changed = true; } // Synchronise state to block chain. // This should remove any transactions on our queue that are included within our state. // It also guarantees that the state reflects the longest (valid!) chain on the block chain. // This might mean reverting to an earlier state and replaying some blocks, or, (worst-case: // if there are no checkpoints before our fork) reverting to the genesis block and replaying // all blocks. // Resynchronise state with block chain & trans { lock_guard<mutex> l(m_lock); if (m_s.sync(m_bc)) { if (m_doMine) cnote << "Externally mined block: Restarting mining operation."; changed = true; m_miningStarted = true; // need to re-commit to mine. m_mined = m_s; } if (m_mined.sync(m_tq)) { if (m_doMine) cnote << "Additional transaction ready: Restarting mining operation."; changed = true; m_miningStarted = true; } } if (m_doMine) { if (m_miningStarted) { lock_guard<mutex> l(m_lock); m_mined.commitToMine(m_bc); } m_miningStarted = false; // Mine for a while. MineInfo mineInfo = m_mined.mine(100); m_mineProgress.best = max(m_mineProgress.best, mineInfo.best); m_mineProgress.current = mineInfo.best; m_mineProgress.requirement = mineInfo.requirement; if (mineInfo.completed) { // Import block. lock_guard<mutex> l(m_lock); m_bc.attemptImport(m_mined.blockData(), m_stateDB); m_mineProgress.best = 0; m_changed = true; m_miningStarted = true; // need to re-commit to mine. } } else this_thread::sleep_for(chrono::milliseconds(100)); m_changed = m_changed || changed; } void Client::lock() { m_lock.lock(); } void Client::unlock() { m_lock.unlock(); } <|endoftext|>
<commit_before> #include "GasMeter.h" #include <llvm/IR/GlobalVariable.h> #include <llvm/IR/Function.h> #include <llvm/IR/IntrinsicInst.h> #include <libevmface/Instruction.h> #include <libevm/FeeStructure.h> #include "Type.h" #include "Ext.h" namespace dev { namespace eth { namespace jit { namespace // Helper functions { uint64_t getStepCost(Instruction inst) // TODO: Add this function to FeeSructure (pull request submitted) { switch (inst) { case Instruction::STOP: case Instruction::SUICIDE: return 0; case Instruction::SSTORE: return static_cast<uint64_t>(FeeStructure::c_sstoreGas); case Instruction::SLOAD: return static_cast<uint64_t>(FeeStructure::c_sloadGas); case Instruction::SHA3: return static_cast<uint64_t>(FeeStructure::c_sha3Gas); case Instruction::BALANCE: return static_cast<uint64_t>(FeeStructure::c_sha3Gas); case Instruction::CALL: case Instruction::CALLCODE: return static_cast<uint64_t>(FeeStructure::c_callGas); case Instruction::CREATE: return static_cast<uint64_t>(FeeStructure::c_createGas); default: // Assumes instruction code is valid return static_cast<uint64_t>(FeeStructure::c_stepGas); } } bool isCostBlockEnd(Instruction _inst) { // Basic block terminators like STOP are not needed on the list // as cost will be commited at the end of basic block // CALL & CALLCODE are commited manually switch (_inst) { case Instruction::CALLDATACOPY: case Instruction::CODECOPY: case Instruction::MLOAD: case Instruction::MSTORE: case Instruction::MSTORE8: case Instruction::SSTORE: case Instruction::GAS: case Instruction::CREATE: return true; default: return false; } } } GasMeter::GasMeter(llvm::IRBuilder<>& _builder) : CompilerHelper(_builder) { auto module = getModule(); m_gas = new llvm::GlobalVariable(*module, Type::i256, false, llvm::GlobalVariable::ExternalLinkage, nullptr, "gas"); m_gas->setUnnamedAddr(true); // Address is not important m_gasCheckFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, Type::i256, false), llvm::Function::PrivateLinkage, "gas.check", module); InsertPointGuard guard(m_builder); auto checkBB = llvm::BasicBlock::Create(_builder.getContext(), "Check", m_gasCheckFunc); auto outOfGasBB = llvm::BasicBlock::Create(_builder.getContext(), "OutOfGas", m_gasCheckFunc); auto updateBB = llvm::BasicBlock::Create(_builder.getContext(), "Update", m_gasCheckFunc); m_builder.SetInsertPoint(checkBB); llvm::Value* cost = m_gasCheckFunc->arg_begin(); cost->setName("cost"); llvm::Value* gas = m_builder.CreateLoad(m_gas, "gas"); auto isOutOfGas = m_builder.CreateICmpUGT(cost, gas, "isOutOfGas"); m_builder.CreateCondBr(isOutOfGas, outOfGasBB, updateBB); m_builder.SetInsertPoint(outOfGasBB); //auto longjmpFunc = llvm::Intrinsic::getDeclaration(_module, llvm::Intrinsic::eh_sjlj_longjmp); auto extJmpBuf = new llvm::GlobalVariable(*module, Type::BytePtr, false, llvm::GlobalVariable::ExternalLinkage, nullptr, "rt_jmpBuf"); llvm::Type* args[] = {Type::BytePtr, m_builder.getInt32Ty()}; auto longjmpNative = llvm::Function::Create(llvm::FunctionType::get(Type::Void, args, false), llvm::Function::ExternalLinkage, "longjmp", module); m_builder.CreateCall2(longjmpNative, m_builder.CreateLoad(extJmpBuf), Constant::get(ReturnCode::OutOfGas)); m_builder.CreateUnreachable(); m_builder.SetInsertPoint(updateBB); gas = m_builder.CreateSub(gas, cost); m_builder.CreateStore(gas, m_gas); m_builder.CreateRetVoid(); } void GasMeter::count(Instruction _inst) { if (!m_checkCall) { // Create gas check call with mocked block cost at begining of current cost-block m_checkCall = m_builder.CreateCall(m_gasCheckFunc, llvm::UndefValue::get(Type::i256)); } if (_inst != Instruction::SSTORE) // Handle cost of SSTORE separately in countSStore() m_blockCost += getStepCost(_inst); if (isCostBlockEnd(_inst)) commitCostBlock(); } void GasMeter::countSStore(Ext& _ext, llvm::Value* _index, llvm::Value* _newValue) { assert(!m_checkCall); // Everything should've been commited before static const auto sstoreCost = static_cast<uint64_t>(FeeStructure::c_sstoreGas); // [ADD] if oldValue == 0 and newValue != 0 => 2*cost // [DEL] if oldValue != 0 and newValue == 0 => 0 auto oldValue = _ext.store(_index); auto oldValueIsZero = m_builder.CreateICmpEQ(oldValue, Constant::get(0), "oldValueIsZero"); auto newValueIsZero = m_builder.CreateICmpEQ(_newValue, Constant::get(0), "newValueIsZero"); auto oldValueIsntZero = m_builder.CreateICmpNE(oldValue, Constant::get(0), "oldValueIsntZero"); auto newValueIsntZero = m_builder.CreateICmpNE(_newValue, Constant::get(0), "newValueIsntZero"); auto isAdd = m_builder.CreateAnd(oldValueIsZero, newValueIsntZero, "isAdd"); auto isDel = m_builder.CreateAnd(oldValueIsntZero, newValueIsZero, "isDel"); auto cost = m_builder.CreateSelect(isAdd, Constant::get(2 * sstoreCost), Constant::get(sstoreCost), "cost"); cost = m_builder.CreateSelect(isDel, Constant::get(0), cost, "cost"); m_builder.CreateCall(m_gasCheckFunc, cost); } void GasMeter::giveBack(llvm::Value* _gas) { llvm::Value* gasCounter = m_builder.CreateLoad(m_gas, "gas"); gasCounter = m_builder.CreateAdd(gasCounter, _gas); m_builder.CreateStore(gasCounter, m_gas); } void GasMeter::commitCostBlock(llvm::Value* _additionalCost) { assert(!_additionalCost || m_checkCall); // _additionalCost => m_checkCall; Must be inside cost-block // If any uncommited block if (m_checkCall) { if (m_blockCost == 0 && !_additionalCost) // Do not check 0 { m_checkCall->eraseFromParent(); // Remove the gas check call return; } llvm::Value* cost = Constant::get(m_blockCost); if (_additionalCost) cost = m_builder.CreateAdd(cost, _additionalCost); m_checkCall->setArgOperand(0, cost); // Update block cost in gas check call m_checkCall = nullptr; // End cost-block m_blockCost = 0; } assert(m_blockCost == 0); } void GasMeter::checkMemory(llvm::Value* _additionalMemoryInWords, llvm::IRBuilder<>& _builder) { // Memory uses other builder, but that can be changes later auto cost = _builder.CreateMul(_additionalMemoryInWords, Constant::get(static_cast<uint64_t>(FeeStructure::c_memoryGas)), "memcost"); _builder.CreateCall(m_gasCheckFunc, cost); } llvm::Value* GasMeter::getGas() { return m_builder.CreateLoad(m_gas, "gas"); } } } } <commit_msg>Fix GasMeter not nulling cost call<commit_after> #include "GasMeter.h" #include <llvm/IR/GlobalVariable.h> #include <llvm/IR/Function.h> #include <llvm/IR/IntrinsicInst.h> #include <libevmface/Instruction.h> #include <libevm/FeeStructure.h> #include "Type.h" #include "Ext.h" namespace dev { namespace eth { namespace jit { namespace // Helper functions { uint64_t getStepCost(Instruction inst) // TODO: Add this function to FeeSructure (pull request submitted) { switch (inst) { case Instruction::STOP: case Instruction::SUICIDE: return 0; case Instruction::SSTORE: return static_cast<uint64_t>(FeeStructure::c_sstoreGas); case Instruction::SLOAD: return static_cast<uint64_t>(FeeStructure::c_sloadGas); case Instruction::SHA3: return static_cast<uint64_t>(FeeStructure::c_sha3Gas); case Instruction::BALANCE: return static_cast<uint64_t>(FeeStructure::c_sha3Gas); case Instruction::CALL: case Instruction::CALLCODE: return static_cast<uint64_t>(FeeStructure::c_callGas); case Instruction::CREATE: return static_cast<uint64_t>(FeeStructure::c_createGas); default: // Assumes instruction code is valid return static_cast<uint64_t>(FeeStructure::c_stepGas); } } bool isCostBlockEnd(Instruction _inst) { // Basic block terminators like STOP are not needed on the list // as cost will be commited at the end of basic block // CALL & CALLCODE are commited manually switch (_inst) { case Instruction::CALLDATACOPY: case Instruction::CODECOPY: case Instruction::MLOAD: case Instruction::MSTORE: case Instruction::MSTORE8: case Instruction::SSTORE: case Instruction::GAS: case Instruction::CREATE: return true; default: return false; } } } GasMeter::GasMeter(llvm::IRBuilder<>& _builder) : CompilerHelper(_builder) { auto module = getModule(); m_gas = new llvm::GlobalVariable(*module, Type::i256, false, llvm::GlobalVariable::ExternalLinkage, nullptr, "gas"); m_gas->setUnnamedAddr(true); // Address is not important m_gasCheckFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, Type::i256, false), llvm::Function::PrivateLinkage, "gas.check", module); InsertPointGuard guard(m_builder); auto checkBB = llvm::BasicBlock::Create(_builder.getContext(), "Check", m_gasCheckFunc); auto outOfGasBB = llvm::BasicBlock::Create(_builder.getContext(), "OutOfGas", m_gasCheckFunc); auto updateBB = llvm::BasicBlock::Create(_builder.getContext(), "Update", m_gasCheckFunc); m_builder.SetInsertPoint(checkBB); llvm::Value* cost = m_gasCheckFunc->arg_begin(); cost->setName("cost"); llvm::Value* gas = m_builder.CreateLoad(m_gas, "gas"); auto isOutOfGas = m_builder.CreateICmpUGT(cost, gas, "isOutOfGas"); m_builder.CreateCondBr(isOutOfGas, outOfGasBB, updateBB); m_builder.SetInsertPoint(outOfGasBB); //auto longjmpFunc = llvm::Intrinsic::getDeclaration(_module, llvm::Intrinsic::eh_sjlj_longjmp); auto extJmpBuf = new llvm::GlobalVariable(*module, Type::BytePtr, false, llvm::GlobalVariable::ExternalLinkage, nullptr, "rt_jmpBuf"); llvm::Type* args[] = {Type::BytePtr, m_builder.getInt32Ty()}; auto longjmpNative = llvm::Function::Create(llvm::FunctionType::get(Type::Void, args, false), llvm::Function::ExternalLinkage, "longjmp", module); m_builder.CreateCall2(longjmpNative, m_builder.CreateLoad(extJmpBuf), Constant::get(ReturnCode::OutOfGas)); m_builder.CreateUnreachable(); m_builder.SetInsertPoint(updateBB); gas = m_builder.CreateSub(gas, cost); m_builder.CreateStore(gas, m_gas); m_builder.CreateRetVoid(); } void GasMeter::count(Instruction _inst) { if (!m_checkCall) { // Create gas check call with mocked block cost at begining of current cost-block m_checkCall = m_builder.CreateCall(m_gasCheckFunc, llvm::UndefValue::get(Type::i256)); } if (_inst != Instruction::SSTORE) // Handle cost of SSTORE separately in countSStore() m_blockCost += getStepCost(_inst); if (isCostBlockEnd(_inst)) commitCostBlock(); } void GasMeter::countSStore(Ext& _ext, llvm::Value* _index, llvm::Value* _newValue) { assert(!m_checkCall); // Everything should've been commited before static const auto sstoreCost = static_cast<uint64_t>(FeeStructure::c_sstoreGas); // [ADD] if oldValue == 0 and newValue != 0 => 2*cost // [DEL] if oldValue != 0 and newValue == 0 => 0 auto oldValue = _ext.store(_index); auto oldValueIsZero = m_builder.CreateICmpEQ(oldValue, Constant::get(0), "oldValueIsZero"); auto newValueIsZero = m_builder.CreateICmpEQ(_newValue, Constant::get(0), "newValueIsZero"); auto oldValueIsntZero = m_builder.CreateICmpNE(oldValue, Constant::get(0), "oldValueIsntZero"); auto newValueIsntZero = m_builder.CreateICmpNE(_newValue, Constant::get(0), "newValueIsntZero"); auto isAdd = m_builder.CreateAnd(oldValueIsZero, newValueIsntZero, "isAdd"); auto isDel = m_builder.CreateAnd(oldValueIsntZero, newValueIsZero, "isDel"); auto cost = m_builder.CreateSelect(isAdd, Constant::get(2 * sstoreCost), Constant::get(sstoreCost), "cost"); cost = m_builder.CreateSelect(isDel, Constant::get(0), cost, "cost"); m_builder.CreateCall(m_gasCheckFunc, cost); } void GasMeter::giveBack(llvm::Value* _gas) { llvm::Value* gasCounter = m_builder.CreateLoad(m_gas, "gas"); gasCounter = m_builder.CreateAdd(gasCounter, _gas); m_builder.CreateStore(gasCounter, m_gas); } void GasMeter::commitCostBlock(llvm::Value* _additionalCost) { assert(!_additionalCost || m_checkCall); // _additionalCost => m_checkCall; Must be inside cost-block // If any uncommited block if (m_checkCall) { if (m_blockCost == 0 && !_additionalCost) // Do not check 0 { m_checkCall->eraseFromParent(); // Remove the gas check call m_checkCall = nullptr; return; } llvm::Value* cost = Constant::get(m_blockCost); if (_additionalCost) cost = m_builder.CreateAdd(cost, _additionalCost); m_checkCall->setArgOperand(0, cost); // Update block cost in gas check call m_checkCall = nullptr; // End cost-block m_blockCost = 0; } assert(m_blockCost == 0); } void GasMeter::checkMemory(llvm::Value* _additionalMemoryInWords, llvm::IRBuilder<>& _builder) { // Memory uses other builder, but that can be changes later auto cost = _builder.CreateMul(_additionalMemoryInWords, Constant::get(static_cast<uint64_t>(FeeStructure::c_memoryGas)), "memcost"); _builder.CreateCall(m_gasCheckFunc, cost); } llvm::Value* GasMeter::getGas() { return m_builder.CreateLoad(m_gas, "gas"); } } } } <|endoftext|>
<commit_before>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Serge Bazanski <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "quadtree.h" #include "gtest/gtest.h" #include "nextpnr.h" USING_NEXTPNR_NAMESPACE using QT = QuadTree<int, int>; class QuadTreeTest : public ::testing::Test { protected: virtual void SetUp() { qt_ = new QT(QT::BoundingBox(0, 0, width_, height_)); } virtual void TearDown() { delete qt_; } int width_ = 100; int height_ = 100; QT *qt_; }; // Test that we're doing bound checking correctly. TEST_F(QuadTreeTest, insert_bound_checking) { ASSERT_TRUE(qt_->insert(QT::BoundingBox(10, 10, 20, 20), 10)); ASSERT_TRUE(qt_->insert(QT::BoundingBox(0, 0, 100, 100), 10)); ASSERT_FALSE(qt_->insert(QT::BoundingBox(10, 10, 101, 20), 10)); ASSERT_FALSE(qt_->insert(QT::BoundingBox(-1, 10, 101, 20), 10)); ASSERT_FALSE(qt_->insert(QT::BoundingBox(-1, -1, 20, 20), 10)); } // Test whether we are not losing any elements. TEST_F(QuadTreeTest, insert_count) { auto rng = NEXTPNR_NAMESPACE::DeterministicRNG(); // Add 10000 random rectangles. for (unsigned int i = 0; i < 10000; i++) { int x0 = rng.rng(width_); int y0 = rng.rng(height_); int w = rng.rng(width_ - x0); int h = rng.rng(width_ - y0); int x1 = x0 + w; int y1 = y0 + h; ASSERT_TRUE(qt_->insert(QT::BoundingBox(x0, y0, x1, y1), i)); ASSERT_EQ(qt_->size(), i + 1); } // Add 100000 random points. for (unsigned int i = 0; i < 100000; i++) { int x0 = rng.rng(width_); int y0 = rng.rng(height_); int x1 = x0; int y1 = y0; ASSERT_TRUE(qt_->insert(QT::BoundingBox(x0, y0, x1, y1), i)); ASSERT_EQ(qt_->size(), i + 10001); } } // Test that we can insert and retrieve the same element. TEST_F(QuadTreeTest, insert_retrieve_same) { auto rng = NEXTPNR_NAMESPACE::DeterministicRNG(); // Add 10000 small random rectangles. rng.rngseed(0); for (int i = 0; i < 10000; i++) { int x0 = rng.rng(width_); int y0 = rng.rng(height_); int w = rng.rng(width_ - x0); int h = rng.rng(width_ - y0); int x1 = x0 + w / 4; int y1 = y0 + h / 4; ASSERT_TRUE(qt_->insert(QT::BoundingBox(x0, y0, x1, y1), i)); } // Restart RNG, make sure we get the same rectangles back. rng.rngseed(0); for (int i = 0; i < 10000; i++) { int x0 = rng.rng(width_); int y0 = rng.rng(height_); int w = rng.rng(width_ - x0); int h = rng.rng(width_ - y0); int x1 = x0 + w / 4; int y1 = y0 + h / 4; // try to find something in the middle of the square int x = (x1 - x0) / 2 + x0; int y = (y1 - y0) / 2 + y0; auto res = qt_->get(x, y); // Somewhat arbirary test to make sure we don't return obscene // amounts of data. ASSERT_LT(res.size(), 200UL); bool found = false; for (auto elem : res) { // Is this what we're looking for? if (elem == i) { found = true; break; } } ASSERT_TRUE(found); } } <commit_msg>gui: fix quadtree test<commit_after>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Serge Bazanski <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "gtest/gtest.h" #include "nextpnr.h" #include "quadtree.h" USING_NEXTPNR_NAMESPACE using QT = QuadTree<int, int>; class QuadTreeTest : public ::testing::Test { protected: virtual void SetUp() { qt_ = new QT(QT::BoundingBox(0, 0, width_, height_)); } virtual void TearDown() { delete qt_; } int width_ = 100; int height_ = 100; QT *qt_; }; // Test that we're doing bound checking correctly. TEST_F(QuadTreeTest, insert_bound_checking) { ASSERT_TRUE(qt_->insert(QT::BoundingBox(10, 10, 20, 20), 10)); ASSERT_TRUE(qt_->insert(QT::BoundingBox(0, 0, 100, 100), 10)); ASSERT_FALSE(qt_->insert(QT::BoundingBox(10, 10, 101, 20), 10)); ASSERT_FALSE(qt_->insert(QT::BoundingBox(-1, 10, 101, 20), 10)); ASSERT_FALSE(qt_->insert(QT::BoundingBox(-1, -1, 20, 20), 10)); } // Test whether we are not losing any elements. TEST_F(QuadTreeTest, insert_count) { auto rng = NEXTPNR_NAMESPACE::DeterministicRNG(); // Add 10000 random rectangles. for (unsigned int i = 0; i < 10000; i++) { int x0 = rng.rng(width_); int y0 = rng.rng(height_); int w = rng.rng(width_ - x0); int h = rng.rng(width_ - y0); int x1 = x0 + w; int y1 = y0 + h; ASSERT_TRUE(qt_->insert(QT::BoundingBox(x0, y0, x1, y1), i)); ASSERT_EQ(qt_->size(), i + 1); } // Add 100000 random points. for (unsigned int i = 0; i < 100000; i++) { int x0 = rng.rng(width_); int y0 = rng.rng(height_); int x1 = x0; int y1 = y0; ASSERT_TRUE(qt_->insert(QT::BoundingBox(x0, y0, x1, y1), i)); ASSERT_EQ(qt_->size(), i + 10001); } } // Test that we can insert and retrieve the same element. TEST_F(QuadTreeTest, insert_retrieve_same) { auto rng = NEXTPNR_NAMESPACE::DeterministicRNG(); // Add 10000 small random rectangles. rng.rngseed(0); for (int i = 0; i < 10000; i++) { int x0 = rng.rng(width_); int y0 = rng.rng(height_); int w = rng.rng(width_ - x0); int h = rng.rng(width_ - y0); int x1 = x0 + w / 4; int y1 = y0 + h / 4; ASSERT_TRUE(qt_->insert(QT::BoundingBox(x0, y0, x1, y1), i)); } // Restart RNG, make sure we get the same rectangles back. rng.rngseed(0); for (int i = 0; i < 10000; i++) { int x0 = rng.rng(width_); int y0 = rng.rng(height_); int w = rng.rng(width_ - x0); int h = rng.rng(width_ - y0); int x1 = x0 + w / 4; int y1 = y0 + h / 4; // try to find something in the middle of the square int x = (x1 - x0) / 2 + x0; int y = (y1 - y0) / 2 + y0; auto res = qt_->get(x, y); // Somewhat arbirary test to make sure we don't return obscene // amounts of data. ASSERT_LT(res.size(), 200UL); bool found = false; for (auto elem : res) { // Is this what we're looking for? if (elem == i) { found = true; break; } } ASSERT_TRUE(found); } } <|endoftext|>
<commit_before>#include <Game.h> Game::Game(const std::string& _name) { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Initialization" INFO("Initializing new Game: %s", _name.c_str()); config.name = _name; readConfig(); INFO("Creating %dx%d render target", renderWidth, renderHeight); screen.create(renderWidth, renderHeight); createWindow(config.fullscreen); INFO("Creating gameplay entities"); spritesMutex.lock(); player = new GamePlayer; player->setPosition(renderWidth * 1 / 2, renderHeight * 3 / 4); sprites.push_back(player); spritesMutex.unlock(); INFO("Created player"); isReady = true; INFO("Initialization Complete"); } Game& Game::getGame(const std::string& _name) { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Initialization" static Game* instance = new Game(_name); INFO("Getting Game instance"); return *instance; } bool Game::ready() { return isReady; } void Game::run() { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Event Loop" releaseWindow(); sf::Thread renderThread(&Game::renderLoop, this); renderThread.launch(); INFO("Initializing eventLoop"); sf::Clock gameClock; sf::Time elapsedTime; sf::Int32 lastUpdateTime; sf::Int32 totalUpdateTime = 0; sf::Int32 averageUpdateTime; sf::Int32 updateCount = 0; INFO("Starting eventLoop"); while (window.isOpen()) { elapsedTime = gameClock.restart(); processEvents(); updateControls(); updateWorld(elapsedTime); lastUpdateTime = gameClock.getElapsedTime().asMilliseconds(); totalUpdateTime += lastUpdateTime; averageUpdateTime = totalUpdateTime / ++updateCount; // log the average time per update every seconds if (updateCount % (60 * 1) == 0) { DBUG("Average update time: %d ms", averageUpdateTime); } // update at approximately 60 Hz sf::sleep(sf::milliseconds(16)); } INFO("Stopped eventLoop"); } void inline Game::lockWindow(bool log) { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Window Control" if (log) DBUG("Grabbing window lock"); windowMutex.lock(); window.setActive(true); } void inline Game::releaseWindow(bool log) { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Window Control" if (log) DBUG("Releasing window lock"); window.setActive(false); windowMutex.unlock(); } void Game::readConfig() { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Configuration" std::__cxx11::string iniFilename = config.name; iniFilename.append(".ini"); INIReader reader(iniFilename); INFO("Reading config from '%s'", iniFilename.c_str()); if (reader.ParseError() < 0) { ERR("Can't load '%s', using defaults", iniFilename.c_str()); } else { // 1200x675 is a 16:9 window that fits inside a 1366x768 screen on most systems config.width = (unsigned int) std::abs(reader.GetInteger("game", "width", (long) config.width)); config.height = (unsigned int) std::abs(reader.GetInteger("game", "height", (long) config.height)); config.fullscreen = reader.GetBoolean("game", "fullscreen", config.fullscreen); config.useDesktopSize = reader.GetBoolean("game", "useDesktopSize", config.useDesktopSize); config.vsync = reader.GetBoolean("game", "vsync", config.useDesktopSize); config.deadZone = static_cast<float>(reader.GetReal("game", "deadZone", config.deadZone)); config.keySpeed = static_cast<float>(reader.GetReal("game", "keySpeed", config.keySpeed)); } INFO("Current settings:"); INFO("\twidth = %d", config.width); INFO("\theight = %d", config.height); INFO("\tfullscreen = %s", (config.fullscreen ? "true" : "false")); INFO("\tuseDesktopSize = %s", (config.useDesktopSize ? "true" : "false")); INFO("\tvsync = %s", (config.vsync ? "true" : "false")); INFO("\tdeadZone = %f", config.deadZone); INFO("\tkeySpeed = %f", config.keySpeed); } void Game::createWindow(bool shouldFullscreen) { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Window Creation" unsigned int flags = 0; lockWindow(); INFO("Reading config"); sf::VideoMode mode; config.fullscreen = shouldFullscreen; if (config.fullscreen) { INFO("Going fullscreen"); window.setMouseCursorVisible(false); if (config.useDesktopSize) { INFO("Setting fullscreen mode (using desktop size): %dx%d", sf::VideoMode::getDesktopMode().width, sf::VideoMode::getDesktopMode().height); mode = sf::VideoMode::getDesktopMode(); } else { INFO("Setting fullscreen mode: %dx%d", config.width, config.height); mode = sf::VideoMode(config.width, config.height); } flags = sf::Style::Fullscreen; } else { INFO("Setting windowed mode: %dx%d", config.width, config.height); window.setMouseCursorVisible(true); mode = sf::VideoMode(config.width, config.height); flags = sf::Style::Titlebar | sf::Style::Close | sf::Style::Resize; } INFO("Creating the main window"); window.create(mode, config.name, flags); if (!window.isOpen()) { ERR("Could not create main window"); exit(EXIT_FAILURE); } sf::ContextSettings settings = window.getSettings(); INFO("Using OpenGL %d.%d", settings.majorVersion, settings.minorVersion); // initialize the view INFO("Setting window view"); view = window.getDefaultView(); view.setSize(renderWidth, renderHeight); view.setCenter(renderWidth / 2, renderHeight / 2); window.setView(view); if (config.vsync) { INFO("Enabling V-sync"); window.setVerticalSyncEnabled(true); } releaseWindow(); // scale the viewport to maintain good aspect adjustAspect(window.getSize()); } void Game::adjustAspect(sf::Event::SizeEvent newSize) { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Aspect Adjustment" // save the new window size since this came from a resize event // not from a window creation event (initialization or fullscreen toggle) config.width = newSize.width; config.height = newSize.height; INFO("Window resized to: %dx%d", config.width, config.height); // do the calculation adjustAspect(sf::Vector2u(newSize.width, newSize.height)); } void Game::adjustAspect(sf::Vector2u newSize) { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Aspect Adjustment" INFO("Adjusting aspect for window size ", newSize.x, newSize.y); // compute the current aspect float currentRatio = (float) newSize.x / (float) newSize.y; // used to offset and scale the viewport to maintain 16:9 aspect float widthScale = 1.0f; float widthOffset = 0.0f; float heightScale = 1.0f; float heightOffset = 0.0f; // used to compare and compute aspect ratios // for logging std::string isSixteenNine = "16:9"; if (currentRatio > 16.0f / 9.0f) { // we are wider isSixteenNine = "wide"; widthScale = newSize.y * (16.0f / 9.0f) / newSize.x; widthOffset = (1.0f - widthScale) / 2.0f; } else if (currentRatio < 16.0f / 9.0f) { // we are narrower isSixteenNine = "narrow"; heightScale = newSize.x * (9.0f / 16.0f) / newSize.y; heightOffset = (1.0f - heightScale) / 2.0f; } lockWindow(); INFO("Setting %s viewport (wo:%f, ho:%f; ws:%f, hs: %f", isSixteenNine.c_str(), widthOffset, heightOffset, widthScale, heightScale); view.setViewport(sf::FloatRect(widthOffset, heightOffset, widthScale, heightScale)); window.setView(view); releaseWindow(); } void Game::processEvents() { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Event Processing" static sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: INFO("Window closed"); window.close(); break; case sf::Event::Resized: adjustAspect(event.size); break; case sf::Event::KeyPressed: handleKeyPress(event); break; case sf::Event::KeyReleased: handleKeyRelease(event); break; default: break; } } } void Game::handleKeyPress(const sf::Event& event) { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Event Processing" switch (event.key.code) { case sf::Keyboard::Escape: INFO("Key: Escape: exiting"); window.close(); break; case sf::Keyboard::Return: if (event.key.alt) { createWindow(!config.fullscreen); } break; default: break; } } void Game::handleKeyRelease(const sf::Event& event) { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Event Processing" switch (event.key.code) { default: break; } } void Game::updateControls() { float x, y = 0; float joy0_X = sf::Joystick::getAxisPosition(0, sf::Joystick::X); float joy0_y = sf::Joystick::getAxisPosition(0, sf::Joystick::Y); x = fabs(joy0_X) < config.deadZone ? 0 : joy0_X; y = fabs(joy0_y) < config.deadZone ? 0 : joy0_y; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) { y += -config.keySpeed; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) { x += config.keySpeed; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) { y += config.keySpeed; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) { x += -config.keySpeed; } spritesMutex.lock(); player->moveBy(x, y); spritesMutex.unlock(); } void Game::updateWorld(sf::Time elapsed) { spritesMutex.lock(); const int millis = elapsed.asMilliseconds(); for (auto sprite : sprites) { sprite->update(millis); } spritesMutex.unlock(); } void Game::renderLoop() { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Render Loop" INFO("Initializing renderLoop"); sf::Clock frameClock; sf::Int32 lastFrameTime; sf::Int32 averageFrameTime; sf::Int32 totalFrameTime = 0; sf::Int32 frameCount = 0; INFO("Starting renderLoop"); while (window.isOpen()) { frameClock.restart(); // blank the render target to black screen.clear(sf::Color::Black); // render all the normal sprites spritesMutex.lock(); for (const auto sprite : sprites) { screen.draw(*sprite); } spritesMutex.unlock(); // update the target screen.display(); lockWindow(false); // blank the window to gray window.clear(sf::Color(128, 128, 128)); // copy render target to window window.draw(sf::Sprite(screen.getTexture())); // update thw window window.display(); releaseWindow(false); lastFrameTime = frameClock.getElapsedTime().asMilliseconds(); totalFrameTime += lastFrameTime; averageFrameTime = totalFrameTime / ++frameCount; // log the time per frame every 60 frames (every second if at 60 Hz) if (frameCount % (60 * 1) == 0) { DBUG("Average frame time: %d ms", averageFrameTime); } } INFO("Stopped renderLoop"); }<commit_msg>Fix weird __cxx11 thing from IDEA's refactoring.<commit_after>#include <Game.h> Game::Game(const std::string& _name) { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Initialization" INFO("Initializing new Game: %s", _name.c_str()); config.name = _name; readConfig(); INFO("Creating %dx%d render target", renderWidth, renderHeight); screen.create(renderWidth, renderHeight); createWindow(config.fullscreen); INFO("Creating gameplay entities"); spritesMutex.lock(); player = new GamePlayer; player->setPosition(renderWidth * 1 / 2, renderHeight * 3 / 4); sprites.push_back(player); spritesMutex.unlock(); INFO("Created player"); isReady = true; INFO("Initialization Complete"); } Game& Game::getGame(const std::string& _name) { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Initialization" static Game* instance = new Game(_name); INFO("Getting Game instance"); return *instance; } bool Game::ready() { return isReady; } void Game::run() { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Event Loop" releaseWindow(); sf::Thread renderThread(&Game::renderLoop, this); renderThread.launch(); INFO("Initializing eventLoop"); sf::Clock gameClock; sf::Time elapsedTime; sf::Int32 lastUpdateTime; sf::Int32 totalUpdateTime = 0; sf::Int32 averageUpdateTime; sf::Int32 updateCount = 0; INFO("Starting eventLoop"); while (window.isOpen()) { elapsedTime = gameClock.restart(); processEvents(); updateControls(); updateWorld(elapsedTime); lastUpdateTime = gameClock.getElapsedTime().asMilliseconds(); totalUpdateTime += lastUpdateTime; averageUpdateTime = totalUpdateTime / ++updateCount; // log the average time per update every seconds if (updateCount % (60 * 1) == 0) { DBUG("Average update time: %d ms", averageUpdateTime); } // update at approximately 60 Hz sf::sleep(sf::milliseconds(16)); } INFO("Stopped eventLoop"); } void inline Game::lockWindow(bool log) { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Window Control" if (log) DBUG("Grabbing window lock"); windowMutex.lock(); window.setActive(true); } void inline Game::releaseWindow(bool log) { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Window Control" if (log) DBUG("Releasing window lock"); window.setActive(false); windowMutex.unlock(); } void Game::readConfig() { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Configuration" std::string iniFilename = config.name; iniFilename.append(".ini"); INIReader reader(iniFilename); INFO("Reading config from '%s'", iniFilename.c_str()); if (reader.ParseError() < 0) { ERR("Can't load '%s', using defaults", iniFilename.c_str()); } else { // 1200x675 is a 16:9 window that fits inside a 1366x768 screen on most systems config.width = (unsigned int) std::abs(reader.GetInteger("game", "width", (long) config.width)); config.height = (unsigned int) std::abs(reader.GetInteger("game", "height", (long) config.height)); config.fullscreen = reader.GetBoolean("game", "fullscreen", config.fullscreen); config.useDesktopSize = reader.GetBoolean("game", "useDesktopSize", config.useDesktopSize); config.vsync = reader.GetBoolean("game", "vsync", config.useDesktopSize); config.deadZone = static_cast<float>(reader.GetReal("game", "deadZone", config.deadZone)); config.keySpeed = static_cast<float>(reader.GetReal("game", "keySpeed", config.keySpeed)); } INFO("Current settings:"); INFO("\twidth = %d", config.width); INFO("\theight = %d", config.height); INFO("\tfullscreen = %s", (config.fullscreen ? "true" : "false")); INFO("\tuseDesktopSize = %s", (config.useDesktopSize ? "true" : "false")); INFO("\tvsync = %s", (config.vsync ? "true" : "false")); INFO("\tdeadZone = %f", config.deadZone); INFO("\tkeySpeed = %f", config.keySpeed); } void Game::createWindow(bool shouldFullscreen) { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Window Creation" unsigned int flags = 0; lockWindow(); INFO("Reading config"); sf::VideoMode mode; config.fullscreen = shouldFullscreen; if (config.fullscreen) { INFO("Going fullscreen"); window.setMouseCursorVisible(false); if (config.useDesktopSize) { INFO("Setting fullscreen mode (using desktop size): %dx%d", sf::VideoMode::getDesktopMode().width, sf::VideoMode::getDesktopMode().height); mode = sf::VideoMode::getDesktopMode(); } else { INFO("Setting fullscreen mode: %dx%d", config.width, config.height); mode = sf::VideoMode(config.width, config.height); } flags = sf::Style::Fullscreen; } else { INFO("Setting windowed mode: %dx%d", config.width, config.height); window.setMouseCursorVisible(true); mode = sf::VideoMode(config.width, config.height); flags = sf::Style::Titlebar | sf::Style::Close | sf::Style::Resize; } INFO("Creating the main window"); window.create(mode, config.name, flags); if (!window.isOpen()) { ERR("Could not create main window"); exit(EXIT_FAILURE); } sf::ContextSettings settings = window.getSettings(); INFO("Using OpenGL %d.%d", settings.majorVersion, settings.minorVersion); // initialize the view INFO("Setting window view"); view = window.getDefaultView(); view.setSize(renderWidth, renderHeight); view.setCenter(renderWidth / 2, renderHeight / 2); window.setView(view); if (config.vsync) { INFO("Enabling V-sync"); window.setVerticalSyncEnabled(true); } releaseWindow(); // scale the viewport to maintain good aspect adjustAspect(window.getSize()); } void Game::adjustAspect(sf::Event::SizeEvent newSize) { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Aspect Adjustment" // save the new window size since this came from a resize event // not from a window creation event (initialization or fullscreen toggle) config.width = newSize.width; config.height = newSize.height; INFO("Window resized to: %dx%d", config.width, config.height); // do the calculation adjustAspect(sf::Vector2u(newSize.width, newSize.height)); } void Game::adjustAspect(sf::Vector2u newSize) { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Aspect Adjustment" INFO("Adjusting aspect for window size ", newSize.x, newSize.y); // compute the current aspect float currentRatio = (float) newSize.x / (float) newSize.y; // used to offset and scale the viewport to maintain 16:9 aspect float widthScale = 1.0f; float widthOffset = 0.0f; float heightScale = 1.0f; float heightOffset = 0.0f; // used to compare and compute aspect ratios // for logging std::string isSixteenNine = "16:9"; if (currentRatio > 16.0f / 9.0f) { // we are wider isSixteenNine = "wide"; widthScale = newSize.y * (16.0f / 9.0f) / newSize.x; widthOffset = (1.0f - widthScale) / 2.0f; } else if (currentRatio < 16.0f / 9.0f) { // we are narrower isSixteenNine = "narrow"; heightScale = newSize.x * (9.0f / 16.0f) / newSize.y; heightOffset = (1.0f - heightScale) / 2.0f; } lockWindow(); INFO("Setting %s viewport (wo:%f, ho:%f; ws:%f, hs: %f", isSixteenNine.c_str(), widthOffset, heightOffset, widthScale, heightScale); view.setViewport(sf::FloatRect(widthOffset, heightOffset, widthScale, heightScale)); window.setView(view); releaseWindow(); } void Game::processEvents() { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Event Processing" static sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: INFO("Window closed"); window.close(); break; case sf::Event::Resized: adjustAspect(event.size); break; case sf::Event::KeyPressed: handleKeyPress(event); break; case sf::Event::KeyReleased: handleKeyRelease(event); break; default: break; } } } void Game::handleKeyPress(const sf::Event& event) { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Event Processing" switch (event.key.code) { case sf::Keyboard::Escape: INFO("Key: Escape: exiting"); window.close(); break; case sf::Keyboard::Return: if (event.key.alt) { createWindow(!config.fullscreen); } break; default: break; } } void Game::handleKeyRelease(const sf::Event& event) { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Event Processing" switch (event.key.code) { default: break; } } void Game::updateControls() { float x, y = 0; float joy0_X = sf::Joystick::getAxisPosition(0, sf::Joystick::X); float joy0_y = sf::Joystick::getAxisPosition(0, sf::Joystick::Y); x = fabs(joy0_X) < config.deadZone ? 0 : joy0_X; y = fabs(joy0_y) < config.deadZone ? 0 : joy0_y; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) { y += -config.keySpeed; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) { x += config.keySpeed; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) { y += config.keySpeed; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) { x += -config.keySpeed; } spritesMutex.lock(); player->moveBy(x, y); spritesMutex.unlock(); } void Game::updateWorld(sf::Time elapsed) { spritesMutex.lock(); const int millis = elapsed.asMilliseconds(); for (auto sprite : sprites) { sprite->update(millis); } spritesMutex.unlock(); } void Game::renderLoop() { #undef LOGOG_CATEGORY #define LOGOG_CATEGORY "Render Loop" INFO("Initializing renderLoop"); sf::Clock frameClock; sf::Int32 lastFrameTime; sf::Int32 averageFrameTime; sf::Int32 totalFrameTime = 0; sf::Int32 frameCount = 0; INFO("Starting renderLoop"); while (window.isOpen()) { frameClock.restart(); // blank the render target to black screen.clear(sf::Color::Black); // render all the normal sprites spritesMutex.lock(); for (const auto sprite : sprites) { screen.draw(*sprite); } spritesMutex.unlock(); // update the target screen.display(); lockWindow(false); // blank the window to gray window.clear(sf::Color(128, 128, 128)); // copy render target to window window.draw(sf::Sprite(screen.getTexture())); // update thw window window.display(); releaseWindow(false); lastFrameTime = frameClock.getElapsedTime().asMilliseconds(); totalFrameTime += lastFrameTime; averageFrameTime = totalFrameTime / ++frameCount; // log the time per frame every 60 frames (every second if at 60 Hz) if (frameCount % (60 * 1) == 0) { DBUG("Average frame time: %d ms", averageFrameTime); } } INFO("Stopped renderLoop"); }<|endoftext|>
<commit_before>/* Copyright (c) 2013 Daniele Bartolini, Michele Rossi Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Compiler.h" #include "Filesystem.h" #include "DiskFileSource.h" #include "ResourceFormat.h" #include "File.h" namespace crown { //----------------------------------------------------------------------------- bool Compiler::compile(const char* root_path, const char* dest_path, const char* name_in, const char* name_out) { DiskFileSource root_disk(root_path); DiskFileSource dest_disk(dest_path); Filesystem root_fs(root_disk); Filesystem dest_fs(dest_disk); // The compilation fails when returned size is zero size_t resource_size = 0; if ((resource_size = compile_impl(root_fs, name_in)) == 0) { Log::e("Compilation failed"); return false; } // Setup resource header ResourceHeader resource_header; resource_header.magic = RESOURCE_MAGIC_NUMBER; resource_header.version = RESOURCE_VERSION; resource_header.size = resource_size; // Open destination file and write the header File* out_file = dest_fs.open(name_out, FOM_WRITE); if (out_file) { // Write header out_file->write((char*)&resource_header, sizeof(ResourceHeader)); // Write resource-specific data write_impl(out_file); dest_fs.close(out_file); cleanup(); return true; } Log::e("Unable to write compiled file."); return false; } //----------------------------------------------------------------------------- void Compiler::cleanup() { } } // namespace crown <commit_msg>Fix Compiler building<commit_after>/* Copyright (c) 2013 Daniele Bartolini, Michele Rossi Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Compiler.h" #include "Filesystem.h" #include "DiskFilesystem.h" #include "ResourceFormat.h" #include "File.h" namespace crown { //----------------------------------------------------------------------------- bool Compiler::compile(const char* root_path, const char* dest_path, const char* name_in, const char* name_out) { DiskFilesystem root_fs(root_path); DiskFilesystem dest_fs(dest_path); // The compilation fails when returned size is zero size_t resource_size = 0; if ((resource_size = compile_impl(root_fs, name_in)) == 0) { Log::e("Compilation failed"); return false; } // Setup resource header ResourceHeader resource_header; resource_header.magic = RESOURCE_MAGIC_NUMBER; resource_header.version = RESOURCE_VERSION; resource_header.size = resource_size; // Open destination file and write the header File* out_file = dest_fs.open(name_out, FOM_WRITE); if (out_file) { // Write header out_file->write((char*)&resource_header, sizeof(ResourceHeader)); // Write resource-specific data write_impl(out_file); dest_fs.close(out_file); cleanup(); return true; } Log::e("Unable to write compiled file."); return false; } //----------------------------------------------------------------------------- void Compiler::cleanup() { } } // namespace crown <|endoftext|>
<commit_before>/* * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. * */ #ifdef RTC_ENABLE_VP9 #include "modules/video_coding/codecs/vp9/vp9_frame_buffer_pool.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/ref_counted_object.h" #include "vpx/vpx_codec.h" #include "vpx/vpx_decoder.h" #include "vpx/vpx_frame_buffer.h" namespace webrtc { uint8_t* Vp9FrameBufferPool::Vp9FrameBuffer::GetData() { return data_.data<uint8_t>(); } size_t Vp9FrameBufferPool::Vp9FrameBuffer::GetDataSize() const { return data_.size(); } void Vp9FrameBufferPool::Vp9FrameBuffer::SetSize(size_t size) { data_.SetSize(size); } bool Vp9FrameBufferPool::InitializeVpxUsePool( vpx_codec_ctx* vpx_codec_context) { RTC_DCHECK(vpx_codec_context); // Tell libvpx to use this pool. if (vpx_codec_set_frame_buffer_functions( // In which context to use these callback functions. vpx_codec_context, // Called by libvpx when it needs another frame buffer. &Vp9FrameBufferPool::VpxGetFrameBuffer, // Called by libvpx when it no longer uses a frame buffer. &Vp9FrameBufferPool::VpxReleaseFrameBuffer, // |this| will be passed as |user_priv| to VpxGetFrameBuffer. this)) { // Failed to configure libvpx to use Vp9FrameBufferPool. return false; } return true; } rtc::scoped_refptr<Vp9FrameBufferPool::Vp9FrameBuffer> Vp9FrameBufferPool::GetFrameBuffer(size_t min_size) { RTC_DCHECK_GT(min_size, 0); rtc::scoped_refptr<Vp9FrameBuffer> available_buffer = nullptr; { rtc::CritScope cs(&buffers_lock_); // Do we have a buffer we can recycle? for (const auto& buffer : allocated_buffers_) { if (buffer->HasOneRef()) { available_buffer = buffer; break; } } // Otherwise create one. if (available_buffer == nullptr) { available_buffer = new rtc::RefCountedObject<Vp9FrameBuffer>(); allocated_buffers_.push_back(available_buffer); if (allocated_buffers_.size() > max_num_buffers_) { RTC_LOG(LS_WARNING) << allocated_buffers_.size() << " Vp9FrameBuffers have been " << "allocated by a Vp9FrameBufferPool (exceeding what is " << "considered reasonable, " << max_num_buffers_ << ")."; // TODO(phoglund): this limit is being hit in tests since Oct 5 2016. // See https://bugs.chromium.org/p/webrtc/issues/detail?id=6484. // RTC_NOTREACHED(); } } } available_buffer->SetSize(min_size); return available_buffer; } int Vp9FrameBufferPool::GetNumBuffersInUse() const { int num_buffers_in_use = 0; rtc::CritScope cs(&buffers_lock_); for (const auto& buffer : allocated_buffers_) { if (!buffer->HasOneRef()) ++num_buffers_in_use; } return num_buffers_in_use; } void Vp9FrameBufferPool::ClearPool() { rtc::CritScope cs(&buffers_lock_); allocated_buffers_.clear(); } // static int32_t Vp9FrameBufferPool::VpxGetFrameBuffer(void* user_priv, size_t min_size, vpx_codec_frame_buffer* fb) { RTC_DCHECK(user_priv); RTC_DCHECK(fb); Vp9FrameBufferPool* pool = static_cast<Vp9FrameBufferPool*>(user_priv); rtc::scoped_refptr<Vp9FrameBuffer> buffer = pool->GetFrameBuffer(min_size); fb->data = buffer->GetData(); fb->size = buffer->GetDataSize(); // Store Vp9FrameBuffer* in |priv| for use in VpxReleaseFrameBuffer. // This also makes vpx_codec_get_frame return images with their |fb_priv| set // to |buffer| which is important for external reference counting. // Release from refptr so that the buffer's |ref_count_| remains 1 when // |buffer| goes out of scope. fb->priv = static_cast<void*>(buffer.release()); return 0; } // static int32_t Vp9FrameBufferPool::VpxReleaseFrameBuffer(void* user_priv, vpx_codec_frame_buffer* fb) { RTC_DCHECK(user_priv); RTC_DCHECK(fb); Vp9FrameBuffer* buffer = static_cast<Vp9FrameBuffer*>(fb->priv); if (buffer != nullptr) { buffer->Release(); // When libvpx fails to decode and you continue to try to decode (and fail) // libvpx can for some reason try to release the same buffer multiple times. // Setting |priv| to null protects against trying to Release multiple times. fb->priv = nullptr; } return 0; } } // namespace webrtc #endif // RTC_ENABLE_VP9 <commit_msg>Cap vp9 fuzzer frame size to prevent OOM<commit_after>/* * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. * */ #ifdef RTC_ENABLE_VP9 #include "modules/video_coding/codecs/vp9/vp9_frame_buffer_pool.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/ref_counted_object.h" #include "vpx/vpx_codec.h" #include "vpx/vpx_decoder.h" #include "vpx/vpx_frame_buffer.h" namespace webrtc { uint8_t* Vp9FrameBufferPool::Vp9FrameBuffer::GetData() { return data_.data<uint8_t>(); } size_t Vp9FrameBufferPool::Vp9FrameBuffer::GetDataSize() const { return data_.size(); } void Vp9FrameBufferPool::Vp9FrameBuffer::SetSize(size_t size) { data_.SetSize(size); } bool Vp9FrameBufferPool::InitializeVpxUsePool( vpx_codec_ctx* vpx_codec_context) { RTC_DCHECK(vpx_codec_context); // Tell libvpx to use this pool. if (vpx_codec_set_frame_buffer_functions( // In which context to use these callback functions. vpx_codec_context, // Called by libvpx when it needs another frame buffer. &Vp9FrameBufferPool::VpxGetFrameBuffer, // Called by libvpx when it no longer uses a frame buffer. &Vp9FrameBufferPool::VpxReleaseFrameBuffer, // |this| will be passed as |user_priv| to VpxGetFrameBuffer. this)) { // Failed to configure libvpx to use Vp9FrameBufferPool. return false; } return true; } rtc::scoped_refptr<Vp9FrameBufferPool::Vp9FrameBuffer> Vp9FrameBufferPool::GetFrameBuffer(size_t min_size) { RTC_DCHECK_GT(min_size, 0); rtc::scoped_refptr<Vp9FrameBuffer> available_buffer = nullptr; { rtc::CritScope cs(&buffers_lock_); // Do we have a buffer we can recycle? for (const auto& buffer : allocated_buffers_) { if (buffer->HasOneRef()) { available_buffer = buffer; break; } } // Otherwise create one. if (available_buffer == nullptr) { available_buffer = new rtc::RefCountedObject<Vp9FrameBuffer>(); allocated_buffers_.push_back(available_buffer); if (allocated_buffers_.size() > max_num_buffers_) { RTC_LOG(LS_WARNING) << allocated_buffers_.size() << " Vp9FrameBuffers have been " << "allocated by a Vp9FrameBufferPool (exceeding what is " << "considered reasonable, " << max_num_buffers_ << ")."; // TODO(phoglund): this limit is being hit in tests since Oct 5 2016. // See https://bugs.chromium.org/p/webrtc/issues/detail?id=6484. // RTC_NOTREACHED(); } } } available_buffer->SetSize(min_size); return available_buffer; } int Vp9FrameBufferPool::GetNumBuffersInUse() const { int num_buffers_in_use = 0; rtc::CritScope cs(&buffers_lock_); for (const auto& buffer : allocated_buffers_) { if (!buffer->HasOneRef()) ++num_buffers_in_use; } return num_buffers_in_use; } void Vp9FrameBufferPool::ClearPool() { rtc::CritScope cs(&buffers_lock_); allocated_buffers_.clear(); } // static int32_t Vp9FrameBufferPool::VpxGetFrameBuffer(void* user_priv, size_t min_size, vpx_codec_frame_buffer* fb) { RTC_DCHECK(user_priv); RTC_DCHECK(fb); #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION // Limit size of 8k YUV highdef frame size_t size_limit = 7680 * 4320 * 3 / 2 * 2; if (min_size > size_limit) return -1; #endif Vp9FrameBufferPool* pool = static_cast<Vp9FrameBufferPool*>(user_priv); rtc::scoped_refptr<Vp9FrameBuffer> buffer = pool->GetFrameBuffer(min_size); fb->data = buffer->GetData(); fb->size = buffer->GetDataSize(); // Store Vp9FrameBuffer* in |priv| for use in VpxReleaseFrameBuffer. // This also makes vpx_codec_get_frame return images with their |fb_priv| set // to |buffer| which is important for external reference counting. // Release from refptr so that the buffer's |ref_count_| remains 1 when // |buffer| goes out of scope. fb->priv = static_cast<void*>(buffer.release()); return 0; } // static int32_t Vp9FrameBufferPool::VpxReleaseFrameBuffer(void* user_priv, vpx_codec_frame_buffer* fb) { RTC_DCHECK(user_priv); RTC_DCHECK(fb); Vp9FrameBuffer* buffer = static_cast<Vp9FrameBuffer*>(fb->priv); if (buffer != nullptr) { buffer->Release(); // When libvpx fails to decode and you continue to try to decode (and fail) // libvpx can for some reason try to release the same buffer multiple times. // Setting |priv| to null protects against trying to Release multiple times. fb->priv = nullptr; } return 0; } } // namespace webrtc #endif // RTC_ENABLE_VP9 <|endoftext|>
<commit_before>#include "PenaltyCircuitPotential.h" #include "MooseMesh.h" template<> InputParameters validParams<PenaltyCircuitPotential>() { InputParameters p = validParams<NonlocalIntegratedBC>(); p.addRequiredParam<UserObjectName>("current", "The postprocessor response for calculating the current passing through the needle surface."); p.addRequiredParam<Real>("surface_potential", "The electrical potential applied to the surface if no current was flowing in the circuit."); p.addRequiredParam<std::string>("surface", "Whether you are specifying the potential on the anode or the cathode with the requirement that the other metal surface be grounded."); p.addRequiredParam<Real>("penalty", "The constant multiplying the penalty term."); p.addRequiredParam<UserObjectName>("data_provider", "The name of the UserObject that can provide some data to materials, bcs, etc."); p.addRequiredCoupledVar("em", "The electron variable."); p.addRequiredCoupledVar("ip", "The ion variable."); p.addRequiredCoupledVar("mean_en", "The ion variable."); p.addParam<Real>("area", "Must be provided when the number of dimensions equals 1."); p.addRequiredParam<std::string>("potential_units", "The potential units."); p.addRequiredParam<Real>("position_units", "Units of position."); p.addRequiredParam<Real>("resistance", "The ballast resistance in Ohms."); return p; } PenaltyCircuitPotential::PenaltyCircuitPotential(const InputParameters & parameters) : NonlocalIntegratedBC(parameters), _current_uo(getUserObject<CurrentDensityShapeSideUserObject>("current")), _current(_current_uo.getIntegral()), _current_jac(_current_uo.getJacobian()), _surface_potential(getParam<Real>("surface_potential")), _surface(getParam<std::string>("surface")), _p(getParam<Real>("penalty")), _data(getUserObject<ProvideMobility>("data_provider")), _var_dofs(_var.dofIndices()), _em_id(coupled("em")), _em_dofs(getVar("em", 0)->dofIndices()), _ip_id(coupled("ip")), _ip_dofs(getVar("ip", 0)->dofIndices()), _mean_en_id(coupled("mean_en")), _mean_en_dofs(getVar("mean_en", 0)->dofIndices()), _r_units(1. / getParam<Real>("position_units")), _resistance(getParam<Real>("resistance")) { if (_surface.compare("anode") == 0) _current_sign = -1.; else if (_surface.compare("cathode") == 0) _current_sign = 1.; if (_mesh.dimension() == 1 && isParamValid("area")) { _area = getParam<Real>("area"); _use_area = true; } else if (_mesh.dimension() == 1 && !(isParamValid("area"))) mooseError("In a one-dimensional simulation, the area parameter must be set."); else _use_area = false; if (getParam<std::string>("potential_units").compare("V") == 0) _voltage_scaling = 1.; else if (getParam<std::string>("potential_units").compare("kV") == 0) _voltage_scaling = 1000; else mooseError("Potential specified must be either 'V' or 'kV'."); } Real PenaltyCircuitPotential::computeQpResidual() { Real curr_times_resist = _current_sign * _current * _resistance / _voltage_scaling; if (_use_area) curr_times_resist *= _area; return _test[_i][_qp] * _p * (_surface_potential - _u[_qp] + curr_times_resist); } Real PenaltyCircuitPotential::computeQpJacobian() { Real d_curr_times_resist_d_potential = _current_sign * _current_jac[_var_dofs[_j]] * _resistance / _voltage_scaling; if (_use_area) d_curr_times_resist_d_potential *= _area; return _test[_i][_qp] * _p * (-_phi[_j][_qp] + d_curr_times_resist_d_potential); } Real PenaltyCircuitPotential::computeQpOffDiagJacobian(unsigned int jvar) { if (jvar == _em_id) { Real d_curr_times_resist_d_em = _current_sign * _current_jac[_em_dofs[_j]] * _resistance / _voltage_scaling; if (_use_area) d_curr_times_resist_d_em *= _area; return _test[_i][_qp] * _p * d_curr_times_resist_d_em; } else if (jvar == _ip_id) { Real d_curr_times_resist_d_ip = _current_sign * _current_jac[_ip_dofs[_j]] * _resistance / _voltage_scaling; if (_use_area) d_curr_times_resist_d_ip *= _area; return _test[_i][_qp] * _p * d_curr_times_resist_d_ip; } else if (jvar == _mean_en_id) { Real d_curr_times_resist_d_mean_en = _current_sign * _current_jac[_mean_en_dofs[_j]] * _resistance / _voltage_scaling; if (_use_area) d_curr_times_resist_d_mean_en *= _area; return _test[_i][_qp] * _p * d_curr_times_resist_d_mean_en; } else return 0; } Real PenaltyCircuitPotential::computeQpNonlocalJacobian(dof_id_type dof_index) { Real d_curr_times_resist_d_potential = _current_sign * _current_jac[dof_index] * _resistance / _voltage_scaling; if (_use_area) d_curr_times_resist_d_potential *= _area; return _test[_i][_qp] * _p * d_curr_times_resist_d_potential; } Real PenaltyCircuitPotential::computeQpNonlocalOffDiagJacobian(unsigned int jvar, dof_id_type dof_index) { if (jvar == _em_id || jvar == _ip_id || jvar == _mean_en_id) { Real d_curr_times_resist_d_coupled_var = _current_sign * _current_jac[dof_index] * _resistance / _voltage_scaling; if (_use_area) d_curr_times_resist_d_coupled_var *= _area; return _test[_i][_qp] * _p * d_curr_times_resist_d_coupled_var; } return 0; } <commit_msg>Add r_units.<commit_after>#include "PenaltyCircuitPotential.h" #include "MooseMesh.h" template<> InputParameters validParams<PenaltyCircuitPotential>() { InputParameters p = validParams<NonlocalIntegratedBC>(); p.addRequiredParam<UserObjectName>("current", "The postprocessor response for calculating the current passing through the needle surface."); p.addRequiredParam<Real>("surface_potential", "The electrical potential applied to the surface if no current was flowing in the circuit."); p.addRequiredParam<std::string>("surface", "Whether you are specifying the potential on the anode or the cathode with the requirement that the other metal surface be grounded."); p.addRequiredParam<Real>("penalty", "The constant multiplying the penalty term."); p.addRequiredParam<UserObjectName>("data_provider", "The name of the UserObject that can provide some data to materials, bcs, etc."); p.addRequiredCoupledVar("em", "The electron variable."); p.addRequiredCoupledVar("ip", "The ion variable."); p.addRequiredCoupledVar("mean_en", "The ion variable."); p.addParam<Real>("area", "Must be provided when the number of dimensions equals 1."); p.addRequiredParam<std::string>("potential_units", "The potential units."); p.addRequiredParam<Real>("position_units", "Units of position."); p.addRequiredParam<Real>("resistance", "The ballast resistance in Ohms."); return p; } PenaltyCircuitPotential::PenaltyCircuitPotential(const InputParameters & parameters) : NonlocalIntegratedBC(parameters), _current_uo(getUserObject<CurrentDensityShapeSideUserObject>("current")), _current(_current_uo.getIntegral()), _current_jac(_current_uo.getJacobian()), _surface_potential(getParam<Real>("surface_potential")), _surface(getParam<std::string>("surface")), _p(getParam<Real>("penalty")), _data(getUserObject<ProvideMobility>("data_provider")), _var_dofs(_var.dofIndices()), _em_id(coupled("em")), _em_dofs(getVar("em", 0)->dofIndices()), _ip_id(coupled("ip")), _ip_dofs(getVar("ip", 0)->dofIndices()), _mean_en_id(coupled("mean_en")), _mean_en_dofs(getVar("mean_en", 0)->dofIndices()), _r_units(1. / getParam<Real>("position_units")), _resistance(getParam<Real>("resistance")) { if (_surface.compare("anode") == 0) _current_sign = -1.; else if (_surface.compare("cathode") == 0) _current_sign = 1.; if (_mesh.dimension() == 1 && isParamValid("area")) { _area = getParam<Real>("area"); _use_area = true; } else if (_mesh.dimension() == 1 && !(isParamValid("area"))) mooseError("In a one-dimensional simulation, the area parameter must be set."); else _use_area = false; if (getParam<std::string>("potential_units").compare("V") == 0) _voltage_scaling = 1.; else if (getParam<std::string>("potential_units").compare("kV") == 0) _voltage_scaling = 1000; else mooseError("Potential specified must be either 'V' or 'kV'."); } Real PenaltyCircuitPotential::computeQpResidual() { Real curr_times_resist = _current_sign * _current * _resistance / _voltage_scaling; if (_use_area) curr_times_resist *= _area; return _test[_i][_qp] * _r_units * _p * (_surface_potential - _u[_qp] + curr_times_resist); } Real PenaltyCircuitPotential::computeQpJacobian() { Real d_curr_times_resist_d_potential = _current_sign * _current_jac[_var_dofs[_j]] * _resistance / _voltage_scaling; if (_use_area) d_curr_times_resist_d_potential *= _area; return _test[_i][_qp] * _r_units * _p * (-_phi[_j][_qp] + d_curr_times_resist_d_potential); } Real PenaltyCircuitPotential::computeQpOffDiagJacobian(unsigned int jvar) { if (jvar == _em_id) { Real d_curr_times_resist_d_em = _current_sign * _current_jac[_em_dofs[_j]] * _resistance / _voltage_scaling; if (_use_area) d_curr_times_resist_d_em *= _area; return _test[_i][_qp] * _r_units * _p * d_curr_times_resist_d_em; } else if (jvar == _ip_id) { Real d_curr_times_resist_d_ip = _current_sign * _current_jac[_ip_dofs[_j]] * _resistance / _voltage_scaling; if (_use_area) d_curr_times_resist_d_ip *= _area; return _test[_i][_qp] * _r_units * _p * d_curr_times_resist_d_ip; } else if (jvar == _mean_en_id) { Real d_curr_times_resist_d_mean_en = _current_sign * _current_jac[_mean_en_dofs[_j]] * _resistance / _voltage_scaling; if (_use_area) d_curr_times_resist_d_mean_en *= _area; return _test[_i][_qp] * _r_units * _p * d_curr_times_resist_d_mean_en; } else return 0; } Real PenaltyCircuitPotential::computeQpNonlocalJacobian(dof_id_type dof_index) { Real d_curr_times_resist_d_potential = _current_sign * _current_jac[dof_index] * _resistance / _voltage_scaling; if (_use_area) d_curr_times_resist_d_potential *= _area; return _test[_i][_qp] * _r_units * _p * d_curr_times_resist_d_potential; } Real PenaltyCircuitPotential::computeQpNonlocalOffDiagJacobian(unsigned int jvar, dof_id_type dof_index) { if (jvar == _em_id || jvar == _ip_id || jvar == _mean_en_id) { Real d_curr_times_resist_d_coupled_var = _current_sign * _current_jac[dof_index] * _resistance / _voltage_scaling; if (_use_area) d_curr_times_resist_d_coupled_var *= _area; return _test[_i][_qp] * _r_units * _p * d_curr_times_resist_d_coupled_var; } return 0; } <|endoftext|>
<commit_before>#ifndef PCL_TRACKING_IMPL_KLD_ADAPTIVE_PARTICLE_FILTER_H_ #define PCL_TRACKING_IMPL_KLD_ADAPTIVE_PARTICLE_FILTER_H_ #include <pcl/tracking/kld_adaptive_particle_filter.h> template <typename PointInT, typename StateT> bool pcl::tracking::KLDAdaptiveParticleFilterTracker<PointInT, StateT>::initCompute () { if (!Tracker<PointInT, StateT>::initCompute ()) { PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ()); return (false); } if (transed_reference_vector_.empty ()) { // only one time allocation transed_reference_vector_.resize (maximum_particle_number_); for (unsigned int i = 0; i < maximum_particle_number_; i++) { transed_reference_vector_[i] = PointCloudInPtr (new PointCloudIn ()); } } coherence_->setTargetCloud (input_); if (!change_detector_) change_detector_ = boost::shared_ptr<pcl::octree::OctreePointCloudChangeDetector<PointInT> >(new pcl::octree::OctreePointCloudChangeDetector<PointInT> (change_detector_resolution_)); if (!particles_ || particles_->points.empty ()) initParticles (true); return (true); } template <typename PointInT, typename StateT> bool pcl::tracking::KLDAdaptiveParticleFilterTracker<PointInT, StateT>::insertIntoBins (std::vector<int> bin, std::vector<std::vector<int> > &B) { for (size_t i = 0; i < B.size (); i++) { if (equalBin (bin, B[i])) return false; } B.push_back (bin); return true; } template <typename PointInT, typename StateT> void pcl::tracking::KLDAdaptiveParticleFilterTracker<PointInT, StateT>::resample () { unsigned int k = 0; unsigned int n = 0; PointCloudStatePtr S (new PointCloudState); std::vector<std::vector<int> > B; // bins // initializing for sampling without replacement std::vector<int> a (particles_->points.size ()); std::vector<double> q (particles_->points.size ()); this->genAliasTable (a, q, particles_); const std::vector<double> zero_mean (StateT::stateDimension (), 0.0); // select the particles with KLD sampling do { int j_n = sampleWithReplacement (a, q); StateT x_t = particles_->points[j_n]; x_t.sample (zero_mean, step_noise_covariance_); // motion if (rand () / double (RAND_MAX) < motion_ratio_) x_t = x_t + motion_; S->points.push_back (x_t); // calc bin std::vector<int> bin (StateT::stateDimension ()); for (int i = 0; i < StateT::stateDimension (); i++) bin[i] = static_cast<int> (x_t[i] / bin_size_[i]); // calc bin index... how? if (insertIntoBins (bin, B)) ++k; ++n; } while (k < 2 || (n < maximum_particle_number_ && n < calcKLBound (k))); particles_ = S; // swap particle_num_ = static_cast<int> (particles_->points.size ()); } #define PCL_INSTANTIATE_KLDAdaptiveParticleFilterTracker(T,ST) template class PCL_EXPORTS pcl::tracking::KLDAdaptiveParticleFilterTracker<T,ST>; #endif <commit_msg>Fix occasional seg fault with KLDAdaptiveParticleFilterOMPTracker<commit_after>#ifndef PCL_TRACKING_IMPL_KLD_ADAPTIVE_PARTICLE_FILTER_H_ #define PCL_TRACKING_IMPL_KLD_ADAPTIVE_PARTICLE_FILTER_H_ #include <pcl/tracking/kld_adaptive_particle_filter.h> template <typename PointInT, typename StateT> bool pcl::tracking::KLDAdaptiveParticleFilterTracker<PointInT, StateT>::initCompute () { if (!Tracker<PointInT, StateT>::initCompute ()) { PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ()); return (false); } if (transed_reference_vector_.empty ()) { // only one time allocation transed_reference_vector_.resize (maximum_particle_number_); for (unsigned int i = 0; i < maximum_particle_number_; i++) { transed_reference_vector_[i] = PointCloudInPtr (new PointCloudIn ()); } } coherence_->setTargetCloud (input_); if (!change_detector_) change_detector_ = boost::shared_ptr<pcl::octree::OctreePointCloudChangeDetector<PointInT> >(new pcl::octree::OctreePointCloudChangeDetector<PointInT> (change_detector_resolution_)); if (!particles_ || particles_->points.empty ()) initParticles (true); return (true); } template <typename PointInT, typename StateT> bool pcl::tracking::KLDAdaptiveParticleFilterTracker<PointInT, StateT>::insertIntoBins (std::vector<int> bin, std::vector<std::vector<int> > &B) { for (size_t i = 0; i < B.size (); i++) { if (equalBin (bin, B[i])) return false; } B.push_back (bin); return true; } template <typename PointInT, typename StateT> void pcl::tracking::KLDAdaptiveParticleFilterTracker<PointInT, StateT>::resample () { unsigned int k = 0; unsigned int n = 0; PointCloudStatePtr S (new PointCloudState); std::vector<std::vector<int> > B; // bins // initializing for sampling without replacement std::vector<int> a (particles_->points.size ()); std::vector<double> q (particles_->points.size ()); this->genAliasTable (a, q, particles_); const std::vector<double> zero_mean (StateT::stateDimension (), 0.0); // select the particles with KLD sampling do { int j_n = sampleWithReplacement (a, q); StateT x_t = particles_->points[j_n]; x_t.sample (zero_mean, step_noise_covariance_); // motion if (rand () / double (RAND_MAX) < motion_ratio_) x_t = x_t + motion_; S->points.push_back (x_t); // calc bin std::vector<int> bin (StateT::stateDimension ()); for (int i = 0; i < StateT::stateDimension (); i++) bin[i] = static_cast<int> (x_t[i] / bin_size_[i]); // calc bin index... how? if (insertIntoBins (bin, B)) ++k; ++n; } while (n < maximum_particle_number_ && (k < 2 || n < calcKLBound (k))); particles_ = S; // swap particle_num_ = static_cast<int> (particles_->points.size ()); } #define PCL_INSTANTIATE_KLDAdaptiveParticleFilterTracker(T,ST) template class PCL_EXPORTS pcl::tracking::KLDAdaptiveParticleFilterTracker<T,ST>; #endif <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <vector> #include <string> #include <list> #include <map> #include <algorithm> #include <locale> #include <getopt.h> #include <stdlib.h> #include <unordered_map> #include "search.h" #include "stats.h" #include "seq.h" void build_patterns(std::ifstream & kmers_f, int polyG, std::vector <std::pair <std::string, Node::Type> > & patterns) { std::string tmp; while (!kmers_f.eof()) { std::getline(kmers_f, tmp); std::transform(tmp.begin(), tmp.end(), tmp.begin(), ::toupper); if (!tmp.empty()) { size_t tab = tmp.find('\t'); if (tab == std::string::npos) { patterns.push_back(std::make_pair(tmp, Node::Type::adapter)); } else { patterns.push_back(std::make_pair(tmp.substr(0, tab), Node::Type::adapter)); } } } kmers_f.close(); patterns.push_back(std::make_pair("NNNNN", Node::Type::n)); if (polyG) { patterns.push_back(std::make_pair(std::string(polyG, 'G'), Node::Type::polyG)); patterns.push_back(std::make_pair(std::string(polyG, 'C'), Node::Type::polyC)); } } double get_dust_score(std::string const & read, int k) { std::unordered_map <int, int> counts; static std::unordered_map <char, int> hashes = {{'N', 1}, {'A', 2}, {'C', 3}, {'G', 4}, {'T', 5}}; unsigned int hash = 0; unsigned int max_pow = pow(10, k - 1); for (auto it = read.begin(); it != read.end(); ++it) { char c = (*it > 96) ? (*it - 32) : *it; hash = hash * 10 + hashes[c]; if (it - read.begin() >= k - 1) { ++counts[hash]; hash = hash - (hash / max_pow) * max_pow; } } double score = 0; double total = 0; for (auto it = counts.begin(); it != counts.end(); ++it) { score += it->second * (it->second - 1) / 2; total += score; } // std::cout << (total / (read.size() - k + 1)) << std::endl; return (total / (read.size() - k + 1)); } ReadType check_read(std::string const & read, Node * root, std::vector <std::pair<std::string, Node::Type> > const & patterns, unsigned int length, int dust_k, int dust_cutoff, int errors) { if (length && read.size() < length) { return ReadType::length; } if (dust_cutoff && get_dust_score(read, dust_k) > dust_cutoff) { return ReadType::dust; } if (errors) { return (ReadType)search_inexact(read, root, patterns, errors); } else { return (ReadType)search_any(read, root); } } void filter_single_reads(std::ifstream & reads_f, std::ofstream & ok_f, std::ofstream & bad_f, Stats & stats, Node * root, std::vector <std::pair<std::string, Node::Type> > const & patterns, int length, int dust_k, int dust_cutoff, int errors) { Seq read; while (read.read_seq(reads_f)) { ReadType type = check_read(read.seq, root, patterns, length, dust_k, dust_cutoff, errors); stats.update(type); if (type == ReadType::ok) { read.write_seq(ok_f); } else { read.update_id(type); read.write_seq(bad_f); } } } void filter_paired_reads(std::ifstream & reads1_f, std::ifstream & reads2_f, std::ofstream & ok1_f, std::ofstream & ok2_f, std::ofstream & bad1_f, std::ofstream & bad2_f, std::ofstream & se1_f, std::ofstream & se2_f, Stats & stats1, Stats & stats2, Node * root, std::vector <std::pair<std::string, Node::Type> > const & patterns, int length, int dust_k, int dust_cutoff, int errors) { Seq read1; Seq read2; while (read1.read_seq(reads1_f) && read2.read_seq(reads2_f)) { ReadType type1 = check_read(read1.seq, root, patterns, length, dust_k, dust_cutoff, errors); ReadType type2 = check_read(read2.seq, root, patterns, length, dust_k, dust_cutoff, errors); if (type1 == ReadType::ok && type2 == ReadType::ok) { read1.write_seq(ok1_f); read2.write_seq(ok2_f); stats1.update(type1, true); stats2.update(type2, true); } else { stats1.update(type1, false); stats2.update(type2, false); if (type1 == ReadType::ok) { read1.write_seq(se1_f); read2.update_id(type2); read2.write_seq(bad2_f); } else if (type2 == ReadType::ok) { read1.update_id(type1); read1.write_seq(bad1_f); read2.write_seq(se2_f); } else { read1.update_id(type1); read2.update_id(type2); read1.write_seq(bad1_f); read2.write_seq(bad2_f); } } } } std::string basename(std::string const & path) { std::string res(path); size_t pos = res.find_last_of('/'); if (pos != std::string::npos) { res.erase(0, pos); } pos = res.find('.'); if (pos != std::string::npos) { res.erase(pos, path.size()); } return res; } void print_help() { std::cout << "./rm_reads [-i raw_data.fastq | -1 raw_data1.fastq -2 raw_data2.fastq] -o output_dir --polyG 13 --length 50 --fragments fragments.dat --dust_cutoff cutoff --dust_k k -e 1" << std::endl; } int main(int argc, char ** argv) { Node root('0'); std::vector <std::pair<std::string, Node::Type> > patterns; std::string kmers, reads, out_dir; std::string reads1, reads2; char rez = 0; int length = 0; int polyG = 0; int dust_k = 4; int dust_cutoff = 0; int errors = 0; const struct option long_options[] = { {"length",required_argument,NULL,'l'}, {"polyG",required_argument,NULL,'p'}, {"fragments",required_argument,NULL,'a'}, {"dust_k",required_argument,NULL,'k'}, {"dust_cutoff",required_argument,NULL,'c'}, {"errors",required_argument,NULL,'e'}, {NULL,0,NULL,0} }; while ((rez = getopt_long(argc, argv, "1:2:l:p:a:i:o:e:", long_options, NULL)) != -1) { switch (rez) { case 'l': length = std::atoi(optarg); break; case 'p': polyG = std::atoi(optarg); // polyG = boost::lexical_cast<int>(optarg); break; case 'a': kmers = optarg; break; case 'i': reads = optarg; break; case '1': reads1 = optarg; break; case '2': reads2 = optarg; break; case 'o': out_dir = optarg; break; case 'c': dust_cutoff = std::atoi(optarg); break; case 'k': dust_k = std::atoi(optarg); break; case 'e': errors = std::atoi(optarg); break; case '?': print_help(); return -1; } } if (errors < 0 || errors > 2) { std::cout << "possible errors count are 0, 1, 2" << std::endl; return -1; } if (kmers.empty() || out_dir.empty() || ( reads.empty() && (reads1.empty() || reads2.empty()))) { print_help(); return -1; } std::ifstream kmers_f (kmers.c_str()); if (!kmers_f.good()) { std::cout << "Cannot open kmers file" << std::endl; print_help(); return -1; } init_type_names(length, polyG, dust_k, dust_cutoff); build_patterns(kmers_f, polyG, patterns); /* for (std::vector <std::string> ::iterator it = patterns.begin(); it != patterns.end(); ++it) { std::cout << *it << std::endl; } */ if (patterns.empty()) { std::cout << "patterns are empty" << std::endl; return -1; } build_trie(root, patterns, errors); add_failures(root); if (!reads.empty()) { std::string reads_base = basename(reads); std::ifstream reads_f (reads.c_str()); std::ofstream ok_f((out_dir + "/" + reads_base + ".ok.fastq").c_str(), std::ofstream::out); std::ofstream bad_f((out_dir + "/" + reads_base + ".filtered.fastq").c_str(), std::ofstream::out); if (!reads_f.good()) { std::cout << "Cannot open reads file" << std::endl; print_help(); return -1; } if (!ok_f.good() || !bad_f.good()) { std::cout << "Cannot open output file" << std::endl; print_help(); return -1; } Stats stats(reads); filter_single_reads(reads_f, ok_f, bad_f, stats, &root, patterns, length, dust_k, dust_cutoff, errors); std::cout << stats; ok_f.close(); bad_f.close(); reads_f.close(); } else { std::string reads1_base = basename(reads1); std::string reads2_base = basename(reads2); std::ifstream reads1_f(reads1.c_str()); std::ifstream reads2_f(reads2.c_str()); std::ofstream ok1_f((out_dir + "/" + reads1_base + ".ok.fastq").c_str(), std::ofstream::out); std::ofstream ok2_f((out_dir + "/" + reads2_base + ".ok.fastq").c_str(), std::ofstream::out); std::ofstream se1_f((out_dir + "/" + reads1_base + ".se.fastq").c_str(), std::ofstream::out); std::ofstream se2_f((out_dir + "/" + reads2_base + ".se.fastq").c_str(), std::ofstream::out); std::ofstream bad1_f((out_dir + "/" + reads1_base + ".filtered.fastq").c_str(), std::ofstream::out); std::ofstream bad2_f((out_dir + "/" + reads2_base + ".filtered.fastq").c_str(), std::ofstream::out); if (!reads1_f.good() || !reads2_f.good()) { std::cout << "reads file is bad" << std::endl; print_help(); return -1; } if (!ok1_f.good() || !ok2_f.good() || !bad1_f.good() || !bad2_f.good() || !se1_f.good() || !se2_f.good()) { std::cout << "out file is bad" << std::endl; print_help(); return -1; } Stats stats1(reads1); Stats stats2(reads2); filter_paired_reads(reads1_f, reads2_f, ok1_f, ok2_f, bad1_f, bad2_f, se1_f, se2_f, stats1, stats2, &root, patterns, length, dust_k, dust_cutoff, errors); std::cout << stats1; std::cout << stats2; ok1_f.close(); ok2_f.close(); bad1_f.close(); bad2_f.close(); reads1_f.close(); reads2_f.close(); } } <commit_msg>Change NNNN with NN pattern<commit_after>#include <iostream> #include <fstream> #include <vector> #include <string> #include <list> #include <map> #include <algorithm> #include <locale> #include <getopt.h> #include <stdlib.h> #include <unordered_map> #include "search.h" #include "stats.h" #include "seq.h" void build_patterns(std::ifstream & kmers_f, int polyG, std::vector <std::pair <std::string, Node::Type> > & patterns) { std::string tmp; while (!kmers_f.eof()) { std::getline(kmers_f, tmp); std::transform(tmp.begin(), tmp.end(), tmp.begin(), ::toupper); if (!tmp.empty()) { size_t tab = tmp.find('\t'); if (tab == std::string::npos) { patterns.push_back(std::make_pair(tmp, Node::Type::adapter)); } else { patterns.push_back(std::make_pair(tmp.substr(0, tab), Node::Type::adapter)); } } } kmers_f.close(); patterns.push_back(std::make_pair("NN", Node::Type::n)); if (polyG) { patterns.push_back(std::make_pair(std::string(polyG, 'G'), Node::Type::polyG)); patterns.push_back(std::make_pair(std::string(polyG, 'C'), Node::Type::polyC)); } } double get_dust_score(std::string const & read, int k) { std::unordered_map <int, int> counts; static std::unordered_map <char, int> hashes = {{'N', 1}, {'A', 2}, {'C', 3}, {'G', 4}, {'T', 5}}; unsigned int hash = 0; unsigned int max_pow = pow(10, k - 1); for (auto it = read.begin(); it != read.end(); ++it) { char c = (*it > 96) ? (*it - 32) : *it; hash = hash * 10 + hashes[c]; if (it - read.begin() >= k - 1) { ++counts[hash]; hash = hash - (hash / max_pow) * max_pow; } } double score = 0; double total = 0; for (auto it = counts.begin(); it != counts.end(); ++it) { score += it->second * (it->second - 1) / 2; total += score; } // std::cout << (total / (read.size() - k + 1)) << std::endl; return (total / (read.size() - k + 1)); } ReadType check_read(std::string const & read, Node * root, std::vector <std::pair<std::string, Node::Type> > const & patterns, unsigned int length, int dust_k, int dust_cutoff, int errors) { if (length && read.size() < length) { return ReadType::length; } if (dust_cutoff && get_dust_score(read, dust_k) > dust_cutoff) { return ReadType::dust; } if (errors) { return (ReadType)search_inexact(read, root, patterns, errors); } else { return (ReadType)search_any(read, root); } } void filter_single_reads(std::ifstream & reads_f, std::ofstream & ok_f, std::ofstream & bad_f, Stats & stats, Node * root, std::vector <std::pair<std::string, Node::Type> > const & patterns, int length, int dust_k, int dust_cutoff, int errors) { Seq read; while (read.read_seq(reads_f)) { ReadType type = check_read(read.seq, root, patterns, length, dust_k, dust_cutoff, errors); stats.update(type); if (type == ReadType::ok) { read.write_seq(ok_f); } else { read.update_id(type); read.write_seq(bad_f); } } } void filter_paired_reads(std::ifstream & reads1_f, std::ifstream & reads2_f, std::ofstream & ok1_f, std::ofstream & ok2_f, std::ofstream & bad1_f, std::ofstream & bad2_f, std::ofstream & se1_f, std::ofstream & se2_f, Stats & stats1, Stats & stats2, Node * root, std::vector <std::pair<std::string, Node::Type> > const & patterns, int length, int dust_k, int dust_cutoff, int errors) { Seq read1; Seq read2; while (read1.read_seq(reads1_f) && read2.read_seq(reads2_f)) { ReadType type1 = check_read(read1.seq, root, patterns, length, dust_k, dust_cutoff, errors); ReadType type2 = check_read(read2.seq, root, patterns, length, dust_k, dust_cutoff, errors); if (type1 == ReadType::ok && type2 == ReadType::ok) { read1.write_seq(ok1_f); read2.write_seq(ok2_f); stats1.update(type1, true); stats2.update(type2, true); } else { stats1.update(type1, false); stats2.update(type2, false); if (type1 == ReadType::ok) { read1.write_seq(se1_f); read2.update_id(type2); read2.write_seq(bad2_f); } else if (type2 == ReadType::ok) { read1.update_id(type1); read1.write_seq(bad1_f); read2.write_seq(se2_f); } else { read1.update_id(type1); read2.update_id(type2); read1.write_seq(bad1_f); read2.write_seq(bad2_f); } } } } std::string basename(std::string const & path) { std::string res(path); size_t pos = res.find_last_of('/'); if (pos != std::string::npos) { res.erase(0, pos); } pos = res.find('.'); if (pos != std::string::npos) { res.erase(pos, path.size()); } return res; } void print_help() { std::cout << "./rm_reads [-i raw_data.fastq | -1 raw_data1.fastq -2 raw_data2.fastq] -o output_dir --polyG 13 --length 50 --fragments fragments.dat --dust_cutoff cutoff --dust_k k -e 1" << std::endl; } int main(int argc, char ** argv) { Node root('0'); std::vector <std::pair<std::string, Node::Type> > patterns; std::string kmers, reads, out_dir; std::string reads1, reads2; char rez = 0; int length = 0; int polyG = 0; int dust_k = 4; int dust_cutoff = 0; int errors = 0; const struct option long_options[] = { {"length",required_argument,NULL,'l'}, {"polyG",required_argument,NULL,'p'}, {"fragments",required_argument,NULL,'a'}, {"dust_k",required_argument,NULL,'k'}, {"dust_cutoff",required_argument,NULL,'c'}, {"errors",required_argument,NULL,'e'}, {NULL,0,NULL,0} }; while ((rez = getopt_long(argc, argv, "1:2:l:p:a:i:o:e:", long_options, NULL)) != -1) { switch (rez) { case 'l': length = std::atoi(optarg); break; case 'p': polyG = std::atoi(optarg); // polyG = boost::lexical_cast<int>(optarg); break; case 'a': kmers = optarg; break; case 'i': reads = optarg; break; case '1': reads1 = optarg; break; case '2': reads2 = optarg; break; case 'o': out_dir = optarg; break; case 'c': dust_cutoff = std::atoi(optarg); break; case 'k': dust_k = std::atoi(optarg); break; case 'e': errors = std::atoi(optarg); break; case '?': print_help(); return -1; } } if (errors < 0 || errors > 2) { std::cout << "possible errors count are 0, 1, 2" << std::endl; return -1; } if (kmers.empty() || out_dir.empty() || ( reads.empty() && (reads1.empty() || reads2.empty()))) { print_help(); return -1; } std::ifstream kmers_f (kmers.c_str()); if (!kmers_f.good()) { std::cout << "Cannot open kmers file" << std::endl; print_help(); return -1; } init_type_names(length, polyG, dust_k, dust_cutoff); build_patterns(kmers_f, polyG, patterns); /* for (std::vector <std::string> ::iterator it = patterns.begin(); it != patterns.end(); ++it) { std::cout << *it << std::endl; } */ if (patterns.empty()) { std::cout << "patterns are empty" << std::endl; return -1; } build_trie(root, patterns, errors); add_failures(root); if (!reads.empty()) { std::string reads_base = basename(reads); std::ifstream reads_f (reads.c_str()); std::ofstream ok_f((out_dir + "/" + reads_base + ".ok.fastq").c_str(), std::ofstream::out); std::ofstream bad_f((out_dir + "/" + reads_base + ".filtered.fastq").c_str(), std::ofstream::out); if (!reads_f.good()) { std::cout << "Cannot open reads file" << std::endl; print_help(); return -1; } if (!ok_f.good() || !bad_f.good()) { std::cout << "Cannot open output file" << std::endl; print_help(); return -1; } Stats stats(reads); filter_single_reads(reads_f, ok_f, bad_f, stats, &root, patterns, length, dust_k, dust_cutoff, errors); std::cout << stats; ok_f.close(); bad_f.close(); reads_f.close(); } else { std::string reads1_base = basename(reads1); std::string reads2_base = basename(reads2); std::ifstream reads1_f(reads1.c_str()); std::ifstream reads2_f(reads2.c_str()); std::ofstream ok1_f((out_dir + "/" + reads1_base + ".ok.fastq").c_str(), std::ofstream::out); std::ofstream ok2_f((out_dir + "/" + reads2_base + ".ok.fastq").c_str(), std::ofstream::out); std::ofstream se1_f((out_dir + "/" + reads1_base + ".se.fastq").c_str(), std::ofstream::out); std::ofstream se2_f((out_dir + "/" + reads2_base + ".se.fastq").c_str(), std::ofstream::out); std::ofstream bad1_f((out_dir + "/" + reads1_base + ".filtered.fastq").c_str(), std::ofstream::out); std::ofstream bad2_f((out_dir + "/" + reads2_base + ".filtered.fastq").c_str(), std::ofstream::out); if (!reads1_f.good() || !reads2_f.good()) { std::cout << "reads file is bad" << std::endl; print_help(); return -1; } if (!ok1_f.good() || !ok2_f.good() || !bad1_f.good() || !bad2_f.good() || !se1_f.good() || !se2_f.good()) { std::cout << "out file is bad" << std::endl; print_help(); return -1; } Stats stats1(reads1); Stats stats2(reads2); filter_paired_reads(reads1_f, reads2_f, ok1_f, ok2_f, bad1_f, bad2_f, se1_f, se2_f, stats1, stats2, &root, patterns, length, dust_k, dust_cutoff, errors); std::cout << stats1; std::cout << stats2; ok1_f.close(); ok2_f.close(); bad1_f.close(); bad2_f.close(); reads1_f.close(); reads2_f.close(); } } <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file Lexr.cxx ** Lexer for R, S, SPlus Statistics Program (Heavily derived from CPP Lexer). ** **/ // Copyright 1998-2002 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" #ifdef SCI_NAMESPACE using namespace Scintilla; #endif static inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_'); } static inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_'); } static inline bool IsAnOperator(const int ch) { if (isascii(ch) && isalnum(ch)) return false; // '.' left out as it is used to make up numbers if (ch == '-' || ch == '+' || ch == '!' || ch == '~' || ch == '?' || ch == ':' || ch == '*' || ch == '/' || ch == '^' || ch == '<' || ch == '>' || ch == '=' || ch == '&' || ch == '|' || ch == '$' || ch == '(' || ch == ')' || ch == '}' || ch == '{' || ch == '[' || ch == ']') return true; return false; } static void ColouriseRDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; // Do not leak onto next line if (initStyle == SCE_R_INFIXEOL) initStyle = SCE_R_DEFAULT; StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { if (sc.atLineStart && (sc.state == SCE_R_STRING)) { // Prevent SCE_R_STRINGEOL from leaking back to previous line sc.SetState(SCE_R_STRING); } // Determine if the current state should terminate. if (sc.state == SCE_R_OPERATOR) { sc.SetState(SCE_R_DEFAULT); } else if (sc.state == SCE_R_NUMBER) { if (!IsADigit(sc.ch) && !(sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_R_DEFAULT); } } else if (sc.state == SCE_R_IDENTIFIER) { if (!IsAWordChar(sc.ch) || (sc.ch == '.')) { char s[100]; sc.GetCurrentLowered(s, sizeof(s)); if (keywords.InList(s)) { sc.ChangeState(SCE_R_KWORD); } else if (keywords2.InList(s)) { sc.ChangeState(SCE_R_BASEKWORD); } else if (keywords3.InList(s)) { sc.ChangeState(SCE_R_OTHERKWORD); } sc.SetState(SCE_R_DEFAULT); } } else if (sc.state == SCE_R_COMMENT) { if (sc.ch == '\r' || sc.ch == '\n') { sc.SetState(SCE_R_DEFAULT); } } else if (sc.state == SCE_R_STRING) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_R_DEFAULT); } } else if (sc.state == SCE_R_INFIX) { if (sc.ch == '%') { sc.ForwardSetState(SCE_R_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_R_INFIXEOL); sc.ForwardSetState(SCE_R_DEFAULT); } }else if (sc.state == SCE_R_STRING2) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\'') { sc.ForwardSetState(SCE_R_DEFAULT); } } // Determine if a new state should be entered. if (sc.state == SCE_R_DEFAULT) { if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_R_NUMBER); } else if (IsAWordStart(sc.ch) ) { sc.SetState(SCE_R_IDENTIFIER); } else if (sc.Match('#')) { sc.SetState(SCE_R_COMMENT); } else if (sc.ch == '\"') { sc.SetState(SCE_R_STRING); } else if (sc.ch == '%') { sc.SetState(SCE_R_INFIX); } else if (sc.ch == '\'') { sc.SetState(SCE_R_STRING2); } else if (IsAnOperator(sc.ch)) { sc.SetState(SCE_R_OPERATOR); } } } sc.Complete(); } // Store both the current line's fold level and the next lines in the // level store to make it easy to pick up with each increment // and to make it possible to fiddle the current level for "} else {". static void FoldRDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) { bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0; unsigned int endPos = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelCurrent = SC_FOLDLEVELBASE; if (lineCurrent > 0) levelCurrent = styler.LevelAt(lineCurrent-1) >> 16; int levelMinCurrent = levelCurrent; int levelNext = levelCurrent; char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); for (unsigned int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (style == SCE_R_OPERATOR) { if (ch == '{') { // Measure the minimum before a '{' to allow // folding on "} else {" if (levelMinCurrent > levelNext) { levelMinCurrent = levelNext; } levelNext++; } else if (ch == '}') { levelNext--; } } if (atEOL) { int levelUse = levelCurrent; if (foldAtElse) { levelUse = levelMinCurrent; } int lev = levelUse | levelNext << 16; if (visibleChars == 0 && foldCompact) lev |= SC_FOLDLEVELWHITEFLAG; if (levelUse < levelNext) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelCurrent = levelNext; levelMinCurrent = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; } } static const char * const RWordLists[] = { "Language Keywords", "Base / Default package function", "Other Package Functions", "Unused", "Unused", 0, }; LexerModule lmR(SCLEX_R, ColouriseRDoc, "r", FoldRDoc, RWordLists); <commit_msg>Bug #2956543, R Lexer is case insensitive for keywords<commit_after>// Scintilla source code edit control /** @file Lexr.cxx ** Lexer for R, S, SPlus Statistics Program (Heavily derived from CPP Lexer). ** **/ // Copyright 1998-2002 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" #ifdef SCI_NAMESPACE using namespace Scintilla; #endif static inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_'); } static inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_'); } static inline bool IsAnOperator(const int ch) { if (isascii(ch) && isalnum(ch)) return false; // '.' left out as it is used to make up numbers if (ch == '-' || ch == '+' || ch == '!' || ch == '~' || ch == '?' || ch == ':' || ch == '*' || ch == '/' || ch == '^' || ch == '<' || ch == '>' || ch == '=' || ch == '&' || ch == '|' || ch == '$' || ch == '(' || ch == ')' || ch == '}' || ch == '{' || ch == '[' || ch == ']') return true; return false; } static void ColouriseRDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; // Do not leak onto next line if (initStyle == SCE_R_INFIXEOL) initStyle = SCE_R_DEFAULT; StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { if (sc.atLineStart && (sc.state == SCE_R_STRING)) { // Prevent SCE_R_STRINGEOL from leaking back to previous line sc.SetState(SCE_R_STRING); } // Determine if the current state should terminate. if (sc.state == SCE_R_OPERATOR) { sc.SetState(SCE_R_DEFAULT); } else if (sc.state == SCE_R_NUMBER) { if (!IsADigit(sc.ch) && !(sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_R_DEFAULT); } } else if (sc.state == SCE_R_IDENTIFIER) { if (!IsAWordChar(sc.ch)) { char s[100]; sc.GetCurrent(s, sizeof(s)); if (keywords.InList(s)) { sc.ChangeState(SCE_R_KWORD); } else if (keywords2.InList(s)) { sc.ChangeState(SCE_R_BASEKWORD); } else if (keywords3.InList(s)) { sc.ChangeState(SCE_R_OTHERKWORD); } sc.SetState(SCE_R_DEFAULT); } } else if (sc.state == SCE_R_COMMENT) { if (sc.ch == '\r' || sc.ch == '\n') { sc.SetState(SCE_R_DEFAULT); } } else if (sc.state == SCE_R_STRING) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_R_DEFAULT); } } else if (sc.state == SCE_R_INFIX) { if (sc.ch == '%') { sc.ForwardSetState(SCE_R_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_R_INFIXEOL); sc.ForwardSetState(SCE_R_DEFAULT); } }else if (sc.state == SCE_R_STRING2) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\'') { sc.ForwardSetState(SCE_R_DEFAULT); } } // Determine if a new state should be entered. if (sc.state == SCE_R_DEFAULT) { if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_R_NUMBER); } else if (IsAWordStart(sc.ch) ) { sc.SetState(SCE_R_IDENTIFIER); } else if (sc.Match('#')) { sc.SetState(SCE_R_COMMENT); } else if (sc.ch == '\"') { sc.SetState(SCE_R_STRING); } else if (sc.ch == '%') { sc.SetState(SCE_R_INFIX); } else if (sc.ch == '\'') { sc.SetState(SCE_R_STRING2); } else if (IsAnOperator(sc.ch)) { sc.SetState(SCE_R_OPERATOR); } } } sc.Complete(); } // Store both the current line's fold level and the next lines in the // level store to make it easy to pick up with each increment // and to make it possible to fiddle the current level for "} else {". static void FoldRDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) { bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0; unsigned int endPos = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelCurrent = SC_FOLDLEVELBASE; if (lineCurrent > 0) levelCurrent = styler.LevelAt(lineCurrent-1) >> 16; int levelMinCurrent = levelCurrent; int levelNext = levelCurrent; char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); for (unsigned int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (style == SCE_R_OPERATOR) { if (ch == '{') { // Measure the minimum before a '{' to allow // folding on "} else {" if (levelMinCurrent > levelNext) { levelMinCurrent = levelNext; } levelNext++; } else if (ch == '}') { levelNext--; } } if (atEOL) { int levelUse = levelCurrent; if (foldAtElse) { levelUse = levelMinCurrent; } int lev = levelUse | levelNext << 16; if (visibleChars == 0 && foldCompact) lev |= SC_FOLDLEVELWHITEFLAG; if (levelUse < levelNext) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelCurrent = levelNext; levelMinCurrent = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; } } static const char * const RWordLists[] = { "Language Keywords", "Base / Default package function", "Other Package Functions", "Unused", "Unused", 0, }; LexerModule lmR(SCLEX_R, ColouriseRDoc, "r", FoldRDoc, RWordLists); <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Copyright (C) 2015 Ruslan Baratov ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Multimedia module. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "VideoFilterRunnable.hpp" #include <cassert> // assert #include <graphics/GLExtra.h> // GATHERER_OPENGL_DEBUG #include "VideoFilter.hpp" #include "TextureBuffer.hpp" #include "libyuv.h" #include "OGLESGPGPUTest.h" #include <opencv2/imgproc.hpp> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <QDateTime> struct QVideoFrameScopeMap { QVideoFrameScopeMap(QVideoFrame *frame, QAbstractVideoBuffer::MapMode mode) : frame(frame) { if(frame) { status = frame->map(mode); if (!status) { qWarning("Can't map!"); } } } ~QVideoFrameScopeMap() { if(frame) { frame->unmap(); } } operator bool() const { return status; } QVideoFrame *frame = nullptr; bool status = false; }; static cv::Mat QVideoFrameToCV(QVideoFrame *input); VideoFilterRunnable::VideoFilterRunnable(VideoFilter *filter) : m_filter(filter), m_outTexture(0), m_lastInputTexture(0) { QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions(); const char *vendor = (const char *) f->glGetString(GL_VENDOR); qDebug("GL_VENDOR: %s", vendor); } VideoFilterRunnable::~VideoFilterRunnable() { } QVideoFrame VideoFilterRunnable::run(QVideoFrame *input, const QVideoSurfaceFormat &surfaceFormat, RunFlags flags) { Q_UNUSED(surfaceFormat); Q_UNUSED(flags); float resolution = 1.0f; void* glContext = 0; #if GATHERER_IOS glContext = ogles_gpgpu::Core::getCurrentEAGLContext(); resolution = 2.0f; #else QOpenGLContext * qContext = QOpenGLContext::currentContext(); glContext = qContext; QOpenGLFunctions glFuncs(qContext); #endif if(!m_pipeline) { QSize size = surfaceFormat.sizeHint(); GLint backingWidth = size.width(), backingHeight = size.height(); // TODO: These calls are failing on OS X glFuncs.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &backingWidth); glFuncs.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &backingHeight); ogles_gpgpu::Tools::checkGLErr("VideoFilterRunnable", "run"); cv::Size screenSize(backingWidth, backingHeight); m_pipeline = std::make_shared<gatherer::graphics::OEGLGPGPUTest>(glContext, screenSize, resolution); m_pipeline->setDoDisplay(false); } // This example supports RGB data only, either in system memory (typical with // cameras on all platforms) or as an OpenGL texture (e.g. video playback on // OS X). The latter is the fast path where everything happens on GPU. The // former involves a texture upload. if (!isFrameValid(*input)) { qWarning("Invalid input format"); return *input; } if (isFrameFormatYUV(*input)) { qWarning("YUV data is not supported"); return *input; } m_outTexture = createTextureForFrame(input); auto size = m_pipeline->getOutputSize(); return TextureBuffer::createVideoFrame(m_outTexture, {size.width, size.height}); } bool VideoFilterRunnable::isFrameValid(const QVideoFrame& frame) { if (!frame.isValid()) { return false; } if (frame.handleType() == QAbstractVideoBuffer::NoHandle) { return true; } if (frame.handleType() == QAbstractVideoBuffer::GLTextureHandle) { return true; } return false; } bool VideoFilterRunnable::isFrameFormatYUV(const QVideoFrame& frame) { if (frame.pixelFormat() == QVideoFrame::Format_YUV420P) { return true; } if (frame.pixelFormat() == QVideoFrame::Format_YV12) { return true; } return false; } // Create a texture from the image data. GLuint VideoFilterRunnable::createTextureForFrame(QVideoFrame* input) { QOpenGLContext* openglContext = QOpenGLContext::currentContext(); if (!openglContext) { qWarning("Can't get context!"); return 0; } assert(openglContext->isValid()); QOpenGLFunctions *f = openglContext->functions(); assert(f != 0); // Already an OpenGL texture. if (input->handleType() == QAbstractVideoBuffer::GLTextureHandle) { assert(input->pixelFormat() == TextureBuffer::qtTextureFormat()); GLuint texture = input->handle().toUInt(); assert(texture != 0); f->glBindTexture(GL_TEXTURE_2D, texture); m_lastInputTexture = texture; const cv::Size size(input->width(), input->height()); void* pixelBuffer = nullptr; // we are using texture const bool useRawPixels = false; // - // - m_pipeline->captureOutput(size, pixelBuffer, useRawPixels, texture); glActiveTexture(GL_TEXTURE0); GLuint outputTexture = m_pipeline->getLastShaderOutputTexture(); f->glBindTexture(GL_TEXTURE_2D, outputTexture); m_outTexture = outputTexture; } else { // Scope based pixel buffer lock for no nios platforms QVideoFrameScopeMap scopeMap(GATHERER_IOS ? nullptr : input, QAbstractVideoBuffer::ReadOnly); if(!(GATHERER_IOS && !scopeMap)) // for non ios platforms { assert((input->pixelFormat() == QVideoFrame::Format_ARGB32) || (GATHERER_IOS && input->pixelFormat() == QVideoFrame::Format_NV12)); #if GATHERER_IOS || defined(Q_OS_OSX) const GLenum rgbaFormat = GL_BGRA; #else const GLenum rgbaFormat = GL_RGBA; #endif #if GATHERER_IOS void * const pixelBuffer = input->pixelBufferRef() #else void * const pixelBuffer = input->bits(); //cv::Mat frame({input->width(), input->height()}, CV_8UC4, pixelBuffer ); //cv::imwrite("/tmp/frame.png", frame); #endif GLenum textureFormat = input->pixelFormat() == QVideoFrame::Format_ARGB32 ? rgbaFormat : 0; // 0 indicates YUV const bool useRawPixels = !(GATHERER_IOS); // ios uses texture cache / pixel buffer const GLuint inputTexture = 0; assert(pixelBuffer != nullptr); m_pipeline->captureOutput({input->width(), input->height()}, pixelBuffer, useRawPixels, inputTexture, textureFormat); // QT is expecting GL_TEXTURE0 to be active glActiveTexture(GL_TEXTURE0); GLuint outputTexture = m_pipeline->getLastShaderOutputTexture(); //GLuint outputTexture = m_pipeline->getInputTexture(); //GLuint outputTexture = m_pipeline->getDisplayTexture(); f->glBindTexture(GL_TEXTURE_2D, outputTexture); m_outTexture = outputTexture; } } const QPoint oldPosition = m_filter->rectanglePosition(); const QSize rectangleSize(100, 100); const bool visible = true; const int xDelta = std::rand() % 10; const int yDelta = std::rand() % 10; const int newX = (oldPosition.x() + xDelta) % input->size().width(); const int newY = (oldPosition.y() + yDelta) % input->size().height(); emit m_filter->updateRectangle(QPoint(newX, newY), rectangleSize, visible); emit m_filter->updateOutputString(QDateTime::currentDateTime().toString()); return m_outTexture; } // We don't ever want to use this in any practical scenario. // To be deprecated... static cv::Mat QVideoFrameToCV(QVideoFrame *input) { cv::Mat frame; switch(input->pixelFormat()) { case QVideoFrame::Format_ARGB32: case QVideoFrame::Format_BGRA32: frame = cv::Mat(input->height(), input->width(), CV_8UC4, input->bits()); break; case QVideoFrame::Format_NV21: frame.create(input->height(), input->width(), CV_8UC4); libyuv::NV21ToARGB(input->bits(), input->bytesPerLine(), input->bits(1), input->bytesPerLine(1), frame.ptr<uint8_t>(), int(frame.step1()), frame.cols, frame.rows); break; case QVideoFrame::Format_NV12: frame.create(input->height(), input->width(), CV_8UC4); libyuv::NV12ToARGB(input->bits(), input->bytesPerLine(), input->bits(1), input->bytesPerLine(1), frame.ptr<uint8_t>(), int(frame.step1()), frame.cols, frame.rows); break; default: CV_Assert(false); } return frame; } <commit_msg>minor changes<commit_after>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Copyright (C) 2015 Ruslan Baratov ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Multimedia module. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "VideoFilterRunnable.hpp" #include <cassert> // assert #include <graphics/GLExtra.h> // GATHERER_OPENGL_DEBUG #include "VideoFilter.hpp" #include "TextureBuffer.hpp" #include "libyuv.h" #include "OGLESGPGPUTest.h" #include <opencv2/imgproc.hpp> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <QDateTime> struct QVideoFrameScopeMap { QVideoFrameScopeMap(QVideoFrame *frame, QAbstractVideoBuffer::MapMode mode) : frame(frame) { if(frame) { status = frame->map(mode); if (!status) { qWarning("Can't map!"); } } } ~QVideoFrameScopeMap() { if(frame) { frame->unmap(); } } operator bool() const { return status; } QVideoFrame *frame = nullptr; bool status = false; }; static cv::Mat QVideoFrameToCV(QVideoFrame *input); VideoFilterRunnable::VideoFilterRunnable(VideoFilter *filter) : m_filter(filter), m_outTexture(0), m_lastInputTexture(0) { QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions(); const char *vendor = (const char *) f->glGetString(GL_VENDOR); qDebug("GL_VENDOR: %s", vendor); } VideoFilterRunnable::~VideoFilterRunnable() { } QVideoFrame VideoFilterRunnable::run(QVideoFrame *input, const QVideoSurfaceFormat &surfaceFormat, RunFlags flags) { Q_UNUSED(surfaceFormat); Q_UNUSED(flags); float resolution = 1.0f; void* glContext = 0; #if GATHERER_IOS glContext = ogles_gpgpu::Core::getCurrentEAGLContext(); resolution = 2.0f; #else QOpenGLContext * qContext = QOpenGLContext::currentContext(); glContext = qContext; QOpenGLFunctions glFuncs(qContext); #endif if(!m_pipeline) { QSize size = surfaceFormat.sizeHint(); GLint backingWidth = size.width(), backingHeight = size.height(); // TODO: These calls are failing on OS X glFuncs.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &backingWidth); glFuncs.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &backingHeight); ogles_gpgpu::Tools::checkGLErr("VideoFilterRunnable", "run"); cv::Size screenSize(backingWidth, backingHeight); m_pipeline = std::make_shared<gatherer::graphics::OEGLGPGPUTest>(glContext, screenSize, resolution); m_pipeline->setDoDisplay(false); } // This example supports RGB data only, either in system memory (typical with // cameras on all platforms) or as an OpenGL texture (e.g. video playback on // OS X). The latter is the fast path where everything happens on GPU. The // former involves a texture upload. if (!isFrameValid(*input)) { qWarning("Invalid input format"); return *input; } if (isFrameFormatYUV(*input)) { qWarning("YUV data is not supported"); return *input; } m_outTexture = createTextureForFrame(input); auto size = m_pipeline->getOutputSize(); return TextureBuffer::createVideoFrame(m_outTexture, {size.width, size.height}); } bool VideoFilterRunnable::isFrameValid(const QVideoFrame& frame) { if (!frame.isValid()) { return false; } if (frame.handleType() == QAbstractVideoBuffer::NoHandle) { return true; } if (frame.handleType() == QAbstractVideoBuffer::GLTextureHandle) { return true; } return false; } bool VideoFilterRunnable::isFrameFormatYUV(const QVideoFrame& frame) { if (frame.pixelFormat() == QVideoFrame::Format_YUV420P) { return true; } if (frame.pixelFormat() == QVideoFrame::Format_YV12) { return true; } return false; } // Create a texture from the image data. GLuint VideoFilterRunnable::createTextureForFrame(QVideoFrame* input) { QOpenGLContext* openglContext = QOpenGLContext::currentContext(); if (!openglContext) { qWarning("Can't get context!"); return 0; } assert(openglContext->isValid()); QOpenGLFunctions *f = openglContext->functions(); assert(f != 0); // Already an OpenGL texture. if (input->handleType() == QAbstractVideoBuffer::GLTextureHandle) { assert(input->pixelFormat() == TextureBuffer::qtTextureFormat()); GLuint texture = input->handle().toUInt(); assert(texture != 0); f->glBindTexture(GL_TEXTURE_2D, texture); m_lastInputTexture = texture; const cv::Size size(input->width(), input->height()); void* pixelBuffer = nullptr; // we are using texture const bool useRawPixels = false; // - // - m_pipeline->captureOutput(size, pixelBuffer, useRawPixels, texture); glActiveTexture(GL_TEXTURE0); GLuint outputTexture = m_pipeline->getLastShaderOutputTexture(); f->glBindTexture(GL_TEXTURE_2D, outputTexture); m_outTexture = outputTexture; } else { // Scope based pixel buffer lock for no nios platforms QVideoFrameScopeMap scopeMap(GATHERER_IOS ? nullptr : input, QAbstractVideoBuffer::ReadOnly); if(!(GATHERER_IOS && !scopeMap)) // for non ios platforms { assert((input->pixelFormat() == QVideoFrame::Format_ARGB32) || (GATHERER_IOS && input->pixelFormat() == QVideoFrame::Format_NV12)); #if defined(Q_OS_IOS) || defined(Q_OS_OSX) const GLenum rgbaFormat = GL_BGRA; #else const GLenum rgbaFormat = GL_RGBA; #endif #if defined(Q_OS_IOS) void * const pixelBuffer = input->pixelBufferRef() #else void * const pixelBuffer = input->bits(); #endif // 0 indicates YUV GLenum textureFormat = input->pixelFormat() == QVideoFrame::Format_ARGB32 ? rgbaFormat : 0; const bool useRawPixels = !(GATHERER_IOS); // ios uses texture cache / pixel buffer const GLuint inputTexture = 0; assert(pixelBuffer != nullptr); m_pipeline->captureOutput({input->width(), input->height()}, pixelBuffer, useRawPixels, inputTexture, textureFormat); // QT is expecting GL_TEXTURE0 to be active glActiveTexture(GL_TEXTURE0); GLuint outputTexture = m_pipeline->getLastShaderOutputTexture(); //GLuint outputTexture = m_pipeline->getInputTexture(); f->glBindTexture(GL_TEXTURE_2D, outputTexture); m_outTexture = outputTexture; } } const QPoint oldPosition = m_filter->rectanglePosition(); const QSize rectangleSize(100, 100); const bool visible = true; const int xDelta = std::rand() % 10; const int yDelta = std::rand() % 10; const int newX = (oldPosition.x() + xDelta) % input->size().width(); const int newY = (oldPosition.y() + yDelta) % input->size().height(); emit m_filter->updateRectangle(QPoint(newX, newY), rectangleSize, visible); emit m_filter->updateOutputString(QDateTime::currentDateTime().toString()); return m_outTexture; } // We don't ever want to use this in any practical scenario. // To be deprecated... static cv::Mat QVideoFrameToCV(QVideoFrame *input) { cv::Mat frame; switch(input->pixelFormat()) { case QVideoFrame::Format_ARGB32: case QVideoFrame::Format_BGRA32: frame = cv::Mat(input->height(), input->width(), CV_8UC4, input->bits()); break; case QVideoFrame::Format_NV21: frame.create(input->height(), input->width(), CV_8UC4); libyuv::NV21ToARGB(input->bits(), input->bytesPerLine(), input->bits(1), input->bytesPerLine(1), frame.ptr<uint8_t>(), int(frame.step1()), frame.cols, frame.rows); break; case QVideoFrame::Format_NV12: frame.create(input->height(), input->width(), CV_8UC4); libyuv::NV12ToARGB(input->bits(), input->bytesPerLine(), input->bits(1), input->bytesPerLine(1), frame.ptr<uint8_t>(), int(frame.step1()), frame.cols, frame.rows); break; default: CV_Assert(false); } return frame; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: actiontriggerpropertyset.hxx,v $ * * $Revision: 1.1 $ * * last change: $Author: cd $ $Date: 2001-12-04 07:37:26 $ * * 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 __FRAMEWORK_CLASSES_ACTIONTRIGGERPROPERTYSET_HXX_ #define __FRAMEWORK_CLASSES_ACTIONTRIGGERPROPERTYSET_HXX_ #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef _CPPUHELPER_PROPSHLP_HXX #include <cppuhelper/propshlp.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef __COM_SUN_STAR_AWT_XBITMAP_HPP_ #include <com/sun/star/awt/XBitmap.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_ #include <com/sun/star/lang/XTypeProvider.hpp> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif #define SERVICENAME_ACTIONTRIGGER "com.sun.star.ui.ActionTrigger" #define IMPLEMENTATIONNAME_ACTIONTRIGGER "com.sun.star.comp.ui.ActionTrigger" namespace framework { class ActionTriggerPropertySet : public ThreadHelpBase , // Struct for right initalization of mutex member! Must be first of baseclasses. public ::com::sun::star::lang::XServiceInfo , public ::com::sun::star::lang::XTypeProvider, public ::cppu::OBroadcastHelper , public ::cppu::OPropertySetHelper , // -> XPropertySet, XFastPropertySet, XMultiPropertySet public ::cppu::OWeakObject { public: ActionTriggerPropertySet( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager ); virtual ~ActionTriggerPropertySet(); // XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire() throw (); virtual void SAL_CALL release() throw (); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException); // XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw (::com::sun::star::uno::RuntimeException); private: //--------------------------------------------------------------------------------------------------------- // OPropertySetHelper //--------------------------------------------------------------------------------------------------------- virtual sal_Bool SAL_CALL convertFastPropertyValue( com::sun::star::uno::Any& aConvertedValue, com::sun::star::uno::Any& aOldValue, sal_Int32 nHandle, const com::sun::star::uno::Any& aValue ) throw( com::sun::star::lang::IllegalArgumentException ); virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const com::sun::star::uno::Any& aValue ) throw( com::sun::star::uno::Exception ); virtual void SAL_CALL getFastPropertyValue( com::sun::star::uno::Any& aValue, sal_Int32 nHandle ) const; virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper(); virtual com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw (::com::sun::star::uno::RuntimeException); static const com::sun::star::uno::Sequence< com::sun::star::beans::Property > impl_getStaticPropertyDescriptor(); //--------------------------------------------------------------------------------------------------------- // helper //--------------------------------------------------------------------------------------------------------- sal_Bool impl_tryToChangeProperty( const rtl::OUString& aCurrentValue , const com::sun::star::uno::Any& aNewValue , com::sun::star::uno::Any& aOldValue , com::sun::star::uno::Any& aConvertedValue ) throw( com::sun::star::lang::IllegalArgumentException ); sal_Bool impl_tryToChangeProperty( const com::sun::star::uno::Reference< com::sun::star::awt::XBitmap > xBitmap, const com::sun::star::uno::Any& aNewValue , com::sun::star::uno::Any& aOldValue , com::sun::star::uno::Any& aConvertedValue ) throw( com::sun::star::lang::IllegalArgumentException ); sal_Bool impl_tryToChangeProperty( const com::sun::star::uno::Reference< com::sun::star::uno::XInterface > xInterface, const com::sun::star::uno::Any& aNewValue , com::sun::star::uno::Any& aOldValue , com::sun::star::uno::Any& aConvertedValue ) throw( com::sun::star::lang::IllegalArgumentException ); //--------------------------------------------------------------------------------------------------------- // members //--------------------------------------------------------------------------------------------------------- rtl::OUString m_aCommandURL; rtl::OUString m_aHelpURL; rtl::OUString m_aText; ::com::sun::star::uno::Reference< ::com::sun::star::awt::XBitmap > m_xBitmap; ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > m_xActionTriggerContainer; }; } #endif // __FRAMEWORK_CLASSES_ACTIONTRIGGERPROPERTYSET_HXX_ <commit_msg>INTEGRATION: CWS ooo19126 (1.1.572); FILE MERGED 2005/09/05 13:04:06 rt 1.1.572.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: actiontriggerpropertyset.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-09 00:01:19 $ * * 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 __FRAMEWORK_CLASSES_ACTIONTRIGGERPROPERTYSET_HXX_ #define __FRAMEWORK_CLASSES_ACTIONTRIGGERPROPERTYSET_HXX_ #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef _CPPUHELPER_PROPSHLP_HXX #include <cppuhelper/propshlp.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef __COM_SUN_STAR_AWT_XBITMAP_HPP_ #include <com/sun/star/awt/XBitmap.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_ #include <com/sun/star/lang/XTypeProvider.hpp> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif #define SERVICENAME_ACTIONTRIGGER "com.sun.star.ui.ActionTrigger" #define IMPLEMENTATIONNAME_ACTIONTRIGGER "com.sun.star.comp.ui.ActionTrigger" namespace framework { class ActionTriggerPropertySet : public ThreadHelpBase , // Struct for right initalization of mutex member! Must be first of baseclasses. public ::com::sun::star::lang::XServiceInfo , public ::com::sun::star::lang::XTypeProvider, public ::cppu::OBroadcastHelper , public ::cppu::OPropertySetHelper , // -> XPropertySet, XFastPropertySet, XMultiPropertySet public ::cppu::OWeakObject { public: ActionTriggerPropertySet( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager ); virtual ~ActionTriggerPropertySet(); // XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire() throw (); virtual void SAL_CALL release() throw (); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException); // XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw (::com::sun::star::uno::RuntimeException); private: //--------------------------------------------------------------------------------------------------------- // OPropertySetHelper //--------------------------------------------------------------------------------------------------------- virtual sal_Bool SAL_CALL convertFastPropertyValue( com::sun::star::uno::Any& aConvertedValue, com::sun::star::uno::Any& aOldValue, sal_Int32 nHandle, const com::sun::star::uno::Any& aValue ) throw( com::sun::star::lang::IllegalArgumentException ); virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const com::sun::star::uno::Any& aValue ) throw( com::sun::star::uno::Exception ); virtual void SAL_CALL getFastPropertyValue( com::sun::star::uno::Any& aValue, sal_Int32 nHandle ) const; virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper(); virtual com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw (::com::sun::star::uno::RuntimeException); static const com::sun::star::uno::Sequence< com::sun::star::beans::Property > impl_getStaticPropertyDescriptor(); //--------------------------------------------------------------------------------------------------------- // helper //--------------------------------------------------------------------------------------------------------- sal_Bool impl_tryToChangeProperty( const rtl::OUString& aCurrentValue , const com::sun::star::uno::Any& aNewValue , com::sun::star::uno::Any& aOldValue , com::sun::star::uno::Any& aConvertedValue ) throw( com::sun::star::lang::IllegalArgumentException ); sal_Bool impl_tryToChangeProperty( const com::sun::star::uno::Reference< com::sun::star::awt::XBitmap > xBitmap, const com::sun::star::uno::Any& aNewValue , com::sun::star::uno::Any& aOldValue , com::sun::star::uno::Any& aConvertedValue ) throw( com::sun::star::lang::IllegalArgumentException ); sal_Bool impl_tryToChangeProperty( const com::sun::star::uno::Reference< com::sun::star::uno::XInterface > xInterface, const com::sun::star::uno::Any& aNewValue , com::sun::star::uno::Any& aOldValue , com::sun::star::uno::Any& aConvertedValue ) throw( com::sun::star::lang::IllegalArgumentException ); //--------------------------------------------------------------------------------------------------------- // members //--------------------------------------------------------------------------------------------------------- rtl::OUString m_aCommandURL; rtl::OUString m_aHelpURL; rtl::OUString m_aText; ::com::sun::star::uno::Reference< ::com::sun::star::awt::XBitmap > m_xBitmap; ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > m_xActionTriggerContainer; }; } #endif // __FRAMEWORK_CLASSES_ACTIONTRIGGERPROPERTYSET_HXX_ <|endoftext|>
<commit_before>#include "osg/ProxyNode" #include "osg/Notify" #include <osg/io_utils> #include "osgDB/Registry" #include "osgDB/Input" #include "osgDB/Output" #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osgDB/FileUtils> #include <osgDB/FileNameUtils> using namespace osg; using namespace osgDB; // forward declare functions to use later. bool ProxyNode_readLocalData(Object& obj, Input& fr); bool ProxyNode_writeLocalData(const Object& obj, Output& fw); // register the read and write functions with the osgDB::Registry. REGISTER_DOTOSGWRAPPER(ProxyNode) ( new osg::ProxyNode, "ProxyNode", "Object Node ProxyNode", &ProxyNode_readLocalData, &ProxyNode_writeLocalData ); bool ProxyNode_readLocalData(Object& obj, Input& fr) { bool iteratorAdvanced = false; ProxyNode& proxyNode = static_cast<ProxyNode&>(obj); if (fr.matchSequence("Center %f %f %f")) { Vec3 center; fr[1].getFloat(center[0]); fr[2].getFloat(center[1]); fr[3].getFloat(center[2]); proxyNode.setCenter(center); iteratorAdvanced = true; fr+=4; } else proxyNode.setCenterMode(osg::ProxyNode::USE_BOUNDING_SPHERE_CENTER); if (fr.matchSequence("ExtRefMode %s") || fr.matchSequence("ExtRefMode %w")) { if (fr[1].matchWord("LOAD_IMMEDIATELY")) proxyNode.setLoadingExternalReferenceMode(ProxyNode::LOAD_IMMEDIATELY); else if (fr[1].matchWord("DEFER_LOADING_TO_DATABASE_PAGER")) proxyNode.setLoadingExternalReferenceMode(ProxyNode::DEFER_LOADING_TO_DATABASE_PAGER); else if (fr[1].matchWord("NO_AUTOMATIC_LOADING")) proxyNode.setLoadingExternalReferenceMode(ProxyNode::NO_AUTOMATIC_LOADING); fr+=2; iteratorAdvanced = true; } float radius; if (fr[0].matchWord("Radius") && fr[1].getFloat(radius)) { proxyNode.setRadius(radius); fr+=2; iteratorAdvanced = true; } if (fr.getOptions() && !fr.getOptions()->getDatabasePathList().empty()) { const std::string& path = fr.getOptions()->getDatabasePathList().front(); if (!path.empty()) { proxyNode.setDatabasePath(path); } } bool matchFirst; if ((matchFirst=fr.matchSequence("FileNameList {")) || fr.matchSequence("FileNameList %i {")) { // set up coordinates. int entry = fr[0].getNoNestedBrackets(); if (matchFirst) { fr += 2; } else { fr += 3; } unsigned int i=0; while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { if (fr[0].isString() || fr[0].isQuotedString()) { if (fr[0].getStr()) proxyNode.setFileName(i,fr[0].getStr()); else proxyNode.setFileName(i,""); ++fr; ++i; } else { ++fr; } } iteratorAdvanced = true; ++fr; } unsigned int num_children = 0; if (fr[0].matchWord("num_children") && fr[1].getUInt(num_children)) { // could allocate space for children here... fr+=2; iteratorAdvanced = true; } unsigned int i; for(i=0; i<num_children; i++) { osgDB::FilePathList& fpl = ((osgDB::ReaderWriter::Options*)fr.getOptions())->getDatabasePathList(); fpl.push_front( fpl.empty() ? osgDB::getFilePath(proxyNode.getFileName(i)) : fpl.front()+'/'+ osgDB::getFilePath(proxyNode.getFileName(i))); Node* node = NULL; if((node=fr.readNode())!=NULL) { proxyNode.addChild(node); iteratorAdvanced = true; } fpl.pop_front(); } if(proxyNode.getLoadingExternalReferenceMode() == ProxyNode::LOAD_IMMEDIATELY) { for(i=0; i<proxyNode.getNumFileNames(); i++) { if(i>=proxyNode.getNumChildren() && !proxyNode.getFileName(i).empty()) { osgDB::FilePathList& fpl = ((osgDB::ReaderWriter::Options*)fr.getOptions())->getDatabasePathList(); fpl.push_front( fpl.empty() ? osgDB::getFilePath(proxyNode.getFileName(i)) : fpl.front()+'/'+ osgDB::getFilePath(proxyNode.getFileName(i))); osg::Node *node = osgDB::readNodeFile(proxyNode.getFileName(i), fr.getOptions()); fpl.pop_front(); if(node) { proxyNode.insertChild(i, node); } } } } return iteratorAdvanced; } bool ProxyNode_writeLocalData(const Object& obj, Output& fw) { bool includeExternalReferences = false; bool useOriginalExternalReferences = true; bool writeExternalReferenceFiles = false; if (fw.getOptions()) { std::string optionsString = fw.getOptions()->getOptionString(); includeExternalReferences = optionsString.find("includeExternalReferences")!=std::string::npos; bool newExternals = optionsString.find("writeExternalReferenceFiles")!=std::string::npos; if (newExternals) { useOriginalExternalReferences = false; writeExternalReferenceFiles = true; } } const ProxyNode& proxyNode = static_cast<const ProxyNode&>(obj); if (proxyNode.getCenterMode()==osg::ProxyNode::USER_DEFINED_CENTER) fw.indent() << "Center "<< proxyNode.getCenter() << std::endl; fw.indent() << "ExtRefMode "; switch(proxyNode.getLoadingExternalReferenceMode()) { case ProxyNode::LOAD_IMMEDIATELY: fw.indent() << "LOAD_IMMEDIATELY" <<std::endl; break; case ProxyNode::DEFER_LOADING_TO_DATABASE_PAGER: fw.indent() << "DEFER_LOADING_TO_DATABASE_PAGER" <<std::endl; break; case ProxyNode::NO_AUTOMATIC_LOADING: fw.indent() << "NO_AUTOMATIC_LOADING" <<std::endl; break; } fw.indent() << "Radius "<<proxyNode.getRadius()<<std::endl; fw.indent() << "FileNameList "<<proxyNode.getNumFileNames()<<" {"<< std::endl; fw.moveIn(); unsigned int numChildrenToWriteOut = 0; for(unsigned int i=0; i<proxyNode.getNumFileNames();++i) { if (proxyNode.getFileName(i).empty()) { fw.indent() << "\"\"" << std::endl; ++numChildrenToWriteOut; } else { if(useOriginalExternalReferences) { fw.indent() << proxyNode.getFileName(i) << std::endl; } else { std::string path = osgDB::getFilePath(fw.getFileName()); std::string new_filename = osgDB::getStrippedName(proxyNode.getFileName(i)) +".osg"; std::string osgname = path.empty() ? new_filename : (path +"/"+ new_filename) ; fw.indent() << osgname << std::endl; } } } fw.moveOut(); fw.indent() << "}"<< std::endl; if(includeExternalReferences) //out->getIncludeExternalReferences()) // inlined mode { fw.indent() << "num_children " << proxyNode.getNumChildren() << std::endl; for(unsigned int i=0; i<proxyNode.getNumChildren(); i++) { fw.writeObject(*proxyNode.getChild(i)); } } else //----------------------------------------- no inlined mode { fw.indent() << "num_children " << numChildrenToWriteOut << std::endl; for(unsigned int i=0; i<proxyNode.getNumChildren(); ++i) { if (proxyNode.getFileName(i).empty()) { fw.writeObject(*proxyNode.getChild(i)); } else if(writeExternalReferenceFiles) //out->getWriteExternalReferenceFiles()) { if(useOriginalExternalReferences) //out->getUseOriginalExternalReferences()) { std::string origname = proxyNode.getFileName(i); if (!fw.getExternalFileWritten(origname)) { osgDB::writeNodeFile(*proxyNode.getChild(i), origname); fw.setExternalFileWritten(origname, true); } } else { std::string path = osgDB::getFilePath(fw.getFileName()); std::string new_filename = osgDB::getStrippedName(proxyNode.getFileName(i)) +".osg"; std::string osgname = path.empty() ? new_filename : (path +"/"+ new_filename) ; if (!fw.getExternalFileWritten(osgname)) { osgDB::writeNodeFile(*proxyNode.getChild(i), osgname); fw.setExternalFileWritten(osgname, true); } } } } } return true; } <commit_msg>From Laurens Voerman, "I found a new way to crach the osgviewer: osgviewer "ProxyNode { FileNameList { cow.osgt } num_children 1 }".osgs<commit_after>#include "osg/ProxyNode" #include "osg/Notify" #include <osg/io_utils> #include "osgDB/Registry" #include "osgDB/Input" #include "osgDB/Output" #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osgDB/FileUtils> #include <osgDB/FileNameUtils> using namespace osg; using namespace osgDB; // forward declare functions to use later. bool ProxyNode_readLocalData(Object& obj, Input& fr); bool ProxyNode_writeLocalData(const Object& obj, Output& fw); // register the read and write functions with the osgDB::Registry. REGISTER_DOTOSGWRAPPER(ProxyNode) ( new osg::ProxyNode, "ProxyNode", "Object Node ProxyNode", &ProxyNode_readLocalData, &ProxyNode_writeLocalData ); bool ProxyNode_readLocalData(Object& obj, Input& fr) { bool iteratorAdvanced = false; ProxyNode& proxyNode = static_cast<ProxyNode&>(obj); if (fr.matchSequence("Center %f %f %f")) { Vec3 center; fr[1].getFloat(center[0]); fr[2].getFloat(center[1]); fr[3].getFloat(center[2]); proxyNode.setCenter(center); iteratorAdvanced = true; fr+=4; } else proxyNode.setCenterMode(osg::ProxyNode::USE_BOUNDING_SPHERE_CENTER); if (fr.matchSequence("ExtRefMode %s") || fr.matchSequence("ExtRefMode %w")) { if (fr[1].matchWord("LOAD_IMMEDIATELY")) proxyNode.setLoadingExternalReferenceMode(ProxyNode::LOAD_IMMEDIATELY); else if (fr[1].matchWord("DEFER_LOADING_TO_DATABASE_PAGER")) proxyNode.setLoadingExternalReferenceMode(ProxyNode::DEFER_LOADING_TO_DATABASE_PAGER); else if (fr[1].matchWord("NO_AUTOMATIC_LOADING")) proxyNode.setLoadingExternalReferenceMode(ProxyNode::NO_AUTOMATIC_LOADING); fr+=2; iteratorAdvanced = true; } float radius; if (fr[0].matchWord("Radius") && fr[1].getFloat(radius)) { proxyNode.setRadius(radius); fr+=2; iteratorAdvanced = true; } if (fr.getOptions() && !fr.getOptions()->getDatabasePathList().empty()) { const std::string& path = fr.getOptions()->getDatabasePathList().front(); if (!path.empty()) { proxyNode.setDatabasePath(path); } } bool matchFirst; if ((matchFirst=fr.matchSequence("FileNameList {")) || fr.matchSequence("FileNameList %i {")) { // set up coordinates. int entry = fr[0].getNoNestedBrackets(); if (matchFirst) { fr += 2; } else { fr += 3; } unsigned int i=0; while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { if (fr[0].isString() || fr[0].isQuotedString()) { if (fr[0].getStr()) proxyNode.setFileName(i,fr[0].getStr()); else proxyNode.setFileName(i,""); ++fr; ++i; } else { ++fr; } } iteratorAdvanced = true; ++fr; } unsigned int num_children = 0; if (fr[0].matchWord("num_children") && fr[1].getUInt(num_children)) { // could allocate space for children here... fr+=2; iteratorAdvanced = true; } bool make_options = (fr.getOptions() == NULL); if (make_options) fr.setOptions(new osgDB::Options()); //need valid options unsigned int i; for(i=0; i<num_children; i++) { osgDB::FilePathList& fpl = ((osgDB::ReaderWriter::Options*)fr.getOptions())->getDatabasePathList(); fpl.push_front( fpl.empty() ? osgDB::getFilePath(proxyNode.getFileName(i)) : fpl.front()+'/'+ osgDB::getFilePath(proxyNode.getFileName(i))); Node* node = NULL; if((node=fr.readNode())!=NULL) { proxyNode.addChild(node); iteratorAdvanced = true; } fpl.pop_front(); } if(proxyNode.getLoadingExternalReferenceMode() == ProxyNode::LOAD_IMMEDIATELY) { for(i=0; i<proxyNode.getNumFileNames(); i++) { if(i>=proxyNode.getNumChildren() && !proxyNode.getFileName(i).empty()) { osgDB::FilePathList& fpl = ((osgDB::ReaderWriter::Options*)fr.getOptions())->getDatabasePathList(); fpl.push_front( fpl.empty() ? osgDB::getFilePath(proxyNode.getFileName(i)) : fpl.front()+'/'+ osgDB::getFilePath(proxyNode.getFileName(i))); osg::Node *node = osgDB::readNodeFile(proxyNode.getFileName(i), fr.getOptions()); fpl.pop_front(); if(node) { proxyNode.insertChild(i, node); } } } } if (make_options) fr.setOptions(NULL); return iteratorAdvanced; } bool ProxyNode_writeLocalData(const Object& obj, Output& fw) { bool includeExternalReferences = false; bool useOriginalExternalReferences = true; bool writeExternalReferenceFiles = false; if (fw.getOptions()) { std::string optionsString = fw.getOptions()->getOptionString(); includeExternalReferences = optionsString.find("includeExternalReferences")!=std::string::npos; bool newExternals = optionsString.find("writeExternalReferenceFiles")!=std::string::npos; if (newExternals) { useOriginalExternalReferences = false; writeExternalReferenceFiles = true; } } const ProxyNode& proxyNode = static_cast<const ProxyNode&>(obj); if (proxyNode.getCenterMode()==osg::ProxyNode::USER_DEFINED_CENTER) fw.indent() << "Center "<< proxyNode.getCenter() << std::endl; fw.indent() << "ExtRefMode "; switch(proxyNode.getLoadingExternalReferenceMode()) { case ProxyNode::LOAD_IMMEDIATELY: fw.indent() << "LOAD_IMMEDIATELY" <<std::endl; break; case ProxyNode::DEFER_LOADING_TO_DATABASE_PAGER: fw.indent() << "DEFER_LOADING_TO_DATABASE_PAGER" <<std::endl; break; case ProxyNode::NO_AUTOMATIC_LOADING: fw.indent() << "NO_AUTOMATIC_LOADING" <<std::endl; break; } fw.indent() << "Radius "<<proxyNode.getRadius()<<std::endl; fw.indent() << "FileNameList "<<proxyNode.getNumFileNames()<<" {"<< std::endl; fw.moveIn(); unsigned int numChildrenToWriteOut = 0; for(unsigned int i=0; i<proxyNode.getNumFileNames();++i) { if (proxyNode.getFileName(i).empty()) { fw.indent() << "\"\"" << std::endl; ++numChildrenToWriteOut; } else { if(useOriginalExternalReferences) { fw.indent() << proxyNode.getFileName(i) << std::endl; } else { std::string path = osgDB::getFilePath(fw.getFileName()); std::string new_filename = osgDB::getStrippedName(proxyNode.getFileName(i)) +".osg"; std::string osgname = path.empty() ? new_filename : (path +"/"+ new_filename) ; fw.indent() << osgname << std::endl; } } } fw.moveOut(); fw.indent() << "}"<< std::endl; if(includeExternalReferences) //out->getIncludeExternalReferences()) // inlined mode { fw.indent() << "num_children " << proxyNode.getNumChildren() << std::endl; for(unsigned int i=0; i<proxyNode.getNumChildren(); i++) { fw.writeObject(*proxyNode.getChild(i)); } } else //----------------------------------------- no inlined mode { fw.indent() << "num_children " << numChildrenToWriteOut << std::endl; for(unsigned int i=0; i<proxyNode.getNumChildren(); ++i) { if (proxyNode.getFileName(i).empty()) { fw.writeObject(*proxyNode.getChild(i)); } else if(writeExternalReferenceFiles) //out->getWriteExternalReferenceFiles()) { if(useOriginalExternalReferences) //out->getUseOriginalExternalReferences()) { std::string origname = proxyNode.getFileName(i); if (!fw.getExternalFileWritten(origname)) { osgDB::writeNodeFile(*proxyNode.getChild(i), origname); fw.setExternalFileWritten(origname, true); } } else { std::string path = osgDB::getFilePath(fw.getFileName()); std::string new_filename = osgDB::getStrippedName(proxyNode.getFileName(i)) +".osg"; std::string osgname = path.empty() ? new_filename : (path +"/"+ new_filename) ; if (!fw.getExternalFileWritten(osgname)) { osgDB::writeNodeFile(*proxyNode.getChild(i), osgname); fw.setExternalFileWritten(osgname, true); } } } } } return true; } <|endoftext|>
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "recoveryvisitor.h" #include <vespa/documentapi/messagebus/messages/visitor.h> #include <vespa/vespalib/stllike/hash_map.hpp> #include <vespa/log/log.h> LOG_SETUP(".visitor.instance.recoveryvisitor"); namespace storage { RecoveryVisitor::RecoveryVisitor(StorageComponent& component, const vdslib::Parameters& params) : Visitor(component) { if (params.hasValue("requestfields")) { std::string fields = params.get("requestfields"); vespalib::StringTokenizer tokenizer(fields); for (uint32_t i = 0; i < tokenizer.size(); i++) { _requestedFields.insert(tokenizer[i]); } } LOG(debug, "Created RecoveryVisitor with %d requested fields", (int)_requestedFields.size()); } void RecoveryVisitor::handleDocuments(const document::BucketId& bid, std::vector<spi::DocEntry::LP>& entries, HitCounter& hitCounter) { vespalib::LockGuard guard(_mutex); LOG(debug, "Visitor %s handling block of %zu documents.", _id.c_str(), entries.size()); documentapi::DocumentListMessage* cmd = NULL; { CommandMap::iterator iter = _activeCommands.find(bid); if (iter == _activeCommands.end()) { CommandPtr ptr(new documentapi::DocumentListMessage(bid)); cmd = ptr.get(); _activeCommands[bid] = ptr; } else { cmd = iter->second.get(); } } // Remove all fields from the document that are not listed in requestedFields. for (size_t i = 0; i < entries.size(); ++i) { const spi::DocEntry& entry(*entries[i]); std::unique_ptr<document::Document> doc(entry.getDocument()->clone()); if (_requestedFields.empty()) { doc->clear(); } else { for (document::Document::const_iterator docIter = doc->begin(); docIter != doc->end(); docIter++) { if (_requestedFields.find(docIter.field().getName()) == _requestedFields.end()) { doc->remove(docIter.field()); } } } hitCounter.addHit(doc->getId(), doc->serialize()->getLength()); int64_t timestamp = doc->getLastModified(); cmd->getDocuments().push_back(documentapi::DocumentListMessage::Entry( timestamp, document::Document::SP(doc.release()), entry.isRemove())); } } void RecoveryVisitor::completedBucket(const document::BucketId& bid, HitCounter&) { documentapi::DocumentMessage::UP _msgToSend; LOG(debug, "Finished bucket %s", bid.toString().c_str()); { vespalib::LockGuard guard(_mutex); CommandMap::iterator iter = _activeCommands.find(bid); if (iter != _activeCommands.end()) { _msgToSend.reset(iter->second.release()); _activeCommands.erase(iter); } } if (_msgToSend.get()) { sendMessage(std::move(_msgToSend)); } } } <commit_msg>No more postfix operator.<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "recoveryvisitor.h" #include <vespa/documentapi/messagebus/messages/visitor.h> #include <vespa/vespalib/stllike/hash_map.hpp> #include <vespa/log/log.h> LOG_SETUP(".visitor.instance.recoveryvisitor"); namespace storage { RecoveryVisitor::RecoveryVisitor(StorageComponent& component, const vdslib::Parameters& params) : Visitor(component) { if (params.hasValue("requestfields")) { std::string fields = params.get("requestfields"); vespalib::StringTokenizer tokenizer(fields); for (uint32_t i = 0; i < tokenizer.size(); i++) { _requestedFields.insert(tokenizer[i]); } } LOG(debug, "Created RecoveryVisitor with %d requested fields", (int)_requestedFields.size()); } void RecoveryVisitor::handleDocuments(const document::BucketId& bid, std::vector<spi::DocEntry::LP>& entries, HitCounter& hitCounter) { vespalib::LockGuard guard(_mutex); LOG(debug, "Visitor %s handling block of %zu documents.", _id.c_str(), entries.size()); documentapi::DocumentListMessage* cmd = NULL; { CommandMap::iterator iter = _activeCommands.find(bid); if (iter == _activeCommands.end()) { CommandPtr ptr(new documentapi::DocumentListMessage(bid)); cmd = ptr.get(); _activeCommands[bid] = ptr; } else { cmd = iter->second.get(); } } // Remove all fields from the document that are not listed in requestedFields. for (size_t i = 0; i < entries.size(); ++i) { const spi::DocEntry& entry(*entries[i]); std::unique_ptr<document::Document> doc(entry.getDocument()->clone()); if (_requestedFields.empty()) { doc->clear(); } else { for (document::Document::const_iterator docIter = doc->begin(); docIter != doc->end(); ++docIter) { if (_requestedFields.find(docIter.field().getName()) == _requestedFields.end()) { doc->remove(docIter.field()); } } } hitCounter.addHit(doc->getId(), doc->serialize()->getLength()); int64_t timestamp = doc->getLastModified(); cmd->getDocuments().push_back(documentapi::DocumentListMessage::Entry( timestamp, document::Document::SP(doc.release()), entry.isRemove())); } } void RecoveryVisitor::completedBucket(const document::BucketId& bid, HitCounter&) { documentapi::DocumentMessage::UP _msgToSend; LOG(debug, "Finished bucket %s", bid.toString().c_str()); { vespalib::LockGuard guard(_mutex); CommandMap::iterator iter = _activeCommands.find(bid); if (iter != _activeCommands.end()) { _msgToSend.reset(iter->second.release()); _activeCommands.erase(iter); } } if (_msgToSend.get()) { sendMessage(std::move(_msgToSend)); } } } <|endoftext|>
<commit_before>#include <windows.h> #include "PopupMenu.hpp" #define TRAY_ID 666 #define TRAY_MSG 666 struct WindowData { PopupMenu* menu; }; void HandleMenuSelection(PopupMenu::MenuItem item, HWND window) { WindowData* data = (WindowData*)GetWindowLongPtr(window, GWLP_USERDATA); if(item.id == data->menu->GetIdByTitle("exit")) SendMessage(window, WM_CLOSE, 0, 0); } LRESULT CALLBACK HitmonWindowProc( HWND window, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { // Handle messages from tray icon case TRAY_MSG: { switch(lParam) { case WM_LBUTTONDOWN: { WindowData* data = (WindowData*)GetWindowLongPtr(window, GWLP_USERDATA); data->menu->Show(); }break; } }break; case WM_CREATE: { // Configure window data WindowData* data = new WindowData(); data->menu = new PopupMenu(window, HandleMenuSelection); data->menu->AddItem(1, "Do something"); data->menu->AddItem(2, "Do something else"); data->menu->AddItem(3, "exit"); // Set userdata SetWindowLongPtr(window, GWLP_USERDATA, (LONG_PTR)data); }break; case WM_DESTROY: { WindowData* data = (WindowData*)GetWindowLongPtr(window, GWLP_USERDATA); delete data->menu; delete data; PostQuitMessage(0); }break; default: { return DefWindowProc(window, msg, wParam, lParam); } } return 0; } WNDCLASSEX CreateWindowClass(HINSTANCE instance) { WNDCLASSEX mainWClass; mainWClass.cbSize = sizeof(WNDCLASSEX); mainWClass.style = CS_HREDRAW | CS_VREDRAW; mainWClass.lpfnWndProc = HitmonWindowProc; mainWClass.cbClsExtra = 0; mainWClass.cbWndExtra = 0; mainWClass.hInstance = instance; mainWClass.hIcon = LoadIcon(0, IDI_SHIELD); mainWClass.hCursor = LoadCursor(0, IDC_CROSS); mainWClass.hbrBackground = 0; mainWClass.lpszMenuName = 0; mainWClass.lpszClassName = "MainWClass"; mainWClass.hIconSm = 0; return mainWClass; } NOTIFYICONDATA ShowTrayIcon(HWND window) { NOTIFYICONDATA rVal; rVal.cbSize = sizeof(rVal); rVal.hWnd = window; rVal.uID = TRAY_ID; rVal.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; rVal.uCallbackMessage = TRAY_MSG; rVal.hIcon = LoadIcon(0, IDI_SHIELD); strncpy(rVal.szTip, "Hitmon is running...", 128); // Set guid later //rVal.guidItem = ...; Shell_NotifyIcon(NIM_ADD, &rVal); return rVal; } int CALLBACK WinMain( HINSTANCE instance, HINSTANCE prevInstance, LPSTR cmdArgs, int cmdShow) { (void)prevInstance; (void)cmdArgs; (void)cmdShow; // Create window class WNDCLASSEX mainWClass = CreateWindowClass(instance); // Register window class if(RegisterClassEx(&mainWClass) == 0) return -1; // Create window HWND window = CreateWindowEx( 0, // Extended window style of the window created "MainWClass", // Class name from previous call to RegisterClass[Ex] "Hitmon", // Window Name 0, // Window style 64, // Initial x position for window 64, // Initial y position for window 640, // Window width 480, // Window height 0, // Handle to parent window 0, // Handle to menu instance, // A handle to the instance of the module to be associated with the window. 0); // Pointer to params for the window if(window == 0) return -1; // Show tray icon NOTIFYICONDATA trayData = ShowTrayIcon(window); MSG msg; int getMsgRVal; while((getMsgRVal = GetMessage(&msg, 0, 0, 0)) != 0) { if(getMsgRVal == -1) return -1; TranslateMessage(&msg); DispatchMessage(&msg); } // Hide tray icon Shell_NotifyIcon(NIM_DELETE, &trayData); return 0; }<commit_msg>Fixed message loop and pre-defined message IDs<commit_after>#include <windows.h> #include "PopupMenu.hpp" #define TRAY_ID WM_USER + 1 #define TRAY_MSG WM_USER + 2 struct WindowData { PopupMenu* menu; }; void HandleMenuSelection(PopupMenu::MenuItem item, HWND window) { WindowData* data = (WindowData*)GetWindowLongPtr(window, GWLP_USERDATA); if(item.id == data->menu->GetIdByTitle("exit")) SendMessage(window, WM_CLOSE, 0, 0); } LRESULT CALLBACK HitmonWindowProc( HWND window, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { // Handle messages from tray icon case TRAY_MSG: { switch(lParam) { case WM_LBUTTONDOWN: { WindowData* data = (WindowData*)GetWindowLongPtr(window, GWLP_USERDATA); data->menu->Show(); }break; } }break; case WM_CREATE: { // Configure window data WindowData* data = new WindowData(); data->menu = new PopupMenu(window, HandleMenuSelection); data->menu->AddItem(1, "Do something"); data->menu->AddItem(2, "Do something else"); data->menu->AddItem(3, "exit"); // Set userdata SetWindowLongPtr(window, GWLP_USERDATA, (LONG_PTR)data); }break; case WM_DESTROY: { WindowData* data = (WindowData*)GetWindowLongPtr(window, GWLP_USERDATA); delete data->menu; delete data; PostQuitMessage(0); }break; default: { return DefWindowProc(window, msg, wParam, lParam); } } return 0; } WNDCLASSEX CreateWindowClass(HINSTANCE instance) { WNDCLASSEX mainWClass; mainWClass.cbSize = sizeof(WNDCLASSEX); mainWClass.style = CS_HREDRAW | CS_VREDRAW; mainWClass.lpfnWndProc = HitmonWindowProc; mainWClass.cbClsExtra = 0; mainWClass.cbWndExtra = 0; mainWClass.hInstance = instance; mainWClass.hIcon = LoadIcon(0, IDI_SHIELD); mainWClass.hCursor = LoadCursor(0, IDC_CROSS); mainWClass.hbrBackground = 0; mainWClass.lpszMenuName = 0; mainWClass.lpszClassName = "MainWClass"; mainWClass.hIconSm = 0; return mainWClass; } NOTIFYICONDATA ShowTrayIcon(HWND window) { NOTIFYICONDATA rVal; rVal.cbSize = sizeof(rVal); rVal.hWnd = window; rVal.uID = TRAY_ID; rVal.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; rVal.uCallbackMessage = TRAY_MSG; rVal.hIcon = LoadIcon(0, IDI_SHIELD); strncpy(rVal.szTip, "Hitmon is running...", 128); // Set guid later //rVal.guidItem = ...; Shell_NotifyIcon(NIM_ADD, &rVal); return rVal; } int CALLBACK WinMain( HINSTANCE instance, HINSTANCE prevInstance, LPSTR cmdArgs, int cmdShow) { (void)prevInstance; (void)cmdArgs; (void)cmdShow; // Create window class WNDCLASSEX mainWClass = CreateWindowClass(instance); // Register window class if(RegisterClassEx(&mainWClass) == 0) return -1; // Create window HWND window = CreateWindowEx( 0, // Extended window style of the window created "MainWClass", // Class name from previous call to RegisterClass[Ex] "Hitmon", // Window Name 0, // Window style 64, // Initial x position for window 64, // Initial y position for window 640, // Window width 480, // Window height 0, // Handle to parent window 0, // Handle to menu instance, // A handle to the instance of the module to be associated with the window. 0); // Pointer to params for the window if(window == 0) return -1; // Show tray icon NOTIFYICONDATA trayData = ShowTrayIcon(window); MSG msg; int getMsgRVal; while((getMsgRVal = GetMessage(&msg, 0, 0, 0)) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } // Hide tray icon Shell_NotifyIcon(NIM_DELETE, &trayData); return 0; }<|endoftext|>
<commit_before>/* Copyright(C) 2014 Naoya Murakami <[email protected]> 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 */ #include <groonga/tokenizer.h> #include <string.h> #include <ctype.h> #include <iostream> #include <string> #include <vector> #include "tinysegmenter.hpp" using namespace std; #ifdef __GNUC__ # define GNUC_UNUSED __attribute__((__unused__)) #else # define GNUC_UNUSED #endif typedef struct { grn_tokenizer_token token; grn_tokenizer_query *query; vector<string> parsed_vector; unsigned int next; unsigned int end; } grn_tinysegmenter_tokenizer; static grn_obj * tinysegmenter_init(grn_ctx *ctx, int nargs, grn_obj **args, grn_user_data *user_data) { grn_tokenizer_query *query; unsigned int normalize_flags = 0; const char *normalized; unsigned int normalized_length_in_bytes; grn_tinysegmenter_tokenizer *tokenizer; TinySegmenter segmenter; query = grn_tokenizer_query_open(ctx, nargs, args, normalize_flags); if (!query) { return NULL; } tokenizer = static_cast<grn_tinysegmenter_tokenizer *>( GRN_PLUGIN_MALLOC(ctx, sizeof(grn_tinysegmenter_tokenizer))); if (!tokenizer) { GRN_PLUGIN_ERROR(ctx,GRN_NO_MEMORY_AVAILABLE, "[tokenizer][tinysegmenter] " "memory allocation to grn_tinysegmenter_tokenizer failed"); grn_tokenizer_query_close(ctx, query); return NULL; } user_data->ptr = tokenizer; grn_tokenizer_token_init(ctx, &(tokenizer->token)); tokenizer->query = query; grn_string_get_normalized(ctx, tokenizer->query->normalized_query, &normalized, &normalized_length_in_bytes, NULL); tokenizer->parsed_vector = segmenter.segment(normalized); tokenizer->next = 0; tokenizer->end = tokenizer->parsed_vector.size(); return NULL; } static grn_obj * tinysegmenter_next(grn_ctx *ctx, GNUC_UNUSED int nargs, GNUC_UNUSED grn_obj **args, grn_user_data *user_data) { grn_tinysegmenter_tokenizer *tokenizer = static_cast<grn_tinysegmenter_tokenizer *>(user_data->ptr); grn_tokenizer_status status; if (tokenizer->next == tokenizer->end - 1) { status = GRN_TOKENIZER_LAST; } else { status = GRN_TOKENIZER_CONTINUE; } grn_tokenizer_token_push(ctx, &(tokenizer->token), tokenizer->parsed_vector[tokenizer->next].c_str(), tokenizer->parsed_vector[tokenizer->next].length(), status); tokenizer->next++; return NULL; } static grn_obj * tinysegmenter_fin(grn_ctx *ctx, GNUC_UNUSED int nargs, GNUC_UNUSED grn_obj **args, grn_user_data *user_data) { grn_tinysegmenter_tokenizer *tokenizer = static_cast<grn_tinysegmenter_tokenizer *>(user_data->ptr); if (!tokenizer) { return NULL; } grn_tokenizer_query_close(ctx, tokenizer->query); grn_tokenizer_token_fin(ctx, &(tokenizer->token)); GRN_PLUGIN_FREE(ctx,tokenizer); return NULL; } extern "C" { grn_rc GRN_PLUGIN_INIT(grn_ctx *ctx) { return ctx->rc; } grn_rc GRN_PLUGIN_REGISTER(grn_ctx *ctx) { grn_rc rc; rc = grn_tokenizer_register(ctx, "TokenTinySegmenter", -1, tinysegmenter_init, tinysegmenter_next, tinysegmenter_fin); return rc; } grn_rc GRN_PLUGIN_FIN(grn_ctx *ctx) { return GRN_SUCCESS; } } <commit_msg>Indent<commit_after>/* Copyright(C) 2014 Naoya Murakami <[email protected]> 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 */ #include <groonga/tokenizer.h> #include <string.h> #include <ctype.h> #include <iostream> #include <string> #include <vector> #include "tinysegmenter.hpp" using namespace std; #ifdef __GNUC__ # define GNUC_UNUSED __attribute__((__unused__)) #else # define GNUC_UNUSED #endif typedef struct { grn_tokenizer_token token; grn_tokenizer_query *query; vector<string> parsed_vector; unsigned int next; unsigned int end; } grn_tinysegmenter_tokenizer; static grn_obj * tinysegmenter_init(grn_ctx *ctx, int nargs, grn_obj **args, grn_user_data *user_data) { grn_tokenizer_query *query; unsigned int normalize_flags = 0; const char *normalized; unsigned int normalized_length_in_bytes; grn_tinysegmenter_tokenizer *tokenizer; TinySegmenter segmenter; query = grn_tokenizer_query_open(ctx, nargs, args, normalize_flags); if (!query) { return NULL; } tokenizer = static_cast<grn_tinysegmenter_tokenizer *>( GRN_PLUGIN_MALLOC(ctx, sizeof(grn_tinysegmenter_tokenizer))); if (!tokenizer) { GRN_PLUGIN_ERROR(ctx,GRN_NO_MEMORY_AVAILABLE, "[tokenizer][tinysegmenter] " "memory allocation to grn_tinysegmenter_tokenizer failed"); grn_tokenizer_query_close(ctx, query); return NULL; } user_data->ptr = tokenizer; grn_tokenizer_token_init(ctx, &(tokenizer->token)); tokenizer->query = query; grn_string_get_normalized(ctx, tokenizer->query->normalized_query, &normalized, &normalized_length_in_bytes, NULL); tokenizer->parsed_vector = segmenter.segment(normalized); tokenizer->next = 0; tokenizer->end = tokenizer->parsed_vector.size(); return NULL; } static grn_obj * tinysegmenter_next(grn_ctx *ctx, GNUC_UNUSED int nargs, GNUC_UNUSED grn_obj **args, grn_user_data *user_data) { grn_tinysegmenter_tokenizer *tokenizer = static_cast<grn_tinysegmenter_tokenizer *>(user_data->ptr); grn_tokenizer_status status; if (tokenizer->next == tokenizer->end - 1) { status = GRN_TOKENIZER_LAST; } else { status = GRN_TOKENIZER_CONTINUE; } grn_tokenizer_token_push(ctx, &(tokenizer->token), tokenizer->parsed_vector[tokenizer->next].c_str(), tokenizer->parsed_vector[tokenizer->next].length(), status); tokenizer->next++; return NULL; } static grn_obj * tinysegmenter_fin(grn_ctx *ctx, GNUC_UNUSED int nargs, GNUC_UNUSED grn_obj **args, grn_user_data *user_data) { grn_tinysegmenter_tokenizer *tokenizer = static_cast<grn_tinysegmenter_tokenizer *>(user_data->ptr); if (!tokenizer) { return NULL; } grn_tokenizer_query_close(ctx, tokenizer->query); grn_tokenizer_token_fin(ctx, &(tokenizer->token)); GRN_PLUGIN_FREE(ctx,tokenizer); return NULL; } extern "C" { grn_rc GRN_PLUGIN_INIT(grn_ctx *ctx) { return ctx->rc; } grn_rc GRN_PLUGIN_REGISTER(grn_ctx *ctx) { grn_rc rc; rc = grn_tokenizer_register(ctx, "TokenTinySegmenter", -1, tinysegmenter_init, tinysegmenter_next, tinysegmenter_fin); return rc; } grn_rc GRN_PLUGIN_FIN(grn_ctx *ctx) { return GRN_SUCCESS; } } <|endoftext|>
<commit_before>/* * Main.cpp * * Created on: Mar 17, 2015 * Author: jonno */ #include <iostream> #include <cstdio> #include <sha.h> #include <memory> #include "Chord.h" using namespace std; void showUsageMessage(string procname) { cerr << "To run Chord, you need to provide a port to listen on." << endl; cerr << "\tUsage: " << procname << " port" << endl; cerr << "\tExample: " << procname << " 8001" << endl; cerr << "If you are connecting to an existing Chord network, use the following:" << endl; cerr << "\t" << procname << " port [entry point IP address] [entry point port]" << endl; cerr << "\tExample: " << procname << " 8001 128.2.205.42 8010" << endl; exit(1); } int main(int argc, const char* argv[]) { string port; string entry_ip, entry_port; unique_ptr<Chord> chord; int listen_port; if (argc < 2) { showUsageMessage(argv[0]); } // port to listen on if (argc > 1) { port = argv[1]; } // connecting to an entry point if (argc > 2) { entry_ip = argv[2]; } // entry point port if (argc > 3) { entry_port = argv[3]; } if (!entry_ip.empty() && entry_port.empty()) { showUsageMessage(argv[0]); } listen_port = atoi(port.c_str()); chord = unique_ptr<Chord>(new Chord(listen_port)); if (entry_ip.empty()) { } if (!entry_ip.empty() && !entry_port.empty()) { int entry_port_i = atoi(entry_port.c_str()); chord->JoinRing(entry_ip, entry_port_i); } chord->Listen(); return 0; } <commit_msg>MAde Main work with Singleton<commit_after>/* * Main.cpp * * Created on: Mar 17, 2015 * Author: jonno */ #include <iostream> #include <cstdio> #include <sha.h> #include <memory> #include "Chord.h" using namespace std; void showUsageMessage(string procname) { cerr << "To run Chord, you need to provide a port to listen on." << endl; cerr << "\tUsage: " << procname << " port" << endl; cerr << "\tExample: " << procname << " 8001" << endl; cerr << "If you are connecting to an existing Chord network, use the following:" << endl; cerr << "\t" << procname << " port [entry point IP address] [entry point port]" << endl; cerr << "\tExample: " << procname << " 8001 128.2.205.42 8010" << endl; exit(1); } int main(int argc, const char* argv[]) { string port; string entry_ip, entry_port; shared_ptr<Chord> chord; int listen_port; if (argc < 2) { showUsageMessage(argv[0]); } // port to listen on if (argc > 1) { port = argv[1]; } // connecting to an entry point if (argc > 2) { entry_ip = argv[2]; } // entry point port if (argc > 3) { entry_port = argv[3]; } if (!entry_ip.empty() && entry_port.empty()) { showUsageMessage(argv[0]); } listen_port = atoi(port.c_str()); chord = Chord::getInstance(); if (chord != nullptr) { chord->init(listen_port); } if (entry_ip.empty()) { } if (!entry_ip.empty() && !entry_port.empty()) { int entry_port_i = atoi(entry_port.c_str()); chord->JoinRing(entry_ip, entry_port_i); } chord->Listen(); return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <fstream> #include "paddle/fluid/framework/data_type_transform.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/platform/device_context.h" namespace paddle { namespace operators { class LoadCombineOp : public framework::OperatorBase { public: LoadCombineOp(const std::string &type, const framework::VariableNameMap &inputs, const framework::VariableNameMap &outputs, const framework::AttributeMap &attrs) : OperatorBase(type, inputs, outputs, attrs) {} private: void RunImpl(const framework::Scope &scope, const platform::Place &place) const override { auto filename = Attr<std::string>("file_path"); auto load_as_fp16 = Attr<bool>("load_as_fp16"); auto model_from_memory = Attr<bool>("model_from_memory"); auto out_var_names = Outputs("Out"); PADDLE_ENFORCE_GT( static_cast<int>(out_var_names.size()), 0, "The number of output variables should be greater than 0."); if (!model_from_memory) { std::ifstream fin(filename, std::ios::binary); PADDLE_ENFORCE(static_cast<bool>(fin), "Cannot open file %s for load_combine op", filename); LoadParamsFromBuffer(scope, place, &fin, load_as_fp16, out_var_names); } else { PADDLE_ENFORCE(!filename.empty(), "Cannot load file from memory"); std::stringstream fin(filename); LoadParamsFromBuffer(scope, place, &fin, load_as_fp16, out_var_names); } } void LoadParamsFromBuffer( const framework::Scope &scope, const platform::Place &place, std::istream *buffer, bool load_as_fp16, const std::vector<std::string> &out_var_names) const { platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance(); auto &dev_ctx = *pool.Get(place); for (size_t i = 0; i < out_var_names.size(); i++) { auto *out_var = scope.FindVar(out_var_names[i]); PADDLE_ENFORCE(out_var != nullptr, "Output variable %s cannot be found", out_var_names[i]); auto *tensor = out_var->GetMutable<framework::LoDTensor>(); // Error checking PADDLE_ENFORCE(static_cast<bool>(buffer), "Cannot read more"); // Get data from fin to tensor DeserializeFromStream(*buffer, tensor, dev_ctx); auto in_dtype = tensor->type(); auto out_dtype = load_as_fp16 ? framework::proto::VarType::FP16 : in_dtype; if (in_dtype != out_dtype) { // convert to float16 tensor auto in_kernel_type = framework::OpKernelType(in_dtype, place); auto out_kernel_type = framework::OpKernelType(out_dtype, place); framework::LoDTensor fp16_tensor; // copy LoD info to the new tensor fp16_tensor.set_lod(tensor->lod()); framework::TransDataType(in_kernel_type, out_kernel_type, *tensor, &fp16_tensor); // reset output tensor out_var->Clear(); tensor = out_var->GetMutable<framework::LoDTensor>(); tensor->set_lod(fp16_tensor.lod()); tensor->ShareDataWith(fp16_tensor); } } } }; class LoadCombineOpProtoMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddOutput( "Out", "(vector) The output LoDTensors that will be read from the input file.") .AsDuplicable(); AddAttr<bool>( "load_as_fp16", "(boolean, default false)" "If true, the tensor will be first loaded and then " "converted to float16 data type. Otherwise, the tensor will be " "directly loaded without data type conversion.") .SetDefault(false); AddAttr<std::string>("file_path", "(string) " "LoDTensors will be loaded from \"file_path\".") .AddCustomChecker( [](const std::string &path) { return !path.empty(); }); AddAttr<bool>("model_from_memory", "(boolean, default false)" "If true, file_path is in memory, and LoDTensors will be " "loaded directly from memory") .SetDefault(false); AddComment(R"DOC( LoadCombine Operator. LoadCombine operator loads LoDTensor variables from a file, which could be loaded in memory already. The file should contain one or more LoDTensors serialized using the SaveCombine operator. The LoadCombine operator applies a deserialization strategy to appropriately load the LodTensors, and this strategy complements the serialization strategy used in the SaveCombine operator. Hence, the LoadCombine operator is tightly coupled with the SaveCombine operator, and can only deserialize one or more LoDTensors that were saved using the SaveCombine operator. )DOC"); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(load_combine, ops::LoadCombineOp, ops::LoadCombineOpProtoMaker); <commit_msg>fix unittest test=develop<commit_after>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <fstream> #include "paddle/fluid/framework/data_type_transform.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/platform/device_context.h" namespace paddle { namespace operators { class LoadCombineOp : public framework::OperatorBase { public: LoadCombineOp(const std::string &type, const framework::VariableNameMap &inputs, const framework::VariableNameMap &outputs, const framework::AttributeMap &attrs) : OperatorBase(type, inputs, outputs, attrs) {} private: void RunImpl(const framework::Scope &scope, const platform::Place &place) const override { auto filename = Attr<std::string>("file_path"); auto load_as_fp16 = Attr<bool>("load_as_fp16"); auto model_from_memory = Attr<bool>("model_from_memory"); auto out_var_names = Outputs("Out"); PADDLE_ENFORCE_GT( static_cast<int>(out_var_names.size()), 0, "The number of output variables should be greater than 0."); if (!model_from_memory) { std::ifstream fin(filename, std::ios::binary); PADDLE_ENFORCE(static_cast<bool>(fin), "Cannot open file %s for load_combine op", filename); LoadParamsFromBuffer(scope, place, &fin, load_as_fp16, out_var_names); } else { PADDLE_ENFORCE(!filename.empty(), "Cannot load file from memory"); std::stringstream fin(filename, std::ios::in | std::ios::binary); LoadParamsFromBuffer(scope, place, &fin, load_as_fp16, out_var_names); } } void LoadParamsFromBuffer( const framework::Scope &scope, const platform::Place &place, std::istream *buffer, bool load_as_fp16, const std::vector<std::string> &out_var_names) const { platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance(); auto &dev_ctx = *pool.Get(place); for (size_t i = 0; i < out_var_names.size(); i++) { auto *out_var = scope.FindVar(out_var_names[i]); PADDLE_ENFORCE(out_var != nullptr, "Output variable %s cannot be found", out_var_names[i]); auto *tensor = out_var->GetMutable<framework::LoDTensor>(); // Error checking PADDLE_ENFORCE(static_cast<bool>(buffer), "Cannot read more"); // Get data from fin to tensor DeserializeFromStream(*buffer, tensor, dev_ctx); auto in_dtype = tensor->type(); auto out_dtype = load_as_fp16 ? framework::proto::VarType::FP16 : in_dtype; if (in_dtype != out_dtype) { // convert to float16 tensor auto in_kernel_type = framework::OpKernelType(in_dtype, place); auto out_kernel_type = framework::OpKernelType(out_dtype, place); framework::LoDTensor fp16_tensor; // copy LoD info to the new tensor fp16_tensor.set_lod(tensor->lod()); framework::TransDataType(in_kernel_type, out_kernel_type, *tensor, &fp16_tensor); // reset output tensor out_var->Clear(); tensor = out_var->GetMutable<framework::LoDTensor>(); tensor->set_lod(fp16_tensor.lod()); tensor->ShareDataWith(fp16_tensor); } } } }; class LoadCombineOpProtoMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddOutput( "Out", "(vector) The output LoDTensors that will be read from the input file.") .AsDuplicable(); AddAttr<bool>( "load_as_fp16", "(boolean, default false)" "If true, the tensor will be first loaded and then " "converted to float16 data type. Otherwise, the tensor will be " "directly loaded without data type conversion.") .SetDefault(false); AddAttr<std::string>("file_path", "(string) " "LoDTensors will be loaded from \"file_path\".") .AddCustomChecker( [](const std::string &path) { return !path.empty(); }); AddAttr<bool>("model_from_memory", "(boolean, default false)" "If true, file_path is in memory, and LoDTensors will be " "loaded directly from memory") .SetDefault(false); AddComment(R"DOC( LoadCombine Operator. LoadCombine operator loads LoDTensor variables from a file, which could be loaded in memory already. The file should contain one or more LoDTensors serialized using the SaveCombine operator. The LoadCombine operator applies a deserialization strategy to appropriately load the LodTensors, and this strategy complements the serialization strategy used in the SaveCombine operator. Hence, the LoadCombine operator is tightly coupled with the SaveCombine operator, and can only deserialize one or more LoDTensors that were saved using the SaveCombine operator. )DOC"); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(load_combine, ops::LoadCombineOp, ops::LoadCombineOpProtoMaker); <|endoftext|>
<commit_before>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include <vistk/scoring/scoring_result.h> #include <vistk/python/any_conversion/prototypes.h> #include <vistk/python/any_conversion/registration.h> #include <boost/python/class.hpp> #include <boost/python/module.hpp> #include <boost/make_shared.hpp> /** * \file scoring_result.cxx * * \brief Python bindings for scoring_result. */ using namespace boost::python; static vistk::scoring_result_t new_result(vistk::scoring_result::count_t hit, vistk::scoring_result::count_t miss, vistk::scoring_result::count_t truth); static vistk::scoring_result::count_t result_get_hit(vistk::scoring_result_t const& self); static vistk::scoring_result::count_t result_get_miss(vistk::scoring_result_t const& self); static vistk::scoring_result::count_t result_get_truth(vistk::scoring_result_t const& self); static vistk::scoring_result::result_t result_get_percent_detection(vistk::scoring_result_t const& self); static vistk::scoring_result::result_t result_get_precision(vistk::scoring_result_t const& self); BOOST_PYTHON_MODULE(scoring_result) { class_<vistk::scoring_result_t>("ScoringResult" , "A result from a scoring algorithm." , no_init) .def("__init__", &new_result , (arg("hit"), arg("miss"), arg("truth")) , "Constructor.") .def("hit_count", &result_get_hit) .def("miss_count", &result_get_miss) .def("truth_count", &result_get_truth) .def("percent_detection", &result_get_percent_detection) .def("precision", &result_get_precision) ; vistk::python::register_type<vistk::scoring_result_t>(20); } vistk::scoring_result_t new_result(vistk::scoring_result::count_t hit, vistk::scoring_result::count_t miss, vistk::scoring_result::count_t truth) { return boost::make_shared<vistk::scoring_result>(hit, miss, truth); } vistk::scoring_result::count_t result_get_hit(vistk::scoring_result_t const& self) { return self->hit_count; } vistk::scoring_result::count_t result_get_miss(vistk::scoring_result_t const& self) { return self->miss_count; } vistk::scoring_result::count_t result_get_truth(vistk::scoring_result_t const& self) { return self->truth_count; } vistk::scoring_result::result_t result_get_percent_detection(vistk::scoring_result_t const& self) { return self->percent_detection(); } vistk::scoring_result::result_t result_get_precision(vistk::scoring_result_t const& self) { return self->precision(); } <commit_msg>Bind scoring addition in Python<commit_after>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include <vistk/scoring/scoring_result.h> #include <vistk/python/any_conversion/prototypes.h> #include <vistk/python/any_conversion/registration.h> #include <boost/python/class.hpp> #include <boost/python/module.hpp> #include <boost/make_shared.hpp> /** * \file scoring_result.cxx * * \brief Python bindings for scoring_result. */ using namespace boost::python; static vistk::scoring_result_t new_result(vistk::scoring_result::count_t hit, vistk::scoring_result::count_t miss, vistk::scoring_result::count_t truth); static vistk::scoring_result::count_t result_get_hit(vistk::scoring_result_t const& self); static vistk::scoring_result::count_t result_get_miss(vistk::scoring_result_t const& self); static vistk::scoring_result::count_t result_get_truth(vistk::scoring_result_t const& self); static vistk::scoring_result::result_t result_get_percent_detection(vistk::scoring_result_t const& self); static vistk::scoring_result::result_t result_get_precision(vistk::scoring_result_t const& self); static vistk::scoring_result_t result_add(vistk::scoring_result_t const& lhs, vistk::scoring_result_t const& rhs); BOOST_PYTHON_MODULE(scoring_result) { class_<vistk::scoring_result_t>("ScoringResult" , "A result from a scoring algorithm." , no_init) .def("__init__", &new_result , (arg("hit"), arg("miss"), arg("truth")) , "Constructor.") .def("hit_count", &result_get_hit) .def("miss_count", &result_get_miss) .def("truth_count", &result_get_truth) .def("percent_detection", &result_get_percent_detection) .def("precision", &result_get_precision) .def("__add__", &result_add , (arg("lhs"), arg("rhs"))) ; vistk::python::register_type<vistk::scoring_result_t>(20); } vistk::scoring_result_t new_result(vistk::scoring_result::count_t hit, vistk::scoring_result::count_t miss, vistk::scoring_result::count_t truth) { return boost::make_shared<vistk::scoring_result>(hit, miss, truth); } vistk::scoring_result::count_t result_get_hit(vistk::scoring_result_t const& self) { return self->hit_count; } vistk::scoring_result::count_t result_get_miss(vistk::scoring_result_t const& self) { return self->miss_count; } vistk::scoring_result::count_t result_get_truth(vistk::scoring_result_t const& self) { return self->truth_count; } vistk::scoring_result::result_t result_get_percent_detection(vistk::scoring_result_t const& self) { return self->percent_detection(); } vistk::scoring_result::result_t result_get_precision(vistk::scoring_result_t const& self) { return self->precision(); } vistk::scoring_result_t result_add(vistk::scoring_result_t const& lhs, vistk::scoring_result_t const& rhs) { return (lhs + rhs); } <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2010 Dennis Nienhüser <[email protected]> // #include "MarbleDeclarativePlugin.h" #include "Coordinate.h" #include "DeclarativeMapThemeManager.h" #include "MarbleDeclarativeWidget.h" #include "PositionSource.h" #include "Tracking.h" #include "Routing.h" #include "Search.h" #include "RouteRequestModel.h" #include "ActivityModel.h" #include "Activity.h" #include "RelatedActivities.h" #include "Settings.h" #include <QtDeclarative/qdeclarative.h> #include <QtDeclarative/QDeclarativeEngine> namespace Marble { namespace Declarative { void MarbleDeclarativePlugin::registerTypes( const char * ) { const char* uri = "org.kde.edu.marble"; qmlRegisterType<Marble::Declarative::Coordinate>( uri, 0, 11, "Coordinate" ); qmlRegisterType<Marble::Declarative::PositionSource>( uri, 0, 11, "PositionSource" ); qmlRegisterType<Marble::Declarative::Tracking>( uri, 0, 11, "Tracking" ); qmlRegisterType<Marble::Declarative::Routing>( uri, 0, 11, "Routing" ); qmlRegisterType<Marble::Declarative::Search>( uri, 0, 11, "Search" ); qmlRegisterType<Marble::Declarative::RouteRequestModel>( uri, 0, 11, "RouteRequestModel" ); qmlRegisterType<Marble::Declarative::ActivityModel>( uri, 0, 11, "ActivityModel" ); qmlRegisterType<Marble::Declarative::Activity>( uri, 0, 11, "Activity" ); qmlRegisterType<Marble::Declarative::RelatedActivities>( uri, 0, 11, "RelatedActivities" ); qmlRegisterType<Marble::Declarative::Settings>( uri, 0, 11, "Settings" ); qmlRegisterType<Marble::Declarative::MarbleWidget>( uri, 0, 11, "MarbleWidget" ); qmlRegisterType<Marble::Declarative::MapThemeManager>( uri, 0, 11, "MapThemeManager" ); } void MarbleDeclarativePlugin::initializeEngine( QDeclarativeEngine *engine, const char *) { engine->addImageProvider( "maptheme", new MapThemeImageProvider ); } } } #include "MarbleDeclarativePlugin.moc" Q_EXPORT_PLUGIN2( MarbleDeclarativePlugin, Marble::Declarative::MarbleDeclarativePlugin ) <commit_msg>Help QtCreator parse the file<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2010 Dennis Nienhüser <[email protected]> // #include "MarbleDeclarativePlugin.h" #include "Coordinate.h" #include "DeclarativeMapThemeManager.h" #include "MarbleDeclarativeWidget.h" #include "PositionSource.h" #include "Tracking.h" #include "Routing.h" #include "Search.h" #include "RouteRequestModel.h" #include "ActivityModel.h" #include "Activity.h" #include "RelatedActivities.h" #include "Settings.h" #include <QtDeclarative/qdeclarative.h> #include <QtDeclarative/QDeclarativeEngine> namespace Marble { namespace Declarative { void MarbleDeclarativePlugin::registerTypes( const char * ) { const char* uri = "org.kde.edu.marble"; //@uri org.kde.edu.marble qmlRegisterType<Marble::Declarative::Coordinate>( uri, 0, 11, "Coordinate" ); qmlRegisterType<Marble::Declarative::PositionSource>( uri, 0, 11, "PositionSource" ); qmlRegisterType<Marble::Declarative::Tracking>( uri, 0, 11, "Tracking" ); qmlRegisterType<Marble::Declarative::Routing>( uri, 0, 11, "Routing" ); qmlRegisterType<Marble::Declarative::Search>( uri, 0, 11, "Search" ); qmlRegisterType<Marble::Declarative::RouteRequestModel>( uri, 0, 11, "RouteRequestModel" ); qmlRegisterType<Marble::Declarative::ActivityModel>( uri, 0, 11, "ActivityModel" ); qmlRegisterType<Marble::Declarative::Activity>( uri, 0, 11, "Activity" ); qmlRegisterType<Marble::Declarative::RelatedActivities>( uri, 0, 11, "RelatedActivities" ); qmlRegisterType<Marble::Declarative::Settings>( uri, 0, 11, "Settings" ); qmlRegisterType<Marble::Declarative::MarbleWidget>( uri, 0, 11, "MarbleWidget" ); qmlRegisterType<Marble::Declarative::MapThemeManager>( uri, 0, 11, "MapThemeManager" ); } void MarbleDeclarativePlugin::initializeEngine( QDeclarativeEngine *engine, const char *) { engine->addImageProvider( "maptheme", new MapThemeImageProvider ); } } } #include "MarbleDeclarativePlugin.moc" Q_EXPORT_PLUGIN2( MarbleDeclarativePlugin, Marble::Declarative::MarbleDeclarativePlugin ) <|endoftext|>
<commit_before>#define ProofTests_cxx ////////////////////////////////////////////////////////// // // Auxilliary TSelector used to test PROOF functionality // ////////////////////////////////////////////////////////// #include "ProofTests.h" #include <TEnv.h> #include <TH1F.h> #include <TH1I.h> #include <TMath.h> #include <TString.h> #include <TSystem.h> #include <TParameter.h> //_____________________________________________________________________________ ProofTests::ProofTests() { // Constructor fTestType = 0; fStat = 0; } //_____________________________________________________________________________ ProofTests::~ProofTests() { // Destructor } //_____________________________________________________________________________ void ProofTests::ParseInput() { // This function sets some control member variables based on the input list // content. Called by Begin and SlaveBegin. // Determine the test type TNamed *ntype = dynamic_cast<TNamed*>(fInput->FindObject("ProofTests_Type")); if (ntype) { if (!strcmp(ntype->GetTitle(), "InputData")) { fTestType = 0; } else if (!strcmp(ntype->GetTitle(), "PackTest1")) { fTestType = 1; } else if (!strcmp(ntype->GetTitle(), "PackTest2")) { fTestType = 2; } else { Warning("ParseInput", "unknown type: '%s'", ntype->GetTitle()); } } Info("ParseInput", "test type: %d (from '%s')", fTestType, ntype ? ntype->GetTitle() : "undef"); } //_____________________________________________________________________________ void ProofTests::Begin(TTree * /*tree*/) { // The Begin() function is called at the start of the query. // When running with PROOF Begin() is only called on the client. // The tree argument is deprecated (on PROOF 0 is passed). } //_____________________________________________________________________________ void ProofTests::SlaveBegin(TTree * /*tree*/) { // The SlaveBegin() function is called after the Begin() function. // When running with PROOF SlaveBegin() is called on each slave server. // The tree argument is deprecated (on PROOF 0 is passed). TString option = GetOption(); // Fill relevant members ParseInput(); // Output histo fStat = new TH1I("TestStat", "Test results", 20, .5, 20.5); fOutput->Add(fStat); // We were started fStat->Fill(1.); // Depends on the test if (fTestType == 0) { // Retrieve objects from the input list and copy them to the output // H1 TList *h1list = dynamic_cast<TList*>(fInput->FindObject("h1list")); if (h1list) { // Retrieve objects from the input list and copy them to the output TH1F *h1 = dynamic_cast<TH1F*>(h1list->FindObject("h1data")); if (h1) { TParameter<Double_t> *h1avg = dynamic_cast<TParameter<Double_t>*>(h1list->FindObject("h1avg")); TParameter<Double_t> *h1rms = dynamic_cast<TParameter<Double_t>*>(h1list->FindObject("h1rms")); if (h1avg && h1rms) { if (TMath::Abs(h1avg->GetVal() - h1->GetMean()) < 0.0001) { if (TMath::Abs(h1rms->GetVal() - h1->GetRMS()) < 0.0001) { fStat->Fill(2.); } } } else { Info("SlaveBegin", "%d: info 'h1avg' or 'h1rms' not found!", fTestType); } } else { Info("SlaveBegin", "%d: input histo 'h1data' not found!", fTestType); } } else { Info("SlaveBegin", "%d: input list 'h1list' not found!", fTestType); } // H2 TList *h2list = dynamic_cast<TList*>(fInput->FindObject("h2list")); if (h2list) { // Retrieve objects from the input list and copy them to the output TH1F *h2 = dynamic_cast<TH1F*>(h2list->FindObject("h2data")); if (h2) { TParameter<Double_t> *h2avg = dynamic_cast<TParameter<Double_t>*>(h2list->FindObject("h2avg")); TParameter<Double_t> *h2rms = dynamic_cast<TParameter<Double_t>*>(h2list->FindObject("h2rms")); if (h2avg && h2rms) { if (TMath::Abs(h2avg->GetVal() - h2->GetMean()) < 0.0001) { if (TMath::Abs(h2rms->GetVal() - h2->GetRMS()) < 0.0001) { fStat->Fill(3.); } } } else { Info("SlaveBegin", "%d: info 'h2avg' or 'h2rms' not found!", fTestType); } } else { Info("SlaveBegin", "%d: input histo 'h2data' not found!", fTestType); } } else { Info("SlaveBegin", "%d: input list 'h2list' not found!", fTestType); } TNamed *iob = dynamic_cast<TNamed*>(fInput->FindObject("InputObject")); if (iob) { fStat->Fill(4.); } else { Info("SlaveBegin", "%d: input histo 'InputObject' not found!", fTestType); } } else if (fTestType == 1) { // We should find in the input list the name of a test variable which should exist // at this point in the gEnv table TNamed *nm = dynamic_cast<TNamed*>(fInput->FindObject("testenv")); if (nm) { if (gEnv->Lookup(nm->GetTitle())) fStat->Fill(2.); } else { Info("SlaveBegin", "%d: TNamed with the test env info not found!", fTestType); } } else if (fTestType == 2) { // We should find in the input list the list of names of test variables which should exist // at this point in the gEnv table TNamed *nm = dynamic_cast<TNamed*>(fInput->FindObject("testenv")); if (nm) { TString nms(nm->GetTitle()), nam; Int_t from = 0; while (nms.Tokenize(nam, from, ",")) { if (gEnv->Lookup(nam)) { Double_t xx = gEnv->GetValue(nam, -1.); if (xx > 1.) fStat->Fill(xx); } } } else { Info("SlaveBegin", "%d: TNamed with the test env info not found!", fTestType); } } } //_____________________________________________________________________________ Bool_t ProofTests::Process(Long64_t) { // The Process() function is called for each entry in the tree (or possibly // keyed object in the case of PROOF) to be processed. The entry argument // specifies which entry in the currently loaded tree is to be processed. // It can be passed to either ProofTests::GetEntry() or TBranch::GetEntry() // to read either all or the required parts of the data. When processing // keyed objects with PROOF, the object is already loaded and is available // via the fObject pointer. // // This function should contain the "body" of the analysis. It can contain // simple or elaborate selection criteria, run algorithms on the data // of the event and typically fill histograms. // // The processing can be stopped by calling Abort(). // // Use fStatus to set the return value of TTree::Process(). // // The return value is currently not used. return kTRUE; } //_____________________________________________________________________________ void ProofTests::SlaveTerminate() { // The SlaveTerminate() function is called after all entries or objects // have been processed. When running with PROOF SlaveTerminate() is called // on each slave server. } //_____________________________________________________________________________ void ProofTests::Terminate() { // The Terminate() function is the last function to be called during // a query. It always runs on the client, it can be used to present // the results graphically or save the results to file. } <commit_msg>Improve on debug statements<commit_after>#define ProofTests_cxx ////////////////////////////////////////////////////////// // // Auxilliary TSelector used to test PROOF functionality // ////////////////////////////////////////////////////////// #include "ProofTests.h" #include <TEnv.h> #include <TH1F.h> #include <TH1I.h> #include <TMath.h> #include <TString.h> #include <TSystem.h> #include <TParameter.h> //_____________________________________________________________________________ ProofTests::ProofTests() { // Constructor fTestType = 0; fStat = 0; } //_____________________________________________________________________________ ProofTests::~ProofTests() { // Destructor } //_____________________________________________________________________________ void ProofTests::ParseInput() { // This function sets some control member variables based on the input list // content. Called by Begin and SlaveBegin. // Determine the test type TNamed *ntype = dynamic_cast<TNamed*>(fInput->FindObject("ProofTests_Type")); if (ntype) { if (!strcmp(ntype->GetTitle(), "InputData")) { fTestType = 0; } else if (!strcmp(ntype->GetTitle(), "PackTest1")) { fTestType = 1; } else if (!strcmp(ntype->GetTitle(), "PackTest2")) { fTestType = 2; } else { Warning("ParseInput", "unknown type: '%s'", ntype->GetTitle()); } } Info("ParseInput", "test type: %d (from '%s')", fTestType, ntype ? ntype->GetTitle() : "undef"); } //_____________________________________________________________________________ void ProofTests::Begin(TTree * /*tree*/) { // The Begin() function is called at the start of the query. // When running with PROOF Begin() is only called on the client. // The tree argument is deprecated (on PROOF 0 is passed). } //_____________________________________________________________________________ void ProofTests::SlaveBegin(TTree * /*tree*/) { // The SlaveBegin() function is called after the Begin() function. // When running with PROOF SlaveBegin() is called on each slave server. // The tree argument is deprecated (on PROOF 0 is passed). TString option = GetOption(); // Fill relevant members ParseInput(); // Output histo fStat = new TH1I("TestStat", "Test results", 20, .5, 20.5); fOutput->Add(fStat); // We were started fStat->Fill(1.); // Depends on the test if (fTestType == 0) { // Retrieve objects from the input list and copy them to the output // H1 TList *h1list = dynamic_cast<TList*>(fInput->FindObject("h1list")); if (h1list) { // Retrieve objects from the input list and copy them to the output TH1F *h1 = dynamic_cast<TH1F*>(h1list->FindObject("h1data")); if (h1) { TParameter<Double_t> *h1avg = dynamic_cast<TParameter<Double_t>*>(h1list->FindObject("h1avg")); TParameter<Double_t> *h1rms = dynamic_cast<TParameter<Double_t>*>(h1list->FindObject("h1rms")); if (h1avg && h1rms) { if (TMath::Abs(h1avg->GetVal() - h1->GetMean()) < 0.0001) { if (TMath::Abs(h1rms->GetVal() - h1->GetRMS()) < 0.0001) { fStat->Fill(2.); } } } else { Warning("SlaveBegin", "%d: info 'h1avg' or 'h1rms' not found!", fTestType); } } else { Warning("SlaveBegin", "%d: input histo 'h1data' not found!", fTestType); } } else { Warning("SlaveBegin", "%d: input list 'h1list' not found!", fTestType); } // H2 TList *h2list = dynamic_cast<TList*>(fInput->FindObject("h2list")); if (h2list) { // Retrieve objects from the input list and copy them to the output TH1F *h2 = dynamic_cast<TH1F*>(h2list->FindObject("h2data")); if (h2) { TParameter<Double_t> *h2avg = dynamic_cast<TParameter<Double_t>*>(h2list->FindObject("h2avg")); TParameter<Double_t> *h2rms = dynamic_cast<TParameter<Double_t>*>(h2list->FindObject("h2rms")); if (h2avg && h2rms) { if (TMath::Abs(h2avg->GetVal() - h2->GetMean()) < 0.0001) { if (TMath::Abs(h2rms->GetVal() - h2->GetRMS()) < 0.0001) { fStat->Fill(3.); } } } else { Warning("SlaveBegin", "%d: info 'h2avg' or 'h2rms' not found!", fTestType); } } else { Warning("SlaveBegin", "%d: input histo 'h2data' not found!", fTestType); } } else { Warning("SlaveBegin", "%d: input list 'h2list' not found!", fTestType); } TNamed *iob = dynamic_cast<TNamed*>(fInput->FindObject("InputObject")); if (iob) { fStat->Fill(4.); } else { Warning("SlaveBegin", "%d: input histo 'InputObject' not found!", fTestType); } } else if (fTestType == 1) { // We should find in the input list the name of a test variable which should exist // at this point in the gEnv table TNamed *nm = dynamic_cast<TNamed*>(fInput->FindObject("testenv")); if (nm) { if (gEnv->Lookup(nm->GetTitle())) fStat->Fill(2.); } else { Warning("SlaveBegin", "%d: TNamed with the test env info not found!", fTestType); } } else if (fTestType == 2) { // We should find in the input list the list of names of test variables which should exist // at this point in the gEnv table TNamed *nm = dynamic_cast<TNamed*>(fInput->FindObject("testenv")); if (nm) { TString nms(nm->GetTitle()), nam; Int_t from = 0; while (nms.Tokenize(nam, from, ",")) { if (gEnv->Lookup(nam)) { Double_t xx = gEnv->GetValue(nam, -1.); if (xx > 1.) fStat->Fill(xx); } else { Warning("SlaveBegin", "RC-env '%s' not found!", nam.Data()); } } } else { Warning("SlaveBegin", "%d: TNamed with the test env info not found!", fTestType); } } } //_____________________________________________________________________________ Bool_t ProofTests::Process(Long64_t) { // The Process() function is called for each entry in the tree (or possibly // keyed object in the case of PROOF) to be processed. The entry argument // specifies which entry in the currently loaded tree is to be processed. // It can be passed to either ProofTests::GetEntry() or TBranch::GetEntry() // to read either all or the required parts of the data. When processing // keyed objects with PROOF, the object is already loaded and is available // via the fObject pointer. // // This function should contain the "body" of the analysis. It can contain // simple or elaborate selection criteria, run algorithms on the data // of the event and typically fill histograms. // // The processing can be stopped by calling Abort(). // // Use fStatus to set the return value of TTree::Process(). // // The return value is currently not used. return kTRUE; } //_____________________________________________________________________________ void ProofTests::SlaveTerminate() { // The SlaveTerminate() function is called after all entries or objects // have been processed. When running with PROOF SlaveTerminate() is called // on each slave server. } //_____________________________________________________________________________ void ProofTests::Terminate() { // The Terminate() function is the last function to be called during // a query. It always runs on the client, it can be used to present // the results graphically or save the results to file. } <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2010 Dennis Nienhüser <[email protected]> // #include "OsmNominatimRunner.h" #include "MarbleAbstractRunner.h" #include "MarbleDebug.h" #include "MarbleLocale.h" #include "GeoDataDocument.h" #include "GeoDataPlacemark.h" #include "GeoDataExtendedData.h" #include "TinyWebBrowser.h" #include <QtCore/QString> #include <QtCore/QVector> #include <QtCore/QUrl> #include <QtCore/QTimer> #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkReply> #include <QtXml/QDomDocument> namespace Marble { OsmNominatimRunner::OsmNominatimRunner( QObject *parent ) : MarbleAbstractRunner( parent ), m_manager( new QNetworkAccessManager (this ) ) { connect(m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(handleResult(QNetworkReply*))); } OsmNominatimRunner::~OsmNominatimRunner() { // nothing to do } GeoDataFeature::GeoDataVisualCategory OsmNominatimRunner::category() const { return GeoDataFeature::OsmSite; } void OsmNominatimRunner::returnNoResults() { emit searchFinished( QVector<GeoDataPlacemark*>() ); } void OsmNominatimRunner::returnNoReverseGeocodingResult() { emit reverseGeocodingFinished( m_coordinates, GeoDataPlacemark() ); } void OsmNominatimRunner::search( const QString &searchTerm ) { QString base = "http://nominatim.openstreetmap.org/search?"; QString query = "q=%1&format=xml&addressdetails=1&accept-language=%2"; QString url = QString(base + query).arg(searchTerm).arg(MarbleLocale::languageCode()); m_searchRequest.setUrl(QUrl(url)); m_searchRequest.setRawHeader("User-Agent", TinyWebBrowser::userAgent("Browser", "OsmNominatimRunner") ); // @todo FIXME Must currently be done in the main thread, see bug 257376 QTimer::singleShot( 0, this, SLOT( startSearch() ) ); } void OsmNominatimRunner::reverseGeocoding( const GeoDataCoordinates &coordinates ) { m_coordinates = coordinates; QString base = "http://nominatim.openstreetmap.org/reverse?format=xml&addressdetails=1"; // @todo: Alternative URI with addressdetails=1 could be used for shorther placemark name QString query = "&lon=%1&lat=%2&accept-language=%3"; double lon = coordinates.longitude( GeoDataCoordinates::Degree ); double lat = coordinates.latitude( GeoDataCoordinates::Degree ); QString url = QString( base + query ).arg( lon ).arg( lat ).arg( MarbleLocale::languageCode() ); m_reverseGeocodingRequest.setUrl(QUrl(url)); m_reverseGeocodingRequest.setRawHeader("User-Agent", TinyWebBrowser::userAgent("Browser", "OsmNominatimRunner") ); // @todo FIXME Must currently be done in the main thread, see bug 257376 QTimer::singleShot( 0, this, SLOT( startReverseGeocoding() ) ); } void OsmNominatimRunner::startSearch() { QNetworkReply *reply = m_manager->get(m_searchRequest); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(returnNoResults())); } void OsmNominatimRunner::startReverseGeocoding() { QNetworkReply *reply = m_manager->get( m_reverseGeocodingRequest ); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(returnNoReverseGeocodingResult())); } void OsmNominatimRunner::handleResult( QNetworkReply* reply ) { bool const isSearch = reply->url().path().endsWith( "search" ); if ( isSearch ) { handleSearchResult( reply ); } else { handleReverseGeocodingResult( reply ); } } void OsmNominatimRunner::handleSearchResult( QNetworkReply* reply ) { QDomDocument xml; if (!xml.setContent(reply->readAll())) { qWarning() << "Cannot parse osm nominatim result"; returnNoResults(); return; } QVector<GeoDataPlacemark*> placemarks; QDomElement root = xml.documentElement(); QDomNodeList places = root.elementsByTagName("place"); for (int i=0; i<places.size(); ++i) { QDomNode place = places.at(i); QDomNamedNodeMap attributes = place.attributes(); QString lon = attributes.namedItem("lon").nodeValue(); QString lat = attributes.namedItem("lat").nodeValue(); QString desc = attributes.namedItem("display_name").nodeValue(); QString key = attributes.namedItem("class").nodeValue(); QString value = attributes.namedItem("type").nodeValue(); QString name = place.firstChildElement(value).text(); QString road = place.firstChildElement("road").text(); QString city = place.firstChildElement("city").text(); if( city.isEmpty() ) { city = place.firstChildElement("town").text(); if( city.isEmpty() ) { city = place.firstChildElement("village").text(); } if( city.isEmpty() ) { city = place.firstChildElement("hamlet").text(); } } QString administrative = place.firstChildElement("county").text(); if( administrative.isEmpty() ) { administrative = place.firstChildElement("region").text(); if( administrative.isEmpty() ) { administrative = place.firstChildElement("state").text(); } } QString country = place.firstChildElement("country").text(); qDebug() << "place " << name << ", " << road << ", " << city << ", " << administrative << ", " << country; QString description; for (int i=0; i<place.childNodes().size(); ++i) { QDomElement item = place.childNodes().at(i).toElement(); description += item.nodeName() + ": " + item.text() + "\n"; } description += "Category: " + key + "/" + value; if (!lon.isEmpty() && !lat.isEmpty() && !desc.isEmpty()) { QString placemarkName; GeoDataPlacemark* placemark = new GeoDataPlacemark; // try to provide 2 fields if (!name.isEmpty()) { placemarkName = name; } if (!road.isEmpty() && road != placemarkName ) { if( !placemarkName.isEmpty() ) { placemarkName += ", "; } placemarkName += road; } if (!city.isEmpty() && !placemarkName.contains(",") && city != placemarkName) { if( !placemarkName.isEmpty() ) { placemarkName += ", "; } placemarkName += city; } if (!administrative.isEmpty()&& !placemarkName.contains(",") && administrative != placemarkName) { if( !placemarkName.isEmpty() ) { placemarkName += ", "; } placemarkName += administrative; } if (!country.isEmpty()&& !placemarkName.contains(",") && country != placemarkName) { if( !placemarkName.isEmpty() ) { placemarkName += ", "; } placemarkName += country; } if (placemarkName.isEmpty()) { placemarkName = desc; } placemark->setName( placemarkName ); placemark->setDescription(description); placemark->setCoordinate(lon.toDouble(), lat.toDouble(), 0, GeoDataPoint::Degree ); GeoDataFeature::GeoDataVisualCategory category = GeoDataFeature::OsmVisualCategory( key + "=" + value ); placemark->setVisualCategory( category ); placemarks << placemark; } } emit searchFinished( placemarks ); } void OsmNominatimRunner::handleReverseGeocodingResult( QNetworkReply* reply ) { if ( !reply->bytesAvailable() ) { returnNoReverseGeocodingResult(); return; } QDomDocument xml; if ( !xml.setContent( reply->readAll() ) ) { mDebug() << "Cannot parse osm nominatim result " << xml.toString(); returnNoReverseGeocodingResult(); return; } QDomElement root = xml.documentElement(); QDomNodeList places = root.elementsByTagName( "result" ); if ( places.size() == 1 ) { QString address = places.item( 0 ).toElement().text(); GeoDataPlacemark placemark; placemark.setAddress( address ); placemark.setCoordinate( GeoDataPoint( m_coordinates ) ); QDomNodeList details = root.elementsByTagName( "addressparts" ); if ( details.size() == 1 ) { GeoDataExtendedData extendedData; addData( details, "road", &extendedData ); addData( details, "house_number", &extendedData ); addData( details, "village", &extendedData ); addData( details, "city", &extendedData ); addData( details, "county", &extendedData ); addData( details, "state", &extendedData ); addData( details, "postcode", &extendedData ); addData( details, "country", &extendedData ); placemark.setExtendedData( extendedData ); } emit reverseGeocodingFinished( m_coordinates, placemark ); } else { returnNoReverseGeocodingResult(); } } void OsmNominatimRunner::addData( const QDomNodeList &node, const QString &key, GeoDataExtendedData *extendedData ) { QDomNodeList child = node.item( 0 ).toElement().elementsByTagName( key ); if ( child.size() > 0 ) { QString text = child.item( 0 ).toElement().text(); extendedData->addValue( GeoDataData( key, text ) ); } } } // namespace Marble #include "OsmNominatimRunner.moc" <commit_msg>OsmNominatim: quieter<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2010 Dennis Nienhüser <[email protected]> // #include "OsmNominatimRunner.h" #include "MarbleAbstractRunner.h" #include "MarbleDebug.h" #include "MarbleLocale.h" #include "GeoDataDocument.h" #include "GeoDataPlacemark.h" #include "GeoDataExtendedData.h" #include "TinyWebBrowser.h" #include <QtCore/QString> #include <QtCore/QVector> #include <QtCore/QUrl> #include <QtCore/QTimer> #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkReply> #include <QtXml/QDomDocument> namespace Marble { OsmNominatimRunner::OsmNominatimRunner( QObject *parent ) : MarbleAbstractRunner( parent ), m_manager( new QNetworkAccessManager (this ) ) { connect(m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(handleResult(QNetworkReply*))); } OsmNominatimRunner::~OsmNominatimRunner() { // nothing to do } GeoDataFeature::GeoDataVisualCategory OsmNominatimRunner::category() const { return GeoDataFeature::OsmSite; } void OsmNominatimRunner::returnNoResults() { emit searchFinished( QVector<GeoDataPlacemark*>() ); } void OsmNominatimRunner::returnNoReverseGeocodingResult() { emit reverseGeocodingFinished( m_coordinates, GeoDataPlacemark() ); } void OsmNominatimRunner::search( const QString &searchTerm ) { QString base = "http://nominatim.openstreetmap.org/search?"; QString query = "q=%1&format=xml&addressdetails=1&accept-language=%2"; QString url = QString(base + query).arg(searchTerm).arg(MarbleLocale::languageCode()); m_searchRequest.setUrl(QUrl(url)); m_searchRequest.setRawHeader("User-Agent", TinyWebBrowser::userAgent("Browser", "OsmNominatimRunner") ); // @todo FIXME Must currently be done in the main thread, see bug 257376 QTimer::singleShot( 0, this, SLOT( startSearch() ) ); } void OsmNominatimRunner::reverseGeocoding( const GeoDataCoordinates &coordinates ) { m_coordinates = coordinates; QString base = "http://nominatim.openstreetmap.org/reverse?format=xml&addressdetails=1"; // @todo: Alternative URI with addressdetails=1 could be used for shorther placemark name QString query = "&lon=%1&lat=%2&accept-language=%3"; double lon = coordinates.longitude( GeoDataCoordinates::Degree ); double lat = coordinates.latitude( GeoDataCoordinates::Degree ); QString url = QString( base + query ).arg( lon ).arg( lat ).arg( MarbleLocale::languageCode() ); m_reverseGeocodingRequest.setUrl(QUrl(url)); m_reverseGeocodingRequest.setRawHeader("User-Agent", TinyWebBrowser::userAgent("Browser", "OsmNominatimRunner") ); // @todo FIXME Must currently be done in the main thread, see bug 257376 QTimer::singleShot( 0, this, SLOT( startReverseGeocoding() ) ); } void OsmNominatimRunner::startSearch() { QNetworkReply *reply = m_manager->get(m_searchRequest); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(returnNoResults())); } void OsmNominatimRunner::startReverseGeocoding() { QNetworkReply *reply = m_manager->get( m_reverseGeocodingRequest ); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(returnNoReverseGeocodingResult())); } void OsmNominatimRunner::handleResult( QNetworkReply* reply ) { bool const isSearch = reply->url().path().endsWith( "search" ); if ( isSearch ) { handleSearchResult( reply ); } else { handleReverseGeocodingResult( reply ); } } void OsmNominatimRunner::handleSearchResult( QNetworkReply* reply ) { QDomDocument xml; if (!xml.setContent(reply->readAll())) { qWarning() << "Cannot parse osm nominatim result"; returnNoResults(); return; } QVector<GeoDataPlacemark*> placemarks; QDomElement root = xml.documentElement(); QDomNodeList places = root.elementsByTagName("place"); for (int i=0; i<places.size(); ++i) { QDomNode place = places.at(i); QDomNamedNodeMap attributes = place.attributes(); QString lon = attributes.namedItem("lon").nodeValue(); QString lat = attributes.namedItem("lat").nodeValue(); QString desc = attributes.namedItem("display_name").nodeValue(); QString key = attributes.namedItem("class").nodeValue(); QString value = attributes.namedItem("type").nodeValue(); QString name = place.firstChildElement(value).text(); QString road = place.firstChildElement("road").text(); QString city = place.firstChildElement("city").text(); if( city.isEmpty() ) { city = place.firstChildElement("town").text(); if( city.isEmpty() ) { city = place.firstChildElement("village").text(); } if( city.isEmpty() ) { city = place.firstChildElement("hamlet").text(); } } QString administrative = place.firstChildElement("county").text(); if( administrative.isEmpty() ) { administrative = place.firstChildElement("region").text(); if( administrative.isEmpty() ) { administrative = place.firstChildElement("state").text(); } } QString country = place.firstChildElement("country").text(); QString description; for (int i=0; i<place.childNodes().size(); ++i) { QDomElement item = place.childNodes().at(i).toElement(); description += item.nodeName() + ": " + item.text() + "\n"; } description += "Category: " + key + "/" + value; if (!lon.isEmpty() && !lat.isEmpty() && !desc.isEmpty()) { QString placemarkName; GeoDataPlacemark* placemark = new GeoDataPlacemark; // try to provide 2 fields if (!name.isEmpty()) { placemarkName = name; } if (!road.isEmpty() && road != placemarkName ) { if( !placemarkName.isEmpty() ) { placemarkName += ", "; } placemarkName += road; } if (!city.isEmpty() && !placemarkName.contains(",") && city != placemarkName) { if( !placemarkName.isEmpty() ) { placemarkName += ", "; } placemarkName += city; } if (!administrative.isEmpty()&& !placemarkName.contains(",") && administrative != placemarkName) { if( !placemarkName.isEmpty() ) { placemarkName += ", "; } placemarkName += administrative; } if (!country.isEmpty()&& !placemarkName.contains(",") && country != placemarkName) { if( !placemarkName.isEmpty() ) { placemarkName += ", "; } placemarkName += country; } if (placemarkName.isEmpty()) { placemarkName = desc; } placemark->setName( placemarkName ); placemark->setDescription(description); placemark->setCoordinate(lon.toDouble(), lat.toDouble(), 0, GeoDataPoint::Degree ); GeoDataFeature::GeoDataVisualCategory category = GeoDataFeature::OsmVisualCategory( key + "=" + value ); placemark->setVisualCategory( category ); placemarks << placemark; } } emit searchFinished( placemarks ); } void OsmNominatimRunner::handleReverseGeocodingResult( QNetworkReply* reply ) { if ( !reply->bytesAvailable() ) { returnNoReverseGeocodingResult(); return; } QDomDocument xml; if ( !xml.setContent( reply->readAll() ) ) { mDebug() << "Cannot parse osm nominatim result " << xml.toString(); returnNoReverseGeocodingResult(); return; } QDomElement root = xml.documentElement(); QDomNodeList places = root.elementsByTagName( "result" ); if ( places.size() == 1 ) { QString address = places.item( 0 ).toElement().text(); GeoDataPlacemark placemark; placemark.setAddress( address ); placemark.setCoordinate( GeoDataPoint( m_coordinates ) ); QDomNodeList details = root.elementsByTagName( "addressparts" ); if ( details.size() == 1 ) { GeoDataExtendedData extendedData; addData( details, "road", &extendedData ); addData( details, "house_number", &extendedData ); addData( details, "village", &extendedData ); addData( details, "city", &extendedData ); addData( details, "county", &extendedData ); addData( details, "state", &extendedData ); addData( details, "postcode", &extendedData ); addData( details, "country", &extendedData ); placemark.setExtendedData( extendedData ); } emit reverseGeocodingFinished( m_coordinates, placemark ); } else { returnNoReverseGeocodingResult(); } } void OsmNominatimRunner::addData( const QDomNodeList &node, const QString &key, GeoDataExtendedData *extendedData ) { QDomNodeList child = node.item( 0 ).toElement().elementsByTagName( key ); if ( child.size() > 0 ) { QString text = child.item( 0 ).toElement().text(); extendedData->addValue( GeoDataData( key, text ) ); } } } // namespace Marble #include "OsmNominatimRunner.moc" <|endoftext|>
<commit_before> #include <algorithm> #include <vector> #include "astronomy/frames.hpp" #include "geometry/interval.hpp" #include "geometry/named_quantities.hpp" #include "glog/logging.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "integrators/methods.hpp" #include "integrators/symmetric_linear_multistep_integrator.hpp" #include "mathematica/mathematica.hpp" #include "numerics/apodization.hpp" #include "numerics/fast_fourier_transform.hpp" #include "numerics/frequency_analysis.hpp" #include "numerics/poisson_series.hpp" #include "numerics/polynomial_evaluators.hpp" #include "physics/ephemeris.hpp" #include "physics/solar_system.hpp" #include "quantities/astronomy.hpp" #include "quantities/quantities.hpp" #include "quantities/si.hpp" #include "testing_utilities/approximate_quantity.hpp" namespace principia { namespace physics { using astronomy::ICRS; using geometry::Displacement; using geometry::Instant; using geometry::Interval; using geometry::Position; using integrators::SymmetricLinearMultistepIntegrator; using integrators::methods::QuinlanTremaine1990Order12; using numerics::EstrinEvaluator; using numerics::FastFourierTransform; using numerics::PoissonSeries; using quantities::Angle; using quantities::AngularFrequency; using quantities::Length; using quantities::Time; using quantities::astronomy::JulianYear; using quantities::si::Metre; using quantities::si::Milli; using quantities::si::Minute; using quantities::si::Radian; using quantities::si::Second; namespace apodization = numerics::apodization; namespace frequency_analysis = numerics::frequency_analysis; static constexpr int approximation_degree = 5; static constexpr int log2_number_of_samples = 10; static constexpr int number_of_frequencies = 10; class AnalyticalSeriesTest : public ::testing::Test { protected: AnalyticalSeriesTest() : logger_(TEMP_DIR / "analytical_series.wl", /*make_unique=*/false) { google::LogToStderr(); } template<int degree> PoissonSeries<Displacement<ICRS>, approximation_degree, EstrinEvaluator> ComputeCompactRepresentation(ContinuousTrajectory<ICRS> const& trajectory) { Instant const t_min = trajectory.t_min(); Instant const t_max = trajectory.t_max(); auto const piecewise_poisson_series = trajectory.ToPiecewisePoissonSeries<degree>(t_min, t_max); int step = 0; auto angular_frequency_calculator = [this, &step, t_min, t_max]( auto const& residual) -> std::optional<AngularFrequency> { Time const Δt = (t_max - t_min) / (1 << log2_number_of_samples); LOG(INFO) << "step=" << step; if (step == 0) { ++step; return AngularFrequency(); } else if (step <= number_of_frequencies) { ++step; Length max_residual; std::vector<Displacement<ICRS>> residuals; for (int i = 0; i < 1 << log2_number_of_samples; ++i) { residuals.push_back(residual(t_min + i * Δt)); max_residual = std::max(max_residual, residuals.back().Norm()); } LOG(INFO) << "max_residual=" << max_residual; auto fft = std::make_unique<FastFourierTransform<Displacement<ICRS>, 1 << log2_number_of_samples>>( residuals, Δt); auto const mode = fft->Mode(); Interval<Time> const period{2 * π * Radian / mode.max, 2 * π * Radian / mode.min}; LOG(INFO) << "period=" << period; auto const precise_mode = frequency_analysis::PreciseMode( mode, residual, apodization::Hann<EstrinEvaluator>(t_min, t_max)); auto const precise_period = 2 * π * Radian / precise_mode; LOG(INFO) << "precise_period=" << precise_period; logger_.Append( "precisePeriods", precise_period, mathematica::ExpressIn(Second)); return precise_mode; } else { Length max_residual; for (int i = 0; i < 1 << log2_number_of_samples; ++i) { max_residual = std::max(max_residual, residual(t_min + i * Δt).Norm()); } LOG(INFO) << "max_residual=" << max_residual; return std::nullopt; } }; return frequency_analysis::IncrementalProjection<approximation_degree>( piecewise_poisson_series, angular_frequency_calculator, apodization::Dirichlet<EstrinEvaluator>(t_min, t_max), t_min, t_max); } mathematica::Logger logger_; }; #define PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( \ degree, approximation, trajectory) \ case degree: { \ approximation = std::make_unique<PoissonSeries<Displacement<ICRS>, \ approximation_degree, \ EstrinEvaluator>>( \ ComputeCompactRepresentation<(degree)>(trajectory)); \ break; \ } #if !_DEBUG TEST_F(AnalyticalSeriesTest, CompactRepresentation) { SolarSystem<ICRS> solar_system_at_j2000( SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt", SOLUTION_DIR / "astronomy" / "sol_initial_state_jd_2451545_000000000.proto.txt"); // NOTE(phl): Keep these parameters aligned with // sol_numerics_blueprint.proto.txt. auto const ephemeris = solar_system_at_j2000.MakeEphemeris( /*accuracy_parameters=*/{/*fitting_tolerance=*/1 * Milli(Metre), /*geopotential_tolerance=*/0x1p-24}, Ephemeris<ICRS>::FixedStepParameters( SymmetricLinearMultistepIntegrator<QuinlanTremaine1990Order12, Position<ICRS>>(), /*step=*/10 * Minute)); ephemeris->Prolong(solar_system_at_j2000.epoch() + 0.25 * JulianYear); auto const& io_trajectory = solar_system_at_j2000.trajectory(*ephemeris, "Io"); int const io_piecewise_poisson_series_degree = io_trajectory.PiecewisePoissonSeriesDegree(io_trajectory.t_min(), io_trajectory.t_max()); std::unique_ptr< PoissonSeries<Displacement<ICRS>, approximation_degree, EstrinEvaluator>> io_approximation; switch (io_piecewise_poisson_series_degree) { PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 3, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 4, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 5, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 6, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 7, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 8, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 9, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 10, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 11, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 12, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 13, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 14, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 15, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 16, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 17, io_approximation, io_trajectory); default: LOG(FATAL) << "Unexpected degree " << io_piecewise_poisson_series_degree; }; logger_.Set("approximation", *io_approximation, mathematica::ExpressIn(Metre, Second, Radian)); } #endif #undef PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE } // namespace physics } // namespace principia <commit_msg>A small trace.<commit_after> #include <algorithm> #include <vector> #include "astronomy/frames.hpp" #include "geometry/interval.hpp" #include "geometry/named_quantities.hpp" #include "glog/logging.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "integrators/methods.hpp" #include "integrators/symmetric_linear_multistep_integrator.hpp" #include "mathematica/mathematica.hpp" #include "numerics/apodization.hpp" #include "numerics/fast_fourier_transform.hpp" #include "numerics/frequency_analysis.hpp" #include "numerics/poisson_series.hpp" #include "numerics/polynomial_evaluators.hpp" #include "physics/ephemeris.hpp" #include "physics/solar_system.hpp" #include "quantities/astronomy.hpp" #include "quantities/quantities.hpp" #include "quantities/si.hpp" #include "testing_utilities/approximate_quantity.hpp" namespace principia { namespace physics { using astronomy::ICRS; using geometry::Displacement; using geometry::Instant; using geometry::Interval; using geometry::Position; using integrators::SymmetricLinearMultistepIntegrator; using integrators::methods::QuinlanTremaine1990Order12; using numerics::EstrinEvaluator; using numerics::FastFourierTransform; using numerics::PoissonSeries; using quantities::Angle; using quantities::AngularFrequency; using quantities::Length; using quantities::Time; using quantities::astronomy::JulianYear; using quantities::si::Metre; using quantities::si::Milli; using quantities::si::Minute; using quantities::si::Radian; using quantities::si::Second; namespace apodization = numerics::apodization; namespace frequency_analysis = numerics::frequency_analysis; static constexpr int approximation_degree = 5; static constexpr int log2_number_of_samples = 10; static constexpr int number_of_frequencies = 10; class AnalyticalSeriesTest : public ::testing::Test { protected: AnalyticalSeriesTest() : logger_(TEMP_DIR / "analytical_series.wl", /*make_unique=*/false) { google::LogToStderr(); } template<int degree> PoissonSeries<Displacement<ICRS>, approximation_degree, EstrinEvaluator> ComputeCompactRepresentation(ContinuousTrajectory<ICRS> const& trajectory) { Instant const t_min = trajectory.t_min(); Instant const t_max = trajectory.t_max(); auto const piecewise_poisson_series = trajectory.ToPiecewisePoissonSeries<degree>(t_min, t_max); logger_.Set("tMin", t_min, mathematica::ExpressIn(Second)); logger_.Set("tMax", t_max, mathematica::ExpressIn(Second)); int step = 0; auto angular_frequency_calculator = [this, &step, t_min, t_max]( auto const& residual) -> std::optional<AngularFrequency> { Time const Δt = (t_max - t_min) / (1 << log2_number_of_samples); LOG(INFO) << "step=" << step; if (step == 0) { ++step; return AngularFrequency(); } else if (step <= number_of_frequencies) { ++step; Length max_residual; std::vector<Displacement<ICRS>> residuals; for (int i = 0; i < 1 << log2_number_of_samples; ++i) { residuals.push_back(residual(t_min + i * Δt)); max_residual = std::max(max_residual, residuals.back().Norm()); } LOG(INFO) << "max_residual=" << max_residual; auto fft = std::make_unique<FastFourierTransform<Displacement<ICRS>, 1 << log2_number_of_samples>>( residuals, Δt); auto const mode = fft->Mode(); Interval<Time> const period{2 * π * Radian / mode.max, 2 * π * Radian / mode.min}; LOG(INFO) << "period=" << period; auto const precise_mode = frequency_analysis::PreciseMode( mode, residual, apodization::Hann<EstrinEvaluator>(t_min, t_max)); auto const precise_period = 2 * π * Radian / precise_mode; LOG(INFO) << "precise_period=" << precise_period; logger_.Append( "precisePeriods", precise_period, mathematica::ExpressIn(Second)); return precise_mode; } else { Length max_residual; for (int i = 0; i < 1 << log2_number_of_samples; ++i) { max_residual = std::max(max_residual, residual(t_min + i * Δt).Norm()); } LOG(INFO) << "max_residual=" << max_residual; return std::nullopt; } }; return frequency_analysis::IncrementalProjection<approximation_degree>( piecewise_poisson_series, angular_frequency_calculator, apodization::Dirichlet<EstrinEvaluator>(t_min, t_max), t_min, t_max); } mathematica::Logger logger_; }; #define PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( \ degree, approximation, trajectory) \ case degree: { \ approximation = std::make_unique<PoissonSeries<Displacement<ICRS>, \ approximation_degree, \ EstrinEvaluator>>( \ ComputeCompactRepresentation<(degree)>(trajectory)); \ break; \ } #if !_DEBUG TEST_F(AnalyticalSeriesTest, CompactRepresentation) { SolarSystem<ICRS> solar_system_at_j2000( SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt", SOLUTION_DIR / "astronomy" / "sol_initial_state_jd_2451545_000000000.proto.txt"); // NOTE(phl): Keep these parameters aligned with // sol_numerics_blueprint.proto.txt. auto const ephemeris = solar_system_at_j2000.MakeEphemeris( /*accuracy_parameters=*/{/*fitting_tolerance=*/1 * Milli(Metre), /*geopotential_tolerance=*/0x1p-24}, Ephemeris<ICRS>::FixedStepParameters( SymmetricLinearMultistepIntegrator<QuinlanTremaine1990Order12, Position<ICRS>>(), /*step=*/10 * Minute)); ephemeris->Prolong(solar_system_at_j2000.epoch() + 0.25 * JulianYear); auto const& io_trajectory = solar_system_at_j2000.trajectory(*ephemeris, "Moon"); int const io_piecewise_poisson_series_degree = io_trajectory.PiecewisePoissonSeriesDegree(io_trajectory.t_min(), io_trajectory.t_max()); std::unique_ptr< PoissonSeries<Displacement<ICRS>, approximation_degree, EstrinEvaluator>> io_approximation; switch (io_piecewise_poisson_series_degree) { PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 3, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 4, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 5, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 6, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 7, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 8, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 9, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 10, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 11, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 12, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 13, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 14, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 15, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 16, io_approximation, io_trajectory); PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE( 17, io_approximation, io_trajectory); default: LOG(FATAL) << "Unexpected degree " << io_piecewise_poisson_series_degree; }; logger_.Set("approximation", *io_approximation, mathematica::ExpressIn(Metre, Second, Radian)); } #endif #undef PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE } // namespace physics } // namespace principia <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "photoeffects.hpp" using namespace cv; TEST(photoeffects, SepiaFakeTest) { Mat src(10, 10, CV_8UC1), dst; EXPECT_EQ(0, sepia(src, dst)); } TEST(photoeffects, SepiaFailTest) { Mat src(10, 10, CV_8UC3), dst; EXPECT_EQ(1, sepia(src, dst)); } TEST(photoeffects, SepiaTest) { Mat src(10, 10, CV_8UC1), dst, hsvDst; vector<Mat> channels(3); EXPECT_EQ(0, sepia(src, dst)); cvtColor(dst, hsvDst, CV_BGR2HSV); split(hsvDst, channels); EXPECT_LE(19 - 1, channels[0].at<uchar>(0, 0)); // hue = 19 EXPECT_GE(19 + 1, channels[0].at<uchar>(0, 0)); EXPECT_LE(78 - 1, channels[1].at<uchar>(0, 0)); // saturation = 78 EXPECT_GE(78 + 1, channels[1].at<uchar>(0, 0)); EXPECT_LE(src.at<uchar>(0, 0) + 20 - 1, channels[2].at<uchar>(0, 0)); EXPECT_GE(src.at<uchar>(0, 0) + 20 + 1, channels[2].at<uchar>(0, 0)); } <commit_msg>Matrix initialization in the test for sepia effect.<commit_after>#include <gtest/gtest.h> #include "photoeffects.hpp" using namespace cv; TEST(photoeffects, SepiaFakeTest) { Mat src(10, 10, CV_8UC1), dst; EXPECT_EQ(0, sepia(src, dst)); } TEST(photoeffects, SepiaFailTest) { Mat src(10, 10, CV_8UC3), dst; EXPECT_EQ(1, sepia(src, dst)); } TEST(photoeffects, SepiaTest) { Mat src(10, 10, CV_8UC1, Scalar(0)), dst, hsvDst; vector<Mat> channels(3); EXPECT_EQ(0, sepia(src, dst)); cvtColor(dst, hsvDst, CV_BGR2HSV); split(hsvDst, channels); EXPECT_LE(19 - 1, channels[0].at<uchar>(0, 0)); // hue = 19 EXPECT_GE(19 + 1, channels[0].at<uchar>(0, 0)); EXPECT_LE(78 - 1, channels[1].at<uchar>(0, 0)); // saturation = 78 EXPECT_GE(78 + 1, channels[1].at<uchar>(0, 0)); EXPECT_LE(src.at<uchar>(0, 0) + 20 - 1, channels[2].at<uchar>(0, 0)); EXPECT_GE(src.at<uchar>(0, 0) + 20 + 1, channels[2].at<uchar>(0, 0)); } <|endoftext|>