text
stringlengths
54
60.6k
<commit_before>#include "output_ts_base.h" #include <mist/bitfields.h> namespace Mist{ TSOutput::TSOutput(Socket::Connection &conn) : TS_BASECLASS(conn){ packCounter = 0; ts_from = 0; setBlocking(true); sendRepeatingHeaders = 0; lastHeaderTime = 0; } void TSOutput::fillPacket(char const *data, size_t dataLen, bool &firstPack, bool video, bool keyframe, size_t pkgPid, uint16_t &contPkg){ do{ if (!packData.getBytesFree()){ if ((sendRepeatingHeaders && thisPacket.getTime() - lastHeaderTime > sendRepeatingHeaders) || !packCounter){ std::set<size_t> selectedTracks; for (std::map<size_t, Comms::Users>::iterator it = userSelect.begin(); it != userSelect.end(); it++){ selectedTracks.insert(it->first); } lastHeaderTime = thisPacket.getTime(); TS::Packet tmpPack; tmpPack.FromPointer(TS::PAT); tmpPack.setContinuityCounter(++contPAT); sendTS(tmpPack.checkAndGetBuffer()); sendTS(TS::createPMT(selectedTracks, M, ++contPMT)); sendTS(TS::createSDT(streamName, ++contSDT)); packCounter += 3; } sendTS(packData.checkAndGetBuffer()); packCounter++; packData.clear(); } if (!dataLen){return;} if (packData.getBytesFree() == 184){ packData.clear(); packData.setPID(pkgPid); packData.setContinuityCounter(++contPkg); if (firstPack){ packData.setUnitStart(1); if (video){ if (keyframe){ packData.setRandomAccess(true); packData.setESPriority(true); } packData.setPCR(thisPacket.getTime() * 27000); } firstPack = false; } } size_t tmp = packData.fillFree(data, dataLen); data += tmp; dataLen -= tmp; }while (dataLen); } void TSOutput::sendNext(){ // Get ready some data to speed up accesses std::string type = M.getType(thisIdx); std::string codec = M.getCodec(thisIdx); bool video = (type == "video"); size_t pkgPid = TS::getUniqTrackID(M, thisIdx); bool &firstPack = first[thisIdx]; uint16_t &contPkg = contCounters[pkgPid]; uint64_t packTime = thisPacket.getTime(); bool keyframe = thisPacket.getInt("keyframe"); firstPack = true; char *dataPointer = 0; size_t dataLen = 0; thisPacket.getString("data", dataPointer, dataLen); // data packTime *= 90; std::string bs; // prepare bufferstring if (video){ if (codec == "H264" || codec == "HEVC"){ uint32_t extraSize = 0; // dataPointer[4] & 0x1f is used to check if this should be done later: // fillPacket("\000\000\000\001\011\360", 6); if (codec == "H264" && (dataPointer[4] & 0x1f) != 0x09){extraSize += 6;} if (keyframe){ if (codec == "H264"){ MP4::AVCC avccbox; avccbox.setPayload(M.getInit(thisIdx)); bs = avccbox.asAnnexB(); extraSize += bs.size(); } /*LTS-START*/ if (codec == "HEVC"){ MP4::HVCC hvccbox; hvccbox.setPayload(M.getInit(thisIdx)); bs = hvccbox.asAnnexB(); extraSize += bs.size(); } /*LTS-END*/ } const uint32_t MAX_PES_SIZE = 65490 - 13; uint32_t ThisNaluSize = 0; uint32_t i = 0; uint64_t offset = thisPacket.getInt("offset") * 90; bs.clear(); TS::Packet::getPESVideoLeadIn(bs, (((dataLen + extraSize) > MAX_PES_SIZE) ? 0 : dataLen + extraSize), packTime, offset, true, M.getBps(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); if (codec == "H264" && (dataPointer[4] & 0x1f) != 0x09){ // End of previous nal unit, if not already present fillPacket("\000\000\000\001\011\360", 6, firstPack, video, keyframe, pkgPid, contPkg); } if (keyframe){ if (codec == "H264"){ MP4::AVCC avccbox; avccbox.setPayload(M.getInit(thisIdx)); bs = avccbox.asAnnexB(); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); } /*LTS-START*/ if (codec == "HEVC"){ MP4::HVCC hvccbox; hvccbox.setPayload(M.getInit(thisIdx)); bs = hvccbox.asAnnexB(); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); } /*LTS-END*/ } while (i + 4 < (unsigned int)dataLen){ ThisNaluSize = Bit::btohl(dataPointer + i); if (ThisNaluSize + i + 4 > dataLen){ WARN_MSG("Too big NALU detected (%" PRIu32 " > %zu) - skipping!", ThisNaluSize + i + 4, dataLen); break; } fillPacket("\000\000\000\001", 4, firstPack, video, keyframe, pkgPid, contPkg); fillPacket(dataPointer + i + 4, ThisNaluSize, firstPack, video, keyframe, pkgPid, contPkg); i += ThisNaluSize + 4; } }else{ uint64_t offset = thisPacket.getInt("offset") * 90; bs.clear(); TS::Packet::getPESVideoLeadIn(bs, 0, packTime, offset, true, M.getBps(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg); } }else if (type == "audio"){ size_t tempLen = dataLen; if (codec == "AAC"){ tempLen += 7; // Make sure TS timestamp is sample-aligned, if possible uint32_t freq = M.getRate(thisIdx); if (freq){ uint64_t aacSamples = packTime * freq / 90000; //round to nearest packet, assuming all 1024 samples (probably wrong, but meh) aacSamples &= ~0x3FF; //Get closest 90kHz clock time to perfect sample alignment packTime = aacSamples * 90000 / freq; } } if (codec == "opus"){ tempLen += 3 + (dataLen/255); bs = TS::Packet::getPESPS1LeadIn(tempLen, packTime, M.getBps(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); bs = "\177\340"; bs.append(dataLen/255, (char)255); bs.append(1, (char)(dataLen-255*(dataLen/255))); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); }else{ bs.clear(); TS::Packet::getPESAudioLeadIn(bs, tempLen, packTime, M.getBps(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); if (codec == "AAC"){ bs = TS::getAudioHeader(dataLen, M.getInit(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); } } fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg); }else if (type == "meta"){ long unsigned int tempLen = dataLen; bs = TS::Packet::getPESMetaLeadIn(tempLen, packTime, M.getBps(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg); } if (packData.getBytesFree() < 184){ packData.addStuffing(); fillPacket(0, 0, firstPack, video, keyframe, pkgPid, contPkg); } } }// namespace Mist <commit_msg>Add a quarter frame offset to MPEG-TS AAC timestamp rounding<commit_after>#include "output_ts_base.h" #include <mist/bitfields.h> namespace Mist{ TSOutput::TSOutput(Socket::Connection &conn) : TS_BASECLASS(conn){ packCounter = 0; ts_from = 0; setBlocking(true); sendRepeatingHeaders = 0; lastHeaderTime = 0; } void TSOutput::fillPacket(char const *data, size_t dataLen, bool &firstPack, bool video, bool keyframe, size_t pkgPid, uint16_t &contPkg){ do{ if (!packData.getBytesFree()){ if ((sendRepeatingHeaders && thisPacket.getTime() - lastHeaderTime > sendRepeatingHeaders) || !packCounter){ std::set<size_t> selectedTracks; for (std::map<size_t, Comms::Users>::iterator it = userSelect.begin(); it != userSelect.end(); it++){ selectedTracks.insert(it->first); } lastHeaderTime = thisPacket.getTime(); TS::Packet tmpPack; tmpPack.FromPointer(TS::PAT); tmpPack.setContinuityCounter(++contPAT); sendTS(tmpPack.checkAndGetBuffer()); sendTS(TS::createPMT(selectedTracks, M, ++contPMT)); sendTS(TS::createSDT(streamName, ++contSDT)); packCounter += 3; } sendTS(packData.checkAndGetBuffer()); packCounter++; packData.clear(); } if (!dataLen){return;} if (packData.getBytesFree() == 184){ packData.clear(); packData.setPID(pkgPid); packData.setContinuityCounter(++contPkg); if (firstPack){ packData.setUnitStart(1); if (video){ if (keyframe){ packData.setRandomAccess(true); packData.setESPriority(true); } packData.setPCR(thisPacket.getTime() * 27000); } firstPack = false; } } size_t tmp = packData.fillFree(data, dataLen); data += tmp; dataLen -= tmp; }while (dataLen); } void TSOutput::sendNext(){ // Get ready some data to speed up accesses std::string type = M.getType(thisIdx); std::string codec = M.getCodec(thisIdx); bool video = (type == "video"); size_t pkgPid = TS::getUniqTrackID(M, thisIdx); bool &firstPack = first[thisIdx]; uint16_t &contPkg = contCounters[pkgPid]; uint64_t packTime = thisPacket.getTime(); bool keyframe = thisPacket.getInt("keyframe"); firstPack = true; char *dataPointer = 0; size_t dataLen = 0; thisPacket.getString("data", dataPointer, dataLen); // data packTime *= 90; std::string bs; // prepare bufferstring if (video){ if (codec == "H264" || codec == "HEVC"){ uint32_t extraSize = 0; // dataPointer[4] & 0x1f is used to check if this should be done later: // fillPacket("\000\000\000\001\011\360", 6); if (codec == "H264" && (dataPointer[4] & 0x1f) != 0x09){extraSize += 6;} if (keyframe){ if (codec == "H264"){ MP4::AVCC avccbox; avccbox.setPayload(M.getInit(thisIdx)); bs = avccbox.asAnnexB(); extraSize += bs.size(); } /*LTS-START*/ if (codec == "HEVC"){ MP4::HVCC hvccbox; hvccbox.setPayload(M.getInit(thisIdx)); bs = hvccbox.asAnnexB(); extraSize += bs.size(); } /*LTS-END*/ } const uint32_t MAX_PES_SIZE = 65490 - 13; uint32_t ThisNaluSize = 0; uint32_t i = 0; uint64_t offset = thisPacket.getInt("offset") * 90; bs.clear(); TS::Packet::getPESVideoLeadIn(bs, (((dataLen + extraSize) > MAX_PES_SIZE) ? 0 : dataLen + extraSize), packTime, offset, true, M.getBps(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); if (codec == "H264" && (dataPointer[4] & 0x1f) != 0x09){ // End of previous nal unit, if not already present fillPacket("\000\000\000\001\011\360", 6, firstPack, video, keyframe, pkgPid, contPkg); } if (keyframe){ if (codec == "H264"){ MP4::AVCC avccbox; avccbox.setPayload(M.getInit(thisIdx)); bs = avccbox.asAnnexB(); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); } /*LTS-START*/ if (codec == "HEVC"){ MP4::HVCC hvccbox; hvccbox.setPayload(M.getInit(thisIdx)); bs = hvccbox.asAnnexB(); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); } /*LTS-END*/ } while (i + 4 < (unsigned int)dataLen){ ThisNaluSize = Bit::btohl(dataPointer + i); if (ThisNaluSize + i + 4 > dataLen){ WARN_MSG("Too big NALU detected (%" PRIu32 " > %zu) - skipping!", ThisNaluSize + i + 4, dataLen); break; } fillPacket("\000\000\000\001", 4, firstPack, video, keyframe, pkgPid, contPkg); fillPacket(dataPointer + i + 4, ThisNaluSize, firstPack, video, keyframe, pkgPid, contPkg); i += ThisNaluSize + 4; } }else{ uint64_t offset = thisPacket.getInt("offset") * 90; bs.clear(); TS::Packet::getPESVideoLeadIn(bs, 0, packTime, offset, true, M.getBps(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg); } }else if (type == "audio"){ size_t tempLen = dataLen; if (codec == "AAC"){ tempLen += 7; // Make sure TS timestamp is sample-aligned, if possible uint32_t freq = M.getRate(thisIdx); if (freq){ uint64_t aacSamples = packTime * freq / 90000; //round to nearest packet, assuming all 1024 samples (probably wrong, but meh) aacSamples += 256;//Add a quarter frame of offset to encourage correct rounding aacSamples &= ~0x3FF; //Get closest 90kHz clock time to perfect sample alignment packTime = aacSamples * 90000 / freq; } } if (codec == "opus"){ tempLen += 3 + (dataLen/255); bs = TS::Packet::getPESPS1LeadIn(tempLen, packTime, M.getBps(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); bs = "\177\340"; bs.append(dataLen/255, (char)255); bs.append(1, (char)(dataLen-255*(dataLen/255))); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); }else{ bs.clear(); TS::Packet::getPESAudioLeadIn(bs, tempLen, packTime, M.getBps(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); if (codec == "AAC"){ bs = TS::getAudioHeader(dataLen, M.getInit(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); } } fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg); }else if (type == "meta"){ long unsigned int tempLen = dataLen; bs = TS::Packet::getPESMetaLeadIn(tempLen, packTime, M.getBps(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg); } if (packData.getBytesFree() < 184){ packData.addStuffing(); fillPacket(0, 0, firstPack, video, keyframe, pkgPid, contPkg); } } }// namespace Mist <|endoftext|>
<commit_before>#include "output_ts_base.h" #include <mist/bitfields.h> namespace Mist{ TSOutput::TSOutput(Socket::Connection &conn) : TS_BASECLASS(conn){ packCounter = 0; ts_from = 0; setBlocking(true); sendRepeatingHeaders = 0; lastHeaderTime = 0; } void TSOutput::fillPacket(char const *data, size_t dataLen, bool &firstPack, bool video, bool keyframe, size_t pkgPid, uint16_t &contPkg){ do{ if (!packData.getBytesFree()){ if ((sendRepeatingHeaders && thisPacket.getTime() - lastHeaderTime > sendRepeatingHeaders) || !packCounter){ std::set<size_t> selectedTracks; for (std::map<size_t, Comms::Users>::iterator it = userSelect.begin(); it != userSelect.end(); it++){ selectedTracks.insert(it->first); } lastHeaderTime = thisPacket.getTime(); TS::Packet tmpPack; tmpPack.FromPointer(TS::PAT); tmpPack.setContinuityCounter(++contPAT); sendTS(tmpPack.checkAndGetBuffer()); sendTS(TS::createPMT(selectedTracks, M, ++contPMT)); sendTS(TS::createSDT(streamName, ++contSDT)); packCounter += 3; } sendTS(packData.checkAndGetBuffer()); packCounter++; packData.clear(); } if (!dataLen){return;} if (packData.getBytesFree() == 184){ packData.clear(); packData.setPID(pkgPid); packData.setContinuityCounter(++contPkg); if (firstPack){ packData.setUnitStart(1); if (video){ if (keyframe){ packData.setRandomAccess(true); packData.setESPriority(true); } packData.setPCR(thisPacket.getTime() * 27000); } firstPack = false; } } size_t tmp = packData.fillFree(data, dataLen); data += tmp; dataLen -= tmp; }while (dataLen); } void TSOutput::sendNext(){ // Get ready some data to speed up accesses std::string type = M.getType(thisIdx); std::string codec = M.getCodec(thisIdx); bool video = (type == "video"); size_t pkgPid = TS::getUniqTrackID(M, thisIdx); bool &firstPack = first[thisIdx]; uint16_t &contPkg = contCounters[pkgPid]; uint64_t packTime = thisPacket.getTime(); bool keyframe = thisPacket.getInt("keyframe"); firstPack = true; char *dataPointer = 0; size_t dataLen = 0; thisPacket.getString("data", dataPointer, dataLen); // data packTime *= 90; std::string bs; // prepare bufferstring if (video){ if (codec == "H264" || codec == "HEVC"){ unsigned int extraSize = 0; // dataPointer[4] & 0x1f is used to check if this should be done later: // fillPacket("\000\000\000\001\011\360", 6); if (codec == "H264" && (dataPointer[4] & 0x1f) != 0x09){extraSize += 6;} if (keyframe){ if (codec == "H264"){ MP4::AVCC avccbox; avccbox.setPayload(M.getInit(thisIdx)); bs = avccbox.asAnnexB(); extraSize += bs.size(); } /*LTS-START*/ if (codec == "HEVC"){ MP4::HVCC hvccbox; hvccbox.setPayload(M.getInit(thisIdx)); bs = hvccbox.asAnnexB(); extraSize += bs.size(); } /*LTS-END*/ } unsigned int watKunnenWeIn1Ding = 65490 - 13; unsigned int splitCount = (dataLen + extraSize) / watKunnenWeIn1Ding; unsigned int currPack = 0; uint64_t ThisNaluSize = 0; unsigned int i = 0; unsigned int nalLead = 0; uint64_t offset = thisPacket.getInt("offset") * 90; while (currPack <= splitCount){ unsigned int alreadySent = 0; bs = TS::Packet::getPESVideoLeadIn( (currPack != splitCount ? watKunnenWeIn1Ding : dataLen + extraSize - currPack * watKunnenWeIn1Ding), packTime, offset, !currPack, M.getBps(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); if (!currPack){ if (codec == "H264" && (dataPointer[4] & 0x1f) != 0x09){ // End of previous nal unit, if not already present fillPacket("\000\000\000\001\011\360", 6, firstPack, video, keyframe, pkgPid, contPkg); alreadySent += 6; } if (keyframe){ if (codec == "H264"){ MP4::AVCC avccbox; avccbox.setPayload(M.getInit(thisIdx)); bs = avccbox.asAnnexB(); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); alreadySent += bs.size(); } /*LTS-START*/ if (codec == "HEVC"){ MP4::HVCC hvccbox; hvccbox.setPayload(M.getInit(thisIdx)); bs = hvccbox.asAnnexB(); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); alreadySent += bs.size(); } /*LTS-END*/ } } while (i + 4 < (unsigned int)dataLen){ if (nalLead){ fillPacket(&"\000\000\000\001"[4 - nalLead], nalLead, firstPack, video, keyframe, pkgPid, contPkg); i += nalLead; alreadySent += nalLead; nalLead = 0; } if (!ThisNaluSize){ ThisNaluSize = Bit::btohl(dataPointer + i); if (ThisNaluSize + i + 4 > dataLen){ WARN_MSG("Too big NALU detected (%" PRIu64 " > %" PRIu64 ") - skipping!", ThisNaluSize + i + 4, dataLen); break; } if (alreadySent + 4 > watKunnenWeIn1Ding){ nalLead = 4 - (watKunnenWeIn1Ding - alreadySent); fillPacket("\000\000\000\001", watKunnenWeIn1Ding - alreadySent, firstPack, video, keyframe, pkgPid, contPkg); i += watKunnenWeIn1Ding - alreadySent; alreadySent += watKunnenWeIn1Ding - alreadySent; }else{ fillPacket("\000\000\000\001", 4, firstPack, video, keyframe, pkgPid, contPkg); alreadySent += 4; i += 4; } } if (alreadySent + ThisNaluSize > watKunnenWeIn1Ding){ fillPacket(dataPointer + i, watKunnenWeIn1Ding - alreadySent, firstPack, video, keyframe, pkgPid, contPkg); i += watKunnenWeIn1Ding - alreadySent; ThisNaluSize -= watKunnenWeIn1Ding - alreadySent; alreadySent += watKunnenWeIn1Ding - alreadySent; }else{ fillPacket(dataPointer + i, ThisNaluSize, firstPack, video, keyframe, pkgPid, contPkg); alreadySent += ThisNaluSize; i += ThisNaluSize; ThisNaluSize = 0; } if (alreadySent == watKunnenWeIn1Ding){ packData.addStuffing(); fillPacket(0, 0, firstPack, video, keyframe, pkgPid, contPkg); firstPack = true; break; } } currPack++; } }else{ uint64_t offset = thisPacket.getInt("offset") * 90; bs = TS::Packet::getPESVideoLeadIn(0, packTime, offset, true, M.getBps(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg); } }else if (type == "audio"){ size_t tempLen = dataLen; if (codec == "AAC"){ tempLen += 7; // Make sure TS timestamp is sample-aligned, if possible uint32_t freq = M.getRate(thisIdx); if (freq){ uint64_t aacSamples = (packTime / 90) * freq / 1000; // round to nearest packet, assuming all 1024 samples (probably wrong, but meh) aacSamples += 512; aacSamples /= 1024; aacSamples *= 1024; // Get closest 90kHz clock time to perfect sample alignment packTime = aacSamples * 90000 / freq; } } bs = TS::Packet::getPESAudioLeadIn(tempLen, packTime, M.getBps(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); if (codec == "AAC"){ bs = TS::getAudioHeader(dataLen, M.getInit(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); } fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg); }else if (type == "meta"){ long unsigned int tempLen = dataLen; bs = TS::Packet::getPESMetaLeadIn(tempLen, packTime, M.getBps(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg); } if (packData.getBytesFree() < 184){ packData.addStuffing(); fillPacket(0, 0, firstPack, video, keyframe, pkgPid, contPkg); } } }// namespace Mist <commit_msg>Large video PES packets are now sent as unbounded packets instead of split over multiple PES packets<commit_after>#include "output_ts_base.h" #include <mist/bitfields.h> namespace Mist{ TSOutput::TSOutput(Socket::Connection &conn) : TS_BASECLASS(conn){ packCounter = 0; ts_from = 0; setBlocking(true); sendRepeatingHeaders = 0; lastHeaderTime = 0; } void TSOutput::fillPacket(char const *data, size_t dataLen, bool &firstPack, bool video, bool keyframe, size_t pkgPid, uint16_t &contPkg){ do{ if (!packData.getBytesFree()){ if ((sendRepeatingHeaders && thisPacket.getTime() - lastHeaderTime > sendRepeatingHeaders) || !packCounter){ std::set<size_t> selectedTracks; for (std::map<size_t, Comms::Users>::iterator it = userSelect.begin(); it != userSelect.end(); it++){ selectedTracks.insert(it->first); } lastHeaderTime = thisPacket.getTime(); TS::Packet tmpPack; tmpPack.FromPointer(TS::PAT); tmpPack.setContinuityCounter(++contPAT); sendTS(tmpPack.checkAndGetBuffer()); sendTS(TS::createPMT(selectedTracks, M, ++contPMT)); sendTS(TS::createSDT(streamName, ++contSDT)); packCounter += 3; } sendTS(packData.checkAndGetBuffer()); packCounter++; packData.clear(); } if (!dataLen){return;} if (packData.getBytesFree() == 184){ packData.clear(); packData.setPID(pkgPid); packData.setContinuityCounter(++contPkg); if (firstPack){ packData.setUnitStart(1); if (video){ if (keyframe){ packData.setRandomAccess(true); packData.setESPriority(true); } packData.setPCR(thisPacket.getTime() * 27000); } firstPack = false; } } size_t tmp = packData.fillFree(data, dataLen); data += tmp; dataLen -= tmp; }while (dataLen); } void TSOutput::sendNext(){ // Get ready some data to speed up accesses std::string type = M.getType(thisIdx); std::string codec = M.getCodec(thisIdx); bool video = (type == "video"); size_t pkgPid = TS::getUniqTrackID(M, thisIdx); bool &firstPack = first[thisIdx]; uint16_t &contPkg = contCounters[pkgPid]; uint64_t packTime = thisPacket.getTime(); bool keyframe = thisPacket.getInt("keyframe"); firstPack = true; char *dataPointer = 0; size_t dataLen = 0; thisPacket.getString("data", dataPointer, dataLen); // data packTime *= 90; std::string bs; // prepare bufferstring if (video){ if (codec == "H264" || codec == "HEVC"){ uint32_t extraSize = 0; // dataPointer[4] & 0x1f is used to check if this should be done later: // fillPacket("\000\000\000\001\011\360", 6); if (codec == "H264" && (dataPointer[4] & 0x1f) != 0x09){extraSize += 6;} if (keyframe){ if (codec == "H264"){ MP4::AVCC avccbox; avccbox.setPayload(M.getInit(thisIdx)); bs = avccbox.asAnnexB(); extraSize += bs.size(); } /*LTS-START*/ if (codec == "HEVC"){ MP4::HVCC hvccbox; hvccbox.setPayload(M.getInit(thisIdx)); bs = hvccbox.asAnnexB(); extraSize += bs.size(); } /*LTS-END*/ } const uint32_t MAX_PES_SIZE = 65490 - 13; uint32_t ThisNaluSize = 0; uint32_t i = 0; uint64_t offset = thisPacket.getInt("offset") * 90; bs = TS::Packet::getPESVideoLeadIn( (((dataLen + extraSize) > MAX_PES_SIZE) ? 0 : dataLen + extraSize), packTime, offset, true, M.getBps(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); if (codec == "H264" && (dataPointer[4] & 0x1f) != 0x09){ // End of previous nal unit, if not already present fillPacket("\000\000\000\001\011\360", 6, firstPack, video, keyframe, pkgPid, contPkg); } if (keyframe){ if (codec == "H264"){ MP4::AVCC avccbox; avccbox.setPayload(M.getInit(thisIdx)); bs = avccbox.asAnnexB(); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); } /*LTS-START*/ if (codec == "HEVC"){ MP4::HVCC hvccbox; hvccbox.setPayload(M.getInit(thisIdx)); bs = hvccbox.asAnnexB(); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); } /*LTS-END*/ } while (i + 4 < (unsigned int)dataLen){ ThisNaluSize = Bit::btohl(dataPointer + i); if (ThisNaluSize + i + 4 > dataLen){ WARN_MSG("Too big NALU detected (%" PRIu32 " > %" PRIu64 ") - skipping!", ThisNaluSize + i + 4, dataLen); break; } fillPacket("\000\000\000\001", 4, firstPack, video, keyframe, pkgPid, contPkg); fillPacket(dataPointer + i + 4, ThisNaluSize, firstPack, video, keyframe, pkgPid, contPkg); i += ThisNaluSize + 4; } }else{ uint64_t offset = thisPacket.getInt("offset") * 90; bs = TS::Packet::getPESVideoLeadIn(0, packTime, offset, true, M.getBps(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg); } }else if (type == "audio"){ size_t tempLen = dataLen; if (codec == "AAC"){ tempLen += 7; // Make sure TS timestamp is sample-aligned, if possible uint32_t freq = M.getRate(thisIdx); if (freq){ uint64_t aacSamples = (packTime / 90) * freq / 1000; // round to nearest packet, assuming all 1024 samples (probably wrong, but meh) aacSamples += 512; aacSamples /= 1024; aacSamples *= 1024; // Get closest 90kHz clock time to perfect sample alignment packTime = aacSamples * 90000 / freq; } } bs = TS::Packet::getPESAudioLeadIn(tempLen, packTime, M.getBps(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); if (codec == "AAC"){ bs = TS::getAudioHeader(dataLen, M.getInit(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); } fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg); }else if (type == "meta"){ long unsigned int tempLen = dataLen; bs = TS::Packet::getPESMetaLeadIn(tempLen, packTime, M.getBps(thisIdx)); fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg); fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg); } if (packData.getBytesFree() < 184){ packData.addStuffing(); fillPacket(0, 0, firstPack, video, keyframe, pkgPid, contPkg); } } }// namespace Mist <|endoftext|>
<commit_before>/** * @file pendingcontactrequest.cpp * @brief Class for manipulating pending contact requests * * (c) 2013-2014 by Mega Limited, Wellsford, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #include "mega/pendingcontactrequest.h" #include "mega/megaclient.h" namespace mega { PendingContactRequest::PendingContactRequest(const handle id) { this->id = id; this->ts = 0; this->uts = 0; this->isoutgoing = true; memset(&changed, 0, sizeof changed); } PendingContactRequest::PendingContactRequest(const handle id,const char *oemail, const char *temail, const m_time_t ts, const m_time_t uts, const char *msg, bool outgoing) { this->id = id; this->targetemail = ""; this->update(oemail, temail, ts, uts, msg, outgoing); } void PendingContactRequest::update(const char *oemail, const char *temail, const m_time_t ts, const m_time_t uts, const char *msg, bool outgoing) { if (oemail) { Node::copystring(&(this->originatoremail), oemail); } if (temail) { Node::copystring(&(this->targetemail), temail); } this->ts = ts; this->uts = uts; if (msg) { Node::copystring(&(this->msg), msg); } this->isoutgoing = outgoing; memset(&changed, 0, sizeof changed); } bool PendingContactRequest::removed() { return changed.accepted || changed.denied || changed.ignored || changed.deleted; } bool PendingContactRequest::serialize(string *d) { unsigned char l; d->append((char*)&id, sizeof id); l = (unsigned char)originatoremail.size(); d->append((char*)&l, sizeof l); d->append(originatoremail.c_str(), l); l = (unsigned char)targetemail.size(); d->append((char*)&l, sizeof l); d->append(targetemail.c_str(), l); d->append((char*)&ts, sizeof ts); d->append((char*)&uts, sizeof uts); l = (unsigned char)msg.size(); d->append((char*)&l, sizeof l); d->append(msg.c_str(), l); d->append((char*)&isoutgoing, sizeof isoutgoing); return true; } PendingContactRequest* PendingContactRequest::unserialize(class MegaClient *client, string *d) { handle id; string oemail; string temail; m_time_t ts; m_time_t uts; string msg; bool isoutgoing; const char* ptr = d->data(); const char* end = ptr + d->size(); unsigned char l; if (ptr + sizeof id + sizeof l > end) { return NULL; } id = MemAccess::get<handle>(ptr); ptr += sizeof id; l = *ptr++; if (ptr + l + sizeof l > end) { return NULL; } oemail.assign(ptr, l); ptr += l; l = *ptr++; if (ptr + l + sizeof ts + sizeof uts + sizeof l > end) { return NULL; } temail.assign(ptr, l); ptr += l; ts = MemAccess::get<m_time_t>(ptr); ptr += sizeof ts; uts = MemAccess::get<m_time_t>(ptr); ptr += sizeof uts; l = *ptr++; if (ptr + l > end) { return NULL; } msg.assign(ptr, l); ptr += l; isoutgoing = MemAccess::get<bool>(ptr); ptr += sizeof isoutgoing; if (ptr == end) { PendingContactRequest *pcr = new PendingContactRequest(id, oemail.c_str(), temail.c_str(), ts, uts, msg.c_str(), isoutgoing); client->mappcr(id, pcr); return pcr; } else { return NULL; } } } //namespace <commit_msg>Fix PCR::unserialize to protect against 0 byte field<commit_after>/** * @file pendingcontactrequest.cpp * @brief Class for manipulating pending contact requests * * (c) 2013-2014 by Mega Limited, Wellsford, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #include "mega/pendingcontactrequest.h" #include "mega/megaclient.h" namespace mega { PendingContactRequest::PendingContactRequest(const handle id) { this->id = id; this->ts = 0; this->uts = 0; this->isoutgoing = true; memset(&changed, 0, sizeof changed); } PendingContactRequest::PendingContactRequest(const handle id,const char *oemail, const char *temail, const m_time_t ts, const m_time_t uts, const char *msg, bool outgoing) { this->id = id; this->targetemail = ""; this->update(oemail, temail, ts, uts, msg, outgoing); } void PendingContactRequest::update(const char *oemail, const char *temail, const m_time_t ts, const m_time_t uts, const char *msg, bool outgoing) { if (oemail) { Node::copystring(&(this->originatoremail), oemail); } if (temail) { Node::copystring(&(this->targetemail), temail); } this->ts = ts; this->uts = uts; if (msg) { Node::copystring(&(this->msg), msg); } this->isoutgoing = outgoing; memset(&changed, 0, sizeof changed); } bool PendingContactRequest::removed() { return changed.accepted || changed.denied || changed.ignored || changed.deleted; } bool PendingContactRequest::serialize(string *d) { unsigned char l; d->append((char*)&id, sizeof id); l = (unsigned char)originatoremail.size(); d->append((char*)&l, sizeof l); d->append(originatoremail.c_str(), l); l = (unsigned char)targetemail.size(); d->append((char*)&l, sizeof l); d->append(targetemail.c_str(), l); d->append((char*)&ts, sizeof ts); d->append((char*)&uts, sizeof uts); l = (unsigned char)msg.size(); d->append((char*)&l, sizeof l); d->append(msg.c_str(), l); d->append((char*)&isoutgoing, sizeof isoutgoing); return true; } PendingContactRequest* PendingContactRequest::unserialize(class MegaClient *client, string *d) { handle id; string oemail; string temail; m_time_t ts; m_time_t uts; string msg; bool isoutgoing; const char* ptr = d->data(); const char* end = ptr + d->size(); unsigned char l; if (ptr + sizeof id + sizeof l > end) { return NULL; } id = MemAccess::get<handle>(ptr); ptr += sizeof id; l = *ptr++; if (ptr + l + sizeof l > end) { return NULL; } oemail.assign(ptr, l); ptr += l; l = *ptr++; if (ptr + l + sizeof ts + sizeof uts + sizeof l > end) { return NULL; } temail.assign(ptr, l); ptr += l; ts = MemAccess::get<m_time_t>(ptr); ptr += sizeof ts; uts = MemAccess::get<m_time_t>(ptr); ptr += sizeof uts; l = *ptr++; if (ptr + l > end) // should be ptr+l+sizeof(isoutgoing), but legacy code writes 0 bytes when false { return NULL; } msg.assign(ptr, l); ptr += l; if (ptr == end) // legacy bug writes 0 bytes for incoming PCRs { isoutgoing = false; } else if (ptr + sizeof isoutgoing == end) { isoutgoing = MemAccess::get<bool>(ptr); ptr += sizeof isoutgoing; } if (ptr == end) { PendingContactRequest *pcr = new PendingContactRequest(id, oemail.c_str(), temail.c_str(), ts, uts, msg.c_str(), isoutgoing); client->mappcr(id, pcr); return pcr; } else { return NULL; } } } //namespace <|endoftext|>
<commit_before><commit_msg>distance joint spring enabled by default<commit_after><|endoftext|>
<commit_before>#include <os> #include <info> #include <smp> #include <statman> #include <kernel/timers.hpp> #include <kernel/solo5_manager.hpp> extern "C" { #include <solo5.h> } // sleep statistics static uint64_t os_cycles_hlt = 0; extern "C" void* get_cpu_esp(); extern uintptr_t _start; extern uintptr_t _end; extern uintptr_t mem_size; extern uintptr_t _ELF_START_; extern uintptr_t _TEXT_START_; extern uintptr_t _LOAD_START_; extern uintptr_t _ELF_END_; // in kernel/os.cpp extern bool os_default_stdout; typedef void (*ctor_t) (); extern ctor_t __init_array_start; extern ctor_t __init_array_end; extern int __run_ctors(ctor_t* begin, ctor_t* end); #define MYINFO(X,...) INFO("Kernel", X, ##__VA_ARGS__) #ifdef ENABLE_PROFILERS #include <profile> #define PROFILE(name) ScopedProfiler __CONCAT(sp, __COUNTER__){name}; #else #define PROFILE(name) /* name */ #endif void solo5_poweroff() { __asm__ __volatile__("cli; hlt"); for(;;); } // returns wall clock time in nanoseconds since the UNIX epoch uint64_t __arch_system_time() noexcept { return solo5_clock_wall(); } timespec __arch_wall_clock() noexcept { uint64_t stamp = solo5_clock_wall(); timespec result; result.tv_sec = stamp / 1000000000ul; result.tv_nsec = stamp % 1000000000ul; return result; } // actually uses nanoseconds (but its just a number) uint64_t OS::cycles_asleep() noexcept { return os_cycles_hlt; } uint64_t OS::nanos_asleep() noexcept { return os_cycles_hlt; } void OS::default_stdout(const char* str, const size_t len) { solo5_console_write(str, len); } void OS::start(const char* cmdline) { OS::cmdline = cmdline; // Initialize stdout handlers if(os_default_stdout) { OS::add_stdout(&OS::default_stdout); } PROFILE(""); // Print a fancy header CAPTION("#include<os> // Literally"); void* esp = get_cpu_esp(); MYINFO("Stack: %p", esp); /// STATMAN /// /// initialize on page 7, 2 pages in size Statman::get().init(0x6000, 0x3000); // Call global ctors PROFILE("Global kernel constructors"); __run_ctors(&__init_array_start, &__init_array_end); PROFILE("Memory map"); // Assign memory ranges used by the kernel auto& memmap = memory_map(); MYINFO("Assigning fixed memory ranges (Memory map)"); memmap.assign_range({0x500, 0x5fff, "solo5"}); memmap.assign_range({0x6000, 0x8fff, "Statman"}); memmap.assign_range({0xA000, 0x9fbff, "Stack"}); memmap.assign_range({(uintptr_t)&_LOAD_START_, (uintptr_t)&_end, "ELF"}); Expects(heap_begin() and heap_max_); // @note for security we don't want to expose this memmap.assign_range({(uintptr_t)&_end + 1, heap_begin() - 1, "Pre-heap"}); uintptr_t span_max = std::numeric_limits<std::ptrdiff_t>::max(); uintptr_t heap_range_max_ = std::min(span_max, heap_max_); MYINFO("Assigning heap"); memmap.assign_range({heap_begin(), heap_range_max_, "Dynamic memory", heap_usage }); MYINFO("Printing memory map"); for (const auto &i : memmap) INFO2("* %s",i.second.to_string().c_str()); extern void __platform_init(); __platform_init(); MYINFO("Booted at monotonic_ns=%ld walltime_ns=%ld", solo5_clock_monotonic(), solo5_clock_wall()); Solo5_manager::init(); // We don't need a start or stop function in solo5. Timers::init( // timer start function [] (auto) {}, // timer stop function [] () {}); Timers::ready(); } static inline void event_loop_inner() { int res = 0; auto nxt = Timers::next(); if (nxt == std::chrono::nanoseconds(0)) { // no next timer, just wait a while res = solo5_yield(solo5_clock_monotonic() + 500000000ULL); // 500 ms //printf("Waiting, next is indeterminate...\n"); } else if (nxt == std::chrono::nanoseconds(1)) { // there is an imminent or activated timer, don't wait //printf("Not waiting, imminent timer...\n"); } else { res = solo5_yield(solo5_clock_monotonic() + nxt.count()); //printf("Waiting %llu nanos\n", nxt.count()); } // handle any activated timers Timers::timers_handler(); if (res != 0) { // handle any network traffic for(auto& nic : hw::Devices::devices<hw::Nic>()) { nic->poll(); } } } void OS::event_loop() { while (power_) { // add a global symbol here so we can quickly discard // event loop from stack sampling asm volatile( ".global _irq_cb_return_location;\n" "_irq_cb_return_location:" ); event_loop_inner(); } MYINFO("Stopping service"); Service::stop(); MYINFO("Powering off"); solo5_poweroff(); } __attribute__((noinline)) void OS::halt() { auto cycles_before = solo5_clock_monotonic(); #if defined(ARCH_x86) asm volatile("hlt"); #else #warning "OS::halt() not implemented for selected arch" #endif // Count sleep nanos os_cycles_hlt += solo5_clock_monotonic() - cycles_before; } void OS::block() { static uint32_t blocking_level = 0; blocking_level += 1; // prevent recursion stack overflow assert(blocking_level < 200); event_loop_inner(); // Decrement level blocking_level -= 1; } <commit_msg>solo5: Wait longer, process events<commit_after>#include <os> #include <info> #include <smp> #include <statman> #include <kernel/events.hpp> #include <kernel/timers.hpp> #include <kernel/solo5_manager.hpp> extern "C" { #include <solo5.h> } // sleep statistics static uint64_t os_cycles_hlt = 0; extern "C" void* get_cpu_esp(); extern uintptr_t _start; extern uintptr_t _end; extern uintptr_t mem_size; extern uintptr_t _ELF_START_; extern uintptr_t _TEXT_START_; extern uintptr_t _LOAD_START_; extern uintptr_t _ELF_END_; // in kernel/os.cpp extern bool os_default_stdout; typedef void (*ctor_t) (); extern ctor_t __init_array_start; extern ctor_t __init_array_end; extern int __run_ctors(ctor_t* begin, ctor_t* end); #define MYINFO(X,...) INFO("Kernel", X, ##__VA_ARGS__) #ifdef ENABLE_PROFILERS #include <profile> #define PROFILE(name) ScopedProfiler __CONCAT(sp, __COUNTER__){name}; #else #define PROFILE(name) /* name */ #endif void solo5_poweroff() { __asm__ __volatile__("cli; hlt"); for(;;); } // returns wall clock time in nanoseconds since the UNIX epoch uint64_t __arch_system_time() noexcept { return solo5_clock_wall(); } timespec __arch_wall_clock() noexcept { uint64_t stamp = solo5_clock_wall(); timespec result; result.tv_sec = stamp / 1000000000ul; result.tv_nsec = stamp % 1000000000ul; return result; } // actually uses nanoseconds (but its just a number) uint64_t OS::cycles_asleep() noexcept { return os_cycles_hlt; } uint64_t OS::nanos_asleep() noexcept { return os_cycles_hlt; } void OS::default_stdout(const char* str, const size_t len) { solo5_console_write(str, len); } void OS::start(const char* cmdline) { OS::cmdline = cmdline; // Initialize stdout handlers if(os_default_stdout) { OS::add_stdout(&OS::default_stdout); } PROFILE(""); // Print a fancy header CAPTION("#include<os> // Literally"); void* esp = get_cpu_esp(); MYINFO("Stack: %p", esp); /// STATMAN /// /// initialize on page 7, 2 pages in size Statman::get().init(0x6000, 0x3000); // Call global ctors PROFILE("Global kernel constructors"); __run_ctors(&__init_array_start, &__init_array_end); PROFILE("Memory map"); // Assign memory ranges used by the kernel auto& memmap = memory_map(); MYINFO("Assigning fixed memory ranges (Memory map)"); memmap.assign_range({0x500, 0x5fff, "solo5"}); memmap.assign_range({0x6000, 0x8fff, "Statman"}); memmap.assign_range({0xA000, 0x9fbff, "Stack"}); memmap.assign_range({(uintptr_t)&_LOAD_START_, (uintptr_t)&_end, "ELF"}); Expects(heap_begin() and heap_max_); // @note for security we don't want to expose this memmap.assign_range({(uintptr_t)&_end + 1, heap_begin() - 1, "Pre-heap"}); uintptr_t span_max = std::numeric_limits<std::ptrdiff_t>::max(); uintptr_t heap_range_max_ = std::min(span_max, heap_max_); MYINFO("Assigning heap"); memmap.assign_range({heap_begin(), heap_range_max_, "Dynamic memory", heap_usage }); MYINFO("Printing memory map"); for (const auto &i : memmap) INFO2("* %s",i.second.to_string().c_str()); extern void __platform_init(); __platform_init(); MYINFO("Booted at monotonic_ns=%ld walltime_ns=%ld", solo5_clock_monotonic(), solo5_clock_wall()); Solo5_manager::init(); // We don't need a start or stop function in solo5. Timers::init( // timer start function [] (auto) {}, // timer stop function [] () {}); Events::get().defer(Timers::ready); } static inline void event_loop_inner() { int res = 0; auto nxt = Timers::next(); if (nxt == std::chrono::nanoseconds(0)) { // no next timer, wait forever //printf("Waiting 15s, next is indeterminate...\n"); const unsigned long long count = 15000000000ULL; res = solo5_yield(solo5_clock_monotonic() + count); os_cycles_hlt += count; } else if (nxt == std::chrono::nanoseconds(1)) { // there is an imminent or activated timer, don't wait //printf("Not waiting, imminent timer...\n"); } else { //printf("Waiting %llu nanos\n", nxt.count()); res = solo5_yield(solo5_clock_monotonic() + nxt.count()); os_cycles_hlt += nxt.count(); } // handle any activated timers Timers::timers_handler(); Events::get().process_events(); if (res != 0) { // handle any network traffic for(auto& nic : hw::Devices::devices<hw::Nic>()) { nic->poll(); } } } void OS::event_loop() { while (power_) { // add a global symbol here so we can quickly discard // event loop from stack sampling asm volatile( ".global _irq_cb_return_location;\n" "_irq_cb_return_location:" ); event_loop_inner(); } MYINFO("Stopping service"); Service::stop(); MYINFO("Powering off"); solo5_poweroff(); } __attribute__((noinline)) void OS::halt() { auto cycles_before = solo5_clock_monotonic(); #if defined(ARCH_x86) asm volatile("hlt"); #else #warning "OS::halt() not implemented for selected arch" #endif // Count sleep nanos os_cycles_hlt += solo5_clock_monotonic() - cycles_before; } void OS::block() { static uint32_t blocking_level = 0; blocking_level += 1; // prevent recursion stack overflow assert(blocking_level < 200); event_loop_inner(); // Decrement level blocking_level -= 1; } <|endoftext|>
<commit_before> /*! \file \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2014 Igor Mironchik 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. */ // QtMWidgets include. #include "cursorshifter.hpp" #include "color.hpp" #include "fingergeometry.hpp" // Qt include. #include <QTimer> #include <QPainter> #include <QMouseEvent> #include <QPainterPath> #include <QApplication> #include <QEvent> #include <QBitmap> namespace QtMWidgets { // // CursorShifterPrivate // class CursorShifterPrivate { public: CursorShifterPrivate( CursorShifter * parent ) : q( parent ) , leftMouseButtonPressed( false ) , cursorOverrided( false ) { } void init(); CursorShifter * q; QColor color; QColor light; int basicSize; QPoint cursorPos; QTimer * timer; bool leftMouseButtonPressed; QPoint offset; bool cursorOverrided; }; // class CursorShifterPrivate void CursorShifterPrivate::init() { color = q->palette().color( QPalette::Highlight ); light = lighterColor( color, 75 ); basicSize = qRound( (qreal) FingerGeometry::width() * 0.2 ); timer = new QTimer( q ); q->setAttribute( Qt::WA_TranslucentBackground ); q->setAttribute( Qt::WA_NoSystemBackground ); q->setWindowModality( Qt::NonModal ); QObject::connect( timer, SIGNAL( timeout() ), q, SLOT( _q_hideTimer() ) ); } // // CursorShifter // CursorShifter::CursorShifter( QWidget * parent ) : QWidget( parent, Qt::ToolTip | Qt::FramelessWindowHint | Qt::WindowDoesNotAcceptFocus | Qt::WindowTransparentForInput | Qt::NoDropShadowWindowHint | Qt::WindowStaysOnTopHint ) , d( new CursorShifterPrivate( this ) ) { d->init(); } CursorShifter::~CursorShifter() { } QPoint CursorShifter::cursorPos() const { return d->cursorPos; } QSize CursorShifter::minimumSizeHint() const { return QSize( d->basicSize * 2, d->basicSize * 3 ); } QSize CursorShifter::sizeHint() const { return minimumSizeHint(); } void CursorShifter::setCursorPos( const QPoint & pos ) { if( d->cursorPos != pos ) { d->cursorPos = pos; move( QPoint( d->cursorPos.x() - d->basicSize, d->cursorPos.y() ) ); } } void CursorShifter::popup() { qApp->installEventFilter( this ); show(); d->timer->start( 3000 ); } void CursorShifter::immediatelyHide() { d->timer->stop(); qApp->removeEventFilter( this ); hide(); if( d->cursorOverrided ) { d->cursorOverrided = false; QApplication::restoreOverrideCursor(); } } void CursorShifter::paintEvent( QPaintEvent * ) { QPainter p( this ); p.setRenderHint( QPainter::Antialiasing ); QPainterPath roof; roof.moveTo( d->basicSize, 0 ); roof.lineTo( d->basicSize * 2, d->basicSize ); roof.lineTo( 0, d->basicSize ); roof.lineTo( d->basicSize, 0 ); p.setPen( d->color ); p.setBrush( d->light ); p.drawPath( roof ); p.setBrush( d->color ); p.drawRect( 0, d->basicSize, d->basicSize * 2, d->basicSize * 2 ); } bool CursorShifter::eventFilter( QObject * obj, QEvent * e ) { Q_UNUSED( obj ) switch( e->type() ) { case QEvent::MouseButtonPress : { QMouseEvent * me = static_cast< QMouseEvent* > ( e ); QRect r = rect(); r.moveTo( pos() ); const QPoint pos = me->globalPos(); if( isVisible() && r.contains( pos ) ) { d->leftMouseButtonPressed = true; d->timer->stop(); d->offset = QPoint( r.topLeft().x() + d->basicSize - pos.x(), pos.y() - r.topLeft().y() ); return true; } return false; } break; case QEvent::MouseButtonRelease : { if( d->leftMouseButtonPressed ) { d->leftMouseButtonPressed = false; d->timer->start( 3000 ); return true; } return false; } break; case QEvent::MouseMove : { QMouseEvent * me = static_cast< QMouseEvent* > ( e ); QRect r = rect(); r.moveTo( pos() ); const QPoint pos = me->globalPos(); if( isVisible() && r.contains( pos ) && !d->cursorOverrided ) { d->cursorOverrided = true; QApplication::setOverrideCursor( QCursor( Qt::ArrowCursor ) ); } else if( d->cursorOverrided && ( !r.contains( pos ) | !isVisible() ) ) { d->cursorOverrided = false; QApplication::restoreOverrideCursor(); } if( d->leftMouseButtonPressed ) { emit posChanged( me->globalPos() - d->offset ); return true; } return false; } break; default : return false; } } void CursorShifter::_q_hideTimer() { qApp->removeEventFilter( this ); hide(); if( d->cursorOverrided ) { d->cursorOverrided = false; QApplication::restoreOverrideCursor(); } } } /* namespace QtMWidgets */ <commit_msg>Modifier CursorShifter.<commit_after> /*! \file \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2014 Igor Mironchik 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. */ // QtMWidgets include. #include "cursorshifter.hpp" #include "color.hpp" #include "fingergeometry.hpp" // Qt include. #include <QTimer> #include <QPainter> #include <QMouseEvent> #include <QPainterPath> #include <QApplication> #include <QEvent> #include <QBitmap> namespace QtMWidgets { // // CursorShifterPrivate // class CursorShifterPrivate { public: CursorShifterPrivate( CursorShifter * parent ) : q( parent ) , leftMouseButtonPressed( false ) , cursorOverrided( false ) { } void init(); CursorShifter * q; QColor color; QColor light; int basicSize; QPoint cursorPos; QTimer * timer; bool leftMouseButtonPressed; QPoint offset; bool cursorOverrided; }; // class CursorShifterPrivate void CursorShifterPrivate::init() { color = q->palette().color( QPalette::Highlight ); light = lighterColor( color, 75 ); basicSize = qRound( (qreal) FingerGeometry::width() * 0.2 ); timer = new QTimer( q ); q->setWindowModality( Qt::NonModal ); QObject::connect( timer, SIGNAL( timeout() ), q, SLOT( _q_hideTimer() ) ); } // // CursorShifter // CursorShifter::CursorShifter( QWidget * parent ) : QWidget( parent, Qt::ToolTip | Qt::FramelessWindowHint | Qt::WindowDoesNotAcceptFocus | Qt::WindowTransparentForInput | Qt::NoDropShadowWindowHint | Qt::WindowStaysOnTopHint ) , d( new CursorShifterPrivate( this ) ) { d->init(); } CursorShifter::~CursorShifter() { } QPoint CursorShifter::cursorPos() const { return d->cursorPos; } QSize CursorShifter::minimumSizeHint() const { return QSize( d->basicSize * 2, d->basicSize * 3 ); } QSize CursorShifter::sizeHint() const { return minimumSizeHint(); } void CursorShifter::setCursorPos( const QPoint & pos ) { if( d->cursorPos != pos ) { d->cursorPos = pos; move( QPoint( d->cursorPos.x() - d->basicSize, d->cursorPos.y() ) ); } } void CursorShifter::popup() { qApp->installEventFilter( this ); show(); d->timer->start( 3000 ); } void CursorShifter::immediatelyHide() { d->timer->stop(); qApp->removeEventFilter( this ); hide(); if( d->cursorOverrided ) { d->cursorOverrided = false; QApplication::restoreOverrideCursor(); } } void CursorShifter::paintEvent( QPaintEvent * ) { QPainter p( this ); p.setRenderHint( QPainter::Antialiasing ); QPainterPath roof; roof.moveTo( d->basicSize, 0 ); roof.lineTo( d->basicSize * 2, d->basicSize ); roof.lineTo( 0, d->basicSize ); roof.lineTo( d->basicSize, 0 ); p.setPen( d->color ); p.setBrush( d->light ); p.drawPath( roof ); p.setBrush( d->color ); p.drawRect( 0, d->basicSize, d->basicSize * 2, d->basicSize * 2 ); } bool CursorShifter::eventFilter( QObject * obj, QEvent * e ) { Q_UNUSED( obj ) switch( e->type() ) { case QEvent::MouseButtonPress : { QMouseEvent * me = static_cast< QMouseEvent* > ( e ); QRect r = rect(); r.moveTo( pos() ); const QPoint pos = me->globalPos(); if( isVisible() && r.contains( pos ) ) { d->leftMouseButtonPressed = true; d->timer->stop(); d->offset = QPoint( r.topLeft().x() + d->basicSize - pos.x(), pos.y() - r.topLeft().y() ); return true; } return false; } break; case QEvent::MouseButtonRelease : { if( d->leftMouseButtonPressed ) { d->leftMouseButtonPressed = false; d->timer->start( 3000 ); return true; } return false; } break; case QEvent::MouseMove : { QMouseEvent * me = static_cast< QMouseEvent* > ( e ); QRect r = rect(); r.moveTo( pos() ); const QPoint pos = me->globalPos(); if( isVisible() && r.contains( pos ) && !d->cursorOverrided ) { d->cursorOverrided = true; QApplication::setOverrideCursor( QCursor( Qt::ArrowCursor ) ); } else if( d->cursorOverrided && ( !r.contains( pos ) | !isVisible() ) ) { d->cursorOverrided = false; QApplication::restoreOverrideCursor(); } if( d->leftMouseButtonPressed ) { emit posChanged( me->globalPos() - d->offset ); return true; } return false; } break; default : return false; } } void CursorShifter::_q_hideTimer() { qApp->removeEventFilter( this ); hide(); if( d->cursorOverrided ) { d->cursorOverrided = false; QApplication::restoreOverrideCursor(); } } } /* namespace QtMWidgets */ <|endoftext|>
<commit_before>// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <wallet/wallet.h> #include <qt/receivecoinsdialog.h> #include <qt/forms/ui_receivecoinsdialog.h> #include <qt/addressbookpage.h> #include <qt/addresstablemodel.h> #include <qt/bitcoinunits.h> #include <qt/optionsmodel.h> #include <qt/platformstyle.h> #include <qt/receiverequestdialog.h> #include <qt/recentrequeststablemodel.h> #include <qt/walletmodel.h> #include <QAction> #include <QCursor> #include <QMessageBox> #include <QScrollBar> #include <QTextDocument> ReceiveCoinsDialog::ReceiveCoinsDialog(const PlatformStyle *_platformStyle, QWidget *parent) : QDialog(parent), ui(new Ui::ReceiveCoinsDialog), columnResizingFixer(0), model(0), platformStyle(_platformStyle) { ui->setupUi(this); QString theme = GUIUtil::getThemeName(); if (!_platformStyle->getImagesOnButtons()) { ui->clearButton->setIcon(QIcon()); ui->receiveButton->setIcon(QIcon()); ui->showRequestButton->setIcon(QIcon()); ui->removeRequestButton->setIcon(QIcon()); } else { ui->clearButton->setIcon(QIcon(":/icons/" + theme + "/remove")); ui->receiveButton->setIcon(QIcon(":/icons/" + theme + "/receiving_addresses")); ui->showRequestButton->setIcon(QIcon(":/icons/" + theme + "/edit")); ui->removeRequestButton->setIcon(QIcon(":/icons/" + theme + "/remove")); } // context menu actions QAction *copyURIAction = new QAction(tr("Copy URI"), this); QAction *copyLabelAction = new QAction(tr("Copy label"), this); QAction *copyMessageAction = new QAction(tr("Copy message"), this); QAction *copyAmountAction = new QAction(tr("Copy amount"), this); // context menu contextMenu = new QMenu(this); contextMenu->addAction(copyURIAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(copyMessageAction); contextMenu->addAction(copyAmountAction); // context menu signals connect(ui->recentRequestsView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint))); connect(copyURIAction, SIGNAL(triggered()), this, SLOT(copyURI())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel())); connect(copyMessageAction, SIGNAL(triggered()), this, SLOT(copyMessage())); connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); } void ReceiveCoinsDialog::setModel(WalletModel *_model) { this->model = _model; if(_model && _model->getOptionsModel()) { _model->getRecentRequestsTableModel()->sort(RecentRequestsTableModel::Date, Qt::DescendingOrder); connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); updateDisplayUnit(); QTableView* tableView = ui->recentRequestsView; tableView->verticalHeader()->hide(); tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); tableView->setModel(_model->getRecentRequestsTableModel()); tableView->setAlternatingRowColors(true); tableView->setSelectionBehavior(QAbstractItemView::SelectRows); tableView->setSelectionMode(QAbstractItemView::ContiguousSelection); tableView->setColumnWidth(RecentRequestsTableModel::Date, DATE_COLUMN_WIDTH); tableView->setColumnWidth(RecentRequestsTableModel::Label, LABEL_COLUMN_WIDTH); connect(tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(recentRequestsView_selectionChanged(QItemSelection, QItemSelection))); // Last 2 columns are set by the columnResizingFixer, when the table geometry is ready. columnResizingFixer = new GUIUtil::TableViewLastColumnResizingFixer(tableView, AMOUNT_MINIMUM_COLUMN_WIDTH, DATE_COLUMN_WIDTH, this); // configure bech32 checkbox, disable if launched with legacy as default: if (model->wallet().getDefaultAddressType() == OutputType::BECH32) { ui->useBech32->setCheckState(Qt::Checked); } else { ui->useBech32->setCheckState(Qt::Unchecked); } ui->useBech32->setVisible(model->wallet().getDefaultAddressType() != OutputType::LEGACY); } } ReceiveCoinsDialog::~ReceiveCoinsDialog() { delete ui; } void ReceiveCoinsDialog::clear() { ui->reqAmount->clear(); ui->reqLabel->setText(""); ui->reqMessage->setText(""); updateDisplayUnit(); } void ReceiveCoinsDialog::reject() { clear(); } void ReceiveCoinsDialog::accept() { clear(); } void ReceiveCoinsDialog::updateDisplayUnit() { if(model && model->getOptionsModel()) { ui->reqAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } } void ReceiveCoinsDialog::on_receiveButton_clicked() { if(!model || !model->getOptionsModel() || !model->getAddressTableModel() || !model->getRecentRequestsTableModel()) return; QString address; QString label = ui->reqLabel->text(); /* Generate new receiving address */ OutputType address_type = model->wallet().getDefaultAddressType(); if (address_type != OutputType::LEGACY) { address_type = ui->useBech32->isChecked() ? OutputType::BECH32 : OutputType::P2SH_SEGWIT; } address = model->getAddressTableModel()->addRow(AddressTableModel::Receive, label, "", address_type); SendCoinsRecipient info(address, label, ui->reqAmount->value(), ui->reqMessage->text()); ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setModel(model); dialog->setInfo(info); dialog->show(); clear(); /* Store request for later reference */ model->getRecentRequestsTableModel()->addNewRequest(info); } void ReceiveCoinsDialog::on_recentRequestsView_doubleClicked(const QModelIndex &index) { const RecentRequestsTableModel *submodel = model->getRecentRequestsTableModel(); ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this); dialog->setModel(model); dialog->setInfo(submodel->entry(index.row()).recipient); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->show(); } void ReceiveCoinsDialog::recentRequestsView_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { // Enable Show/Remove buttons only if anything is selected. bool enable = !ui->recentRequestsView->selectionModel()->selectedRows().isEmpty(); ui->showRequestButton->setEnabled(enable); ui->removeRequestButton->setEnabled(enable); } void ReceiveCoinsDialog::on_showRequestButton_clicked() { if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel()) return; QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows(); for (const QModelIndex& index : selection) { on_recentRequestsView_doubleClicked(index); } } void ReceiveCoinsDialog::on_removeRequestButton_clicked() { if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel()) return; QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows(); if(selection.empty()) return; // correct for selection mode ContiguousSelection QModelIndex firstIndex = selection.at(0); model->getRecentRequestsTableModel()->removeRows(firstIndex.row(), selection.length(), firstIndex.parent()); } // We override the virtual resizeEvent of the QWidget to adjust tables column // sizes as the tables width is proportional to the dialogs width. void ReceiveCoinsDialog::resizeEvent(QResizeEvent *event) { QWidget::resizeEvent(event); columnResizingFixer->stretchColumnWidth(RecentRequestsTableModel::Message); } void ReceiveCoinsDialog::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Return) { // press return -> submit form if (ui->reqLabel->hasFocus() || ui->reqAmount->hasFocus() || ui->reqMessage->hasFocus()) { event->ignore(); on_receiveButton_clicked(); return; } } this->QDialog::keyPressEvent(event); } QModelIndex ReceiveCoinsDialog::selectedRow() { if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel()) return QModelIndex(); QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows(); if(selection.empty()) return QModelIndex(); // correct for selection mode ContiguousSelection QModelIndex firstIndex = selection.at(0); return firstIndex; } // copy column of selected row to clipboard void ReceiveCoinsDialog::copyColumnToClipboard(int column) { QModelIndex firstIndex = selectedRow(); if (!firstIndex.isValid()) { return; } GUIUtil::setClipboard(model->getRecentRequestsTableModel()->data(firstIndex.child(firstIndex.row(), column), Qt::EditRole).toString()); } // context menu void ReceiveCoinsDialog::showMenu(const QPoint &point) { if (!selectedRow().isValid()) { return; } contextMenu->exec(QCursor::pos()); } // context menu action: copy URI void ReceiveCoinsDialog::copyURI() { QModelIndex sel = selectedRow(); if (!sel.isValid()) { return; } const RecentRequestsTableModel * const submodel = model->getRecentRequestsTableModel(); const QString uri = GUIUtil::formatBitcoinURI(submodel->entry(sel.row()).recipient); GUIUtil::setClipboard(uri); } // context menu action: copy label void ReceiveCoinsDialog::copyLabel() { copyColumnToClipboard(RecentRequestsTableModel::Label); } // context menu action: copy message void ReceiveCoinsDialog::copyMessage() { copyColumnToClipboard(RecentRequestsTableModel::Message); } // context menu action: copy amount void ReceiveCoinsDialog::copyAmount() { copyColumnToClipboard(RecentRequestsTableModel::Amount); } <commit_msg>GUI: Allow generating Bech32 addresses with a legacy-address default<commit_after>// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <wallet/wallet.h> #include <qt/receivecoinsdialog.h> #include <qt/forms/ui_receivecoinsdialog.h> #include <qt/addressbookpage.h> #include <qt/addresstablemodel.h> #include <qt/bitcoinunits.h> #include <qt/optionsmodel.h> #include <qt/platformstyle.h> #include <qt/receiverequestdialog.h> #include <qt/recentrequeststablemodel.h> #include <qt/walletmodel.h> #include <QAction> #include <QCursor> #include <QMessageBox> #include <QScrollBar> #include <QTextDocument> ReceiveCoinsDialog::ReceiveCoinsDialog(const PlatformStyle *_platformStyle, QWidget *parent) : QDialog(parent), ui(new Ui::ReceiveCoinsDialog), columnResizingFixer(0), model(0), platformStyle(_platformStyle) { ui->setupUi(this); QString theme = GUIUtil::getThemeName(); if (!_platformStyle->getImagesOnButtons()) { ui->clearButton->setIcon(QIcon()); ui->receiveButton->setIcon(QIcon()); ui->showRequestButton->setIcon(QIcon()); ui->removeRequestButton->setIcon(QIcon()); } else { ui->clearButton->setIcon(QIcon(":/icons/" + theme + "/remove")); ui->receiveButton->setIcon(QIcon(":/icons/" + theme + "/receiving_addresses")); ui->showRequestButton->setIcon(QIcon(":/icons/" + theme + "/edit")); ui->removeRequestButton->setIcon(QIcon(":/icons/" + theme + "/remove")); } // context menu actions QAction *copyURIAction = new QAction(tr("Copy URI"), this); QAction *copyLabelAction = new QAction(tr("Copy label"), this); QAction *copyMessageAction = new QAction(tr("Copy message"), this); QAction *copyAmountAction = new QAction(tr("Copy amount"), this); // context menu contextMenu = new QMenu(this); contextMenu->addAction(copyURIAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(copyMessageAction); contextMenu->addAction(copyAmountAction); // context menu signals connect(ui->recentRequestsView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint))); connect(copyURIAction, SIGNAL(triggered()), this, SLOT(copyURI())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel())); connect(copyMessageAction, SIGNAL(triggered()), this, SLOT(copyMessage())); connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); } void ReceiveCoinsDialog::setModel(WalletModel *_model) { this->model = _model; if(_model && _model->getOptionsModel()) { _model->getRecentRequestsTableModel()->sort(RecentRequestsTableModel::Date, Qt::DescendingOrder); connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); updateDisplayUnit(); QTableView* tableView = ui->recentRequestsView; tableView->verticalHeader()->hide(); tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); tableView->setModel(_model->getRecentRequestsTableModel()); tableView->setAlternatingRowColors(true); tableView->setSelectionBehavior(QAbstractItemView::SelectRows); tableView->setSelectionMode(QAbstractItemView::ContiguousSelection); tableView->setColumnWidth(RecentRequestsTableModel::Date, DATE_COLUMN_WIDTH); tableView->setColumnWidth(RecentRequestsTableModel::Label, LABEL_COLUMN_WIDTH); connect(tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(recentRequestsView_selectionChanged(QItemSelection, QItemSelection))); // Last 2 columns are set by the columnResizingFixer, when the table geometry is ready. columnResizingFixer = new GUIUtil::TableViewLastColumnResizingFixer(tableView, AMOUNT_MINIMUM_COLUMN_WIDTH, DATE_COLUMN_WIDTH, this); if (model->wallet().getDefaultAddressType() == OutputType::BECH32) { ui->useBech32->setCheckState(Qt::Checked); } else { ui->useBech32->setCheckState(Qt::Unchecked); } } } ReceiveCoinsDialog::~ReceiveCoinsDialog() { delete ui; } void ReceiveCoinsDialog::clear() { ui->reqAmount->clear(); ui->reqLabel->setText(""); ui->reqMessage->setText(""); updateDisplayUnit(); } void ReceiveCoinsDialog::reject() { clear(); } void ReceiveCoinsDialog::accept() { clear(); } void ReceiveCoinsDialog::updateDisplayUnit() { if(model && model->getOptionsModel()) { ui->reqAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } } void ReceiveCoinsDialog::on_receiveButton_clicked() { if(!model || !model->getOptionsModel() || !model->getAddressTableModel() || !model->getRecentRequestsTableModel()) return; QString address; QString label = ui->reqLabel->text(); /* Generate new receiving address */ OutputType address_type; if (ui->useBech32->isChecked()) { address_type = OutputType::BECH32; } else { address_type = model->wallet().getDefaultAddressType(); if (address_type == OutputType::BECH32) { address_type = OutputType::P2SH_SEGWIT; } } address = model->getAddressTableModel()->addRow(AddressTableModel::Receive, label, "", address_type); SendCoinsRecipient info(address, label, ui->reqAmount->value(), ui->reqMessage->text()); ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setModel(model); dialog->setInfo(info); dialog->show(); clear(); /* Store request for later reference */ model->getRecentRequestsTableModel()->addNewRequest(info); } void ReceiveCoinsDialog::on_recentRequestsView_doubleClicked(const QModelIndex &index) { const RecentRequestsTableModel *submodel = model->getRecentRequestsTableModel(); ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this); dialog->setModel(model); dialog->setInfo(submodel->entry(index.row()).recipient); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->show(); } void ReceiveCoinsDialog::recentRequestsView_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { // Enable Show/Remove buttons only if anything is selected. bool enable = !ui->recentRequestsView->selectionModel()->selectedRows().isEmpty(); ui->showRequestButton->setEnabled(enable); ui->removeRequestButton->setEnabled(enable); } void ReceiveCoinsDialog::on_showRequestButton_clicked() { if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel()) return; QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows(); for (const QModelIndex& index : selection) { on_recentRequestsView_doubleClicked(index); } } void ReceiveCoinsDialog::on_removeRequestButton_clicked() { if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel()) return; QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows(); if(selection.empty()) return; // correct for selection mode ContiguousSelection QModelIndex firstIndex = selection.at(0); model->getRecentRequestsTableModel()->removeRows(firstIndex.row(), selection.length(), firstIndex.parent()); } // We override the virtual resizeEvent of the QWidget to adjust tables column // sizes as the tables width is proportional to the dialogs width. void ReceiveCoinsDialog::resizeEvent(QResizeEvent *event) { QWidget::resizeEvent(event); columnResizingFixer->stretchColumnWidth(RecentRequestsTableModel::Message); } void ReceiveCoinsDialog::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Return) { // press return -> submit form if (ui->reqLabel->hasFocus() || ui->reqAmount->hasFocus() || ui->reqMessage->hasFocus()) { event->ignore(); on_receiveButton_clicked(); return; } } this->QDialog::keyPressEvent(event); } QModelIndex ReceiveCoinsDialog::selectedRow() { if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel()) return QModelIndex(); QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows(); if(selection.empty()) return QModelIndex(); // correct for selection mode ContiguousSelection QModelIndex firstIndex = selection.at(0); return firstIndex; } // copy column of selected row to clipboard void ReceiveCoinsDialog::copyColumnToClipboard(int column) { QModelIndex firstIndex = selectedRow(); if (!firstIndex.isValid()) { return; } GUIUtil::setClipboard(model->getRecentRequestsTableModel()->data(firstIndex.child(firstIndex.row(), column), Qt::EditRole).toString()); } // context menu void ReceiveCoinsDialog::showMenu(const QPoint &point) { if (!selectedRow().isValid()) { return; } contextMenu->exec(QCursor::pos()); } // context menu action: copy URI void ReceiveCoinsDialog::copyURI() { QModelIndex sel = selectedRow(); if (!sel.isValid()) { return; } const RecentRequestsTableModel * const submodel = model->getRecentRequestsTableModel(); const QString uri = GUIUtil::formatBitcoinURI(submodel->entry(sel.row()).recipient); GUIUtil::setClipboard(uri); } // context menu action: copy label void ReceiveCoinsDialog::copyLabel() { copyColumnToClipboard(RecentRequestsTableModel::Label); } // context menu action: copy message void ReceiveCoinsDialog::copyMessage() { copyColumnToClipboard(RecentRequestsTableModel::Message); } // context menu action: copy amount void ReceiveCoinsDialog::copyAmount() { copyColumnToClipboard(RecentRequestsTableModel::Amount); } <|endoftext|>
<commit_before>#include "Utility/String.h" #include <string> #include <vector> #include <stdexcept> #include <algorithm> #include <cctype> namespace String { namespace { const auto whitespace = " \t\n"; } } std::vector<std::string> String::split(std::string s, std::string delim, size_t count) { if(delim.empty()) { s = remove_extra_whitespace(s); delim = " "; } std::vector<std::string> result; size_t start_index = 0; size_t end_index = 0; size_t split_count = 0; while(end_index < s.size() && split_count < count) { end_index = s.find(delim, start_index); result.push_back(s.substr(start_index, end_index - start_index)); start_index = std::min(end_index, s.size()) + delim.size(); ++split_count; } if(start_index <= s.size()) { result.push_back(s.substr(start_index)); } return result; } bool String::starts_with(const std::string& s, const std::string& beginning) { return (beginning.size() <= s.size()) && std::equal(beginning.begin(), beginning.end(), s.begin()); } bool String::ends_with(const std::string& s, const std::string& ending) { return (ending.size() <= s.size()) && std::equal(ending.rbegin(), ending.rend(), s.rbegin()); } std::string String::trim_outer_whitespace(const std::string& s) { auto text_start = s.find_first_not_of(whitespace); if(text_start == std::string::npos) { return {}; } auto text_end = s.find_last_not_of(whitespace); return s.substr(text_start, text_end - text_start + 1); } std::string String::remove_extra_whitespace(const std::string& s) { std::string result; for(auto c : trim_outer_whitespace(s)) { if(contains(whitespace, c)) { if(result.back() != ' ') { result.push_back(' '); } } else { result.push_back(c); } } return result; } std::string String::strip_comments(const std::string& str, const std::string& comment) { return trim_outer_whitespace(str.substr(0, str.find(comment))); } std::string String::strip_block_comment(const std::string& str, const std::string& start, const std::string& end) { auto start_comment_index = str.find(start); auto end_comment_index = str.find(end); if(start_comment_index == std::string::npos && end_comment_index == std::string::npos) { return trim_outer_whitespace(str); } if(start_comment_index == std::string::npos || end_comment_index == std::string::npos) { throw std::invalid_argument("\"" + str + "\" is missing a comment delimiter: " + std::string{start} + std::string{end}); } if(start_comment_index >= end_comment_index) { throw std::invalid_argument("\"" + str + "\" contains bad comment delimiters: " + std::string{start} + std::string{end}); } auto first_part = str.substr(0, start_comment_index); auto last_part = str.substr(end_comment_index + end.size()); return strip_block_comment(trim_outer_whitespace(first_part) + " " + trim_outer_whitespace(last_part), start, end); } std::string String::lowercase(std::string s) { for(auto& c : s){ c = std::tolower(c); } return s; } std::string String::format_integer(int n, const std::string& separator) { if(n < 0) { return '-' + format_integer(size_t(-n), separator); } else { return format_integer(size_t(n), separator); } } std::string String::format_integer(size_t n, const std::string& separator) { auto s = std::to_string(n); auto index = s.size() % 3; index = (index == 0 ? 3 : index); auto result = s.substr(0, index); for( ; index < s.size(); index += 3) { result += separator; result += s.substr(index, 3); } return result; } <commit_msg>Empty string results in an empty split() vector<commit_after>#include "Utility/String.h" #include <string> #include <vector> #include <stdexcept> #include <algorithm> #include <cctype> namespace String { namespace { const auto whitespace = " \t\n"; } } std::vector<std::string> String::split(std::string s, std::string delim, size_t count) { if(delim.empty()) { s = remove_extra_whitespace(s); delim = " "; } if(s.empty()) { return {}; } std::vector<std::string> result; size_t start_index = 0; size_t end_index = 0; size_t split_count = 0; while(end_index < s.size() && split_count < count) { end_index = s.find(delim, start_index); result.push_back(s.substr(start_index, end_index - start_index)); start_index = std::min(end_index, s.size()) + delim.size(); ++split_count; } if(start_index <= s.size()) { result.push_back(s.substr(start_index)); } return result; } bool String::starts_with(const std::string& s, const std::string& beginning) { return (beginning.size() <= s.size()) && std::equal(beginning.begin(), beginning.end(), s.begin()); } bool String::ends_with(const std::string& s, const std::string& ending) { return (ending.size() <= s.size()) && std::equal(ending.rbegin(), ending.rend(), s.rbegin()); } std::string String::trim_outer_whitespace(const std::string& s) { auto text_start = s.find_first_not_of(whitespace); if(text_start == std::string::npos) { return {}; } auto text_end = s.find_last_not_of(whitespace); return s.substr(text_start, text_end - text_start + 1); } std::string String::remove_extra_whitespace(const std::string& s) { std::string result; for(auto c : trim_outer_whitespace(s)) { if(contains(whitespace, c)) { if(result.back() != ' ') { result.push_back(' '); } } else { result.push_back(c); } } return result; } std::string String::strip_comments(const std::string& str, const std::string& comment) { return trim_outer_whitespace(str.substr(0, str.find(comment))); } std::string String::strip_block_comment(const std::string& str, const std::string& start, const std::string& end) { auto start_comment_index = str.find(start); auto end_comment_index = str.find(end); if(start_comment_index == std::string::npos && end_comment_index == std::string::npos) { return trim_outer_whitespace(str); } if(start_comment_index == std::string::npos || end_comment_index == std::string::npos) { throw std::invalid_argument("\"" + str + "\" is missing a comment delimiter: " + std::string{start} + std::string{end}); } if(start_comment_index >= end_comment_index) { throw std::invalid_argument("\"" + str + "\" contains bad comment delimiters: " + std::string{start} + std::string{end}); } auto first_part = str.substr(0, start_comment_index); auto last_part = str.substr(end_comment_index + end.size()); return strip_block_comment(trim_outer_whitespace(first_part) + " " + trim_outer_whitespace(last_part), start, end); } std::string String::lowercase(std::string s) { for(auto& c : s){ c = std::tolower(c); } return s; } std::string String::format_integer(int n, const std::string& separator) { if(n < 0) { return '-' + format_integer(size_t(-n), separator); } else { return format_integer(size_t(n), separator); } } std::string String::format_integer(size_t n, const std::string& separator) { auto s = std::to_string(n); auto index = s.size() % 3; index = (index == 0 ? 3 : index); auto result = s.substr(0, index); for( ; index < s.size(); index += 3) { result += separator; result += s.substr(index, 3); } return result; } <|endoftext|>
<commit_before>/* * Tetromino4.cpp * * Created on: 28.04.2014 * Author: nicola */ #include <iostream> #include "Libraries.hpp" #include "Tetromino4.hpp" #include <sstream> std::string itos(int i){ std::stringstream ss; ss<<i; return ss.str(); } /* Definition of static const, Tick time in ms */ const Point2D Tetromino4::startPos = { static_cast<int>(MAP_WIDTH/2), -2 /* So it's not visible just yet */}; Tetromino4::Tetromino4(ColorType Color) :Tetromino(startPos) { /* Initialise square list with only blocks */ for(unsigned int i=0; i<4; i++) { squares.push_back(new Block(Color)); } } Tetromino4::~Tetromino4() { /* Delete square list */ squares.clear(); } void Tetromino4::rotate(bool Cw) { /* Tetromino4 doesn't need to be rotated */ } void Tetromino4::draw() { /* Draw each square */ for(unsigned int i=0; i<4; i++) { if(squares[i].getType() == typeBlock) { int x = position.x*SQUARE_WIDTH; int y = position.y*SQUARE_WIDTH; if(y >= 0) { DrawFilledRectangle(x, y, SQUARE_WIDTH, SQUARE_WIDTH, squares[i].getColor(), 0); } } } } <commit_msg>Fixed block position drawing<commit_after>/* * Tetromino4.cpp * * Created on: 28.04.2014 * Author: nicola */ #include <iostream> #include "Libraries.hpp" #include "Tetromino4.hpp" #include <sstream> std::string itos(int i){ std::stringstream ss; ss<<i; return ss.str(); } /* Definition of static const, Tick time in ms */ const Point2D Tetromino4::startPos = { static_cast<int>(MAP_WIDTH/2)-1, -2 /* So it's not visible just yet */}; Tetromino4::Tetromino4(ColorType Color) :Tetromino(startPos) { /* Initialise square list with only blocks */ for(unsigned int i=0; i<4; i++) { squares.push_back(new Block(Color)); } } Tetromino4::~Tetromino4() { /* Delete square list */ squares.clear(); } void Tetromino4::rotate(bool Cw) { /* Tetromino4 doesn't need to be rotated */ } void Tetromino4::draw() { /* Draw each square */ for(unsigned int i=0; i<2; i++) { for(unsigned int j=0; j<2; j++) { if(squares[i+j].getType() == typeBlock) { int x = (position.x + i%2) * SQUARE_WIDTH; int y = (position.y + j%2) * SQUARE_WIDTH; if(y >= 0) { DrawFilledRectangle(x, y, SQUARE_WIDTH, SQUARE_WIDTH, squares[i+j].getColor(), 0); } } } } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* libmspub * Version: MPL 1.1 / GPLv2+ / LGPLv2+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Major Contributor(s): * Copyright (C) 2012 Fridrich Strba <fridrich.strba@bluewin.ch> * * * All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPLv2+"), or * the GNU Lesser General Public License Version 2 or later (the "LGPLv2+"), * in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable * instead of those above. */ #include <vector> #include "MSPUBStringVector.h" namespace libmspub { class MSPUBStringVectorImpl { public: MSPUBStringVectorImpl() : m_strings() {} ~MSPUBStringVectorImpl() {} std::vector<WPXString> m_strings; }; } // namespace libmspub libmspub::MSPUBStringVector::MSPUBStringVector() : m_pImpl(new MSPUBStringVectorImpl()) { } libmspub::MSPUBStringVector::MSPUBStringVector(const MSPUBStringVector &vec) : m_pImpl(new MSPUBStringVectorImpl(*(vec.m_pImpl))) { } libmspub::MSPUBStringVector::~MSPUBStringVector() { } libmspub::MSPUBStringVector &libmspub::MSPUBStringVector::operator=(const MSPUBStringVector &vec) { // Check for self-assignment if (this == &vec) return *this; if (m_pImpl) delete m_pImpl; m_pImpl = new MSPUBStringVectorImpl(*(vec.m_pImpl)); return *this; } unsigned libmspub::MSPUBStringVector::size() const { return (unsigned)(m_pImpl->m_strings.size()); } bool libmspub::MSPUBStringVector::empty() const { return m_pImpl->m_strings.empty(); } const WPXString &libmspub::MSPUBStringVector::operator[](unsigned idx) const { return m_pImpl->m_strings[idx]; } void libmspub::MSPUBStringVector::append(const WPXString &str) { m_pImpl->m_strings.push_back(str); } void libmspub::MSPUBStringVector::clear() { m_pImpl->m_strings.clear(); } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */ <commit_msg>coverity: memory leak<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* libmspub * Version: MPL 1.1 / GPLv2+ / LGPLv2+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Major Contributor(s): * Copyright (C) 2012 Fridrich Strba <fridrich.strba@bluewin.ch> * * * All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPLv2+"), or * the GNU Lesser General Public License Version 2 or later (the "LGPLv2+"), * in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable * instead of those above. */ #include <vector> #include "MSPUBStringVector.h" namespace libmspub { class MSPUBStringVectorImpl { public: MSPUBStringVectorImpl() : m_strings() {} ~MSPUBStringVectorImpl() {} std::vector<WPXString> m_strings; }; } // namespace libmspub libmspub::MSPUBStringVector::MSPUBStringVector() : m_pImpl(new MSPUBStringVectorImpl()) { } libmspub::MSPUBStringVector::MSPUBStringVector(const MSPUBStringVector &vec) : m_pImpl(new MSPUBStringVectorImpl(*(vec.m_pImpl))) { } libmspub::MSPUBStringVector::~MSPUBStringVector() { delete m_pImpl; } libmspub::MSPUBStringVector &libmspub::MSPUBStringVector::operator=(const MSPUBStringVector &vec) { // Check for self-assignment if (this == &vec) return *this; if (m_pImpl) delete m_pImpl; m_pImpl = new MSPUBStringVectorImpl(*(vec.m_pImpl)); return *this; } unsigned libmspub::MSPUBStringVector::size() const { return (unsigned)(m_pImpl->m_strings.size()); } bool libmspub::MSPUBStringVector::empty() const { return m_pImpl->m_strings.empty(); } const WPXString &libmspub::MSPUBStringVector::operator[](unsigned idx) const { return m_pImpl->m_strings[idx]; } void libmspub::MSPUBStringVector::append(const WPXString &str) { m_pImpl->m_strings.push_back(str); } void libmspub::MSPUBStringVector::clear() { m_pImpl->m_strings.clear(); } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */ <|endoftext|>
<commit_before>#ifndef __STAN__PROB__DIST__UNI__CONTINUOUS__INV_CHI_SQUARE_HPP__ #define __STAN__PROB__DIST__UNI__CONTINUOUS__INV_CHI_SQUARE_HPP__ #include <stan/agrad.hpp> #include <stan/math/error_handling.hpp> #include <stan/math/special_functions.hpp> #include <stan/meta/traits.hpp> #include <stan/prob/constants.hpp> #include <stan/prob/traits.hpp> #include <stan/prob/internal_math.hpp> namespace stan { namespace prob { /** * The log of an inverse chi-squared density for y with the specified * degrees of freedom parameter. * The degrees of freedom prarameter must be greater than 0. * y must be greater than 0. * \f{eqnarray*}{ y &\sim& \mbox{\sf{Inv-}}\chi^2_\nu \\ \log (p (y \,|\, \nu)) &=& \log \left( \frac{2^{-\nu / 2}}{\Gamma (\nu / 2)} y^{- (\nu / 2 + 1)} \exp^{-1 / (2y)} \right) \\ &=& - \frac{\nu}{2} \log(2) - \log (\Gamma (\nu / 2)) - (\frac{\nu}{2} + 1) \log(y) - \frac{1}{2y} \\ & & \mathrm{ where } \; y > 0 \f} * @param y A scalar variable. * @param nu Degrees of freedom. * @throw std::domain_error if nu is not greater than or equal to 0 * @throw std::domain_error if y is not greater than or equal to 0. * @tparam T_y Type of scalar. * @tparam T_dof Type of degrees of freedom. */ template <bool propto, typename T_y, typename T_dof, class Policy> typename return_type<T_y,T_dof>::type inv_chi_square_log(const T_y& y, const T_dof& nu, const Policy&) { static const char* function = "stan::prob::inv_chi_square_log(%1%)"; // check if any vectors are zero length if (!(stan::length(y) && stan::length(nu))) return 0.0; using stan::math::check_finite; using stan::math::check_positive; using stan::math::check_not_nan; using stan::math::value_of; using stan::math::check_consistent_sizes; typename return_type<T_y,T_dof>::type logp(0.0); if (!check_finite(function, nu, "Degrees of freedom parameter", &logp, Policy())) return logp; if (!check_positive(function, nu, "Degrees of freedom parameter", &logp, Policy())) return logp; if (!check_not_nan(function, y, "Random variable", &logp, Policy())) return logp; if (!(check_consistent_sizes(function, y,nu, "Random variable","Degrees of freedom parameter", &logp, Policy()))) return logp; // set up template expressions wrapping scalars into vector views VectorView<const T_y> y_vec(y); VectorView<const T_dof> nu_vec(nu); size_t N = max_size(y, nu); for (size_t n = 0; n < length(y); n++) if (value_of(y_vec[n]) <= 0) return LOG_ZERO; using boost::math::lgamma; using stan::math::multiply_log; for (size_t n = 0; n < N; n++) { if (include_summand<propto,T_dof>::value) logp += nu_vec[n] * NEG_LOG_TWO_OVER_TWO - lgamma(0.5 * nu_vec[n]); if (include_summand<propto,T_y,T_dof>::value) logp -= multiply_log(0.5*nu_vec[n]+1.0, y_vec[n]); if (include_summand<propto,T_y>::value) logp -= 0.5 / y_vec[n]; } return logp; } template <bool propto, typename T_y, typename T_dof> inline typename return_type<T_y,T_dof>::type inv_chi_square_log(const T_y& y, const T_dof& nu) { return inv_chi_square_log<propto>(y,nu,stan::math::default_policy()); } template <typename T_y, typename T_dof, class Policy> inline typename return_type<T_y,T_dof>::type inv_chi_square_log(const T_y& y, const T_dof& nu, const Policy&) { return inv_chi_square_log<false>(y,nu,Policy()); } template <typename T_y, typename T_dof> inline typename return_type<T_y,T_dof>::type inv_chi_square_log(const T_y& y, const T_dof& nu) { return inv_chi_square_log<false>(y,nu,stan::math::default_policy()); } template <typename T_y, typename T_dof, class Policy> typename return_type<T_y,T_dof>::type inv_chi_square_cdf(const T_y& y, const T_dof& nu, const Policy&) { // Size checks if ( !( stan::length(y) && stan::length(nu) ) ) return 0.0; // Error checks static const char* function = "stan::prob::inv_chi_square_cdf(%1%)"; using stan::math::check_finite; using stan::math::check_positive; using stan::math::check_not_nan; using stan::math::check_consistent_sizes; using boost::math::tools::promote_args; double P(1.0); if (!check_finite(function, nu, "Degrees of freedom parameter", &P, Policy())) return P; if (!check_positive(function, nu, "Degrees of freedom parameter", &P, Policy())) return P; if (!check_not_nan(function, y, "Random variable", &P, Policy())) return P; if (!check_positive(function, y, "Random variable", &P, Policy())) return P; if (!(check_consistent_sizes(function, y, nu, "Random variable", "Degrees of freedom parameter", &P, Policy()))) return P; // Wrap arguments in vectors VectorView<const T_y> y_vec(y); VectorView<const T_dof> nu_vec(nu); size_t N = max_size(y, nu); agrad::OperandsAndPartials<T_y, T_dof> operands_and_partials(y, nu); std::fill(operands_and_partials.all_partials, operands_and_partials.all_partials + operands_and_partials.nvaris, 0.0); // Compute CDF and its gradients using stan::math::value_of; using boost::math::gamma_p_derivative; using boost::math::gamma_q; using boost::math::tgamma; using boost::math::digamma; // Cache a few expensive function calls if nu is a parameter DoubleVectorView<!is_constant_struct<T_dof>::value, T_dof> gamma_vec(stan::length(nu)); DoubleVectorView<!is_constant_struct<T_dof>::value, T_dof> digamma_vec(stan::length(nu)); if (!is_constant_struct<T_dof>::value) { for (size_t i = 0; i < stan::length(nu); i++) { const double nu_dbl = value_of(nu_vec[i]); gamma_vec[i] = tgamma(nu_dbl); digamma_vec[i] = digamma(nu_dbl); } } // Compute vectorized CDF and gradient for (size_t n = 0; n < N; n++) { // Pull out values const double y_dbl = value_of(y_vec[n]); const double y_inv_dbl = 1.0 / y_dbl; const double nu_dbl = value_of(nu_vec[n]); // Compute const double Pn = gamma_q(0.5 * nu_dbl, 0.5 * y_inv_dbl); P *= Pn; if (!is_constant_struct<T_y>::value) operands_and_partials.d_x1[n] += 0.5 * y_inv_dbl * y_inv_dbl * gamma_p_derivative(0.5 * nu_dbl, 0.5 * y_inv_dbl) / Pn; if (!is_constant_struct<T_dof>::value) operands_and_partials.d_x2[n] += 0.5 * stan::math::gradRegIncGamma(0.5 * nu_dbl, 0.5 * y_inv_dbl, gamma_vec[n], digamma_vec[n]) / Pn; } for (size_t n = 0; n < N; n++) { if (!is_constant_struct<T_y>::value) operands_and_partials.d_x1[n] *= P; if (!is_constant_struct<T_dof>::value) operands_and_partials.d_x2[n] *= P; } return operands_and_partials.to_var(P); } template <typename T_y, typename T_dof> inline typename return_type<T_y,T_dof>::type inv_chi_square_cdf(const T_y& y, const T_dof& nu) { return inv_chi_square_cdf(y, nu, stan::math::default_policy()); } } } #endif <commit_msg>refactoring inv_chi_square distribution<commit_after>#ifndef __STAN__PROB__DIST__UNI__CONTINUOUS__INV_CHI_SQUARE_HPP__ #define __STAN__PROB__DIST__UNI__CONTINUOUS__INV_CHI_SQUARE_HPP__ #include <stan/agrad.hpp> #include <stan/math/error_handling.hpp> #include <stan/math/special_functions.hpp> #include <stan/meta/traits.hpp> #include <stan/prob/constants.hpp> #include <stan/prob/traits.hpp> #include <stan/prob/internal_math.hpp> namespace stan { namespace prob { /** * The log of an inverse chi-squared density for y with the specified * degrees of freedom parameter. * The degrees of freedom prarameter must be greater than 0. * y must be greater than 0. * \f{eqnarray*}{ y &\sim& \mbox{\sf{Inv-}}\chi^2_\nu \\ \log (p (y \,|\, \nu)) &=& \log \left( \frac{2^{-\nu / 2}}{\Gamma (\nu / 2)} y^{- (\nu / 2 + 1)} \exp^{-1 / (2y)} \right) \\ &=& - \frac{\nu}{2} \log(2) - \log (\Gamma (\nu / 2)) - (\frac{\nu}{2} + 1) \log(y) - \frac{1}{2y} \\ & & \mathrm{ where } \; y > 0 \f} * @param y A scalar variable. * @param nu Degrees of freedom. * @throw std::domain_error if nu is not greater than or equal to 0 * @throw std::domain_error if y is not greater than or equal to 0. * @tparam T_y Type of scalar. * @tparam T_dof Type of degrees of freedom. */ template <bool propto, typename T_y, typename T_dof, class Policy> typename return_type<T_y,T_dof>::type inv_chi_square_log(const T_y& y, const T_dof& nu, const Policy&) { static const char* function = "stan::prob::inv_chi_square_log(%1%)"; // check if any vectors are zero length if (!(stan::length(y) && stan::length(nu))) return 0.0; using stan::math::check_finite; using stan::math::check_positive; using stan::math::check_not_nan; using stan::math::value_of; using stan::math::check_consistent_sizes; typename return_type<T_y,T_dof>::type logp(0.0); if (!check_finite(function, nu, "Degrees of freedom parameter", &logp, Policy())) return logp; if (!check_positive(function, nu, "Degrees of freedom parameter", &logp, Policy())) return logp; if (!check_not_nan(function, y, "Random variable", &logp, Policy())) return logp; if (!(check_consistent_sizes(function, y,nu, "Random variable","Degrees of freedom parameter", &logp, Policy()))) return logp; // set up template expressions wrapping scalars into vector views VectorView<const T_y> y_vec(y); VectorView<const T_dof> nu_vec(nu); size_t N = max_size(y, nu); for (size_t n = 0; n < length(y); n++) if (value_of(y_vec[n]) <= 0) return LOG_ZERO; using boost::math::lgamma; using stan::math::multiply_log; for (size_t n = 0; n < N; n++) { if (include_summand<propto,T_dof>::value) logp += nu_vec[n] * NEG_LOG_TWO_OVER_TWO - lgamma(0.5 * nu_vec[n]); if (include_summand<propto,T_y,T_dof>::value) logp -= multiply_log(0.5*nu_vec[n]+1.0, y_vec[n]); if (include_summand<propto,T_y>::value) logp -= 0.5 / y_vec[n]; } return logp; } template <bool propto, typename T_y, typename T_dof> inline typename return_type<T_y,T_dof>::type inv_chi_square_log(const T_y& y, const T_dof& nu) { return inv_chi_square_log<propto>(y,nu,stan::math::default_policy()); } template <typename T_y, typename T_dof, class Policy> inline typename return_type<T_y,T_dof>::type inv_chi_square_log(const T_y& y, const T_dof& nu, const Policy&) { return inv_chi_square_log<false>(y,nu,Policy()); } template <typename T_y, typename T_dof> inline typename return_type<T_y,T_dof>::type inv_chi_square_log(const T_y& y, const T_dof& nu) { return inv_chi_square_log<false>(y,nu,stan::math::default_policy()); } template <typename T_y, typename T_dof, class Policy> typename return_type<T_y,T_dof>::type inv_chi_square_cdf(const T_y& y, const T_dof& nu, const Policy&) { // Size checks if ( !( stan::length(y) && stan::length(nu) ) ) return 0.0; // Error checks static const char* function = "stan::prob::inv_chi_square_cdf(%1%)"; using stan::math::check_finite; using stan::math::check_positive; using stan::math::check_not_nan; using stan::math::check_consistent_sizes; using boost::math::tools::promote_args; double P(1.0); if (!check_finite(function, nu, "Degrees of freedom parameter", &P, Policy())) return P; if (!check_positive(function, nu, "Degrees of freedom parameter", &P, Policy())) return P; if (!check_not_nan(function, y, "Random variable", &P, Policy())) return P; if (!check_positive(function, y, "Random variable", &P, Policy())) return P; if (!(check_consistent_sizes(function, y, nu, "Random variable", "Degrees of freedom parameter", &P, Policy()))) return P; // Wrap arguments in vectors VectorView<const T_y> y_vec(y); VectorView<const T_dof> nu_vec(nu); size_t N = max_size(y, nu); agrad::OperandsAndPartials<T_y, T_dof> operands_and_partials(y, nu); std::fill(operands_and_partials.all_partials, operands_and_partials.all_partials + operands_and_partials.nvaris, 0.0); // Compute CDF and its gradients using stan::math::value_of; using boost::math::gamma_p_derivative; using boost::math::gamma_q; using boost::math::tgamma; using boost::math::digamma; // Cache a few expensive function calls if nu is a parameter DoubleVectorView<!is_constant_struct<T_dof>::value, is_vector<T_dof>::value> gamma_vec(stan::length(nu)); DoubleVectorView<!is_constant_struct<T_dof>::value, is_vector<T_dof>::value> digamma_vec(stan::length(nu)); if (!is_constant_struct<T_dof>::value) { for (size_t i = 0; i < stan::length(nu); i++) { const double nu_dbl = value_of(nu_vec[i]); gamma_vec[i] = tgamma(nu_dbl); digamma_vec[i] = digamma(nu_dbl); } } // Compute vectorized CDF and gradient for (size_t n = 0; n < N; n++) { // Pull out values const double y_dbl = value_of(y_vec[n]); const double y_inv_dbl = 1.0 / y_dbl; const double nu_dbl = value_of(nu_vec[n]); // Compute const double Pn = gamma_q(0.5 * nu_dbl, 0.5 * y_inv_dbl); P *= Pn; if (!is_constant_struct<T_y>::value) operands_and_partials.d_x1[n] += 0.5 * y_inv_dbl * y_inv_dbl * gamma_p_derivative(0.5 * nu_dbl, 0.5 * y_inv_dbl) / Pn; if (!is_constant_struct<T_dof>::value) operands_and_partials.d_x2[n] += 0.5 * stan::math::gradRegIncGamma(0.5 * nu_dbl, 0.5 * y_inv_dbl, gamma_vec[n], digamma_vec[n]) / Pn; } for (size_t n = 0; n < N; n++) { if (!is_constant_struct<T_y>::value) operands_and_partials.d_x1[n] *= P; if (!is_constant_struct<T_dof>::value) operands_and_partials.d_x2[n] *= P; } return operands_and_partials.to_var(P); } template <typename T_y, typename T_dof> inline typename return_type<T_y,T_dof>::type inv_chi_square_cdf(const T_y& y, const T_dof& nu) { return inv_chi_square_cdf(y, nu, stan::math::default_policy()); } } } #endif <|endoftext|>
<commit_before>// // Copyright Silvin Lubecki 2010 // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef OPENCLAM_CL_HPP_INCLUDED #define OPENCLAM_CL_HPP_INCLUDED #include <CL/cl.h> #include "error.hpp" #include "context.hpp" #include "builtin.hpp" #define __kernel #define kernel #define __global #define global #define APPLY_DEFINES( NAME, FUNCTION ) \ class NAME_CLASS : public openclam::builtin \ { \ private: \ NAME_CLASS() {} \ virtual ~NAME_CLASS() {} \ \ FUNCTION; \ }; \ #define KERNEL( NAME, FUNCTION ) \ #FUNCTION; \ APPLY_DEFINES( NAME, FUNCTION ); #endif // #ifndef OPENCLAM_CL_HPP_INCLUDED <commit_msg>cleaning<commit_after>// // Copyright Silvin Lubecki 2010 // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef OPENCLAM_CL_HPP_INCLUDED #define OPENCLAM_CL_HPP_INCLUDED #include <CL/cl.h> #include "error.hpp" #include "context.hpp" #include "builtin.hpp" #define __kernel #define kernel #define __global #define global #define APPLY_DEFINES( NAME, FUNCTION ) \ class NAME_CLASS : private openclam::builtin \ { \ private: \ NAME_CLASS() {} \ virtual ~NAME_CLASS() {} \ \ FUNCTION; \ }; \ #define KERNEL( NAME, FUNCTION ) \ #FUNCTION; \ APPLY_DEFINES( NAME, FUNCTION ); #endif // #ifndef OPENCLAM_CL_HPP_INCLUDED <|endoftext|>
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "rpc_target.h" #include "shared_rpc_resources.h" #include <vespa/fastos/thread.h> #include <vespa/fnet/frt/supervisor.h> #include <vespa/fnet/frt/target.h> #include <vespa/fnet/transport.h> #include <vespa/slobrok/sbregister.h> #include <vespa/slobrok/sbmirror.h> #include <vespa/vespalib/util/exceptions.h> #include <vespa/vespalib/util/host_name.h> #include <vespa/vespalib/util/stringfmt.h> #include <cassert> #include <chrono> #include <thread> #include <vespa/log/log.h> LOG_SETUP(".storage.shared_rpc_resources"); using namespace std::chrono_literals; namespace storage::rpc { namespace { class RpcTargetImpl : public RpcTarget { private: FRT_Target* _target; vespalib::string _spec; public: RpcTargetImpl(FRT_Target* target, const vespalib::string& spec) : _target(target), _spec(spec) {} ~RpcTargetImpl() override { _target->SubRef(); } FRT_Target* get() noexcept override { return _target; } bool is_valid() const noexcept override { return _target->IsValid(); } const vespalib::string& spec() const noexcept override { return _spec; } }; } class SharedRpcResources::RpcTargetFactoryImpl : public RpcTargetFactory { private: FRT_Supervisor& _orb; public: RpcTargetFactoryImpl(FRT_Supervisor& orb) : _orb(orb) {} std::unique_ptr<RpcTarget> make_target(const vespalib::string& connection_spec) const override { auto* raw_target = _orb.GetTarget(connection_spec.c_str()); if (raw_target) { return std::make_unique<RpcTargetImpl>(raw_target, connection_spec); } return std::unique_ptr<RpcTarget>(); } }; SharedRpcResources::SharedRpcResources(const config::ConfigUri& config_uri, int rpc_server_port, size_t rpc_thread_pool_size, size_t rpc_events_before_wakeup) : _thread_pool(std::make_unique<FastOS_ThreadPool>(1024*60)), _transport(std::make_unique<FNET_Transport>(fnet::TransportConfig(rpc_thread_pool_size). events_before_wakeup(rpc_events_before_wakeup))), _orb(std::make_unique<FRT_Supervisor>(_transport.get())), _slobrok_register(std::make_unique<slobrok::api::RegisterAPI>(*_orb, slobrok::ConfiguratorFactory(config_uri))), _slobrok_mirror(std::make_unique<slobrok::api::MirrorAPI>(*_orb, slobrok::ConfiguratorFactory(config_uri))), _target_factory(std::make_unique<RpcTargetFactoryImpl>(*_orb)), _hostname(vespalib::HostName::get()), _rpc_server_port(rpc_server_port), _shutdown(false) { } // TODO make sure init/shutdown is safe for aborted init in comm. mgr. SharedRpcResources::~SharedRpcResources() { if (!_shutdown) { shutdown(); } } void SharedRpcResources::start_server_and_register_slobrok(vespalib::stringref my_handle) { LOG(debug, "Starting main RPC supervisor on port %d with slobrok handle '%s'", _rpc_server_port, vespalib::string(my_handle).c_str()); if (!_orb->Listen(_rpc_server_port)) { throw vespalib::IllegalStateException(vespalib::make_string("Failed to listen to RPC port %d", _rpc_server_port), VESPA_STRLOC); } _transport->Start(_thread_pool.get()); _slobrok_register->registerName(my_handle); wait_until_slobrok_is_ready(); _handle = my_handle; } void SharedRpcResources::wait_until_slobrok_is_ready() { // TODO look more closely at how mbus does its slobrok business while (_slobrok_register->busy() || !_slobrok_mirror->ready()) { // TODO some form of timeout mechanism here, and warning logging to identify SB issues LOG(debug, "Waiting for Slobrok to become ready"); std::this_thread::sleep_for(50ms); } } void SharedRpcResources::shutdown() { assert(!_shutdown); if (listen_port() > 0) { _slobrok_register->unregisterName(_handle); // Give slobrok some time to dispatch unregister RPC while (_slobrok_register->busy()) { std::this_thread::sleep_for(10ms); } } _slobrok_register.reset(); // Implicitly kill any pending slobrok tasks prior to shutting down transport layer _transport->ShutDown(true); // FIXME need to reset to break weak_ptrs? But ShutDown should already sync pending resolves...! _shutdown = true; } int SharedRpcResources::listen_port() const noexcept { return _orb->GetListenPort(); } const RpcTargetFactory& SharedRpcResources::target_factory() const { return *_target_factory; } } <commit_msg>delay destruction of the slobrok register component<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "rpc_target.h" #include "shared_rpc_resources.h" #include <vespa/fastos/thread.h> #include <vespa/fnet/frt/supervisor.h> #include <vespa/fnet/frt/target.h> #include <vespa/fnet/transport.h> #include <vespa/slobrok/sbregister.h> #include <vespa/slobrok/sbmirror.h> #include <vespa/vespalib/util/exceptions.h> #include <vespa/vespalib/util/host_name.h> #include <vespa/vespalib/util/stringfmt.h> #include <cassert> #include <chrono> #include <thread> #include <vespa/log/log.h> LOG_SETUP(".storage.shared_rpc_resources"); using namespace std::chrono_literals; namespace storage::rpc { namespace { class RpcTargetImpl : public RpcTarget { private: FRT_Target* _target; vespalib::string _spec; public: RpcTargetImpl(FRT_Target* target, const vespalib::string& spec) : _target(target), _spec(spec) {} ~RpcTargetImpl() override { _target->SubRef(); } FRT_Target* get() noexcept override { return _target; } bool is_valid() const noexcept override { return _target->IsValid(); } const vespalib::string& spec() const noexcept override { return _spec; } }; } class SharedRpcResources::RpcTargetFactoryImpl : public RpcTargetFactory { private: FRT_Supervisor& _orb; public: RpcTargetFactoryImpl(FRT_Supervisor& orb) : _orb(orb) {} std::unique_ptr<RpcTarget> make_target(const vespalib::string& connection_spec) const override { auto* raw_target = _orb.GetTarget(connection_spec.c_str()); if (raw_target) { return std::make_unique<RpcTargetImpl>(raw_target, connection_spec); } return std::unique_ptr<RpcTarget>(); } }; SharedRpcResources::SharedRpcResources(const config::ConfigUri& config_uri, int rpc_server_port, size_t rpc_thread_pool_size, size_t rpc_events_before_wakeup) : _thread_pool(std::make_unique<FastOS_ThreadPool>(1024*60)), _transport(std::make_unique<FNET_Transport>(fnet::TransportConfig(rpc_thread_pool_size). events_before_wakeup(rpc_events_before_wakeup))), _orb(std::make_unique<FRT_Supervisor>(_transport.get())), _slobrok_register(std::make_unique<slobrok::api::RegisterAPI>(*_orb, slobrok::ConfiguratorFactory(config_uri))), _slobrok_mirror(std::make_unique<slobrok::api::MirrorAPI>(*_orb, slobrok::ConfiguratorFactory(config_uri))), _target_factory(std::make_unique<RpcTargetFactoryImpl>(*_orb)), _hostname(vespalib::HostName::get()), _rpc_server_port(rpc_server_port), _shutdown(false) { } // TODO make sure init/shutdown is safe for aborted init in comm. mgr. SharedRpcResources::~SharedRpcResources() { if (!_shutdown) { shutdown(); } } void SharedRpcResources::start_server_and_register_slobrok(vespalib::stringref my_handle) { LOG(debug, "Starting main RPC supervisor on port %d with slobrok handle '%s'", _rpc_server_port, vespalib::string(my_handle).c_str()); if (!_orb->Listen(_rpc_server_port)) { throw vespalib::IllegalStateException(vespalib::make_string("Failed to listen to RPC port %d", _rpc_server_port), VESPA_STRLOC); } _transport->Start(_thread_pool.get()); _slobrok_register->registerName(my_handle); wait_until_slobrok_is_ready(); _handle = my_handle; } void SharedRpcResources::wait_until_slobrok_is_ready() { // TODO look more closely at how mbus does its slobrok business while (_slobrok_register->busy() || !_slobrok_mirror->ready()) { // TODO some form of timeout mechanism here, and warning logging to identify SB issues LOG(debug, "Waiting for Slobrok to become ready"); std::this_thread::sleep_for(50ms); } } void SharedRpcResources::shutdown() { assert(!_shutdown); if (listen_port() > 0) { _slobrok_register->unregisterName(_handle); // Give slobrok some time to dispatch unregister RPC while (_slobrok_register->busy()) { std::this_thread::sleep_for(10ms); } } _transport->ShutDown(true); // FIXME need to reset to break weak_ptrs? But ShutDown should already sync pending resolves...! _shutdown = true; } int SharedRpcResources::listen_port() const noexcept { return _orb->GetListenPort(); } const RpcTargetFactory& SharedRpcResources::target_factory() const { return *_target_factory; } } <|endoftext|>
<commit_before>/* Copyright 2021 The TensorFlow 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 <cstdint> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" // Please use the appropriate namespace for your project namespace tensorflow { namespace custom_op_examples { using ::tensorflow::OpKernel; using ::tensorflow::OpKernelConstruction; using ::tensorflow::OpKernelContext; using ::tensorflow::Tensor; using ::tensorflow::errors::Internal; using ::tensorflow::errors::InvalidArgument; // Multiple types for the values inside two of the input tensors // (e.g. int32, float) are supported by using a template where the type is T. template <typename T> class MultiplexDenseOp : public OpKernel { public: explicit MultiplexDenseOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("N", &num_cond_a_)); } MultiplexDenseOp(const MultiplexDenseOp& other) = delete; MultiplexDenseOp& operator=(const MultiplexDenseOp& other) = delete; ~MultiplexDenseOp() override = default; void Compute(OpKernelContext* ctx) override { // Optional error checking: cond and a_values are lists of N, so there are // a total of 2N+1 inputs. Check that the number of inputs and the // `N` Attr is consistent. const int64_t expected_inputs = 2 * num_cond_a_ + 1; OP_REQUIRES(ctx, expected_inputs == ctx->num_inputs(), Internal("expected_inputs != num_inputs(): ", expected_inputs, " != ", ctx->num_inputs())); VLOG(1) << "N " << num_cond_a_; const auto& first_cond_tensor = ctx->input(0); const auto& first_a_values_tensor = ctx->input(num_cond_a_); const auto& b_values_tensor = ctx->input(2 * num_cond_a_); // Allow any shape, but require that a_values, b_values, and cond all // have the same shape. // Note that ::tensorflow::TensorShapeUtils has some useful functions // for checking shapes. for (int64_t i = 0; i < num_cond_a_; i++) { const auto& cond_tensor_i = ctx->input(i); const auto& a_values_tensor_i = ctx->input(num_cond_a_ + i); OP_REQUIRES( ctx, a_values_tensor_i.shape() == b_values_tensor.shape(), InvalidArgument( "a_values[", i, "] and b_values must have the same shape. " "a_values[", i, "] shape: ", a_values_tensor_i.DebugString(), " b_values shape: ", b_values_tensor.shape().DebugString())); OP_REQUIRES( ctx, cond_tensor_i.shape() == b_values_tensor.shape(), InvalidArgument( "cond_values[", i, "] and b_valuesmust have the same shape. " "cond_values[", i, "] shape: ", first_a_values_tensor.shape().DebugString(), " b_values shape: ", first_cond_tensor.shape().DebugString())); } // Create an output tensor Tensor* output_tensor = nullptr; OP_REQUIRES_OK( ctx, ctx->allocate_output(0, b_values_tensor.shape(), &output_tensor)); auto output = output_tensor->template flat<T>(); const auto b_values = b_values_tensor.flat<T>(); // np.select style behavior, `cond` and `a_values` are lists of tensors. // Also works for the np.where style case where there is only one `cond` // and one `a_values` tensor. const int64_t N = first_a_values_tensor.NumElements(); for (int64_t i = 0; i < N; i++) { bool flag = false; for (int64_t list_index = 0; list_index < num_cond_a_; list_index++) { const auto& cond_tensor = ctx->input(list_index); const auto& a_values_tensor = ctx->input(num_cond_a_ + list_index); const auto cond = cond_tensor.flat<bool>(); const auto a_values = a_values_tensor.flat<T>(); if (cond(i)) { output(i) = a_values(i); flag = true; VLOG(1) << "A " << list_index << " for " << i; break; } } if (!flag) { output(i) = b_values(i); VLOG(1) << "B for " << i; } } } private: int64_t num_cond_a_; // the number of `cond` and `a` input tensors }; // The "Name" used by REGISTER_KERNEL_BUILDER is defined by REGISTER_OP, // see multiplex_4_op.cc. // To support tensors containing different types (e.g. int32, float), one // kernel per type is registered and is templatized by the "T" attr value. // The TF_CALL_ALL_TYPES macro registers the op for all types appropriate for // the target platform. See go/tf-custom-ops-guide #define REGISTER_KERNELS(type) \ REGISTER_KERNEL_BUILDER(Name("Examples>MultiplexDense") \ .Device(::tensorflow::DEVICE_CPU) \ .TypeConstraint<type>("T"), \ MultiplexDenseOp<type>) TF_CALL_ALL_TYPES(REGISTER_KERNELS); #undef REGISTER_KERNELS } // namespace custom_op_examples } // namespace tensorflow <commit_msg>use 'template' keyword to treat 'flat' as a dependent template name in multiplex_4<commit_after>/* Copyright 2021 The TensorFlow 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 <cstdint> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" // Please use the appropriate namespace for your project namespace tensorflow { namespace custom_op_examples { using ::tensorflow::OpKernel; using ::tensorflow::OpKernelConstruction; using ::tensorflow::OpKernelContext; using ::tensorflow::Tensor; using ::tensorflow::errors::Internal; using ::tensorflow::errors::InvalidArgument; // Multiple types for the values inside two of the input tensors // (e.g. int32, float) are supported by using a template where the type is T. template <typename T> class MultiplexDenseOp : public OpKernel { public: explicit MultiplexDenseOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("N", &num_cond_a_)); } MultiplexDenseOp(const MultiplexDenseOp& other) = delete; MultiplexDenseOp& operator=(const MultiplexDenseOp& other) = delete; ~MultiplexDenseOp() override = default; void Compute(OpKernelContext* ctx) override { // Optional error checking: cond and a_values are lists of N, so there are // a total of 2N+1 inputs. Check that the number of inputs and the // `N` Attr is consistent. const int64_t expected_inputs = 2 * num_cond_a_ + 1; OP_REQUIRES(ctx, expected_inputs == ctx->num_inputs(), Internal("expected_inputs != num_inputs(): ", expected_inputs, " != ", ctx->num_inputs())); VLOG(1) << "N " << num_cond_a_; const auto& first_cond_tensor = ctx->input(0); const auto& first_a_values_tensor = ctx->input(num_cond_a_); const auto& b_values_tensor = ctx->input(2 * num_cond_a_); // Allow any shape, but require that a_values, b_values, and cond all // have the same shape. // Note that ::tensorflow::TensorShapeUtils has some useful functions // for checking shapes. for (int64_t i = 0; i < num_cond_a_; i++) { const auto& cond_tensor_i = ctx->input(i); const auto& a_values_tensor_i = ctx->input(num_cond_a_ + i); OP_REQUIRES( ctx, a_values_tensor_i.shape() == b_values_tensor.shape(), InvalidArgument( "a_values[", i, "] and b_values must have the same shape. " "a_values[", i, "] shape: ", a_values_tensor_i.DebugString(), " b_values shape: ", b_values_tensor.shape().DebugString())); OP_REQUIRES( ctx, cond_tensor_i.shape() == b_values_tensor.shape(), InvalidArgument( "cond_values[", i, "] and b_valuesmust have the same shape. " "cond_values[", i, "] shape: ", first_a_values_tensor.shape().DebugString(), " b_values shape: ", first_cond_tensor.shape().DebugString())); } // Create an output tensor Tensor* output_tensor = nullptr; OP_REQUIRES_OK( ctx, ctx->allocate_output(0, b_values_tensor.shape(), &output_tensor)); auto output = output_tensor->template flat<T>(); const auto b_values = b_values_tensor.template flat<T>(); // np.select style behavior, `cond` and `a_values` are lists of tensors. // Also works for the np.where style case where there is only one `cond` // and one `a_values` tensor. const int64_t N = first_a_values_tensor.NumElements(); for (int64_t i = 0; i < N; i++) { bool flag = false; for (int64_t list_index = 0; list_index < num_cond_a_; list_index++) { const auto& cond_tensor = ctx->input(list_index); const auto& a_values_tensor = ctx->input(num_cond_a_ + list_index); const auto cond = cond_tensor.template flat<bool>(); const auto a_values = a_values_tensor.template flat<T>(); if (cond(i)) { output(i) = a_values(i); flag = true; VLOG(1) << "A " << list_index << " for " << i; break; } } if (!flag) { output(i) = b_values(i); VLOG(1) << "B for " << i; } } } private: int64_t num_cond_a_; // the number of `cond` and `a` input tensors }; // The "Name" used by REGISTER_KERNEL_BUILDER is defined by REGISTER_OP, // see multiplex_4_op.cc. // To support tensors containing different types (e.g. int32, float), one // kernel per type is registered and is templatized by the "T" attr value. // The TF_CALL_ALL_TYPES macro registers the op for all types appropriate for // the target platform. See go/tf-custom-ops-guide #define REGISTER_KERNELS(type) \ REGISTER_KERNEL_BUILDER(Name("Examples>MultiplexDense") \ .Device(::tensorflow::DEVICE_CPU) \ .TypeConstraint<type>("T"), \ MultiplexDenseOp<type>) TF_CALL_ALL_TYPES(REGISTER_KERNELS); #undef REGISTER_KERNELS } // namespace custom_op_examples } // namespace tensorflow <|endoftext|>
<commit_before>/* * Copyright (c) 2007 The Hewlett-Packard Development Company * All rights reserved. * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2003-2007 The Regents of The University of Michigan * 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: Gabe Black */ #include "arch/x86/generated/decoder.hh" #include "arch/x86/faults.hh" #include "arch/x86/isa_traits.hh" #include "base/trace.hh" #include "cpu/thread_context.hh" #include "debug/Faults.hh" #include "sim/full_system.hh" namespace X86ISA { void X86FaultBase::invoke(ThreadContext * tc, StaticInstPtr inst) { if (!FullSystem) { FaultBase::invoke(tc, inst); return; } PCState pcState = tc->pcState(); Addr pc = pcState.pc(); DPRINTF(Faults, "RIP %#x: vector %d: %s\n", pc, vector, describe()); using namespace X86ISAInst::RomLabels; HandyM5Reg m5reg = tc->readMiscRegNoEffect(MISCREG_M5_REG); MicroPC entry; if (m5reg.mode == LongMode) { if (isSoft()) { entry = extern_label_longModeSoftInterrupt; } else { entry = extern_label_longModeInterrupt; } } else { entry = extern_label_legacyModeInterrupt; } tc->setIntReg(INTREG_MICRO(1), vector); tc->setIntReg(INTREG_MICRO(7), pc); if (errorCode != (uint64_t)(-1)) { if (m5reg.mode == LongMode) { entry = extern_label_longModeInterruptWithError; } else { panic("Legacy mode interrupts with error codes " "aren't implementde.\n"); } // Software interrupts shouldn't have error codes. If one // does, there would need to be microcode to set it up. assert(!isSoft()); tc->setIntReg(INTREG_MICRO(15), errorCode); } pcState.upc(romMicroPC(entry)); pcState.nupc(romMicroPC(entry) + 1); tc->pcState(pcState); } std::string X86FaultBase::describe() const { std::stringstream ss; ccprintf(ss, "%s", mnemonic()); if (errorCode != (uint64_t)(-1)) { ccprintf(ss, "(%#x)", errorCode); } return ss.str(); } void X86Trap::invoke(ThreadContext * tc, StaticInstPtr inst) { X86FaultBase::invoke(tc); if (!FullSystem) return; // This is the same as a fault, but it happens -after- the // instruction. PCState pc = tc->pcState(); pc.uEnd(); } void X86Abort::invoke(ThreadContext * tc, StaticInstPtr inst) { panic("Abort exception!"); } void InvalidOpcode::invoke(ThreadContext * tc, StaticInstPtr inst) { if (FullSystem) { X86Fault::invoke(tc, inst); } else { panic("Unrecognized/invalid instruction executed:\n %s", inst->machInst); } } void PageFault::invoke(ThreadContext * tc, StaticInstPtr inst) { if (FullSystem) { HandyM5Reg m5reg = tc->readMiscRegNoEffect(MISCREG_M5_REG); X86FaultBase::invoke(tc); /* * If something bad happens while trying to enter the page fault * handler, I'm pretty sure that's a double fault and then all * bets are off. That means it should be safe to update this * state now. */ if (m5reg.mode == LongMode) { tc->setMiscReg(MISCREG_CR2, addr); } else { tc->setMiscReg(MISCREG_CR2, (uint32_t)addr); } } else { PageFaultErrorCode code = errorCode; const char *modeStr = ""; if (code.fetch) modeStr = "execute"; else if (code.write) modeStr = "write"; else modeStr = "read"; panic("Tried to %s unmapped address %#x.\n", modeStr, addr); } } std::string PageFault::describe() const { std::stringstream ss; ccprintf(ss, "%s at %#x", X86FaultBase::describe(), addr); return ss.str(); } void InitInterrupt::invoke(ThreadContext *tc, StaticInstPtr inst) { DPRINTF(Faults, "Init interrupt.\n"); // The otherwise unmodified integer registers should be set to 0. for (int index = 0; index < NUM_INTREGS; index++) { tc->setIntReg(index, 0); } CR0 cr0 = tc->readMiscReg(MISCREG_CR0); CR0 newCR0 = 1 << 4; newCR0.cd = cr0.cd; newCR0.nw = cr0.nw; tc->setMiscReg(MISCREG_CR0, newCR0); tc->setMiscReg(MISCREG_CR2, 0); tc->setMiscReg(MISCREG_CR3, 0); tc->setMiscReg(MISCREG_CR4, 0); tc->setMiscReg(MISCREG_RFLAGS, 0x0000000000000002ULL); tc->setMiscReg(MISCREG_EFER, 0); SegAttr dataAttr = 0; dataAttr.dpl = 0; dataAttr.unusable = 0; dataAttr.defaultSize = 0; dataAttr.longMode = 0; dataAttr.avl = 0; dataAttr.granularity = 0; dataAttr.present = 1; dataAttr.type = 3; dataAttr.writable = 1; dataAttr.readable = 1; dataAttr.expandDown = 0; dataAttr.system = 1; for (int seg = 0; seg != NUM_SEGMENTREGS; seg++) { tc->setMiscReg(MISCREG_SEG_SEL(seg), 0); tc->setMiscReg(MISCREG_SEG_BASE(seg), 0); tc->setMiscReg(MISCREG_SEG_EFF_BASE(seg), 0); tc->setMiscReg(MISCREG_SEG_LIMIT(seg), 0xffff); tc->setMiscReg(MISCREG_SEG_ATTR(seg), dataAttr); } SegAttr codeAttr = 0; codeAttr.dpl = 0; codeAttr.unusable = 0; codeAttr.defaultSize = 0; codeAttr.longMode = 0; codeAttr.avl = 0; codeAttr.granularity = 0; codeAttr.present = 1; codeAttr.type = 10; codeAttr.writable = 0; codeAttr.readable = 1; codeAttr.expandDown = 0; codeAttr.system = 1; tc->setMiscReg(MISCREG_CS, 0xf000); tc->setMiscReg(MISCREG_CS_BASE, 0x00000000ffff0000ULL); tc->setMiscReg(MISCREG_CS_EFF_BASE, 0x00000000ffff0000ULL); // This has the base value pre-added. tc->setMiscReg(MISCREG_CS_LIMIT, 0xffffffff); tc->setMiscReg(MISCREG_CS_ATTR, codeAttr); PCState pc(0x000000000000fff0ULL + tc->readMiscReg(MISCREG_CS_BASE)); tc->pcState(pc); tc->setMiscReg(MISCREG_TSG_BASE, 0); tc->setMiscReg(MISCREG_TSG_LIMIT, 0xffff); tc->setMiscReg(MISCREG_IDTR_BASE, 0); tc->setMiscReg(MISCREG_IDTR_LIMIT, 0xffff); tc->setMiscReg(MISCREG_TSL, 0); tc->setMiscReg(MISCREG_TSL_BASE, 0); tc->setMiscReg(MISCREG_TSL_LIMIT, 0xffff); tc->setMiscReg(MISCREG_TSL_ATTR, 0); tc->setMiscReg(MISCREG_TR, 0); tc->setMiscReg(MISCREG_TR_BASE, 0); tc->setMiscReg(MISCREG_TR_LIMIT, 0xffff); tc->setMiscReg(MISCREG_TR_ATTR, 0); // This value should be the family/model/stepping of the processor. // (page 418). It should be consistent with the value from CPUID, but // the actual value probably doesn't matter much. tc->setIntReg(INTREG_RDX, 0); tc->setMiscReg(MISCREG_DR0, 0); tc->setMiscReg(MISCREG_DR1, 0); tc->setMiscReg(MISCREG_DR2, 0); tc->setMiscReg(MISCREG_DR3, 0); tc->setMiscReg(MISCREG_DR6, 0x00000000ffff0ff0ULL); tc->setMiscReg(MISCREG_DR7, 0x0000000000000400ULL); // Update the handy M5 Reg. tc->setMiscReg(MISCREG_M5_REG, 0); MicroPC entry = X86ISAInst::RomLabels::extern_label_initIntHalt; pc.upc(romMicroPC(entry)); pc.nupc(romMicroPC(entry) + 1); tc->pcState(pc); } void StartupInterrupt::invoke(ThreadContext *tc, StaticInstPtr inst) { DPRINTF(Faults, "Startup interrupt with vector %#x.\n", vector); HandyM5Reg m5Reg = tc->readMiscReg(MISCREG_M5_REG); if (m5Reg.mode != LegacyMode || m5Reg.submode != RealMode) { panic("Startup IPI recived outside of real mode. " "Don't know what to do. %d, %d", m5Reg.mode, m5Reg.submode); } tc->setMiscReg(MISCREG_CS, vector << 8); tc->setMiscReg(MISCREG_CS_BASE, vector << 12); tc->setMiscReg(MISCREG_CS_EFF_BASE, vector << 12); // This has the base value pre-added. tc->setMiscReg(MISCREG_CS_LIMIT, 0xffff); tc->pcState(tc->readMiscReg(MISCREG_CS_BASE)); } } // namespace X86ISA <commit_msg>x86: Initialize the MXCSR register<commit_after>/* * Copyright (c) 2007 The Hewlett-Packard Development Company * All rights reserved. * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2003-2007 The Regents of The University of Michigan * 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: Gabe Black */ #include "arch/x86/generated/decoder.hh" #include "arch/x86/faults.hh" #include "arch/x86/isa_traits.hh" #include "base/trace.hh" #include "cpu/thread_context.hh" #include "debug/Faults.hh" #include "sim/full_system.hh" namespace X86ISA { void X86FaultBase::invoke(ThreadContext * tc, StaticInstPtr inst) { if (!FullSystem) { FaultBase::invoke(tc, inst); return; } PCState pcState = tc->pcState(); Addr pc = pcState.pc(); DPRINTF(Faults, "RIP %#x: vector %d: %s\n", pc, vector, describe()); using namespace X86ISAInst::RomLabels; HandyM5Reg m5reg = tc->readMiscRegNoEffect(MISCREG_M5_REG); MicroPC entry; if (m5reg.mode == LongMode) { if (isSoft()) { entry = extern_label_longModeSoftInterrupt; } else { entry = extern_label_longModeInterrupt; } } else { entry = extern_label_legacyModeInterrupt; } tc->setIntReg(INTREG_MICRO(1), vector); tc->setIntReg(INTREG_MICRO(7), pc); if (errorCode != (uint64_t)(-1)) { if (m5reg.mode == LongMode) { entry = extern_label_longModeInterruptWithError; } else { panic("Legacy mode interrupts with error codes " "aren't implementde.\n"); } // Software interrupts shouldn't have error codes. If one // does, there would need to be microcode to set it up. assert(!isSoft()); tc->setIntReg(INTREG_MICRO(15), errorCode); } pcState.upc(romMicroPC(entry)); pcState.nupc(romMicroPC(entry) + 1); tc->pcState(pcState); } std::string X86FaultBase::describe() const { std::stringstream ss; ccprintf(ss, "%s", mnemonic()); if (errorCode != (uint64_t)(-1)) { ccprintf(ss, "(%#x)", errorCode); } return ss.str(); } void X86Trap::invoke(ThreadContext * tc, StaticInstPtr inst) { X86FaultBase::invoke(tc); if (!FullSystem) return; // This is the same as a fault, but it happens -after- the // instruction. PCState pc = tc->pcState(); pc.uEnd(); } void X86Abort::invoke(ThreadContext * tc, StaticInstPtr inst) { panic("Abort exception!"); } void InvalidOpcode::invoke(ThreadContext * tc, StaticInstPtr inst) { if (FullSystem) { X86Fault::invoke(tc, inst); } else { panic("Unrecognized/invalid instruction executed:\n %s", inst->machInst); } } void PageFault::invoke(ThreadContext * tc, StaticInstPtr inst) { if (FullSystem) { HandyM5Reg m5reg = tc->readMiscRegNoEffect(MISCREG_M5_REG); X86FaultBase::invoke(tc); /* * If something bad happens while trying to enter the page fault * handler, I'm pretty sure that's a double fault and then all * bets are off. That means it should be safe to update this * state now. */ if (m5reg.mode == LongMode) { tc->setMiscReg(MISCREG_CR2, addr); } else { tc->setMiscReg(MISCREG_CR2, (uint32_t)addr); } } else { PageFaultErrorCode code = errorCode; const char *modeStr = ""; if (code.fetch) modeStr = "execute"; else if (code.write) modeStr = "write"; else modeStr = "read"; panic("Tried to %s unmapped address %#x.\n", modeStr, addr); } } std::string PageFault::describe() const { std::stringstream ss; ccprintf(ss, "%s at %#x", X86FaultBase::describe(), addr); return ss.str(); } void InitInterrupt::invoke(ThreadContext *tc, StaticInstPtr inst) { DPRINTF(Faults, "Init interrupt.\n"); // The otherwise unmodified integer registers should be set to 0. for (int index = 0; index < NUM_INTREGS; index++) { tc->setIntReg(index, 0); } CR0 cr0 = tc->readMiscReg(MISCREG_CR0); CR0 newCR0 = 1 << 4; newCR0.cd = cr0.cd; newCR0.nw = cr0.nw; tc->setMiscReg(MISCREG_CR0, newCR0); tc->setMiscReg(MISCREG_CR2, 0); tc->setMiscReg(MISCREG_CR3, 0); tc->setMiscReg(MISCREG_CR4, 0); tc->setMiscReg(MISCREG_RFLAGS, 0x0000000000000002ULL); tc->setMiscReg(MISCREG_EFER, 0); SegAttr dataAttr = 0; dataAttr.dpl = 0; dataAttr.unusable = 0; dataAttr.defaultSize = 0; dataAttr.longMode = 0; dataAttr.avl = 0; dataAttr.granularity = 0; dataAttr.present = 1; dataAttr.type = 3; dataAttr.writable = 1; dataAttr.readable = 1; dataAttr.expandDown = 0; dataAttr.system = 1; for (int seg = 0; seg != NUM_SEGMENTREGS; seg++) { tc->setMiscReg(MISCREG_SEG_SEL(seg), 0); tc->setMiscReg(MISCREG_SEG_BASE(seg), 0); tc->setMiscReg(MISCREG_SEG_EFF_BASE(seg), 0); tc->setMiscReg(MISCREG_SEG_LIMIT(seg), 0xffff); tc->setMiscReg(MISCREG_SEG_ATTR(seg), dataAttr); } SegAttr codeAttr = 0; codeAttr.dpl = 0; codeAttr.unusable = 0; codeAttr.defaultSize = 0; codeAttr.longMode = 0; codeAttr.avl = 0; codeAttr.granularity = 0; codeAttr.present = 1; codeAttr.type = 10; codeAttr.writable = 0; codeAttr.readable = 1; codeAttr.expandDown = 0; codeAttr.system = 1; tc->setMiscReg(MISCREG_CS, 0xf000); tc->setMiscReg(MISCREG_CS_BASE, 0x00000000ffff0000ULL); tc->setMiscReg(MISCREG_CS_EFF_BASE, 0x00000000ffff0000ULL); // This has the base value pre-added. tc->setMiscReg(MISCREG_CS_LIMIT, 0xffffffff); tc->setMiscReg(MISCREG_CS_ATTR, codeAttr); PCState pc(0x000000000000fff0ULL + tc->readMiscReg(MISCREG_CS_BASE)); tc->pcState(pc); tc->setMiscReg(MISCREG_TSG_BASE, 0); tc->setMiscReg(MISCREG_TSG_LIMIT, 0xffff); tc->setMiscReg(MISCREG_IDTR_BASE, 0); tc->setMiscReg(MISCREG_IDTR_LIMIT, 0xffff); tc->setMiscReg(MISCREG_TSL, 0); tc->setMiscReg(MISCREG_TSL_BASE, 0); tc->setMiscReg(MISCREG_TSL_LIMIT, 0xffff); tc->setMiscReg(MISCREG_TSL_ATTR, 0); tc->setMiscReg(MISCREG_TR, 0); tc->setMiscReg(MISCREG_TR_BASE, 0); tc->setMiscReg(MISCREG_TR_LIMIT, 0xffff); tc->setMiscReg(MISCREG_TR_ATTR, 0); // This value should be the family/model/stepping of the processor. // (page 418). It should be consistent with the value from CPUID, but // the actual value probably doesn't matter much. tc->setIntReg(INTREG_RDX, 0); tc->setMiscReg(MISCREG_DR0, 0); tc->setMiscReg(MISCREG_DR1, 0); tc->setMiscReg(MISCREG_DR2, 0); tc->setMiscReg(MISCREG_DR3, 0); tc->setMiscReg(MISCREG_DR6, 0x00000000ffff0ff0ULL); tc->setMiscReg(MISCREG_DR7, 0x0000000000000400ULL); tc->setMiscReg(MISCREG_MXCSR, 0x1f80); // Update the handy M5 Reg. tc->setMiscReg(MISCREG_M5_REG, 0); MicroPC entry = X86ISAInst::RomLabels::extern_label_initIntHalt; pc.upc(romMicroPC(entry)); pc.nupc(romMicroPC(entry) + 1); tc->pcState(pc); } void StartupInterrupt::invoke(ThreadContext *tc, StaticInstPtr inst) { DPRINTF(Faults, "Startup interrupt with vector %#x.\n", vector); HandyM5Reg m5Reg = tc->readMiscReg(MISCREG_M5_REG); if (m5Reg.mode != LegacyMode || m5Reg.submode != RealMode) { panic("Startup IPI recived outside of real mode. " "Don't know what to do. %d, %d", m5Reg.mode, m5Reg.submode); } tc->setMiscReg(MISCREG_CS, vector << 8); tc->setMiscReg(MISCREG_CS_BASE, vector << 12); tc->setMiscReg(MISCREG_CS_EFF_BASE, vector << 12); // This has the base value pre-added. tc->setMiscReg(MISCREG_CS_LIMIT, 0xffff); tc->pcState(tc->readMiscReg(MISCREG_CS_BASE)); } } // namespace X86ISA <|endoftext|>
<commit_before>namespace mant { class StandardParticleSwarmOptimisation2011 : public PopulationBasedOptimisationAlgorithm<double> { public: inline explicit StandardParticleSwarmOptimisation2011( const std::shared_ptr<OptimisationProblem<double>> optimisationProblem, const unsigned int populationSize) noexcept; inline void setNeighbourhoodProbability( const double neighbourhoodProbability) noexcept; inline void setMaximalAcceleration( const double maximalAcceleration) noexcept; inline void setMaximalLocalAttraction( const double maximalLocalAttraction) noexcept; inline void setMaximalGlobalAttraction( const double maximalGlobalAttraction) noexcept; inline void setMaximalSwarmConvergence( const double maximalSwarmConvergence) noexcept; inline std::string toString() const noexcept override; protected: double neighbourhoodProbability_; double maximalAcceleration_; double maximalLocalAttraction_; double maximalGlobalAttraction_; double maximalSwarmConvergence_; arma::Mat<double> particles_; arma::Mat<double> velocities_; unsigned int particleIndex_; arma::Col<double> particle_; arma::Col<unsigned int> neighbourhoodParticlesIndecies_; unsigned int neighbourhoodBestParticleIndex_; arma::Col<double> attractionCenter_; arma::Mat<double> localBestSolutions_; arma::Row<double> localBestSoftConstraintsValues_; arma::Row<double> localBestObjectiveValues_; bool randomizeTopology_; arma::Mat<unsigned int> topology_; inline void optimiseImplementation() noexcept override; inline void initialiseSwarm() noexcept; inline arma::Mat<unsigned int> getRandomNeighbourhoodTopology() noexcept; inline double getAcceleration() noexcept; inline arma::Col<double> getVelocity() noexcept; }; // // Implementation // inline StandardParticleSwarmOptimisation2011::StandardParticleSwarmOptimisation2011( const std::shared_ptr<OptimisationProblem<double>> optimisationProblem, const unsigned int populationSize) noexcept : PopulationBasedOptimisationAlgorithm<double>(optimisationProblem, populationSize), localBestObjectiveValues_(this->populationSize_), randomizeTopology_(true) { setNeighbourhoodProbability(std::pow(1.0 - 1.0 / static_cast<double>(this->populationSize_), 3.0)); setMaximalAcceleration(1.0 / (2.0 * std::log(2.0))); setMaximalLocalAttraction(0.5 + std::log(2.0)); setMaximalGlobalAttraction(maximalLocalAttraction_); setMaximalSwarmConvergence(0.05); // TODO Check value within the paper } inline void StandardParticleSwarmOptimisation2011::optimiseImplementation() noexcept { initialiseSwarm(); while(!this->isFinished() && !this->isTerminated()) { if (randomizeTopology_) { topology_ = getRandomNeighbourhoodTopology(); randomizeTopology_ = false; } const arma::Col<unsigned int>& permutation = getRandomPermutation(this->populationSize_); for (std::size_t n = 0; n < this->populationSize_; ++n) { ++this->numberOfIterations_; particleIndex_ = permutation(n); particle_ = particles_.col(particleIndex_); neighbourhoodParticlesIndecies_ = arma::find(topology_.col(particleIndex_)); static_cast<arma::Col<double>>(localBestObjectiveValues_.elem(neighbourhoodParticlesIndecies_)).min(neighbourhoodBestParticleIndex_); neighbourhoodBestParticleIndex_ = neighbourhoodParticlesIndecies_(neighbourhoodBestParticleIndex_); if (neighbourhoodBestParticleIndex_ == particleIndex_) { attractionCenter_ = (maximalLocalAttraction_ * (localBestSolutions_.col(particleIndex_) - particle_)) / 2.0; } else { attractionCenter_ = (maximalLocalAttraction_ * (localBestSolutions_.col(particleIndex_) - particle_) + maximalGlobalAttraction_ * (localBestSolutions_.col(neighbourhoodBestParticleIndex_) - particle_)) / 3.0; } arma::Col<double> velocityCandidate = maximalAcceleration_ * getAcceleration() * velocities_.col(particleIndex_) + getVelocity() * arma::norm(attractionCenter_) + attractionCenter_; arma::Col<double> solutionCandidate = particle_ + velocityCandidate; const arma::Col<unsigned int>& belowLowerBound = arma::find(solutionCandidate < this->getLowerBounds()); const arma::Col<unsigned int>& aboveUpperBound = arma::find(solutionCandidate > this->getUpperBounds()); velocityCandidate.elem(belowLowerBound) *= -0.5; velocityCandidate.elem(aboveUpperBound) *= -0.5; solutionCandidate.elem(belowLowerBound) = this->getLowerBounds().elem(belowLowerBound); solutionCandidate.elem(aboveUpperBound) = this->getUpperBounds().elem(aboveUpperBound); velocities_.col(particleIndex_) = velocityCandidate; particles_.col(particleIndex_) = solutionCandidate; const double& objectiveValue = this->getObjectiveValue(solutionCandidate) + this->getSoftConstraintsValue(solutionCandidate); if (objectiveValue < localBestObjectiveValues_(particleIndex_)) { localBestObjectiveValues_(particleIndex_) = objectiveValue; localBestSolutions_.col(particleIndex_) = solutionCandidate; } if (objectiveValue < this->bestObjectiveValue_) { this->bestObjectiveValue_ = objectiveValue; this->bestParameter_ = solutionCandidate; } else { randomizeTopology_ = true; } if (this->isFinished() || this->isTerminated()) { break; } } if (static_cast<arma::Row<double>>(arma::stddev(particles_, 1)).max() < maximalSwarmConvergence_) { initialiseSwarm(); } } } inline void StandardParticleSwarmOptimisation2011::initialiseSwarm() noexcept { particles_ = arma::randu<arma::Mat<double>>(this->numberOfDimensions_, this->populationSize_); particles_.each_col() %= this->getUpperBounds() - this->getLowerBounds(); particles_.each_col() += this->getLowerBounds(); velocities_ = arma::randu<arma::Mat<double>>(this->numberOfDimensions_, this->populationSize_); velocities_.each_col() %= this->getUpperBounds() - this->getLowerBounds(); velocities_.each_col() += this->getLowerBounds(); velocities_ -= particles_; localBestSolutions_ = particles_; for (std::size_t n = 0; n < this->populationSize_; ++n) { ++this->numberOfIterations_; arma::Col<double> localBestSolution = localBestSolutions_.col(n); double localBestObjectiveValue = this->getObjectiveValue(localBestSolution) + this->getSoftConstraintsValue(localBestSolution); localBestObjectiveValues_(n) = localBestObjectiveValue; if (localBestObjectiveValue < this->bestObjectiveValue_) { this->bestParameter_ = localBestSolution; this->bestObjectiveValue_ = localBestObjectiveValue; } if (this->isFinished() || this->isTerminated()) { break; } } randomizeTopology_ = true; } inline double StandardParticleSwarmOptimisation2011::getAcceleration() noexcept { return std::uniform_real_distribution<double>(0.0, 1.0)(Rng::getGenerator()); } inline arma::Col<double> StandardParticleSwarmOptimisation2011::getVelocity() noexcept { return arma::normalise(arma::randn<arma::Col<double>>(this->numberOfDimensions_)) * std::uniform_real_distribution<double>(0.0, 1.0)(Rng::getGenerator()); } inline arma::Mat<unsigned int> StandardParticleSwarmOptimisation2011::getRandomNeighbourhoodTopology() noexcept { arma::Mat<unsigned int> topology = (arma::randu<arma::Mat<double>>(this->populationSize_, this->populationSize_) <= neighbourhoodProbability_); topology.diag() += 1.0; return topology; } inline void StandardParticleSwarmOptimisation2011::setNeighbourhoodProbability( const double neighbourhoodProbability) noexcept { neighbourhoodProbability_ = neighbourhoodProbability; } inline void StandardParticleSwarmOptimisation2011::setMaximalAcceleration( const double maximalAcceleration) noexcept { maximalAcceleration_ = maximalAcceleration; } inline void StandardParticleSwarmOptimisation2011::setMaximalLocalAttraction( const double maximalLocalAttraction) noexcept { maximalLocalAttraction_ = maximalLocalAttraction; } inline void StandardParticleSwarmOptimisation2011::setMaximalGlobalAttraction( const double maximalGlobalAttraction) noexcept { maximalGlobalAttraction_ = maximalGlobalAttraction; } inline void StandardParticleSwarmOptimisation2011::setMaximalSwarmConvergence( const double maximalSwarmConvergence) noexcept { maximalSwarmConvergence_ = maximalSwarmConvergence; } inline std::string StandardParticleSwarmOptimisation2011::toString() const noexcept { return "StandardParticleSwarmOptimisation2011"; } } <commit_msg>Added template information<commit_after>namespace mant { template <typename T> class StandardParticleSwarmOptimisation2011 : public PopulationBasedOptimisationAlgorithm<T> { public: inline explicit StandardParticleSwarmOptimisation2011( const std::shared_ptr<OptimisationProblem<T>> optimisationProblem, const unsigned int populationSize) noexcept; inline void setNeighbourhoodProbability( const T neighbourhoodProbability) noexcept; inline void setMaximalAcceleration( const T maximalAcceleration) noexcept; inline void setMaximalLocalAttraction( const T maximalLocalAttraction) noexcept; inline void setMaximalGlobalAttraction( const T maximalGlobalAttraction) noexcept; inline void setMaximalSwarmConvergence( const T maximalSwarmConvergence) noexcept; inline std::string toString() const noexcept override; protected: T neighbourhoodProbability_; T maximalAcceleration_; T maximalLocalAttraction_; T maximalGlobalAttraction_; T maximalSwarmConvergence_; arma::Mat<T> particles_; arma::Mat<T> velocities_; unsigned int particleIndex_; arma::Col<T> particle_; arma::Col<unsigned int> neighbourhoodParticlesIndecies_; unsigned int neighbourhoodBestParticleIndex_; arma::Col<T> attractionCenter_; arma::Mat<T> localBestSolutions_; arma::Row<double> localBestSoftConstraintsValues_; arma::Row<double> localBestObjectiveValues_; bool randomizeTopology_; arma::Mat<unsigned int> topology_; inline void optimiseImplementation() noexcept override; inline void initialiseSwarm() noexcept; inline arma::Mat<unsigned int> getRandomNeighbourhoodTopology() noexcept; inline T getAcceleration() noexcept; inline arma::Col<T> getVelocity() noexcept; }; // // Implementation // template <typename T> inline StandardParticleSwarmOptimisation2011<T>::StandardParticleSwarmOptimisation2011( const std::shared_ptr<OptimisationProblem<T>> optimisationProblem, const unsigned int populationSize) noexcept : PopulationBasedOptimisationAlgorithm<T>(optimisationProblem, populationSize), localBestObjectiveValues_(this->populationSize_), randomizeTopology_(true) { setNeighbourhoodProbability(std::pow(1.0 - 1.0 / static_cast<T>(this->populationSize_), 3.0)); setMaximalAcceleration(1.0 / (2.0 * std::log(2.0))); setMaximalLocalAttraction(0.5 + std::log(2.0)); setMaximalGlobalAttraction(maximalLocalAttraction_); setMaximalSwarmConvergence(0.05); // TODO Check value within the paper } template <typename T> inline void StandardParticleSwarmOptimisation2011<T>::optimiseImplementation() noexcept { initialiseSwarm(); while(!this->isFinished() && !this->isTerminated()) { if (randomizeTopology_) { topology_ = getRandomNeighbourhoodTopology(); randomizeTopology_ = false; } const arma::Col<unsigned int>& permutation = getRandomPermutation(this->populationSize_); for (std::size_t n = 0; n < this->populationSize_; ++n) { ++this->numberOfIterations_; particleIndex_ = permutation(n); particle_ = particles_.col(particleIndex_); neighbourhoodParticlesIndecies_ = arma::find(topology_.col(particleIndex_)); static_cast<arma::Col<T>>(localBestObjectiveValues_.elem(neighbourhoodParticlesIndecies_)).min(neighbourhoodBestParticleIndex_); neighbourhoodBestParticleIndex_ = neighbourhoodParticlesIndecies_(neighbourhoodBestParticleIndex_); if (neighbourhoodBestParticleIndex_ == particleIndex_) { attractionCenter_ = (maximalLocalAttraction_ * (localBestSolutions_.col(particleIndex_) - particle_)) / 2.0; } else { attractionCenter_ = (maximalLocalAttraction_ * (localBestSolutions_.col(particleIndex_) - particle_) + maximalGlobalAttraction_ * (localBestSolutions_.col(neighbourhoodBestParticleIndex_) - particle_)) / 3.0; } arma::Col<T> velocityCandidate = maximalAcceleration_ * getAcceleration() * velocities_.col(particleIndex_) + getVelocity() * arma::norm(attractionCenter_) + attractionCenter_; arma::Col<T> solutionCandidate = particle_ + velocityCandidate; const arma::Col<unsigned int>& belowLowerBound = arma::find(solutionCandidate < this->getLowerBounds()); const arma::Col<unsigned int>& aboveUpperBound = arma::find(solutionCandidate > this->getUpperBounds()); velocityCandidate.elem(belowLowerBound) *= -0.5; velocityCandidate.elem(aboveUpperBound) *= -0.5; solutionCandidate.elem(belowLowerBound) = this->getLowerBounds().elem(belowLowerBound); solutionCandidate.elem(aboveUpperBound) = this->getUpperBounds().elem(aboveUpperBound); velocities_.col(particleIndex_) = velocityCandidate; particles_.col(particleIndex_) = solutionCandidate; const double& objectiveValue = this->getObjectiveValue(solutionCandidate) + this->getSoftConstraintsValue(solutionCandidate); if (objectiveValue < localBestObjectiveValues_(particleIndex_)) { localBestObjectiveValues_(particleIndex_) = objectiveValue; localBestSolutions_.col(particleIndex_) = solutionCandidate; } if (objectiveValue < this->bestObjectiveValue_) { this->bestObjectiveValue_ = objectiveValue; this->bestParameter_ = solutionCandidate; } else { randomizeTopology_ = true; } if (this->isFinished() || this->isTerminated()) { break; } } if (static_cast<arma::Row<T>>(arma::stddev(particles_, 1)).max() < maximalSwarmConvergence_) { initialiseSwarm(); } } } template <typename T> inline void StandardParticleSwarmOptimisation2011<T>::initialiseSwarm() noexcept { particles_ = arma::randu<arma::Mat<T>>(this->numberOfDimensions_, this->populationSize_); particles_.each_col() %= this->getUpperBounds() - this->getLowerBounds(); particles_.each_col() += this->getLowerBounds(); velocities_ = arma::randu<arma::Mat<T>>(this->numberOfDimensions_, this->populationSize_); velocities_.each_col() %= this->getUpperBounds() - this->getLowerBounds(); velocities_.each_col() += this->getLowerBounds(); velocities_ -= particles_; localBestSolutions_ = particles_; for (std::size_t n = 0; n < this->populationSize_; ++n) { ++this->numberOfIterations_; arma::Col<double> localBestSolution = localBestSolutions_.col(n); double localBestObjectiveValue = this->getObjectiveValue(localBestSolution) + this->getSoftConstraintsValue(localBestSolution); localBestObjectiveValues_(n) = localBestObjectiveValue; if (localBestObjectiveValue < this->bestObjectiveValue_) { this->bestParameter_ = localBestSolution; this->bestObjectiveValue_ = localBestObjectiveValue; } if (this->isFinished() || this->isTerminated()) { break; } } randomizeTopology_ = true; } template <typename T> inline T StandardParticleSwarmOptimisation2011<T>::getAcceleration() noexcept { return std::uniform_real_distribution<T>(0.0, 1.0)(Rng::getGenerator()); } template <typename T> inline arma::Col<T> StandardParticleSwarmOptimisation2011<T>::getVelocity() noexcept { return arma::normalise(arma::randn<arma::Col<T>>(this->numberOfDimensions_)) * std::uniform_real_distribution<T>(0.0, 1.0)(Rng::getGenerator()); } template <typename T> inline arma::Mat<unsigned int> StandardParticleSwarmOptimisation2011<T>::getRandomNeighbourhoodTopology() noexcept { arma::Mat<unsigned int> topology = (arma::randu<arma::Mat<T>>(this->populationSize_, this->populationSize_) <= neighbourhoodProbability_); topology.diag() += 1.0; return topology; } template <typename T> inline void StandardParticleSwarmOptimisation2011<T>::setNeighbourhoodProbability( const T neighbourhoodProbability) noexcept { neighbourhoodProbability_ = neighbourhoodProbability; } template <typename T> inline void StandardParticleSwarmOptimisation2011<T>::setMaximalAcceleration( const T maximalAcceleration) noexcept { maximalAcceleration_ = maximalAcceleration; } template <typename T> inline void StandardParticleSwarmOptimisation2011<T>::setMaximalLocalAttraction( const T maximalLocalAttraction) noexcept { maximalLocalAttraction_ = maximalLocalAttraction; } template <typename T> inline void StandardParticleSwarmOptimisation2011<T>::setMaximalGlobalAttraction( const T maximalGlobalAttraction) noexcept { maximalGlobalAttraction_ = maximalGlobalAttraction; } template <typename T> inline void StandardParticleSwarmOptimisation2011<T>::setMaximalSwarmConvergence( const T maximalSwarmConvergence) noexcept { maximalSwarmConvergence_ = maximalSwarmConvergence; } template <typename T> inline std::string StandardParticleSwarmOptimisation2011<T>::toString() const noexcept { return "StandardParticleSwarmOptimisation2011"; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2018 The Android Open Source Project * * 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 "perfetto/ext/base/file_utils.h" #include <sys/stat.h> #include <sys/types.h> #include <algorithm> #include <deque> #include <string> #include <vector> #include "perfetto/base/build_config.h" #include "perfetto/base/logging.h" #include "perfetto/base/platform_handle.h" #include "perfetto/base/status.h" #include "perfetto/ext/base/scoped_file.h" #include "perfetto/ext/base/utils.h" #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) #include <Windows.h> #include <direct.h> #include <io.h> #else #include <dirent.h> #include <unistd.h> #endif namespace perfetto { namespace base { namespace { constexpr size_t kBufSize = 2048; #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Wrap FindClose to: (1) make the return unix-style; (2) deal with stdcall. int CloseFindHandle(HANDLE h) { return FindClose(h) ? 0 : -1; }; #endif } // namespace ssize_t Read(int fd, void* dst, size_t dst_size) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) return _read(fd, dst, static_cast<unsigned>(dst_size)); #else return PERFETTO_EINTR(read(fd, dst, dst_size)); #endif } bool ReadFileDescriptor(int fd, std::string* out) { // Do not override existing data in string. size_t i = out->size(); struct stat buf {}; if (fstat(fd, &buf) != -1) { if (buf.st_size > 0) out->resize(i + static_cast<size_t>(buf.st_size)); } ssize_t bytes_read; for (;;) { if (out->size() < i + kBufSize) out->resize(out->size() + kBufSize); bytes_read = Read(fd, &((*out)[i]), kBufSize); if (bytes_read > 0) { i += static_cast<size_t>(bytes_read); } else { out->resize(i); return bytes_read == 0; } } } bool ReadPlatformHandle(PlatformHandle h, std::string* out) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Do not override existing data in string. size_t i = out->size(); for (;;) { if (out->size() < i + kBufSize) out->resize(out->size() + kBufSize); DWORD bytes_read = 0; auto res = ::ReadFile(h, &((*out)[i]), kBufSize, &bytes_read, nullptr); if (res && bytes_read > 0) { i += static_cast<size_t>(bytes_read); } else { out->resize(i); const bool is_eof = res && bytes_read == 0; auto err = res ? 0 : GetLastError(); // The "Broken pipe" error on Windows is slighly different than Unix: // On Unix: a "broken pipe" error can happen only on the writer side. On // the reader there is no broken pipe, just a EOF. // On windows: the reader also sees a broken pipe error. // Here we normalize on the Unix behavior, treating broken pipe as EOF. return is_eof || err == ERROR_BROKEN_PIPE; } } #else return ReadFileDescriptor(h, out); #endif } bool ReadFileStream(FILE* f, std::string* out) { return ReadFileDescriptor(fileno(f), out); } bool ReadFile(const std::string& path, std::string* out) { base::ScopedFile fd = base::OpenFile(path, O_RDONLY); if (!fd) return false; return ReadFileDescriptor(*fd, out); } ssize_t WriteAll(int fd, const void* buf, size_t count) { size_t written = 0; while (written < count) { // write() on windows takes an unsigned int size. uint32_t bytes_left = static_cast<uint32_t>( std::min(count - written, static_cast<size_t>(UINT32_MAX))); ssize_t wr = PERFETTO_EINTR( write(fd, static_cast<const char*>(buf) + written, bytes_left)); if (wr == 0) break; if (wr < 0) return wr; written += static_cast<size_t>(wr); } return static_cast<ssize_t>(written); } ssize_t WriteAllHandle(PlatformHandle h, const void* buf, size_t count) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) DWORD wsize = 0; if (::WriteFile(h, buf, static_cast<DWORD>(count), &wsize, nullptr)) { return wsize; } else { return -1; } #else return WriteAll(h, buf, count); #endif } bool FlushFile(int fd) { PERFETTO_DCHECK(fd != 0); #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) return !PERFETTO_EINTR(fdatasync(fd)); #elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) return !PERFETTO_EINTR(_commit(fd)); #else return !PERFETTO_EINTR(fsync(fd)); #endif } bool Mkdir(const std::string& path) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) return _mkdir(path.c_str()) == 0; #else return mkdir(path.c_str(), 0755) == 0; #endif } bool Rmdir(const std::string& path) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) return _rmdir(path.c_str()) == 0; #else return rmdir(path.c_str()) == 0; #endif } int CloseFile(int fd) { return close(fd); } ScopedFile OpenFile(const std::string& path, int flags, FileOpenMode mode) { PERFETTO_DCHECK((flags & O_CREAT) == 0 || mode != kFileModeInvalid); #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Always use O_BINARY on Windows, to avoid silly EOL translations. ScopedFile fd(_open(path.c_str(), flags | O_BINARY, mode)); #else // Always open a ScopedFile with O_CLOEXEC so we can safely fork and exec. ScopedFile fd(open(path.c_str(), flags | O_CLOEXEC, mode)); #endif return fd; } bool FileExists(const std::string& path) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) return _access(path.c_str(), 0) == 0; #else return access(path.c_str(), F_OK) == 0; #endif } // Declared in base/platform_handle.h. int ClosePlatformHandle(PlatformHandle handle) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Make the return value UNIX-style. return CloseHandle(handle) ? 0 : -1; #else return close(handle); #endif } base::Status ListFilesRecursive(const std::string& dir_path, std::vector<std::string>& output) { std::string root_dir_path = dir_path; if (root_dir_path.back() == '\\') { root_dir_path.back() = '/'; } else if (root_dir_path.back() != '/') { root_dir_path.push_back('/'); } // dir_queue contains full paths to the directories. The paths include the // root_dir_path at the beginning and the trailing slash at the end. std::deque<std::string> dir_queue; dir_queue.push_back(root_dir_path); while (!dir_queue.empty()) { const std::string cur_dir = std::move(dir_queue.front()); dir_queue.pop_front(); #if PERFETTO_BUILDFLAG(PERFETTO_OS_NACL) return base::ErrStatus("ListFilesRecursive not supported yet"); #elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) std::string glob_path = cur_dir + "*"; // + 1 because we also have to count the NULL terminator. if (glob_path.length() + 1 > MAX_PATH) return base::ErrStatus("Directory path %s is too long", dir_path.c_str()); WIN32_FIND_DATAA ffd; base::ScopedResource<HANDLE, CloseFindHandle, nullptr, false, base::PlatformHandleChecker> hFind(FindFirstFileA(glob_path.c_str(), &ffd)); if (!hFind) { // For empty directories, there should be at least one entry '.'. // If FindFirstFileA returns INVALID_HANDLE_VALUE, this means directory // couldn't be accessed. return base::ErrStatus("Failed to open directory %s", cur_dir.c_str()); } do { if (strcmp(ffd.cFileName, ".") == 0 || strcmp(ffd.cFileName, "..") == 0) continue; if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { std::string subdir_path = cur_dir + ffd.cFileName + '/'; dir_queue.push_back(subdir_path); } else { const std::string full_path = cur_dir + ffd.cFileName; PERFETTO_CHECK(full_path.length() > root_dir_path.length()); output.push_back(full_path.substr(root_dir_path.length())); } } while (FindNextFileA(*hFind, &ffd)); #else ScopedDir dir = ScopedDir(opendir(cur_dir.c_str())); if (!dir) { return base::ErrStatus("Failed to open directory %s", cur_dir.c_str()); } for (auto* dirent = readdir(dir.get()); dirent != nullptr; dirent = readdir(dir.get())) { if (strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0) { continue; } if (dirent->d_type == DT_DIR) { dir_queue.push_back(cur_dir + dirent->d_name + '/'); } else if (dirent->d_type == DT_REG) { const std::string full_path = cur_dir + dirent->d_name; PERFETTO_CHECK(full_path.length() > root_dir_path.length()); output.push_back(full_path.substr(root_dir_path.length())); } } #endif } return base::OkStatus(); } std::string GetFileExtension(const std::string& filename) { auto ext_idx = filename.rfind('.'); if (ext_idx == std::string::npos) return std::string(); return filename.substr(ext_idx); } base::Optional<size_t> GetFileSize(const std::string& file_path) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) HANDLE file = CreateFileA(file_path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) { return nullopt; } LARGE_INTEGER file_size; file_size.QuadPart = 0; BOOL ok = GetFileSizeEx(file, &file_size); CloseHandle(file); if (!ok) { return nullopt; } return static_cast<size_t>(file_size.QuadPart); #else base::ScopedFile fd(base::OpenFile(file_path, O_RDONLY | O_CLOEXEC)); if (!fd) { return nullopt; } struct stat buf{}; if (fstat(*fd, &buf) == -1) { return nullopt; } return static_cast<size_t>(buf.st_size); #endif } } // namespace base } // namespace perfetto <commit_msg>Fix chromium windows build am: d21ed9d314 am: a73d9a39da am: 2b5bba496b am: ebb9ca236d<commit_after>/* * Copyright (C) 2018 The Android Open Source Project * * 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 "perfetto/ext/base/file_utils.h" #include <sys/stat.h> #include <sys/types.h> #include <algorithm> #include <deque> #include <string> #include <vector> #include "perfetto/base/build_config.h" #include "perfetto/base/logging.h" #include "perfetto/base/platform_handle.h" #include "perfetto/base/status.h" #include "perfetto/ext/base/scoped_file.h" #include "perfetto/ext/base/utils.h" #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) #include <Windows.h> #include <direct.h> #include <io.h> #else #include <dirent.h> #include <unistd.h> #endif namespace perfetto { namespace base { namespace { constexpr size_t kBufSize = 2048; #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Wrap FindClose to: (1) make the return unix-style; (2) deal with stdcall. int CloseFindHandle(HANDLE h) { return FindClose(h) ? 0 : -1; } #endif } // namespace ssize_t Read(int fd, void* dst, size_t dst_size) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) return _read(fd, dst, static_cast<unsigned>(dst_size)); #else return PERFETTO_EINTR(read(fd, dst, dst_size)); #endif } bool ReadFileDescriptor(int fd, std::string* out) { // Do not override existing data in string. size_t i = out->size(); struct stat buf {}; if (fstat(fd, &buf) != -1) { if (buf.st_size > 0) out->resize(i + static_cast<size_t>(buf.st_size)); } ssize_t bytes_read; for (;;) { if (out->size() < i + kBufSize) out->resize(out->size() + kBufSize); bytes_read = Read(fd, &((*out)[i]), kBufSize); if (bytes_read > 0) { i += static_cast<size_t>(bytes_read); } else { out->resize(i); return bytes_read == 0; } } } bool ReadPlatformHandle(PlatformHandle h, std::string* out) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Do not override existing data in string. size_t i = out->size(); for (;;) { if (out->size() < i + kBufSize) out->resize(out->size() + kBufSize); DWORD bytes_read = 0; auto res = ::ReadFile(h, &((*out)[i]), kBufSize, &bytes_read, nullptr); if (res && bytes_read > 0) { i += static_cast<size_t>(bytes_read); } else { out->resize(i); const bool is_eof = res && bytes_read == 0; auto err = res ? 0 : GetLastError(); // The "Broken pipe" error on Windows is slighly different than Unix: // On Unix: a "broken pipe" error can happen only on the writer side. On // the reader there is no broken pipe, just a EOF. // On windows: the reader also sees a broken pipe error. // Here we normalize on the Unix behavior, treating broken pipe as EOF. return is_eof || err == ERROR_BROKEN_PIPE; } } #else return ReadFileDescriptor(h, out); #endif } bool ReadFileStream(FILE* f, std::string* out) { return ReadFileDescriptor(fileno(f), out); } bool ReadFile(const std::string& path, std::string* out) { base::ScopedFile fd = base::OpenFile(path, O_RDONLY); if (!fd) return false; return ReadFileDescriptor(*fd, out); } ssize_t WriteAll(int fd, const void* buf, size_t count) { size_t written = 0; while (written < count) { // write() on windows takes an unsigned int size. uint32_t bytes_left = static_cast<uint32_t>( std::min(count - written, static_cast<size_t>(UINT32_MAX))); ssize_t wr = PERFETTO_EINTR( write(fd, static_cast<const char*>(buf) + written, bytes_left)); if (wr == 0) break; if (wr < 0) return wr; written += static_cast<size_t>(wr); } return static_cast<ssize_t>(written); } ssize_t WriteAllHandle(PlatformHandle h, const void* buf, size_t count) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) DWORD wsize = 0; if (::WriteFile(h, buf, static_cast<DWORD>(count), &wsize, nullptr)) { return wsize; } else { return -1; } #else return WriteAll(h, buf, count); #endif } bool FlushFile(int fd) { PERFETTO_DCHECK(fd != 0); #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) return !PERFETTO_EINTR(fdatasync(fd)); #elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) return !PERFETTO_EINTR(_commit(fd)); #else return !PERFETTO_EINTR(fsync(fd)); #endif } bool Mkdir(const std::string& path) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) return _mkdir(path.c_str()) == 0; #else return mkdir(path.c_str(), 0755) == 0; #endif } bool Rmdir(const std::string& path) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) return _rmdir(path.c_str()) == 0; #else return rmdir(path.c_str()) == 0; #endif } int CloseFile(int fd) { return close(fd); } ScopedFile OpenFile(const std::string& path, int flags, FileOpenMode mode) { PERFETTO_DCHECK((flags & O_CREAT) == 0 || mode != kFileModeInvalid); #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Always use O_BINARY on Windows, to avoid silly EOL translations. ScopedFile fd(_open(path.c_str(), flags | O_BINARY, mode)); #else // Always open a ScopedFile with O_CLOEXEC so we can safely fork and exec. ScopedFile fd(open(path.c_str(), flags | O_CLOEXEC, mode)); #endif return fd; } bool FileExists(const std::string& path) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) return _access(path.c_str(), 0) == 0; #else return access(path.c_str(), F_OK) == 0; #endif } // Declared in base/platform_handle.h. int ClosePlatformHandle(PlatformHandle handle) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Make the return value UNIX-style. return CloseHandle(handle) ? 0 : -1; #else return close(handle); #endif } base::Status ListFilesRecursive(const std::string& dir_path, std::vector<std::string>& output) { std::string root_dir_path = dir_path; if (root_dir_path.back() == '\\') { root_dir_path.back() = '/'; } else if (root_dir_path.back() != '/') { root_dir_path.push_back('/'); } // dir_queue contains full paths to the directories. The paths include the // root_dir_path at the beginning and the trailing slash at the end. std::deque<std::string> dir_queue; dir_queue.push_back(root_dir_path); while (!dir_queue.empty()) { const std::string cur_dir = std::move(dir_queue.front()); dir_queue.pop_front(); #if PERFETTO_BUILDFLAG(PERFETTO_OS_NACL) return base::ErrStatus("ListFilesRecursive not supported yet"); #elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) std::string glob_path = cur_dir + "*"; // + 1 because we also have to count the NULL terminator. if (glob_path.length() + 1 > MAX_PATH) return base::ErrStatus("Directory path %s is too long", dir_path.c_str()); WIN32_FIND_DATAA ffd; base::ScopedResource<HANDLE, CloseFindHandle, nullptr, false, base::PlatformHandleChecker> hFind(FindFirstFileA(glob_path.c_str(), &ffd)); if (!hFind) { // For empty directories, there should be at least one entry '.'. // If FindFirstFileA returns INVALID_HANDLE_VALUE, this means directory // couldn't be accessed. return base::ErrStatus("Failed to open directory %s", cur_dir.c_str()); } do { if (strcmp(ffd.cFileName, ".") == 0 || strcmp(ffd.cFileName, "..") == 0) continue; if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { std::string subdir_path = cur_dir + ffd.cFileName + '/'; dir_queue.push_back(subdir_path); } else { const std::string full_path = cur_dir + ffd.cFileName; PERFETTO_CHECK(full_path.length() > root_dir_path.length()); output.push_back(full_path.substr(root_dir_path.length())); } } while (FindNextFileA(*hFind, &ffd)); #else ScopedDir dir = ScopedDir(opendir(cur_dir.c_str())); if (!dir) { return base::ErrStatus("Failed to open directory %s", cur_dir.c_str()); } for (auto* dirent = readdir(dir.get()); dirent != nullptr; dirent = readdir(dir.get())) { if (strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0) { continue; } if (dirent->d_type == DT_DIR) { dir_queue.push_back(cur_dir + dirent->d_name + '/'); } else if (dirent->d_type == DT_REG) { const std::string full_path = cur_dir + dirent->d_name; PERFETTO_CHECK(full_path.length() > root_dir_path.length()); output.push_back(full_path.substr(root_dir_path.length())); } } #endif } return base::OkStatus(); } std::string GetFileExtension(const std::string& filename) { auto ext_idx = filename.rfind('.'); if (ext_idx == std::string::npos) return std::string(); return filename.substr(ext_idx); } base::Optional<size_t> GetFileSize(const std::string& file_path) { #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) HANDLE file = CreateFileA(file_path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) { return nullopt; } LARGE_INTEGER file_size; file_size.QuadPart = 0; BOOL ok = GetFileSizeEx(file, &file_size); CloseHandle(file); if (!ok) { return nullopt; } return static_cast<size_t>(file_size.QuadPart); #else base::ScopedFile fd(base::OpenFile(file_path, O_RDONLY | O_CLOEXEC)); if (!fd) { return nullopt; } struct stat buf{}; if (fstat(*fd, &buf) == -1) { return nullopt; } return static_cast<size_t>(buf.st_size); #endif } } // namespace base } // namespace perfetto <|endoftext|>
<commit_before>#include <iostream> #include <ipc_msgque.hh> #include <string.h> #include <stdlib.h> #include <string> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <imque/queue.hh> const int CHILD_NUM = 200; const int LOOP_COUNT = 400; void sigsegv_handler(int sig) { std::cerr << "#" << getpid() << ":" << sig << std::endl; exit(1); } void gen_random_string(std::string& s, std::size_t size) { const char cs[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; s.resize(size); for(int i=0; i < size; i++) { s[i] = cs[rand() % strlen(cs)]; } } void writer_start(msgque_t& que) { std::cout << "# child(writer): " << getpid() << std::endl; srand(time(NULL)+getpid()); for(int i=0; i < LOOP_COUNT; i++) { unsigned size = (rand() % 128) + 3; std::string s; gen_random_string(s, size); if(que.push(s.c_str(), s.size()) == false) { std::cout << "@ [" << getpid() << "] queue is full" << std::endl; usleep(rand() % 300); } else { std::cout << "@ [" << getpid() << "] write: " << s << std::endl; } usleep(rand() % 400); } std::cout << "# exit: " << getpid() << std::endl; } void reader_start(msgque_t& que) { std::cout << "# child(reader): " << getpid() << std::endl; srand(time(NULL)); usleep(10); for(int i=0; i < LOOP_COUNT*3.5; i++) { std::string s; if(que.pop(s) == false) { std::cout << "@ [" << getpid() << "] queue is empty" << std::endl; usleep(rand() % 200); } else { std::cout << "@ [" << getpid() << "] read: " << s << std::endl; } } std::cout << "# exit: " << getpid() << std::endl; } int main(int argc, char** argv) { msgque_t que(1024*32, 1024*1024*4); que.init(); signal(SIGSEGV, sigsegv_handler); if(! que) { std::cerr << "[ERROR] message queue initialization failed" << std::endl; return 1; } for(int i=0; i < CHILD_NUM; i++) { if(fork() == 0) { if(i % 3 == 0) { reader_start(que); } else { writer_start(que); } return 0; } } waitid(P_ALL, 0, NULL, WEXITED); return 0; } <commit_msg>Queueクラスがある程度動くようになった<commit_after>#include <iostream> #include <ipc_msgque.hh> #include <imque/queue.hh> #include <string.h> #include <stdlib.h> #include <string> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <imque/queue.hh> const int CHILD_NUM = 200; const int LOOP_COUNT = 400; void sigsegv_handler(int sig) { std::cerr << "#" << getpid() << ":" << sig << std::endl; exit(1); } void gen_random_string(std::string& s, std::size_t size) { const char cs[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; s.resize(size); for(int i=0; i < size; i++) { s[i] = cs[rand() % strlen(cs)]; } } void writer_start(msgque_t& que) { std::cout << "# child(writer): " << getpid() << std::endl; srand(time(NULL)+getpid()); for(int i=0; i < LOOP_COUNT; i++) { unsigned size = (rand() % 128) + 3; std::string s; gen_random_string(s, size); if(que.push(s.c_str(), s.size()) == false) { std::cout << "@ [" << getpid() << "] queue is full" << std::endl; usleep(rand() % 300); } else { std::cout << "@ [" << getpid() << "] write: " << s << std::endl; } usleep(rand() % 400); } std::cout << "# exit: " << getpid() << std::endl; } void reader_start(msgque_t& que) { std::cout << "# child(reader): " << getpid() << std::endl; srand(time(NULL)); usleep(10); for(int i=0; i < LOOP_COUNT*3.5; i++) { std::string s; if(que.pop(s) == false) { std::cout << "@ [" << getpid() << "] queue is empty" << std::endl; usleep(rand() % 200); } else { std::cout << "@ [" << getpid() << "] read: " << s << std::endl; } } std::cout << "# exit: " << getpid() << std::endl; } int main(int argc, char** argv) { imque::Queue que2(1024, 1024*1024); assert(que2); que2.init(); int val = 111; que2.enq(&val, sizeof(int)); std::cout << "# enq" << std::endl; size_t size; int* pval = (int*)que2.deq(size); std::cout << "# deq" << std::endl; std::cout << "# " << *pval << ", " << size << std::endl; return 0; msgque_t que(1024*32, 1024*1024*4); que.init(); signal(SIGSEGV, sigsegv_handler); if(! que) { std::cerr << "[ERROR] message queue initialization failed" << std::endl; return 1; } for(int i=0; i < CHILD_NUM; i++) { if(fork() == 0) { if(i % 3 == 0) { reader_start(que); } else { writer_start(que); } return 0; } } waitid(P_ALL, 0, NULL, WEXITED); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "blockencodings.h" #include "chainparams.h" #include "consensus/consensus.h" #include "consensus/validation.h" #include "globals.h" #include "hash.h" #include "random.h" #include "streams.h" #include "txmempool.h" #include "util.h" #include "validation.h" #include <unordered_map> CBlockHeaderAndShortTxIDs::CBlockHeaderAndShortTxIDs(const CBlock &block) : nonce(GetRand(std::numeric_limits<uint64_t>::max())), shorttxids(block.vtx.size() - 1), prefilledtxn(1), header(block) { FillShortTxIDSelector(); // TODO: Use our mempool prior to block acceptance to predictively fill more // than just the coinbase. prefilledtxn[0] = {0, block.vtx[0]}; for (size_t i = 1; i < block.vtx.size(); i++) { const CTransaction &tx = *block.vtx[i]; shorttxids[i - 1] = GetShortID(tx.GetHash()); } } void CBlockHeaderAndShortTxIDs::FillShortTxIDSelector() const { CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream << header << nonce; CSHA256 hasher; hasher.Write((unsigned char *)&(*stream.begin()), stream.end() - stream.begin()); uint256 shorttxidhash; hasher.Finalize(shorttxidhash.begin()); shorttxidk0 = shorttxidhash.GetUint64(0); shorttxidk1 = shorttxidhash.GetUint64(1); } uint64_t CBlockHeaderAndShortTxIDs::GetShortID(const uint256 &txhash) const { static_assert(SHORTTXIDS_LENGTH == 6, "shorttxids calculation assumes 6-byte shorttxids"); return SipHashUint256(shorttxidk0, shorttxidk1, txhash) & 0xffffffffffffL; } ReadStatus PartiallyDownloadedBlock::InitData( const CBlockHeaderAndShortTxIDs &cmpctblock, const std::vector<std::pair<uint256, CTransactionRef>> &extra_txn) { if (cmpctblock.header.IsNull() || (cmpctblock.shorttxids.empty() && cmpctblock.prefilledtxn.empty())) return READ_STATUS_INVALID; if (cmpctblock.shorttxids.size() + cmpctblock.prefilledtxn.size() > nMaxBlockSize / MIN_TRANSACTION_SIZE) return READ_STATUS_INVALID; assert(header.IsNull() && txn_available.empty()); header = cmpctblock.header; txn_available.resize(cmpctblock.BlockTxCount()); int32_t lastprefilledindex = -1; for (size_t i = 0; i < cmpctblock.prefilledtxn.size(); i++) { if (cmpctblock.prefilledtxn[i].tx->IsNull()) return READ_STATUS_INVALID; lastprefilledindex += cmpctblock.prefilledtxn[i].index + 1; // index is a uint16_t, so can't overflow here if (lastprefilledindex > std::numeric_limits<uint16_t>::max()) return READ_STATUS_INVALID; if ((uint32_t)lastprefilledindex > cmpctblock.shorttxids.size() + i) { // If we are inserting a tx at an index greater than our full list // of shorttxids // plus the number of prefilled txn we've inserted, then we have txn // for which we // have neither a prefilled txn or a shorttxid! return READ_STATUS_INVALID; } txn_available[lastprefilledindex] = cmpctblock.prefilledtxn[i].tx; } prefilled_count = cmpctblock.prefilledtxn.size(); // Calculate map of txids -> positions and check mempool to see what we have // (or don't). Because well-formed cmpctblock messages will have a // (relatively) uniform distribution of short IDs, any highly-uneven // distribution of elements can be safely treated as a READ_STATUS_FAILED. std::unordered_map<uint64_t, uint16_t> shorttxids( cmpctblock.shorttxids.size()); uint16_t index_offset = 0; for (size_t i = 0; i < cmpctblock.shorttxids.size(); i++) { while (txn_available[i + index_offset]) index_offset++; shorttxids[cmpctblock.shorttxids[i]] = i + index_offset; // To determine the chance that the number of entries in a bucket // exceeds N, we use the fact that the number of elements in a single // bucket is binomially distributed (with n = the number of shorttxids // S, and p = 1 / the number of buckets), that in the worst case the // number of buckets is equal to S (due to std::unordered_map having a // default load factor of 1.0), and that the chance for any bucket to // exceed N elements is at most buckets * (the chance that any given // bucket is above N elements). Thus: P(max_elements_per_bucket > N) <= // S * (1 - cdf(binomial(n=S,p=1/S), N)). If we assume blocks of up to // 16000, allowing 12 elements per bucket should only fail once per ~1 // million block transfers (per peer and connection). if (shorttxids.bucket_size( shorttxids.bucket(cmpctblock.shorttxids[i])) > 12) return READ_STATUS_FAILED; } // TODO: in the shortid-collision case, we should instead request both // transactions which collided. Falling back to full-block-request here is // overkill. if (shorttxids.size() != cmpctblock.shorttxids.size()) { // Short ID collision return READ_STATUS_FAILED; } std::vector<bool> have_txn(txn_available.size()); { LOCK(pool->cs); const std::vector<std::pair<uint256, CTxMemPool::txiter>> &vTxHashes = pool->vTxHashes; for (size_t i = 0; i < vTxHashes.size(); i++) { uint64_t shortid = cmpctblock.GetShortID(vTxHashes[i].first); std::unordered_map<uint64_t, uint16_t>::iterator idit = shorttxids.find(shortid); if (idit != shorttxids.end()) { if (!have_txn[idit->second]) { txn_available[idit->second] = vTxHashes[i].second->GetSharedTx(); have_txn[idit->second] = true; mempool_count++; } else { // If we find two mempool txn that match the short id, just // request it. This should be rare enough that the extra // bandwidth doesn't matter, but eating a round-trip due to // FillBlock failure would be annoying. if (txn_available[idit->second]) { txn_available[idit->second].reset(); mempool_count--; } } } // Though ideally we'd continue scanning for the // two-txn-match-shortid case, the performance win of an early exit // here is too good to pass up and worth the extra risk. if (mempool_count == shorttxids.size()) break; } } for (size_t i = 0; i < extra_txn.size(); i++) { uint64_t shortid = cmpctblock.GetShortID(extra_txn[i].first); std::unordered_map<uint64_t, uint16_t>::iterator idit = shorttxids.find(shortid); if (idit != shorttxids.end()) { if (!have_txn[idit->second]) { txn_available[idit->second] = extra_txn[i].second; have_txn[idit->second] = true; mempool_count++; extra_count++; } else { // If we find two mempool/extra txn that match the short id, // just request it. This should be rare enough that the extra // bandwidth doesn't matter, but eating a round-trip due to // FillBlock failure would be annoying. Note that we dont want // duplication between extra_txn and mempool to trigger this // case, so we compare hashes first. if (txn_available[idit->second] && txn_available[idit->second]->GetHash() != extra_txn[i].second->GetHash()) { txn_available[idit->second].reset(); mempool_count--; extra_count--; } } } // Though ideally we'd continue scanning for the two-txn-match-shortid // case, the performance win of an early exit here is too good to pass // up and worth the extra risk. if (mempool_count == shorttxids.size()) break; } LogPrint("cmpctblock", "Initialized PartiallyDownloadedBlock for block %s " "using a cmpctblock of size %lu\n", cmpctblock.header.GetHash().ToString(), GetSerializeSize(cmpctblock, SER_NETWORK, PROTOCOL_VERSION)); return READ_STATUS_OK; } bool PartiallyDownloadedBlock::IsTxAvailable(size_t index) const { assert(!header.IsNull()); assert(index < txn_available.size()); return txn_available[index] ? true : false; } ReadStatus PartiallyDownloadedBlock::FillBlock( CBlock &block, const std::vector<CTransactionRef> &vtx_missing) { assert(!header.IsNull()); uint256 hash = header.GetHash(); block = header; block.vtx.resize(txn_available.size()); size_t tx_missing_offset = 0; for (size_t i = 0; i < txn_available.size(); i++) { if (!txn_available[i]) { if (vtx_missing.size() <= tx_missing_offset) return READ_STATUS_INVALID; block.vtx[i] = vtx_missing[tx_missing_offset++]; } else block.vtx[i] = std::move(txn_available[i]); } // Make sure we can't call FillBlock again. header.SetNull(); txn_available.clear(); if (vtx_missing.size() != tx_missing_offset) return READ_STATUS_INVALID; CValidationState state; if (!CheckBlock(block, state, Params().GetConsensus())) { // TODO: We really want to just check merkle tree manually here, but // that is expensive, and CheckBlock caches a block's "checked-status" // (in the CBlock?). CBlock should be able to check its own merkle root // and cache that check. if (state.CorruptionPossible()) { // Possible Short ID collision. return READ_STATUS_FAILED; } return READ_STATUS_CHECKBLOCK_FAILED; } LogPrint("cmpctblock", "Successfully reconstructed block %s with %lu txn " "prefilled, %lu txn from mempool (incl at least %lu " "from extra pool) and %lu txn requested\n", hash.ToString(), prefilled_count, mempool_count, extra_count, vtx_missing.size()); if (vtx_missing.size() < 5) { for (const auto &tx : vtx_missing) LogPrint("cmpctblock", "Reconstructed block %s required tx %s\n", hash.ToString(), tx->GetId().ToString()); } return READ_STATUS_OK; } <commit_msg>Relayout some comment in blockencoding.cpp<commit_after>// Copyright (c) 2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "blockencodings.h" #include "chainparams.h" #include "consensus/consensus.h" #include "consensus/validation.h" #include "globals.h" #include "hash.h" #include "random.h" #include "streams.h" #include "txmempool.h" #include "util.h" #include "validation.h" #include <unordered_map> CBlockHeaderAndShortTxIDs::CBlockHeaderAndShortTxIDs(const CBlock &block) : nonce(GetRand(std::numeric_limits<uint64_t>::max())), shorttxids(block.vtx.size() - 1), prefilledtxn(1), header(block) { FillShortTxIDSelector(); // TODO: Use our mempool prior to block acceptance to predictively fill more // than just the coinbase. prefilledtxn[0] = {0, block.vtx[0]}; for (size_t i = 1; i < block.vtx.size(); i++) { const CTransaction &tx = *block.vtx[i]; shorttxids[i - 1] = GetShortID(tx.GetHash()); } } void CBlockHeaderAndShortTxIDs::FillShortTxIDSelector() const { CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream << header << nonce; CSHA256 hasher; hasher.Write((unsigned char *)&(*stream.begin()), stream.end() - stream.begin()); uint256 shorttxidhash; hasher.Finalize(shorttxidhash.begin()); shorttxidk0 = shorttxidhash.GetUint64(0); shorttxidk1 = shorttxidhash.GetUint64(1); } uint64_t CBlockHeaderAndShortTxIDs::GetShortID(const uint256 &txhash) const { static_assert(SHORTTXIDS_LENGTH == 6, "shorttxids calculation assumes 6-byte shorttxids"); return SipHashUint256(shorttxidk0, shorttxidk1, txhash) & 0xffffffffffffL; } ReadStatus PartiallyDownloadedBlock::InitData( const CBlockHeaderAndShortTxIDs &cmpctblock, const std::vector<std::pair<uint256, CTransactionRef>> &extra_txn) { if (cmpctblock.header.IsNull() || (cmpctblock.shorttxids.empty() && cmpctblock.prefilledtxn.empty())) return READ_STATUS_INVALID; if (cmpctblock.shorttxids.size() + cmpctblock.prefilledtxn.size() > nMaxBlockSize / MIN_TRANSACTION_SIZE) return READ_STATUS_INVALID; assert(header.IsNull() && txn_available.empty()); header = cmpctblock.header; txn_available.resize(cmpctblock.BlockTxCount()); int32_t lastprefilledindex = -1; for (size_t i = 0; i < cmpctblock.prefilledtxn.size(); i++) { if (cmpctblock.prefilledtxn[i].tx->IsNull()) return READ_STATUS_INVALID; // index is a uint16_t, so can't overflow here. lastprefilledindex += cmpctblock.prefilledtxn[i].index + 1; if (lastprefilledindex > std::numeric_limits<uint16_t>::max()) return READ_STATUS_INVALID; if ((uint32_t)lastprefilledindex > cmpctblock.shorttxids.size() + i) { // If we are inserting a tx at an index greater than our full list // of shorttxids plus the number of prefilled txn we've inserted, // then we have txn for which we have neither a prefilled txn or a // shorttxid! return READ_STATUS_INVALID; } txn_available[lastprefilledindex] = cmpctblock.prefilledtxn[i].tx; } prefilled_count = cmpctblock.prefilledtxn.size(); // Calculate map of txids -> positions and check mempool to see what we have // (or don't). Because well-formed cmpctblock messages will have a // (relatively) uniform distribution of short IDs, any highly-uneven // distribution of elements can be safely treated as a READ_STATUS_FAILED. std::unordered_map<uint64_t, uint16_t> shorttxids( cmpctblock.shorttxids.size()); uint16_t index_offset = 0; for (size_t i = 0; i < cmpctblock.shorttxids.size(); i++) { while (txn_available[i + index_offset]) index_offset++; shorttxids[cmpctblock.shorttxids[i]] = i + index_offset; // To determine the chance that the number of entries in a bucket // exceeds N, we use the fact that the number of elements in a single // bucket is binomially distributed (with n = the number of shorttxids // S, and p = 1 / the number of buckets), that in the worst case the // number of buckets is equal to S (due to std::unordered_map having a // default load factor of 1.0), and that the chance for any bucket to // exceed N elements is at most buckets * (the chance that any given // bucket is above N elements). Thus: P(max_elements_per_bucket > N) <= // S * (1 - cdf(binomial(n=S,p=1/S), N)). If we assume blocks of up to // 16000, allowing 12 elements per bucket should only fail once per ~1 // million block transfers (per peer and connection). if (shorttxids.bucket_size( shorttxids.bucket(cmpctblock.shorttxids[i])) > 12) return READ_STATUS_FAILED; } // TODO: in the shortid-collision case, we should instead request both // transactions which collided. Falling back to full-block-request here is // overkill. if (shorttxids.size() != cmpctblock.shorttxids.size()) { // Short ID collision return READ_STATUS_FAILED; } std::vector<bool> have_txn(txn_available.size()); { LOCK(pool->cs); const std::vector<std::pair<uint256, CTxMemPool::txiter>> &vTxHashes = pool->vTxHashes; for (size_t i = 0; i < vTxHashes.size(); i++) { uint64_t shortid = cmpctblock.GetShortID(vTxHashes[i].first); std::unordered_map<uint64_t, uint16_t>::iterator idit = shorttxids.find(shortid); if (idit != shorttxids.end()) { if (!have_txn[idit->second]) { txn_available[idit->second] = vTxHashes[i].second->GetSharedTx(); have_txn[idit->second] = true; mempool_count++; } else { // If we find two mempool txn that match the short id, just // request it. This should be rare enough that the extra // bandwidth doesn't matter, but eating a round-trip due to // FillBlock failure would be annoying. if (txn_available[idit->second]) { txn_available[idit->second].reset(); mempool_count--; } } } // Though ideally we'd continue scanning for the // two-txn-match-shortid case, the performance win of an early exit // here is too good to pass up and worth the extra risk. if (mempool_count == shorttxids.size()) break; } } for (size_t i = 0; i < extra_txn.size(); i++) { uint64_t shortid = cmpctblock.GetShortID(extra_txn[i].first); std::unordered_map<uint64_t, uint16_t>::iterator idit = shorttxids.find(shortid); if (idit != shorttxids.end()) { if (!have_txn[idit->second]) { txn_available[idit->second] = extra_txn[i].second; have_txn[idit->second] = true; mempool_count++; extra_count++; } else { // If we find two mempool/extra txn that match the short id, // just request it. This should be rare enough that the extra // bandwidth doesn't matter, but eating a round-trip due to // FillBlock failure would be annoying. Note that we dont want // duplication between extra_txn and mempool to trigger this // case, so we compare hashes first. if (txn_available[idit->second] && txn_available[idit->second]->GetHash() != extra_txn[i].second->GetHash()) { txn_available[idit->second].reset(); mempool_count--; extra_count--; } } } // Though ideally we'd continue scanning for the two-txn-match-shortid // case, the performance win of an early exit here is too good to pass // up and worth the extra risk. if (mempool_count == shorttxids.size()) break; } LogPrint("cmpctblock", "Initialized PartiallyDownloadedBlock for block %s " "using a cmpctblock of size %lu\n", cmpctblock.header.GetHash().ToString(), GetSerializeSize(cmpctblock, SER_NETWORK, PROTOCOL_VERSION)); return READ_STATUS_OK; } bool PartiallyDownloadedBlock::IsTxAvailable(size_t index) const { assert(!header.IsNull()); assert(index < txn_available.size()); return txn_available[index] ? true : false; } ReadStatus PartiallyDownloadedBlock::FillBlock( CBlock &block, const std::vector<CTransactionRef> &vtx_missing) { assert(!header.IsNull()); uint256 hash = header.GetHash(); block = header; block.vtx.resize(txn_available.size()); size_t tx_missing_offset = 0; for (size_t i = 0; i < txn_available.size(); i++) { if (!txn_available[i]) { if (vtx_missing.size() <= tx_missing_offset) return READ_STATUS_INVALID; block.vtx[i] = vtx_missing[tx_missing_offset++]; } else block.vtx[i] = std::move(txn_available[i]); } // Make sure we can't call FillBlock again. header.SetNull(); txn_available.clear(); if (vtx_missing.size() != tx_missing_offset) return READ_STATUS_INVALID; CValidationState state; if (!CheckBlock(block, state, Params().GetConsensus())) { // TODO: We really want to just check merkle tree manually here, but // that is expensive, and CheckBlock caches a block's "checked-status" // (in the CBlock?). CBlock should be able to check its own merkle root // and cache that check. if (state.CorruptionPossible()) { // Possible Short ID collision. return READ_STATUS_FAILED; } return READ_STATUS_CHECKBLOCK_FAILED; } LogPrint("cmpctblock", "Successfully reconstructed block %s with %lu txn " "prefilled, %lu txn from mempool (incl at least %lu " "from extra pool) and %lu txn requested\n", hash.ToString(), prefilled_count, mempool_count, extra_count, vtx_missing.size()); if (vtx_missing.size() < 5) { for (const auto &tx : vtx_missing) LogPrint("cmpctblock", "Reconstructed block %s required tx %s\n", hash.ToString(), tx->GetId().ToString()); } return READ_STATUS_OK; } <|endoftext|>
<commit_before>#include <array> #include <iterator> #include <vector> #include <functional> #include <algorithm> #include <numeric> #include "builtin.hh" #include "util.hh" #include "number.hh" #include "procedure.hh" #include "lisp_ptr.hh" #include "eval.hh" #include "builtin_util.hh" #include "printer.hh" using namespace std; using namespace Procedure; namespace { template<typename Fun> inline void number_pred(Fun&& fun){ auto arg = pick_args_1(); auto num = arg.get<Number*>(); if(!num){ VM.return_value = Lisp_ptr{false}; return; } VM.return_value = Lisp_ptr{fun(num)}; } void complexp(){ number_pred([](Number* n){ return n->type() >= Number::Type::integer; }); } void realp(){ number_pred([](Number* n){ return n->type() >= Number::Type::integer && n->type() <= Number::Type::real; }); } void rationalp(){ number_pred([](Number* n){ return n->type() >= Number::Type::integer && n->type() < Number::Type::real; }); } void integerp(){ number_pred([](Number* n){ return n->type() == Number::Type::integer; }); } void exactp(){ number_pred([](Number* n){ return n->type() == Number::Type::integer; }); } void inexactp(){ number_pred([](Number* n){ return n->type() == Number::Type::complex || n->type() == Number::Type::real; }); } void number_type_check_failed(const char* func_name, Lisp_ptr p){ fprintf(zs::err, "native func: %s: arg is not number! (%s)\n", func_name, stringify(p.tag())); VM.return_value = {}; } struct complex_found{ static constexpr const char* msg = "native func: number compare: complex cannot be ordinated\n"; bool operator()(const Number::complex_type&, const Number::complex_type&) const{ fprintf(zs::err, msg); return false; } }; template<template <typename> class Fun, class ComplexComparator = complex_found> struct number_comparator { Lisp_ptr non_number_found; number_comparator() : non_number_found(){} inline bool operator()(const Lisp_ptr& p1, const Lisp_ptr& p2){ auto n1 = p1.get<Number*>(); if(!n1 || n1->type() < Number::Type::integer){ non_number_found = p1; return true; } auto n2 = p2.get<Number*>(); if(!n2 || n2->type() < Number::Type::integer){ non_number_found = p2; return true; } if(n1->type() == Number::Type::integer && n2->type() == Number::Type::integer){ static const Fun<Number::integer_type> fun; return fun(n1->get<Number::integer_type>(), n2->get<Number::integer_type>()); }else if(n1->type() <= Number::Type::real && n2->type() <= Number::Type::real){ static const Fun<Number::real_type> fun; return fun(n1->coerce<Number::real_type>(), n2->coerce<Number::real_type>()); }else{ static const ComplexComparator fun; return fun(n1->coerce<Number::complex_type>(), n2->coerce<Number::complex_type>()); } } struct for_is_sorted : public number_comparator { inline bool operator()(const Lisp_ptr& p1, const Lisp_ptr& p2){ return !number_comparator::operator()(p2, p1); } }; }; template<typename Fun> inline void number_compare(const char* name, Fun&& fun){ std::vector<Lisp_ptr> args; stack_to_vector(VM.stack, args); auto ret = std::is_sorted(begin(args), end(args), fun); if(fun.non_number_found){ number_type_check_failed(name, fun.non_number_found); return; } VM.return_value = Lisp_ptr{ret}; } void number_equal(){ number_compare("=", number_comparator<std::equal_to, std::equal_to<Number::complex_type> >::for_is_sorted()); } void number_less(){ number_compare("<", number_comparator<std::less>::for_is_sorted()); } void number_greater(){ number_compare(">", number_comparator<std::greater>::for_is_sorted()); } void number_less_eq(){ number_compare("<=", number_comparator<std::less_equal>::for_is_sorted()); } void number_greater_eq(){ number_compare(">=", number_comparator<std::greater_equal>::for_is_sorted()); } void zerop(){ number_pred([](Number* num) -> bool { switch(num->type()){ case Number::Type::complex: { auto c = num->get<Number::complex_type>(); return (c.real() == 0 && c.imag() == 0); } case Number::Type::real: return num->get<Number::real_type>() == 0; case Number::Type::integer: return num->get<Number::integer_type>() == 0; case Number::Type::uninitialized: default: UNEXP_DEFAULT(); } }); } template<template <typename> class Fun> struct pos_neg_pred{ inline bool operator()(Number* num){ static constexpr Fun<Number::integer_type> fun; switch(num->type()){ case Number::Type::complex: return false; case Number::Type::real: return fun(num->get<Number::real_type>(), 0); case Number::Type::integer: return fun(num->get<Number::integer_type>(), 0); case Number::Type::uninitialized: default: UNEXP_DEFAULT(); } } }; void positivep(){ number_pred(pos_neg_pred<std::greater>()); } void negativep(){ number_pred(pos_neg_pred<std::less>()); } template<template <typename> class Fun> struct even_odd_pred{ inline bool operator()(Number* num){ static constexpr Fun<Number::integer_type> fun; switch(num->type()){ case Number::Type::complex: case Number::Type::real: return false; case Number::Type::integer: return fun(num->get<Number::integer_type>() % 2, 0); case Number::Type::uninitialized: default: UNEXP_DEFAULT(); } } }; void oddp(){ number_pred(even_odd_pred<std::not_equal_to>()); } void evenp(){ number_pred(even_odd_pred<std::equal_to>()); } template<class Fun> inline void number_accumulate(const char* name, Number&& init, Fun&& fun){ std::vector<Lisp_ptr> args; stack_to_vector(VM.stack, args); for(auto i = begin(args), e = end(args); i != e; ++i){ auto n = i->get<Number*>(); if(!n){ number_type_check_failed(name, *i); return; } if(!fun(init, *n)){ VM.return_value = {}; return; } } VM.return_value = {new Number(init)}; } void number_max(){ number_accumulate("max", Number(), [](Number& n1, const Number& n2) -> bool { if(n1.type() == Number::Type::uninitialized){ n1 = n2; return true; } if(n2.type() == Number::Type::uninitialized){ return true; } if(n1.type() == Number::Type::integer && n2.type() == Number::Type::integer){ if(n1.get<Number::integer_type>() < n2.get<Number::integer_type>()) n1 = n2; return true; } if(n1.type() <= Number::Type::real && n2.type() <= Number::Type::real){ if(n1.coerce<Number::real_type>() < n2.coerce<Number::real_type>()) n1 = Number{n2.coerce<Number::real_type>()}; if(n1.type() != Number::Type::real) n1 = Number{n1.coerce<Number::real_type>()}; return true; } fprintf(zs::err, complex_found::msg); return false; }); } void number_min(){ number_accumulate("min", Number(), [](Number& n1, const Number& n2) -> bool { if(n1.type() == Number::Type::uninitialized){ n1 = n2; return true; } if(n2.type() == Number::Type::uninitialized){ return true; } if(n1.type() == Number::Type::integer && n2.type() == Number::Type::integer){ if(n1.get<Number::integer_type>() > n2.get<Number::integer_type>()) n1 = n2; return true; } if(n1.type() <= Number::Type::real && n2.type() <= Number::Type::real){ if(n1.coerce<Number::real_type>() > n2.coerce<Number::real_type>()) n1 = Number{n2.coerce<Number::real_type>()}; if(n1.type() != Number::Type::real) n1 = Number{n1.coerce<Number::real_type>()}; return true; } fprintf(zs::err, complex_found::msg); return false; }); } void number_plus(){ number_accumulate("+", Number(0l), [](Number& n1, const Number& n2) -> bool { if(n1.type() == Number::Type::uninitialized){ n1 = n2; return true; } if(n2.type() == Number::Type::uninitialized){ return true; } // n1 type <= n2 type if(n1.type() == Number::Type::integer && n2.type() == Number::Type::integer){ n1.get<Number::integer_type>() += n2.get<Number::integer_type>(); return true; } if(n1.type() == Number::Type::real && n2.type() <= Number::Type::real){ n1.get<Number::real_type>() += n2.coerce<Number::real_type>(); return true; } if(n1.type() == Number::Type::complex && n2.type() <= Number::Type::complex){ n1.get<Number::complex_type>() += n2.coerce<Number::complex_type>(); return true; } // n1 type > n2 type if(n1.type() < Number::Type::real && n2.type() == Number::Type::real){ n1 = Number{n1.coerce<Number::real_type>() + n2.get<Number::real_type>()}; return true; } if(n1.type() < Number::Type::complex && n2.type() == Number::Type::complex){ n1 = Number{n1.coerce<Number::complex_type>() + n2.get<Number::complex_type>()}; return true; } // ??? fprintf(zs::err, "native func: +: failed at numeric conversion!\n"); return false; }); } constexpr struct Entry { const char* name; const NProcedure func; constexpr Entry(const char* n, const NProcedure& f) : name(n), func(f){} } builtin_numeric[] = { {"complex?", { complexp, Calling::function, {1, false}}}, {"real?", { realp, Calling::function, {1, false}}}, {"rational?", { rationalp, Calling::function, {1, false}}}, {"integer?", { integerp, Calling::function, {1, false}}}, {"exact?", { exactp, Calling::function, {1, false}}}, {"inexact?", { inexactp, Calling::function, {1, false}}}, {"=", { number_equal, Calling::function, {2, true}}}, {"<", { number_less, Calling::function, {2, true}}}, {">", { number_greater, Calling::function, {2, true}}}, {"<=", { number_less_eq, Calling::function, {2, true}}}, {">=", { number_greater_eq, Calling::function, {2, true}}}, {"zero?", { zerop, Calling::function, {1, false}}}, {"positive?", { positivep, Calling::function, {1, false}}}, {"negative?", { negativep, Calling::function, {1, false}}}, {"odd?", { oddp, Calling::function, {1, false}}}, {"even?", { evenp, Calling::function, {1, false}}}, {"max", { number_max, Calling::function, {2, true}}}, {"min", { number_min, Calling::function, {2, true}}}, {"+", { number_plus, Calling::function, {0, true}}} }; } //namespace void install_builtin_numeric(){ for(auto& e : builtin_numeric){ VM.set(intern(VM.symtable, e.name), {&e.func}); } } <commit_msg>rewrite number comparator<commit_after>#include <array> #include <iterator> #include <vector> #include <functional> #include <algorithm> #include <numeric> #include "builtin.hh" #include "util.hh" #include "number.hh" #include "procedure.hh" #include "lisp_ptr.hh" #include "eval.hh" #include "builtin_util.hh" #include "printer.hh" using namespace std; using namespace Procedure; namespace { template<typename Fun> inline void number_pred(Fun&& fun){ auto arg = pick_args_1(); auto num = arg.get<Number*>(); if(!num){ VM.return_value = Lisp_ptr{false}; return; } VM.return_value = Lisp_ptr{fun(num)}; } void complexp(){ number_pred([](Number* n){ return n->type() >= Number::Type::integer; }); } void realp(){ number_pred([](Number* n){ return n->type() >= Number::Type::integer && n->type() <= Number::Type::real; }); } void rationalp(){ number_pred([](Number* n){ return n->type() >= Number::Type::integer && n->type() < Number::Type::real; }); } void integerp(){ number_pred([](Number* n){ return n->type() == Number::Type::integer; }); } void exactp(){ number_pred([](Number* n){ return n->type() == Number::Type::integer; }); } void inexactp(){ number_pred([](Number* n){ return n->type() == Number::Type::complex || n->type() == Number::Type::real; }); } void number_type_check_failed(const char* func_name, Lisp_ptr p){ fprintf(zs::err, "native func: %s: arg is not number! (%s)\n", func_name, stringify(p.tag())); VM.return_value = {}; } struct complex_found{ static constexpr const char* msg = "native func: number compare: complex cannot be ordinated\n"; bool operator()(const Number::complex_type&, const Number::complex_type&) const{ fprintf(zs::err, msg); return false; } }; template<template <typename> class Fun, class ComplexComparator = complex_found> struct number_comparator { inline bool operator()(const Number* n1, const Number* n2){ if(n1->type() == Number::Type::integer && n2->type() == Number::Type::integer){ static const Fun<Number::integer_type> fun; return fun(n1->get<Number::integer_type>(), n2->get<Number::integer_type>()); }else if(n1->type() <= Number::Type::real && n2->type() <= Number::Type::real){ static const Fun<Number::real_type> fun; return fun(n1->coerce<Number::real_type>(), n2->coerce<Number::real_type>()); }else{ static const ComplexComparator fun; return fun(n1->coerce<Number::complex_type>(), n2->coerce<Number::complex_type>()); } } }; template<typename Fun> inline void number_compare(const char* name, Fun&& fun){ std::vector<Lisp_ptr> args; stack_to_vector(VM.stack, args); auto i1 = begin(args); const auto e = end(args); auto n1 = i1->get<Number*>(); if(!n1 || n1->type() < Number::Type::integer){ number_type_check_failed(name, *i1); return; } for(auto i2 = next(i1); i2 != e; i1 = i2, ++i2){ auto n2 = i2->get<Number*>(); if(!n2 || n2->type() < Number::Type::integer){ number_type_check_failed(name, *i2); return; } if(!fun(n1, n2)){ VM.return_value = Lisp_ptr{false}; return; } n1 = n2; } VM.return_value = Lisp_ptr{true}; } void number_equal(){ number_compare("=", number_comparator<std::equal_to, std::equal_to<Number::complex_type> >()); } void number_less(){ number_compare("<", number_comparator<std::less>()); } void number_greater(){ number_compare(">", number_comparator<std::greater>()); } void number_less_eq(){ number_compare("<=", number_comparator<std::less_equal>()); } void number_greater_eq(){ number_compare(">=", number_comparator<std::greater_equal>()); } void zerop(){ number_pred([](Number* num) -> bool { switch(num->type()){ case Number::Type::complex: { auto c = num->get<Number::complex_type>(); return (c.real() == 0 && c.imag() == 0); } case Number::Type::real: return num->get<Number::real_type>() == 0; case Number::Type::integer: return num->get<Number::integer_type>() == 0; case Number::Type::uninitialized: default: UNEXP_DEFAULT(); } }); } template<template <typename> class Fun> struct pos_neg_pred{ inline bool operator()(Number* num){ static constexpr Fun<Number::integer_type> fun; switch(num->type()){ case Number::Type::complex: return false; case Number::Type::real: return fun(num->get<Number::real_type>(), 0); case Number::Type::integer: return fun(num->get<Number::integer_type>(), 0); case Number::Type::uninitialized: default: UNEXP_DEFAULT(); } } }; void positivep(){ number_pred(pos_neg_pred<std::greater>()); } void negativep(){ number_pred(pos_neg_pred<std::less>()); } template<template <typename> class Fun> struct even_odd_pred{ inline bool operator()(Number* num){ static constexpr Fun<Number::integer_type> fun; switch(num->type()){ case Number::Type::complex: case Number::Type::real: return false; case Number::Type::integer: return fun(num->get<Number::integer_type>() % 2, 0); case Number::Type::uninitialized: default: UNEXP_DEFAULT(); } } }; void oddp(){ number_pred(even_odd_pred<std::not_equal_to>()); } void evenp(){ number_pred(even_odd_pred<std::equal_to>()); } template<class Fun> inline void number_accumulate(const char* name, Number&& init, Fun&& fun){ std::vector<Lisp_ptr> args; stack_to_vector(VM.stack, args); for(auto i = begin(args), e = end(args); i != e; ++i){ auto n = i->get<Number*>(); if(!n){ number_type_check_failed(name, *i); return; } if(!fun(init, *n)){ VM.return_value = {}; return; } } VM.return_value = {new Number(init)}; } void number_max(){ number_accumulate("max", Number(), [](Number& n1, const Number& n2) -> bool { if(n1.type() == Number::Type::uninitialized){ n1 = n2; return true; } if(n2.type() == Number::Type::uninitialized){ return true; } if(n1.type() == Number::Type::integer && n2.type() == Number::Type::integer){ if(n1.get<Number::integer_type>() < n2.get<Number::integer_type>()) n1 = n2; return true; } if(n1.type() <= Number::Type::real && n2.type() <= Number::Type::real){ if(n1.coerce<Number::real_type>() < n2.coerce<Number::real_type>()) n1 = Number{n2.coerce<Number::real_type>()}; if(n1.type() != Number::Type::real) n1 = Number{n1.coerce<Number::real_type>()}; return true; } fprintf(zs::err, complex_found::msg); return false; }); } void number_min(){ number_accumulate("min", Number(), [](Number& n1, const Number& n2) -> bool { if(n1.type() == Number::Type::uninitialized){ n1 = n2; return true; } if(n2.type() == Number::Type::uninitialized){ return true; } if(n1.type() == Number::Type::integer && n2.type() == Number::Type::integer){ if(n1.get<Number::integer_type>() > n2.get<Number::integer_type>()) n1 = n2; return true; } if(n1.type() <= Number::Type::real && n2.type() <= Number::Type::real){ if(n1.coerce<Number::real_type>() > n2.coerce<Number::real_type>()) n1 = Number{n2.coerce<Number::real_type>()}; if(n1.type() != Number::Type::real) n1 = Number{n1.coerce<Number::real_type>()}; return true; } fprintf(zs::err, complex_found::msg); return false; }); } void number_plus(){ number_accumulate("+", Number(0l), [](Number& n1, const Number& n2) -> bool { if(n1.type() == Number::Type::uninitialized){ n1 = n2; return true; } if(n2.type() == Number::Type::uninitialized){ return true; } // n1 type <= n2 type if(n1.type() == Number::Type::integer && n2.type() == Number::Type::integer){ n1.get<Number::integer_type>() += n2.get<Number::integer_type>(); return true; } if(n1.type() == Number::Type::real && n2.type() <= Number::Type::real){ n1.get<Number::real_type>() += n2.coerce<Number::real_type>(); return true; } if(n1.type() == Number::Type::complex && n2.type() <= Number::Type::complex){ n1.get<Number::complex_type>() += n2.coerce<Number::complex_type>(); return true; } // n1 type > n2 type if(n1.type() < Number::Type::real && n2.type() == Number::Type::real){ n1 = Number{n1.coerce<Number::real_type>() + n2.get<Number::real_type>()}; return true; } if(n1.type() < Number::Type::complex && n2.type() == Number::Type::complex){ n1 = Number{n1.coerce<Number::complex_type>() + n2.get<Number::complex_type>()}; return true; } // ??? fprintf(zs::err, "native func: +: failed at numeric conversion!\n"); return false; }); } constexpr struct Entry { const char* name; const NProcedure func; constexpr Entry(const char* n, const NProcedure& f) : name(n), func(f){} } builtin_numeric[] = { {"complex?", { complexp, Calling::function, {1, false}}}, {"real?", { realp, Calling::function, {1, false}}}, {"rational?", { rationalp, Calling::function, {1, false}}}, {"integer?", { integerp, Calling::function, {1, false}}}, {"exact?", { exactp, Calling::function, {1, false}}}, {"inexact?", { inexactp, Calling::function, {1, false}}}, {"=", { number_equal, Calling::function, {2, true}}}, {"<", { number_less, Calling::function, {2, true}}}, {">", { number_greater, Calling::function, {2, true}}}, {"<=", { number_less_eq, Calling::function, {2, true}}}, {">=", { number_greater_eq, Calling::function, {2, true}}}, {"zero?", { zerop, Calling::function, {1, false}}}, {"positive?", { positivep, Calling::function, {1, false}}}, {"negative?", { negativep, Calling::function, {1, false}}}, {"odd?", { oddp, Calling::function, {1, false}}}, {"even?", { evenp, Calling::function, {1, false}}}, {"max", { number_max, Calling::function, {2, true}}}, {"min", { number_min, Calling::function, {2, true}}}, {"+", { number_plus, Calling::function, {0, true}}} }; } //namespace void install_builtin_numeric(){ for(auto& e : builtin_numeric){ VM.set(intern(VM.symtable, e.name), {&e.func}); } } <|endoftext|>
<commit_before>/* Copyright (c) 2010, The Barbarian Group All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "cinder/ip/Trim.h" namespace cinder { namespace ip { template<typename T> bool transparentHorizontalScanline( const SurfaceT<T> &surface, int32_t row, int32_t x1, int32_t x2 ) { const T *dstPtr = surface.getDataAlpha( Vec2i( x1, row ) ); uint8_t inc = surface.getPixelInc(); for( int32_t x = x1; x < x2; ++x ) { if( *dstPtr ) return false; dstPtr += inc; } return true; } template<typename T> bool transparentVerticalScanline( const SurfaceT<T> &surface, int32_t column, int32_t y1, int32_t y2 ) { const T *dstPtr = surface.getDataAlpha( Vec2i( column, y1 ) ); int32_t rowBytes = surface.getRowBytes(); for( int32_t y = y1; y < y2; ++y ) { if( *dstPtr ) return false; dstPtr += rowBytes; } return true; } template<typename T> Area findNonTransparentArea( const SurfaceT<T> &surface, const Area &unclippedBounds ) { const Area bounds = unclippedBounds.getClipBy( surface.getBounds() ); // if no alpha we'll fail over the to alpha-less fill if( ! surface.hasAlpha() ) { return surface.getBounds(); } int32_t topLine, bottomLine; int32_t leftColumn, rightColumn; // find the top and bottom lines for( topLine = bounds.getY1(); topLine < bounds.getY2(); ++topLine ) { if( ! transparentHorizontalScanline( surface, topLine, bounds.getX1(), bounds.getX2() ) ) { break; } } for( bottomLine = bounds.getY2() - 1; bottomLine > topLine; --bottomLine ) { if( ! transparentHorizontalScanline( surface, bottomLine, bounds.getX1(), bounds.getX2() ) ) { break; } } // find the left and right columns for( leftColumn = bounds.getX1(); leftColumn < bounds.getX2(); ++leftColumn ) { if( ! transparentVerticalScanline( surface, leftColumn, topLine, bottomLine ) ) { break; } } for( rightColumn = bounds.getX2(); rightColumn > leftColumn; --rightColumn ) { if( ! transparentVerticalScanline( surface, rightColumn, topLine, bottomLine ) ) { break; } } return Area( leftColumn, topLine, rightColumn, bottomLine ); } #define TRIM_PROTOTYPES(r,data,T)\ template Area findNonTransparentArea( const SurfaceT<T> &surface, const Area &unclippedBounds ); BOOST_PP_SEQ_FOR_EACH( TRIM_PROTOTYPES, ~, CHANNEL_TYPES ) } } // namespace cinder::ip <commit_msg>Fixing off-by-one on right/bottom for ip::findNonTransparentArea<commit_after>/* Copyright (c) 2010, The Barbarian Group All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "cinder/ip/Trim.h" namespace cinder { namespace ip { template<typename T> bool transparentHorizontalScanline( const SurfaceT<T> &surface, int32_t row, int32_t x1, int32_t x2 ) { const T *dstPtr = surface.getDataAlpha( Vec2i( x1, row ) ); uint8_t inc = surface.getPixelInc(); for( int32_t x = x1; x < x2; ++x ) { if( *dstPtr ) return false; dstPtr += inc; } return true; } template<typename T> bool transparentVerticalScanline( const SurfaceT<T> &surface, int32_t column, int32_t y1, int32_t y2 ) { const T *dstPtr = surface.getDataAlpha( Vec2i( column, y1 ) ); int32_t rowBytes = surface.getRowBytes(); for( int32_t y = y1; y < y2; ++y ) { if( *dstPtr ) return false; dstPtr += rowBytes; } return true; } template<typename T> Area findNonTransparentArea( const SurfaceT<T> &surface, const Area &unclippedBounds ) { const Area bounds = unclippedBounds.getClipBy( surface.getBounds() ); // if no alpha we'll fail over the to alpha-less fill if( ! surface.hasAlpha() ) { return surface.getBounds(); } int32_t topLine, bottomLine; int32_t leftColumn, rightColumn; // find the top and bottom lines for( topLine = bounds.getY1(); topLine < bounds.getY2(); ++topLine ) { if( ! transparentHorizontalScanline( surface, topLine, bounds.getX1(), bounds.getX2() ) ) { break; } } for( bottomLine = bounds.getY2() - 1; bottomLine > topLine; --bottomLine ) { if( ! transparentHorizontalScanline( surface, bottomLine, bounds.getX1(), bounds.getX2() ) ) { break; } } // find the left and right columns for( leftColumn = bounds.getX1(); leftColumn < bounds.getX2(); ++leftColumn ) { if( ! transparentVerticalScanline( surface, leftColumn, topLine, bottomLine ) ) { break; } } for( rightColumn = bounds.getX2(); rightColumn > leftColumn; --rightColumn ) { if( ! transparentVerticalScanline( surface, rightColumn, topLine, bottomLine ) ) { break; } } // we add one to right and bottom because Area represents an inclusive range on top/left and exclusive range on bottom/right return Area( leftColumn, topLine, rightColumn + 1, bottomLine + 1 ); } #define TRIM_PROTOTYPES(r,data,T)\ template Area findNonTransparentArea( const SurfaceT<T> &surface, const Area &unclippedBounds ); BOOST_PP_SEQ_FOR_EACH( TRIM_PROTOTYPES, ~, CHANNEL_TYPES ) } } // namespace cinder::ip <|endoftext|>
<commit_before>/* * (C) 2014,2015 Jack Lloyd * 2016 Matthias Gierlings * * Botan is released under the Simplified BSD License (see license.txt) */ #include "cli.h" #if defined(BOTAN_HAS_TLS) && defined(BOTAN_TARGET_OS_HAS_SOCKETS) #include <botan/tls_client.h> #include <botan/hex.h> #if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER) #include <botan/tls_session_manager_sqlite.h> #endif #include <string> #include <memory> #include <sys/types.h> #include <sys/time.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #if !defined(MSG_NOSIGNAL) #define MSG_NOSIGNAL 0 #endif #include "credentials.h" namespace Botan_CLI { class TLS_Client final : public Command, public Botan::TLS::Callbacks { public: TLS_Client() : Command("tls_client host --port=443 --print-certs --policy= " "--tls1.0 --tls1.1 --tls1.2 " "--session-db= --session-db-pass= --next-protocols= --type=tcp") {} void go() override { // TODO client cert auth std::unique_ptr<Botan::TLS::Session_Manager> session_mgr; const std::string sessions_db = get_arg("session-db"); if(!sessions_db.empty()) { #if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER) const std::string sessions_passphrase = get_arg("session-db-pass"); session_mgr.reset(new Botan::TLS::Session_Manager_SQLite(sessions_passphrase, rng(), sessions_db)); #else error_output() << "Ignoring session DB file, sqlite not enabled\n"; #endif } if(!session_mgr) { session_mgr.reset(new Botan::TLS::Session_Manager_In_Memory(rng())); } std::string policy_file = get_arg("policy"); std::unique_ptr<Botan::TLS::Policy> policy; if(policy_file.size() > 0) { std::ifstream policy_stream(policy_file); if(!policy_stream.good()) { error_output() << "Failed reading policy file\n"; return; } policy.reset(new Botan::TLS::Text_Policy(policy_stream)); } if(!policy) { policy.reset(new Botan::TLS::Policy); } Basic_Credentials_Manager creds; const std::string host = get_arg("host"); const uint16_t port = get_arg_sz("port"); const std::string transport = get_arg("type"); if(transport != "tcp" && transport != "udp") throw CLI_Usage_Error("Invalid transport type '" + transport + "' for TLS"); const bool use_tcp = (transport == "tcp"); const std::vector<std::string> protocols_to_offer = Botan::split_on("next-protocols", ','); m_sockfd = connect_to_host(host, port, use_tcp); using namespace std::placeholders; auto version = policy->latest_supported_version(!use_tcp); if(flag_set("tls1.0")) { version = Botan::TLS::Protocol_Version::TLS_V10; } else if(flag_set("tls1.1")) { version = Botan::TLS::Protocol_Version::TLS_V11; } Botan::TLS::Client client(*this, *session_mgr, creds, *policy, rng(), Botan::TLS::Server_Information(host, port), version, protocols_to_offer); bool first_active = true; while(!client.is_closed()) { fd_set readfds; FD_ZERO(&readfds); FD_SET(m_sockfd, &readfds); if(client.is_active()) { FD_SET(STDIN_FILENO, &readfds); if(first_active && !protocols_to_offer.empty()) { std::string app = client.application_protocol(); if(app != "") output() << "Server choose protocol: " << client.application_protocol() << "\n"; first_active = false; } } struct timeval timeout = { 1, 0 }; ::select(m_sockfd + 1, &readfds, nullptr, nullptr, &timeout); if(FD_ISSET(m_sockfd, &readfds)) { uint8_t buf[4*1024] = { 0 }; ssize_t got = ::read(m_sockfd, buf, sizeof(buf)); if(got == 0) { output() << "EOF on socket\n"; break; } else if(got == -1) { output() << "Socket error: " << errno << " " << strerror(errno) << "\n"; continue; } client.received_data(buf, got); } if(FD_ISSET(STDIN_FILENO, &readfds)) { uint8_t buf[1024] = { 0 }; ssize_t got = read(STDIN_FILENO, buf, sizeof(buf)); if(got == 0) { output() << "EOF on stdin\n"; client.close(); break; } else if(got == -1) { output() << "Stdin error: " << errno << " " << strerror(errno) << "\n"; continue; } if(got == 2 && buf[1] == '\n') { char cmd = buf[0]; if(cmd == 'R' || cmd == 'r') { output() << "Client initiated renegotiation\n"; client.renegotiate(cmd == 'R'); } else if(cmd == 'Q') { output() << "Client initiated close\n"; client.close(); } } else client.send(buf, got); } if(client.timeout_check()) { output() << "Timeout detected\n"; } } ::close(m_sockfd); } private: int connect_to_host(const std::string& host, uint16_t port, bool tcp) { hostent* host_addr = ::gethostbyname(host.c_str()); if(!host_addr) throw CLI_Error("gethostbyname failed for " + host); if(host_addr->h_addrtype != AF_INET) // FIXME throw CLI_Error(host + " has IPv6 address, not supported"); int type = tcp ? SOCK_STREAM : SOCK_DGRAM; int fd = ::socket(PF_INET, type, 0); if(fd == -1) throw CLI_Error("Unable to acquire socket"); sockaddr_in socket_info; ::memset(&socket_info, 0, sizeof(socket_info)); socket_info.sin_family = AF_INET; socket_info.sin_port = htons(port); ::memcpy(&socket_info.sin_addr, host_addr->h_addr, host_addr->h_length); socket_info.sin_addr = *reinterpret_cast<struct in_addr*>(host_addr->h_addr); // FIXME if(::connect(fd, reinterpret_cast<sockaddr*>(&socket_info), sizeof(struct sockaddr)) != 0) { ::close(fd); throw CLI_Error("connect failed"); } return fd; } bool tls_session_established(const Botan::TLS::Session& session) override { output() << "Handshake complete, " << session.version().to_string() << " using " << session.ciphersuite().to_string() << "\n"; if(!session.session_id().empty()) output() << "Session ID " << Botan::hex_encode(session.session_id()) << "\n"; if(!session.session_ticket().empty()) output() << "Session ticket " << Botan::hex_encode(session.session_ticket()) << "\n"; if(flag_set("print-certs")) { const std::vector<Botan::X509_Certificate>& certs = session.peer_certs(); for(size_t i = 0; i != certs.size(); ++i) { output() << "Certificate " << i+1 << "/" << certs.size() << "\n"; output() << certs[i].to_string(); output() << certs[i].PEM_encode(); } } return true; } static void dgram_socket_write(int sockfd, const uint8_t buf[], size_t length) { int r = send(sockfd, buf, length, MSG_NOSIGNAL); if(r == -1) throw CLI_Error("Socket write failed errno=" + std::to_string(errno)); } void tls_emit_data(const uint8_t buf[], size_t length) override { size_t offset = 0; while(length) { ssize_t sent = ::send(m_sockfd, buf + offset, length, MSG_NOSIGNAL); if(sent == -1) { if(errno == EINTR) sent = 0; else throw CLI_Error("Socket write failed errno=" + std::to_string(errno)); } offset += sent; length -= sent; } } void tls_alert(Botan::TLS::Alert alert) override { output() << "Alert: " << alert.type_string() << "\n"; } void tls_record_received(uint64_t /*seq_no*/, const uint8_t buf[], size_t buf_size) override { for(size_t i = 0; i != buf_size; ++i) output() << buf[i]; } private: int m_sockfd = -1; }; BOTAN_REGISTER_COMMAND("tls_client", TLS_Client); } #endif <commit_msg>Fix TLS client next protocol handling<commit_after>/* * (C) 2014,2015 Jack Lloyd * 2016 Matthias Gierlings * * Botan is released under the Simplified BSD License (see license.txt) */ #include "cli.h" #if defined(BOTAN_HAS_TLS) && defined(BOTAN_TARGET_OS_HAS_SOCKETS) #include <botan/tls_client.h> #include <botan/hex.h> #if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER) #include <botan/tls_session_manager_sqlite.h> #endif #include <string> #include <memory> #include <sys/types.h> #include <sys/time.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #if !defined(MSG_NOSIGNAL) #define MSG_NOSIGNAL 0 #endif #include "credentials.h" namespace Botan_CLI { class TLS_Client final : public Command, public Botan::TLS::Callbacks { public: TLS_Client() : Command("tls_client host --port=443 --print-certs --policy= " "--tls1.0 --tls1.1 --tls1.2 " "--session-db= --session-db-pass= --next-protocols= --type=tcp") {} void go() override { // TODO client cert auth std::unique_ptr<Botan::TLS::Session_Manager> session_mgr; const std::string sessions_db = get_arg("session-db"); if(!sessions_db.empty()) { #if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER) const std::string sessions_passphrase = get_arg("session-db-pass"); session_mgr.reset(new Botan::TLS::Session_Manager_SQLite(sessions_passphrase, rng(), sessions_db)); #else error_output() << "Ignoring session DB file, sqlite not enabled\n"; #endif } if(!session_mgr) { session_mgr.reset(new Botan::TLS::Session_Manager_In_Memory(rng())); } std::string policy_file = get_arg("policy"); std::unique_ptr<Botan::TLS::Policy> policy; if(policy_file.size() > 0) { std::ifstream policy_stream(policy_file); if(!policy_stream.good()) { error_output() << "Failed reading policy file\n"; return; } policy.reset(new Botan::TLS::Text_Policy(policy_stream)); } if(!policy) { policy.reset(new Botan::TLS::Policy); } Basic_Credentials_Manager creds; const std::string host = get_arg("host"); const uint16_t port = get_arg_sz("port"); const std::string transport = get_arg("type"); const std::string next_protos = get_arg("next-protocols"); if(transport != "tcp" && transport != "udp") throw CLI_Usage_Error("Invalid transport type '" + transport + "' for TLS"); const bool use_tcp = (transport == "tcp"); const std::vector<std::string> protocols_to_offer = Botan::split_on(next_protos, ','); m_sockfd = connect_to_host(host, port, use_tcp); using namespace std::placeholders; auto version = policy->latest_supported_version(!use_tcp); if(flag_set("tls1.0")) { version = Botan::TLS::Protocol_Version::TLS_V10; } else if(flag_set("tls1.1")) { version = Botan::TLS::Protocol_Version::TLS_V11; } Botan::TLS::Client client(*this, *session_mgr, creds, *policy, rng(), Botan::TLS::Server_Information(host, port), version, protocols_to_offer); bool first_active = true; while(!client.is_closed()) { fd_set readfds; FD_ZERO(&readfds); FD_SET(m_sockfd, &readfds); if(client.is_active()) { FD_SET(STDIN_FILENO, &readfds); if(first_active && !protocols_to_offer.empty()) { std::string app = client.application_protocol(); if(app != "") output() << "Server choose protocol: " << client.application_protocol() << "\n"; first_active = false; } } struct timeval timeout = { 1, 0 }; ::select(m_sockfd + 1, &readfds, nullptr, nullptr, &timeout); if(FD_ISSET(m_sockfd, &readfds)) { uint8_t buf[4*1024] = { 0 }; ssize_t got = ::read(m_sockfd, buf, sizeof(buf)); if(got == 0) { output() << "EOF on socket\n"; break; } else if(got == -1) { output() << "Socket error: " << errno << " " << strerror(errno) << "\n"; continue; } client.received_data(buf, got); } if(FD_ISSET(STDIN_FILENO, &readfds)) { uint8_t buf[1024] = { 0 }; ssize_t got = read(STDIN_FILENO, buf, sizeof(buf)); if(got == 0) { output() << "EOF on stdin\n"; client.close(); break; } else if(got == -1) { output() << "Stdin error: " << errno << " " << strerror(errno) << "\n"; continue; } if(got == 2 && buf[1] == '\n') { char cmd = buf[0]; if(cmd == 'R' || cmd == 'r') { output() << "Client initiated renegotiation\n"; client.renegotiate(cmd == 'R'); } else if(cmd == 'Q') { output() << "Client initiated close\n"; client.close(); } } else client.send(buf, got); } if(client.timeout_check()) { output() << "Timeout detected\n"; } } ::close(m_sockfd); } private: int connect_to_host(const std::string& host, uint16_t port, bool tcp) { hostent* host_addr = ::gethostbyname(host.c_str()); if(!host_addr) throw CLI_Error("gethostbyname failed for " + host); if(host_addr->h_addrtype != AF_INET) // FIXME throw CLI_Error(host + " has IPv6 address, not supported"); int type = tcp ? SOCK_STREAM : SOCK_DGRAM; int fd = ::socket(PF_INET, type, 0); if(fd == -1) throw CLI_Error("Unable to acquire socket"); sockaddr_in socket_info; ::memset(&socket_info, 0, sizeof(socket_info)); socket_info.sin_family = AF_INET; socket_info.sin_port = htons(port); ::memcpy(&socket_info.sin_addr, host_addr->h_addr, host_addr->h_length); socket_info.sin_addr = *reinterpret_cast<struct in_addr*>(host_addr->h_addr); // FIXME if(::connect(fd, reinterpret_cast<sockaddr*>(&socket_info), sizeof(struct sockaddr)) != 0) { ::close(fd); throw CLI_Error("connect failed"); } return fd; } bool tls_session_established(const Botan::TLS::Session& session) override { output() << "Handshake complete, " << session.version().to_string() << " using " << session.ciphersuite().to_string() << "\n"; if(!session.session_id().empty()) output() << "Session ID " << Botan::hex_encode(session.session_id()) << "\n"; if(!session.session_ticket().empty()) output() << "Session ticket " << Botan::hex_encode(session.session_ticket()) << "\n"; if(flag_set("print-certs")) { const std::vector<Botan::X509_Certificate>& certs = session.peer_certs(); for(size_t i = 0; i != certs.size(); ++i) { output() << "Certificate " << i+1 << "/" << certs.size() << "\n"; output() << certs[i].to_string(); output() << certs[i].PEM_encode(); } } return true; } static void dgram_socket_write(int sockfd, const uint8_t buf[], size_t length) { int r = send(sockfd, buf, length, MSG_NOSIGNAL); if(r == -1) throw CLI_Error("Socket write failed errno=" + std::to_string(errno)); } void tls_emit_data(const uint8_t buf[], size_t length) override { size_t offset = 0; while(length) { ssize_t sent = ::send(m_sockfd, buf + offset, length, MSG_NOSIGNAL); if(sent == -1) { if(errno == EINTR) sent = 0; else throw CLI_Error("Socket write failed errno=" + std::to_string(errno)); } offset += sent; length -= sent; } } void tls_alert(Botan::TLS::Alert alert) override { output() << "Alert: " << alert.type_string() << "\n"; } void tls_record_received(uint64_t /*seq_no*/, const uint8_t buf[], size_t buf_size) override { for(size_t i = 0; i != buf_size; ++i) output() << buf[i]; } private: int m_sockfd = -1; }; BOTAN_REGISTER_COMMAND("tls_client", TLS_Client); } #endif <|endoftext|>
<commit_before>#include "command_manager.hh" #include "utils.hh" #include "assert.hh" #include <algorithm> namespace Kakoune { void CommandManager::register_command(const std::string& command_name, Command command, const CommandCompleter& completer) { m_commands[command_name] = CommandAndCompleter { command, completer }; } void CommandManager::register_command(const std::vector<std::string>& command_names, Command command, const CommandCompleter& completer) { for (auto command_name : command_names) register_command(command_name, command, completer); } typedef std::vector<std::pair<size_t, size_t>> TokenList; static TokenList split(const std::string& line) { TokenList result; size_t pos = 0; while (pos < line.length()) { while(line[pos] == ' ' and pos != line.length()) ++pos; char delimiter = ' '; if (line[pos] == '"' or line[pos] == '\'') { delimiter = line[pos]; ++pos; } size_t token_start = pos; while ((line[pos] != delimiter or line[pos-1] == '\\') and pos != line.length()) ++pos; result.push_back(std::make_pair(token_start, pos)); ++pos; } return result; } struct command_not_found : runtime_error { command_not_found(const std::string& command) : runtime_error(command + " : no such command") {} }; void CommandManager::execute(const std::string& command_line, const Context& context) { TokenList tokens = split(command_line); if (tokens.empty()) return; CommandParameters params; for (auto it = tokens.begin(); it != tokens.end(); ++it) { params.push_back(command_line.substr(it->first, it->second - it->first)); } execute(params, context); } void CommandManager::execute(const CommandParameters& params, const Context& context) { if (params.empty()) return; auto command_it = m_commands.find(params[0]); if (command_it == m_commands.end()) throw command_not_found(params[0]); command_it->second.command(CommandParameters(params.begin() + 1, params.end()), context); } Completions CommandManager::complete(const std::string& command_line, size_t cursor_pos) { TokenList tokens = split(command_line); size_t token_to_complete = tokens.size(); for (size_t i = 0; i < tokens.size(); ++i) { if (tokens[i].first <= cursor_pos and tokens[i].second >= cursor_pos) { token_to_complete = i; break; } } if (token_to_complete == 0 or tokens.empty()) // command name completion { size_t cmd_start = tokens.empty() ? 0 : tokens[0].first; Completions result(cmd_start, cursor_pos); std::string prefix = command_line.substr(cmd_start, cursor_pos - cmd_start); for (auto& command : m_commands) { if (command.first.substr(0, prefix.length()) == prefix) result.candidates.push_back(command.first); } return result; } assert(not tokens.empty()); std::string command_name = command_line.substr(tokens[0].first, tokens[0].second - tokens[0].first); auto command_it = m_commands.find(command_name); if (command_it == m_commands.end() or not command_it->second.completer) return Completions(); CommandParameters params; for (auto it = tokens.begin() + 1; it != tokens.end(); ++it) { params.push_back(command_line.substr(it->first, it->second - it->first)); } size_t start = token_to_complete < tokens.size() ? tokens[token_to_complete].first : cursor_pos; Completions result(start , cursor_pos); size_t cursor_pos_in_token = cursor_pos - start; result.candidates = command_it->second.completer(params, token_to_complete - 1, cursor_pos_in_token); return result; } CandidateList PerArgumentCommandCompleter::operator()(const CommandParameters& params, size_t token_to_complete, size_t pos_in_token) const { if (token_to_complete >= m_completers.size()) return CandidateList(); // it is possible to try to complete a new argument assert(token_to_complete <= params.size()); const std::string& argument = token_to_complete < params.size() ? params[token_to_complete] : std::string(); return m_completers[token_to_complete](argument, pos_in_token); } } <commit_msg>CommandManager: support ';' as a command separator<commit_after>#include "command_manager.hh" #include "utils.hh" #include "assert.hh" #include <algorithm> namespace Kakoune { void CommandManager::register_command(const std::string& command_name, Command command, const CommandCompleter& completer) { m_commands[command_name] = CommandAndCompleter { command, completer }; } void CommandManager::register_command(const std::vector<std::string>& command_names, Command command, const CommandCompleter& completer) { for (auto command_name : command_names) register_command(command_name, command, completer); } typedef std::vector<std::pair<size_t, size_t>> TokenList; static TokenList split(const std::string& line) { TokenList result; size_t pos = 0; while (pos < line.length()) { while(line[pos] == ' ' and pos != line.length()) ++pos; char delimiter = ' '; if (line[pos] == '"' or line[pos] == '\'') { delimiter = line[pos]; ++pos; } size_t token_start = pos; while (((line[pos] != delimiter and line[pos] != ';') or line[pos-1] == '\\') and pos != line.length()) ++pos; result.push_back(std::make_pair(token_start, pos)); if (line[pos] == ';') result.push_back(std::make_pair(pos, pos+1)); ++pos; } return result; } struct command_not_found : runtime_error { command_not_found(const std::string& command) : runtime_error(command + " : no such command") {} }; void CommandManager::execute(const std::string& command_line, const Context& context) { TokenList tokens = split(command_line); if (tokens.empty()) return; CommandParameters params; for (auto it = tokens.begin(); it != tokens.end(); ++it) { params.push_back(command_line.substr(it->first, it->second - it->first)); } execute(params, context); } void CommandManager::execute(const CommandParameters& params, const Context& context) { if (params.empty()) return; auto begin = params.begin(); auto end = begin; while (true) { while (end != params.end() and *end != ";") ++end; if (end != begin) { auto command_it = m_commands.find(*begin); if (command_it == m_commands.end()) throw command_not_found(*begin); command_it->second.command(CommandParameters(begin + 1, end), context); } if (end == params.end()) break; begin = end+1; end = begin; } } Completions CommandManager::complete(const std::string& command_line, size_t cursor_pos) { TokenList tokens = split(command_line); size_t token_to_complete = tokens.size(); for (size_t i = 0; i < tokens.size(); ++i) { if (tokens[i].first <= cursor_pos and tokens[i].second >= cursor_pos) { token_to_complete = i; break; } } if (token_to_complete == 0 or tokens.empty()) // command name completion { size_t cmd_start = tokens.empty() ? 0 : tokens[0].first; Completions result(cmd_start, cursor_pos); std::string prefix = command_line.substr(cmd_start, cursor_pos - cmd_start); for (auto& command : m_commands) { if (command.first.substr(0, prefix.length()) == prefix) result.candidates.push_back(command.first); } return result; } assert(not tokens.empty()); std::string command_name = command_line.substr(tokens[0].first, tokens[0].second - tokens[0].first); auto command_it = m_commands.find(command_name); if (command_it == m_commands.end() or not command_it->second.completer) return Completions(); CommandParameters params; for (auto it = tokens.begin() + 1; it != tokens.end(); ++it) { params.push_back(command_line.substr(it->first, it->second - it->first)); } size_t start = token_to_complete < tokens.size() ? tokens[token_to_complete].first : cursor_pos; Completions result(start , cursor_pos); size_t cursor_pos_in_token = cursor_pos - start; result.candidates = command_it->second.completer(params, token_to_complete - 1, cursor_pos_in_token); return result; } CandidateList PerArgumentCommandCompleter::operator()(const CommandParameters& params, size_t token_to_complete, size_t pos_in_token) const { if (token_to_complete >= m_completers.size()) return CandidateList(); // it is possible to try to complete a new argument assert(token_to_complete <= params.size()); const std::string& argument = token_to_complete < params.size() ? params[token_to_complete] : std::string(); return m_completers[token_to_complete](argument, pos_in_token); } } <|endoftext|>
<commit_before>#include "io_utar.h" #include "logger.h" #include <fstream> #include <cmath> #include <cstdint> #include <boost/iostreams/device/file.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filter/gzip.hpp> #include <boost/iostreams/filter/bzip2.hpp> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/device/array.hpp> #include <boost/algorithm/string.hpp> namespace ncv { // http://techoverflow.net/blog/2013/03/29/reading-tar-files-in-c/ namespace { using std::int64_t; using std::uint64_t; /// /// \brief convert an ascii digit to the corresponding number (assuming it is an ASCII digit) /// uint64_t ascii_to_number(unsigned char num) { return ((num) - 48); } /// /// \brief decode a TAR octal number. ignores everything after the first NUL or space character. /// uint64_t decode_tar_octal(const char* data, size_t size = 12) { const unsigned char* currentPtr = (const unsigned char*)data + size; const unsigned char* checkPtr = currentPtr; for (; checkPtr >= (const unsigned char*) data; checkPtr --) { if ((*checkPtr) == 0 || (*checkPtr) == ' ') { currentPtr = checkPtr - 1; } } uint64_t sum = 0; uint64_t currentMultiplier = 1; for (; currentPtr >= (const unsigned char*)data; currentPtr --) { sum += ascii_to_number(*currentPtr) * currentMultiplier; currentMultiplier *= 8; } return sum; } struct TARFileHeader { char filename[100]; char mode[8]; char uid[8]; char gid[8]; char fileSize[12]; char lastModification[12]; char checksum[8]; char typeFlag; char linkedFileName[100]; char ustarIndicator[6]; char ustarVersion[2]; char ownerUserName[32]; char ownerGroupName[32]; char deviceMajorNumber[8]; char deviceMinorNumber[8]; char filenamePrefix[155]; char padding[12]; size_t filesize() const { return decode_tar_octal(fileSize); } }; } namespace { bool io_untar( boost::iostreams::filtering_istream& in, const io::untar_callback_t& callback, const std::string& info_header, const std::string& error_header) { char zeroBlock[512]; memset(zeroBlock, 0, 512); bool nextEntryHasLongName = false; while (in) { TARFileHeader header; in.read((char*)&header, 512); if (memcmp(&header, zeroBlock, 512) == 0) { log_info() << info_header << "found TAR end."; break; } // compose the filename std::string filename(header.filename, std::min((size_t)100, strlen(header.filename))); const size_t prefixLength = strlen(header.filenamePrefix); if (prefixLength > 0) { filename = std::string(header.filenamePrefix, std::min((size_t)155, prefixLength)) + "/" + filename; } if (header.typeFlag == '0' || header.typeFlag == 0) { // handle GNU TAR long filenames if (nextEntryHasLongName) { filename = std::string(header.filename); in.read((char*) &header, 512); nextEntryHasLongName = false; } const size_t size = header.filesize(); log_info() << info_header << "found file <" << filename << "> (" << size << " bytes)."; //Read the file into memory // This won't work for very large files -- use streaming methods there! { std::vector<unsigned char> filedata(size); char* const pdata = reinterpret_cast<char*>(filedata.data()); in.read(pdata, size); // decode archive type if ( boost::algorithm::iends_with(filename, ".tar.gz") || boost::algorithm::iends_with(filename, ".tgz")) { boost::iostreams::filtering_istream in_; in_.push(boost::iostreams::gzip_decompressor()); in_.push(boost::iostreams::basic_array_source<char>(pdata, filedata.size())); if (!io_untar(in_, callback, info_header, error_header)) { return false; } } else if (boost::algorithm::iends_with(filename, ".tar.bz2")) { boost::iostreams::filtering_istream in_; in_.push(boost::iostreams::bzip2_decompressor()); in_.push(boost::iostreams::basic_array_source<char>(pdata, filedata.size())); if (!io_untar(in_, callback, info_header, error_header)) { return false; } } else if (boost::algorithm::iends_with(filename, ".tar")) { // no decompression filter needed boost::iostreams::filtering_istream in_; in_.push(boost::iostreams::basic_array_source<char>(pdata, filedata.size())); if (!io_untar(in_, callback, info_header, error_header)) { return false; } } else { callback(filename, filedata); } } // ignore padding const size_t paddingBytes = (512 - (size % 512)) % 512; in.ignore(paddingBytes); } else if (header.typeFlag == '5') { log_info() << info_header << "found directory <" << filename << ">."; } else if(header.typeFlag == 'L') { nextEntryHasLongName = true; } else { log_info() << info_header << "found unhandled TAR entry type <" << header.typeFlag << ">."; } } // OK return true; } } bool io::untar( const std::string& path, const untar_callback_t& callback, const std::string& info_header, const std::string& error_header) { std::ifstream fin(path.c_str(), std::ios_base::in | std::ios_base::binary); if (!fin.is_open()) { log_error() << error_header << "failed to open file <" << path << ">!"; return false; } boost::iostreams::filtering_istream in; // decode archive type if ( boost::algorithm::iends_with(path, ".tar.gz") || boost::algorithm::iends_with(path, ".tgz")) { in.push(boost::iostreams::gzip_decompressor()); } else if (boost::algorithm::iends_with(path, ".tar.bz2")) { in.push(boost::iostreams::bzip2_decompressor()); } else if (boost::algorithm::iends_with(path, ".tar")) { // no decompression filter needed } else if (boost::algorithm::iends_with(path, ".gz")) { in.push(boost::iostreams::gzip_decompressor()); in.push(fin); std::vector<unsigned char> filedata; const size_t chunk = 4096; char data[chunk]; std::streamsize read_size; while ((read_size = boost::iostreams::read(in, data, chunk)) > 0) { filedata.insert(filedata.end(), reinterpret_cast<const unsigned char*>(data), reinterpret_cast<const unsigned char*>(data) + read_size); } callback(path, filedata); return true; } else { log_error() << error_header << "unknown file suffix <" << path << ">!"; return false; } in.push(fin); return io_untar(in, callback, info_header, error_header); } } <commit_msg>also handle tbz extensions<commit_after>#include "io_utar.h" #include "logger.h" #include <fstream> #include <cmath> #include <cstdint> #include <boost/iostreams/device/file.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filter/gzip.hpp> #include <boost/iostreams/filter/bzip2.hpp> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/device/array.hpp> #include <boost/algorithm/string.hpp> namespace ncv { // http://techoverflow.net/blog/2013/03/29/reading-tar-files-in-c/ namespace { using std::int64_t; using std::uint64_t; /// /// \brief convert an ascii digit to the corresponding number (assuming it is an ASCII digit) /// uint64_t ascii_to_number(unsigned char num) { return ((num) - 48); } /// /// \brief decode a TAR octal number. ignores everything after the first NUL or space character. /// uint64_t decode_tar_octal(const char* data, size_t size = 12) { const unsigned char* currentPtr = (const unsigned char*)data + size; const unsigned char* checkPtr = currentPtr; for (; checkPtr >= (const unsigned char*) data; checkPtr --) { if ((*checkPtr) == 0 || (*checkPtr) == ' ') { currentPtr = checkPtr - 1; } } uint64_t sum = 0; uint64_t currentMultiplier = 1; for (; currentPtr >= (const unsigned char*)data; currentPtr --) { sum += ascii_to_number(*currentPtr) * currentMultiplier; currentMultiplier *= 8; } return sum; } struct TARFileHeader { char filename[100]; char mode[8]; char uid[8]; char gid[8]; char fileSize[12]; char lastModification[12]; char checksum[8]; char typeFlag; char linkedFileName[100]; char ustarIndicator[6]; char ustarVersion[2]; char ownerUserName[32]; char ownerGroupName[32]; char deviceMajorNumber[8]; char deviceMinorNumber[8]; char filenamePrefix[155]; char padding[12]; size_t filesize() const { return decode_tar_octal(fileSize); } }; } namespace { bool io_untar( boost::iostreams::filtering_istream& in, const io::untar_callback_t& callback, const std::string& info_header, const std::string& error_header) { char zeroBlock[512]; memset(zeroBlock, 0, 512); bool nextEntryHasLongName = false; while (in) { TARFileHeader header; in.read((char*)&header, 512); if (memcmp(&header, zeroBlock, 512) == 0) { log_info() << info_header << "found TAR end."; break; } // compose the filename std::string filename(header.filename, std::min((size_t)100, strlen(header.filename))); const size_t prefixLength = strlen(header.filenamePrefix); if (prefixLength > 0) { filename = std::string(header.filenamePrefix, std::min((size_t)155, prefixLength)) + "/" + filename; } if (header.typeFlag == '0' || header.typeFlag == 0) { // handle GNU TAR long filenames if (nextEntryHasLongName) { filename = std::string(header.filename); in.read((char*) &header, 512); nextEntryHasLongName = false; } const size_t size = header.filesize(); log_info() << info_header << "found file <" << filename << "> (" << size << " bytes)."; //Read the file into memory // This won't work for very large files -- use streaming methods there! { std::vector<unsigned char> filedata(size); char* const pdata = reinterpret_cast<char*>(filedata.data()); in.read(pdata, size); // decode archive type if ( boost::algorithm::iends_with(filename, ".tar.gz") || boost::algorithm::iends_with(filename, ".tgz")) { boost::iostreams::filtering_istream in_; in_.push(boost::iostreams::gzip_decompressor()); in_.push(boost::iostreams::basic_array_source<char>(pdata, filedata.size())); if (!io_untar(in_, callback, info_header, error_header)) { return false; } } else if (boost::algorithm::iends_with(filename, ".tar.bz2") || boost::algorithm::iends_with(filename, ".tbz")) { boost::iostreams::filtering_istream in_; in_.push(boost::iostreams::bzip2_decompressor()); in_.push(boost::iostreams::basic_array_source<char>(pdata, filedata.size())); if (!io_untar(in_, callback, info_header, error_header)) { return false; } } else if (boost::algorithm::iends_with(filename, ".tar")) { // no decompression filter needed boost::iostreams::filtering_istream in_; in_.push(boost::iostreams::basic_array_source<char>(pdata, filedata.size())); if (!io_untar(in_, callback, info_header, error_header)) { return false; } } else { callback(filename, filedata); } } // ignore padding const size_t paddingBytes = (512 - (size % 512)) % 512; in.ignore(paddingBytes); } else if (header.typeFlag == '5') { log_info() << info_header << "found directory <" << filename << ">."; } else if(header.typeFlag == 'L') { nextEntryHasLongName = true; } else { log_info() << info_header << "found unhandled TAR entry type <" << header.typeFlag << ">."; } } // OK return true; } } bool io::untar( const std::string& path, const untar_callback_t& callback, const std::string& info_header, const std::string& error_header) { std::ifstream fin(path.c_str(), std::ios_base::in | std::ios_base::binary); if (!fin.is_open()) { log_error() << error_header << "failed to open file <" << path << ">!"; return false; } boost::iostreams::filtering_istream in; // decode archive type if ( boost::algorithm::iends_with(path, ".tar.gz") || boost::algorithm::iends_with(path, ".tgz")) { in.push(boost::iostreams::gzip_decompressor()); } else if (boost::algorithm::iends_with(path, ".tar.bz2") || boost::algorithm::iends_with(path, ".tbz")) { in.push(boost::iostreams::bzip2_decompressor()); } else if (boost::algorithm::iends_with(path, ".tar")) { // no decompression filter needed } else if (boost::algorithm::iends_with(path, ".gz")) { in.push(boost::iostreams::gzip_decompressor()); in.push(fin); std::vector<unsigned char> filedata; const size_t chunk = 4096; char data[chunk]; std::streamsize read_size; while ((read_size = boost::iostreams::read(in, data, chunk)) > 0) { filedata.insert(filedata.end(), reinterpret_cast<const unsigned char*>(data), reinterpret_cast<const unsigned char*>(data) + read_size); } callback(path, filedata); return true; } else { log_error() << error_header << "unknown file suffix <" << path << ">!"; return false; } in.push(fin); return io_untar(in, callback, info_header, error_header); } } <|endoftext|>
<commit_before>#include <node.h> #include <node_buffer.h> #include <string.h> #include <v8.h> #include <math.h> #include <stdlib.h> #include <assert.h> #ifdef __APPLE__ #include <malloc/malloc.h> #endif #include <zlib.h> // zlib magic something #define WBITS 16+MAX_WBITS #define WBITS_RAW -15 #define CHUNK 1024*100 #define HEADER_SIZE 10 #define FOOTER_SIZE 8 #define SPACER_SIZE 6 using namespace v8; using namespace node; static Persistent<String> SYM_BODY; static Persistent<String> SYM_LEFT; static Persistent<String> SYM_RIGHT; static Persistent<String> SYM_LAST; static Persistent<String> SYM_TYPE; static Persistent<String> SYM_OFFSETS; static Persistent<String> SYM_LENGTH; static Persistent<String> SYM_RAW_LENGTH; static Persistent<String> SYM_CRC; static Persistent<String> SYM_META; static Persistent<String> SYM_BUFFERS; static Persistent<String> SYM_HEADER; static Persistent<String> SYM_ODD; static Handle<Value> ThrowNodeError (const char* what = NULL) { return ThrowException(Exception::Error(String::New(what))); } static int meta_uncompress (char *dataIn, size_t bytesIn, int *dataType) { z_stream strmUncompress; strmUncompress.zalloc = Z_NULL; strmUncompress.zfree = Z_NULL; strmUncompress.opaque = Z_NULL; strmUncompress.avail_in = 0; strmUncompress.next_in = Z_NULL; //this can be further improved! //we should only do inflate if the the stream is compressed //and header skip should be done earlier if (inflateInit2(&strmUncompress, WBITS_RAW) != Z_OK) { return -1; } unsigned char *tmp = (unsigned char *) malloc(CHUNK); //skipping header strmUncompress.next_in = ((unsigned char *) dataIn) + HEADER_SIZE; strmUncompress.avail_in = bytesIn - HEADER_SIZE; //checking if stream is compressed, first byte - binary: //xxxxx001 - stream is NOT compressed //xxxxx011 - stream is compressed (using fixed huffman codes) //xxxxx111 - stream is compressed (using dynamic huffman codes) if ((*strmUncompress.next_in & 3) == 3 || (*strmUncompress.next_in & 5) == 5) { for (;;) { strmUncompress.avail_out = CHUNK; strmUncompress.next_out = tmp; int ret = inflate(&strmUncompress, Z_BLOCK); assert(ret != Z_STREAM_ERROR); switch (ret) { case Z_NEED_DICT: ret = Z_DATA_ERROR; /* and fall through */ case Z_DATA_ERROR: case Z_MEM_ERROR: inflateEnd(&strmUncompress); if (tmp != NULL) { free(tmp); } return -2; } if (strmUncompress.data_type & 128) { break; } } *dataType = strmUncompress.data_type; } else { *dataType = 128; } inflateEnd(&strmUncompress); return 0; } static int compress (char *dataIn, size_t bytesIn, int compressionLevel, char **dataOut, size_t *bytesOut) { size_t bytesDeflated = 0; if (compressionLevel < 0 || compressionLevel > 9) { compressionLevel = Z_DEFAULT_COMPRESSION; } z_stream strmCompress; strmCompress.zalloc = Z_NULL; strmCompress.zfree = Z_NULL; strmCompress.opaque = Z_NULL; if (deflateInit2(&strmCompress, compressionLevel, Z_DEFLATED, WBITS, 8L, Z_DEFAULT_STRATEGY) != Z_OK) { return -1; } bytesDeflated = deflateBound(&strmCompress, bytesIn); if (bytesDeflated < 1024) { bytesDeflated = 1024; } *dataOut = (char *) malloc(bytesDeflated); strmCompress.next_in = (Bytef *) dataIn; strmCompress.avail_in = bytesIn; strmCompress.next_out = (Bytef *) *dataOut; strmCompress.avail_out = bytesDeflated; if (deflate(&strmCompress, Z_NO_FLUSH) < Z_OK) { deflateReset(&strmCompress); return -2; } deflate(&strmCompress, Z_FINISH); *bytesOut = strmCompress.total_out; deflateReset(&strmCompress); return 0; } static Handle<Value> onet_compress (const Arguments &args) { HandleScope scope; int compressionLevel = Z_DEFAULT_COMPRESSION; if (args.Length() < 1) { return Undefined(); } if (!Buffer::HasInstance(args[0])) { ThrowNodeError("First argument must be a Buffer"); return Undefined(); } Local<Object> bufferIn = args[0]->ToObject(); if (args.Length() > 1) { compressionLevel = args[1]->IntegerValue(); } char *dataIn = Buffer::Data(bufferIn); size_t bytesIn = Buffer::Length(bufferIn); char *dataOut = 0; size_t bytesOut = 0; int dataType = 0; int status = compress(dataIn, bytesIn, compressionLevel, &dataOut, &bytesOut); if (status != 0) { char msg[30]; sprintf(msg, "Unable to compress: %d", status); ThrowNodeError(msg); return Undefined(); } status = meta_uncompress(dataOut, bytesOut, &dataType); if (status != 0) { char msg[30]; sprintf(msg, "Unable to uncompress: %d", status); ThrowNodeError(msg); return Undefined(); } unsigned int dataLength = bytesOut - HEADER_SIZE - FOOTER_SIZE - 1; Local<Object> result = Object::New(); Buffer *body = Buffer::New((char *) dataOut, bytesOut); result->Set(SYM_BODY, body->handle_); Local<Object> dataOffsets = Object::New(); dataOffsets->Set(SYM_LEFT, Integer::New(HEADER_SIZE)); dataOffsets->Set(SYM_RIGHT, Integer::New(HEADER_SIZE + dataLength)); dataOffsets->Set(SYM_LAST, Integer::New(HEADER_SIZE + dataLength)); Buffer *crc = Buffer::New((char *) dataOut + (bytesOut - FOOTER_SIZE), 4); Local<Object> meta = Object::New(); meta->Set(SYM_TYPE, Integer::New(dataType)); meta->Set(SYM_OFFSETS, dataOffsets); meta->Set(SYM_LENGTH, Integer::New(bytesIn)); meta->Set(SYM_RAW_LENGTH, Integer::New(bytesOut - HEADER_SIZE - FOOTER_SIZE)); meta->Set(SYM_CRC, crc->handle_); result->Set(SYM_META, meta); free(dataOut); return scope.Close(result); } static Handle<Value> compress (const Arguments& args) { HandleScope scope; int compressionLevel = Z_DEFAULT_COMPRESSION; if (args.Length() < 1) { return Undefined(); } if (!Buffer::HasInstance(args[0])) { ThrowNodeError("First argument must be a Buffer"); return Undefined(); } Local<Object> bufferIn = args[0]->ToObject(); if (args.Length() > 1) { compressionLevel = args[1]->IntegerValue(); } char *dataIn = Buffer::Data(bufferIn); size_t bytesIn = Buffer::Length(bufferIn); char *dataOut = 0; size_t bytesOut = 0; int status = compress(dataIn, bytesIn, compressionLevel, &dataOut, &bytesOut); if (status != 0) { ThrowNodeError("Unable to compress"); return Undefined(); } Buffer *buff = Buffer::New(dataOut, bytesOut); return scope.Close(buff->handle_); } static Handle<Value> estimate (const Arguments &args) { HandleScope scope; Local<Array> arr = Local<Array>::Cast(args[0]); int i = 0; int l = arr->Length(); int sum = HEADER_SIZE + FOOTER_SIZE + ((l - 1) * SPACER_SIZE); for(; i < l; i++) { Local<Object> obj = arr->Get(i)->ToObject(); Local<Object> meta = obj->Get(SYM_META)->ToObject(); sum += meta->Get(SYM_RAW_LENGTH)->Uint32Value(); } return scope.Close(Integer::New(sum)); } static unsigned long reverseBytes (unsigned char *buf) { unsigned long v; v = *buf; v += (unsigned long) *(buf + 1) << 8; v += (unsigned long) *(buf + 2) << 16; v += (unsigned long) *(buf + 3) << 24; return v; } static Handle<Value> getCrc (const Arguments &args) { HandleScope scope; unsigned long crc = crc32(0L, Z_NULL, 0); unsigned long tot = 0; Local<Array> arr = Local<Array>::Cast(args[0]); int l = arr->Length(); int i = 0; for (; i < l; i++) { Local<Object> obj = arr->Get(i)->ToObject(); Local<Object> meta = obj->Get(SYM_META)->ToObject(); Local<Object> bufCrc = meta->Get(SYM_CRC)->ToObject(); unsigned long tmpCrc = reverseBytes((unsigned char *) Buffer::Data(bufCrc)); unsigned long tmpLen = meta->Get(SYM_LENGTH)->Uint32Value(); crc = crc32_combine(crc, tmpCrc, tmpLen); tot += tmpLen; } Local<Object> data = Object::New(); data->Set(SYM_CRC, Buffer::New((char *) &crc, 4)->handle_); data->Set(SYM_LENGTH, Buffer::New((char *) &tot, 4)->handle_); return scope.Close(data); } static Handle<Value> uncompress (const Arguments &args) { HandleScope scope; if (args.Length() < 1) { return Undefined(); } if (!Buffer::HasInstance(args[0])) { ThrowNodeError("First argument must be a Buffer"); return Undefined(); } z_stream strmUncompress; strmUncompress.zalloc=Z_NULL; strmUncompress.zfree=Z_NULL; strmUncompress.opaque=Z_NULL; strmUncompress.avail_in = 0; strmUncompress.next_in = Z_NULL; int rci = inflateInit2(&strmUncompress, WBITS); if (rci != Z_OK) { ThrowNodeError("zlib initialization error."); return Undefined(); } Local<Object> bufferIn=args[0]->ToObject(); strmUncompress.next_in = (Bytef*) Buffer::Data(bufferIn); strmUncompress.avail_in = Buffer::Length(bufferIn); Bytef *bufferOut = NULL; uint32_t malloc_size=0; uint32_t currentPosition=0; int ret; do { Bytef *tmp = (Bytef*)malloc(CHUNK); strmUncompress.avail_out = CHUNK; strmUncompress.next_out = tmp; ret = inflate(&strmUncompress, Z_NO_FLUSH); assert(ret != Z_STREAM_ERROR); switch (ret) { case Z_NEED_DICT: ret = Z_DATA_ERROR; /* and fall through */ case Z_DATA_ERROR: case Z_MEM_ERROR: (void)inflateEnd(&strmUncompress); if (bufferOut!=NULL) { free(bufferOut); } if (tmp!=NULL) { free(tmp); } return Undefined(); } uint32_t have = CHUNK - strmUncompress.avail_out; if (have>0) { bufferOut = (Bytef *) realloc(bufferOut, malloc_size+have); malloc_size=malloc_size+have; } memcpy(bufferOut+currentPosition, tmp, have); currentPosition+=have; free(tmp); } while (strmUncompress.avail_out == 0 && ret != Z_STREAM_END); inflateEnd(&strmUncompress); if (ret != Z_STREAM_END) { if (bufferOut!=NULL) { free(bufferOut); } return Undefined(); } Buffer *BufferOut=Buffer::New((char *)bufferOut, malloc_size); free(bufferOut); return scope.Close(BufferOut->handle_); } extern "C" void init (Handle<Object> target) { SYM_BODY = NODE_PSYMBOL("body"); SYM_LEFT = NODE_PSYMBOL("left"); SYM_RIGHT = NODE_PSYMBOL("right"); SYM_LAST = NODE_PSYMBOL("last"); SYM_TYPE = NODE_PSYMBOL("type"); SYM_OFFSETS = NODE_PSYMBOL("offsets"); SYM_LENGTH = NODE_PSYMBOL("length"); SYM_RAW_LENGTH = NODE_PSYMBOL("rawLength"); SYM_CRC = NODE_PSYMBOL("crc"); SYM_META = NODE_PSYMBOL("meta"); SYM_BUFFERS = NODE_PSYMBOL("buffers"); SYM_HEADER = NODE_PSYMBOL("header"); SYM_ODD = NODE_PSYMBOL("odd"); char header[] = {0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff}; Buffer *headerBuffer = Buffer::New(header, 10); char odd[] = {0x00, 0x00, 0xff, 0xff}; Buffer *oddBuffer = Buffer::New(odd, 4); Handle<Object> buffers = Object::New(); buffers->Set(SYM_HEADER, headerBuffer->handle_); buffers->Set(SYM_ODD, oddBuffer->handle_); target->Set(SYM_BUFFERS, buffers); NODE_SET_METHOD(target, "compress", compress); NODE_SET_METHOD(target, "uncompress", uncompress); NODE_SET_METHOD(target, "metaCompress", onet_compress); NODE_SET_METHOD(target, "getCrc", getCrc); NODE_SET_METHOD(target, "estimate", estimate); } NODE_MODULE(compress_buffer_bindings, init); <commit_msg>retab<commit_after>#include <node.h> #include <node_buffer.h> #include <string.h> #include <v8.h> #include <math.h> #include <stdlib.h> #include <assert.h> #ifdef __APPLE__ #include <malloc/malloc.h> #endif #include <zlib.h> // zlib magic something #define WBITS 16+MAX_WBITS #define WBITS_RAW -15 #define CHUNK 1024*100 #define HEADER_SIZE 10 #define FOOTER_SIZE 8 #define SPACER_SIZE 6 using namespace v8; using namespace node; static Persistent<String> SYM_BODY; static Persistent<String> SYM_LEFT; static Persistent<String> SYM_RIGHT; static Persistent<String> SYM_LAST; static Persistent<String> SYM_TYPE; static Persistent<String> SYM_OFFSETS; static Persistent<String> SYM_LENGTH; static Persistent<String> SYM_RAW_LENGTH; static Persistent<String> SYM_CRC; static Persistent<String> SYM_META; static Persistent<String> SYM_BUFFERS; static Persistent<String> SYM_HEADER; static Persistent<String> SYM_ODD; static Handle<Value> ThrowNodeError (const char* what = NULL) { return ThrowException(Exception::Error(String::New(what))); } static int meta_uncompress (char *dataIn, size_t bytesIn, int *dataType) { z_stream strmUncompress; strmUncompress.zalloc = Z_NULL; strmUncompress.zfree = Z_NULL; strmUncompress.opaque = Z_NULL; strmUncompress.avail_in = 0; strmUncompress.next_in = Z_NULL; //this can be further improved! //we should only do inflate if the the stream is compressed //and header skip should be done earlier if (inflateInit2(&strmUncompress, WBITS_RAW) != Z_OK) { return -1; } unsigned char *tmp = (unsigned char *) malloc(CHUNK); //skipping header strmUncompress.next_in = ((unsigned char *) dataIn) + HEADER_SIZE; strmUncompress.avail_in = bytesIn - HEADER_SIZE; //checking if stream is compressed, first byte - binary: //xxxxx001 - stream is NOT compressed //xxxxx011 - stream is compressed (using fixed huffman codes) //xxxxx111 - stream is compressed (using dynamic huffman codes) if ((*strmUncompress.next_in & 3) == 3 || (*strmUncompress.next_in & 5) == 5) { for (;;) { strmUncompress.avail_out = CHUNK; strmUncompress.next_out = tmp; int ret = inflate(&strmUncompress, Z_BLOCK); assert(ret != Z_STREAM_ERROR); switch (ret) { case Z_NEED_DICT: ret = Z_DATA_ERROR; /* and fall through */ case Z_DATA_ERROR: case Z_MEM_ERROR: inflateEnd(&strmUncompress); if (tmp != NULL) { free(tmp); } return -2; } if (strmUncompress.data_type & 128) { break; } } *dataType = strmUncompress.data_type; } else { *dataType = 128; } inflateEnd(&strmUncompress); return 0; } static int compress (char *dataIn, size_t bytesIn, int compressionLevel, char **dataOut, size_t *bytesOut) { size_t bytesDeflated = 0; if (compressionLevel < 0 || compressionLevel > 9) { compressionLevel = Z_DEFAULT_COMPRESSION; } z_stream strmCompress; strmCompress.zalloc = Z_NULL; strmCompress.zfree = Z_NULL; strmCompress.opaque = Z_NULL; if (deflateInit2(&strmCompress, compressionLevel, Z_DEFLATED, WBITS, 8L, Z_DEFAULT_STRATEGY) != Z_OK) { return -1; } bytesDeflated = deflateBound(&strmCompress, bytesIn); if (bytesDeflated < 1024) { bytesDeflated = 1024; } *dataOut = (char *) malloc(bytesDeflated); strmCompress.next_in = (Bytef *) dataIn; strmCompress.avail_in = bytesIn; strmCompress.next_out = (Bytef *) *dataOut; strmCompress.avail_out = bytesDeflated; if (deflate(&strmCompress, Z_NO_FLUSH) < Z_OK) { deflateReset(&strmCompress); return -2; } deflate(&strmCompress, Z_FINISH); *bytesOut = strmCompress.total_out; deflateReset(&strmCompress); return 0; } static Handle<Value> onet_compress (const Arguments &args) { HandleScope scope; int compressionLevel = Z_DEFAULT_COMPRESSION; if (args.Length() < 1) { return Undefined(); } if (!Buffer::HasInstance(args[0])) { ThrowNodeError("First argument must be a Buffer"); return Undefined(); } Local<Object> bufferIn = args[0]->ToObject(); if (args.Length() > 1) { compressionLevel = args[1]->IntegerValue(); } char *dataIn = Buffer::Data(bufferIn); size_t bytesIn = Buffer::Length(bufferIn); char *dataOut = 0; size_t bytesOut = 0; int dataType = 0; int status = compress(dataIn, bytesIn, compressionLevel, &dataOut, &bytesOut); if (status != 0) { char msg[30]; sprintf(msg, "Unable to compress: %d", status); ThrowNodeError(msg); return Undefined(); } status = meta_uncompress(dataOut, bytesOut, &dataType); if (status != 0) { char msg[30]; sprintf(msg, "Unable to uncompress: %d", status); ThrowNodeError(msg); return Undefined(); } unsigned int dataLength = bytesOut - HEADER_SIZE - FOOTER_SIZE - 1; Local<Object> result = Object::New(); Buffer *body = Buffer::New((char *) dataOut, bytesOut); result->Set(SYM_BODY, body->handle_); Local<Object> dataOffsets = Object::New(); dataOffsets->Set(SYM_LEFT, Integer::New(HEADER_SIZE)); dataOffsets->Set(SYM_RIGHT, Integer::New(HEADER_SIZE + dataLength)); dataOffsets->Set(SYM_LAST, Integer::New(HEADER_SIZE + dataLength)); Buffer *crc = Buffer::New((char *) dataOut + (bytesOut - FOOTER_SIZE), 4); Local<Object> meta = Object::New(); meta->Set(SYM_TYPE, Integer::New(dataType)); meta->Set(SYM_OFFSETS, dataOffsets); meta->Set(SYM_LENGTH, Integer::New(bytesIn)); meta->Set(SYM_RAW_LENGTH, Integer::New(bytesOut - HEADER_SIZE - FOOTER_SIZE)); meta->Set(SYM_CRC, crc->handle_); result->Set(SYM_META, meta); free(dataOut); return scope.Close(result); } static Handle<Value> compress (const Arguments& args) { HandleScope scope; int compressionLevel = Z_DEFAULT_COMPRESSION; if (args.Length() < 1) { return Undefined(); } if (!Buffer::HasInstance(args[0])) { ThrowNodeError("First argument must be a Buffer"); return Undefined(); } Local<Object> bufferIn = args[0]->ToObject(); if (args.Length() > 1) { compressionLevel = args[1]->IntegerValue(); } char *dataIn = Buffer::Data(bufferIn); size_t bytesIn = Buffer::Length(bufferIn); char *dataOut = 0; size_t bytesOut = 0; int status = compress(dataIn, bytesIn, compressionLevel, &dataOut, &bytesOut); if (status != 0) { ThrowNodeError("Unable to compress"); return Undefined(); } Buffer *buff = Buffer::New(dataOut, bytesOut); return scope.Close(buff->handle_); } static Handle<Value> estimate (const Arguments &args) { HandleScope scope; Local<Array> arr = Local<Array>::Cast(args[0]); int i = 0; int l = arr->Length(); int sum = HEADER_SIZE + FOOTER_SIZE + ((l - 1) * SPACER_SIZE); for(; i < l; i++) { Local<Object> obj = arr->Get(i)->ToObject(); Local<Object> meta = obj->Get(SYM_META)->ToObject(); sum += meta->Get(SYM_RAW_LENGTH)->Uint32Value(); } return scope.Close(Integer::New(sum)); } static unsigned long reverseBytes (unsigned char *buf) { unsigned long v; v = *buf; v += (unsigned long) *(buf + 1) << 8; v += (unsigned long) *(buf + 2) << 16; v += (unsigned long) *(buf + 3) << 24; return v; } static Handle<Value> getCrc (const Arguments &args) { HandleScope scope; unsigned long crc = crc32(0L, Z_NULL, 0); unsigned long tot = 0; Local<Array> arr = Local<Array>::Cast(args[0]); int l = arr->Length(); int i = 0; for (; i < l; i++) { Local<Object> obj = arr->Get(i)->ToObject(); Local<Object> meta = obj->Get(SYM_META)->ToObject(); Local<Object> bufCrc = meta->Get(SYM_CRC)->ToObject(); unsigned long tmpCrc = reverseBytes((unsigned char *) Buffer::Data(bufCrc)); unsigned long tmpLen = meta->Get(SYM_LENGTH)->Uint32Value(); crc = crc32_combine(crc, tmpCrc, tmpLen); tot += tmpLen; } Local<Object> data = Object::New(); data->Set(SYM_CRC, Buffer::New((char *) &crc, 4)->handle_); data->Set(SYM_LENGTH, Buffer::New((char *) &tot, 4)->handle_); return scope.Close(data); } static Handle<Value> uncompress (const Arguments &args) { HandleScope scope; if (args.Length() < 1) { return Undefined(); } if (!Buffer::HasInstance(args[0])) { ThrowNodeError("First argument must be a Buffer"); return Undefined(); } z_stream strmUncompress; strmUncompress.zalloc=Z_NULL; strmUncompress.zfree=Z_NULL; strmUncompress.opaque=Z_NULL; strmUncompress.avail_in = 0; strmUncompress.next_in = Z_NULL; int rci = inflateInit2(&strmUncompress, WBITS); if (rci != Z_OK) { ThrowNodeError("zlib initialization error."); return Undefined(); } Local<Object> bufferIn=args[0]->ToObject(); strmUncompress.next_in = (Bytef*) Buffer::Data(bufferIn); strmUncompress.avail_in = Buffer::Length(bufferIn); Bytef *bufferOut = NULL; uint32_t malloc_size=0; uint32_t currentPosition=0; int ret; do { Bytef *tmp = (Bytef*)malloc(CHUNK); strmUncompress.avail_out = CHUNK; strmUncompress.next_out = tmp; ret = inflate(&strmUncompress, Z_NO_FLUSH); assert(ret != Z_STREAM_ERROR); switch (ret) { case Z_NEED_DICT: ret = Z_DATA_ERROR; /* and fall through */ case Z_DATA_ERROR: case Z_MEM_ERROR: (void)inflateEnd(&strmUncompress); if (bufferOut!=NULL) { free(bufferOut); } if (tmp!=NULL) { free(tmp); } return Undefined(); } uint32_t have = CHUNK - strmUncompress.avail_out; if (have>0) { bufferOut = (Bytef *) realloc(bufferOut, malloc_size+have); malloc_size=malloc_size+have; } memcpy(bufferOut+currentPosition, tmp, have); currentPosition+=have; free(tmp); } while (strmUncompress.avail_out == 0 && ret != Z_STREAM_END); inflateEnd(&strmUncompress); if (ret != Z_STREAM_END) { if (bufferOut!=NULL) { free(bufferOut); } return Undefined(); } Buffer *BufferOut=Buffer::New((char *)bufferOut, malloc_size); free(bufferOut); return scope.Close(BufferOut->handle_); } extern "C" void init (Handle<Object> target) { SYM_BODY = NODE_PSYMBOL("body"); SYM_LEFT = NODE_PSYMBOL("left"); SYM_RIGHT = NODE_PSYMBOL("right"); SYM_LAST = NODE_PSYMBOL("last"); SYM_TYPE = NODE_PSYMBOL("type"); SYM_OFFSETS = NODE_PSYMBOL("offsets"); SYM_LENGTH = NODE_PSYMBOL("length"); SYM_RAW_LENGTH = NODE_PSYMBOL("rawLength"); SYM_CRC = NODE_PSYMBOL("crc"); SYM_META = NODE_PSYMBOL("meta"); SYM_BUFFERS = NODE_PSYMBOL("buffers"); SYM_HEADER = NODE_PSYMBOL("header"); SYM_ODD = NODE_PSYMBOL("odd"); char header[] = {0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff}; Buffer *headerBuffer = Buffer::New(header, 10); char odd[] = {0x00, 0x00, 0xff, 0xff}; Buffer *oddBuffer = Buffer::New(odd, 4); Handle<Object> buffers = Object::New(); buffers->Set(SYM_HEADER, headerBuffer->handle_); buffers->Set(SYM_ODD, oddBuffer->handle_); target->Set(SYM_BUFFERS, buffers); NODE_SET_METHOD(target, "compress", compress); NODE_SET_METHOD(target, "uncompress", uncompress); NODE_SET_METHOD(target, "metaCompress", onet_compress); NODE_SET_METHOD(target, "getCrc", getCrc); NODE_SET_METHOD(target, "estimate", estimate); } NODE_MODULE(compress_buffer_bindings, init); <|endoftext|>
<commit_before>#pragma once #include <iostream> #define PI 3.1415926535897932 #define TWOPI 2.0*PI #define HPI 0.5*PI #define RPI 1.0/PI #define RTWOPI 1.0/TWOPI #define FPI 4.0*PI #define RFPI 1.0/(FPI) namespace mocc { // Surface and direction indexing enum Surface { EAST = 0, NORTH = 1, WEST = 2, SOUTH = 3, TOP = 4, BOTTOM = 5, INVALID = 6, }; enum class Direction { EAST = 0, NORTH = 1, WEST = 2, SOUTH = 3, TOP = 4, BOTTOM = 5, NE, NW, SW, SE, INVALID }; extern const Surface AllSurfaces[6]; enum class Normal { X_NORM = 0, Y_NORM, Z_NORM }; extern const Normal AllNormals[3]; // Boundary condition enumeration enum class Boundary { /** * Zero incoming flux */ VACUUM, /** * Reflected incoming flux */ REFLECT, /** * Incoming flux communicated between domain nodes */ PARALLEL, /** * Self-explanatory */ PERIODIC, INVALID }; enum class TraceDir { FW, BW }; std::ostream& operator<<(std::ostream& os, const Surface s ); std::ostream& operator<<(std::ostream& os, const Boundary b ); std::ostream& operator<<(std::ostream& os, const Normal n ); Normal surface_to_normal( Surface s ); } <commit_msg>Better comments<commit_after>#pragma once #include <iostream> #define PI 3.1415926535897932 #define TWOPI 2.0*PI #define HPI 0.5*PI #define RPI 1.0/PI #define RTWOPI 1.0/TWOPI #define FPI 4.0*PI #define RFPI 1.0/(FPI) namespace mocc { // Surface and direction indexing enum Surface { EAST = 0, NORTH = 1, WEST = 2, SOUTH = 3, TOP = 4, BOTTOM = 5, INVALID = 6, }; enum class Direction { EAST = 0, NORTH = 1, WEST = 2, SOUTH = 3, TOP = 4, BOTTOM = 5, NE, NW, SW, SE, INVALID }; extern const Surface AllSurfaces[6]; enum class Normal { X_NORM = 0, Y_NORM, Z_NORM }; extern const Normal AllNormals[3]; // Boundary condition enumeration enum class Boundary { /** * Zero incoming flux */ VACUUM, /** * Reflected incoming flux */ REFLECT, /** * Incoming flux communicated between domain nodes */ PARALLEL, /** * Flux exiting one face enters the opposite face, same angle */ PERIODIC, INVALID }; enum class TraceDir { FW, BW }; std::ostream& operator<<(std::ostream& os, const Surface s ); std::ostream& operator<<(std::ostream& os, const Boundary b ); std::ostream& operator<<(std::ostream& os, const Normal n ); Normal surface_to_normal( Surface s ); } <|endoftext|>
<commit_before>/* * Convert GError to a HTTP response. * * author: Max Kellermann <mk@cm4all.com> */ #include "request.hxx" #include "bp_instance.hxx" #include "http_client.hxx" #include "nfs/Quark.hxx" #include "ajp/ajp_client.hxx" #include "memcached/memcached_client.hxx" #include "cgi/cgi_quark.h" #include "fcgi/Quark.hxx" #include "was/was_quark.h" #include "widget/Error.hxx" #include "http_response.hxx" #include "http_server/http_server.hxx" #include "http_server/Request.hxx" #include "http_quark.h" #include "http/MessageHttpResponse.hxx" #include "HttpMessageResponse.hxx" #include "gerrno.h" #include "pool.hxx" #include "util/Exception.hxx" #include <daemon/log.h> #include <nfsc/libnfs-raw-nfs.h> static MessageHttpResponse Dup(struct pool &pool, http_status_t status, const char *msg) { return {status, p_strdup(&pool, msg)}; } gcc_pure static MessageHttpResponse ToResponse(struct pool &pool, GError &error) { if (error.domain == http_response_quark()) return Dup(pool, http_status_t(error.code), error.message); if (error.domain == widget_quark()) { switch (WidgetErrorCode(error.code)) { case WidgetErrorCode::UNSPECIFIED: break; case WidgetErrorCode::WRONG_TYPE: case WidgetErrorCode::UNSUPPORTED_ENCODING: return {HTTP_STATUS_BAD_GATEWAY, "Malformed widget response"}; case WidgetErrorCode::NO_SUCH_VIEW: return {HTTP_STATUS_NOT_FOUND, "No such view"}; case WidgetErrorCode::NOT_A_CONTAINER: return Dup(pool, HTTP_STATUS_NOT_FOUND, error.message); case WidgetErrorCode::FORBIDDEN: return {HTTP_STATUS_FORBIDDEN, "Forbidden"}; } } if (error.domain == nfs_client_quark()) { switch (error.code) { case NFS3ERR_NOENT: case NFS3ERR_NOTDIR: return {HTTP_STATUS_NOT_FOUND, "The requested file does not exist."}; } } if (error.domain == http_client_quark() || error.domain == ajp_client_quark()) return {HTTP_STATUS_BAD_GATEWAY, "Upstream server failed"}; else if (error.domain == cgi_quark() || error.domain == fcgi_quark() || error.domain == was_quark()) return {HTTP_STATUS_BAD_GATEWAY, "Script failed"}; else if (error.domain == errno_quark()) { switch (error.code) { case ENOENT: case ENOTDIR: return {HTTP_STATUS_NOT_FOUND, "The requested file does not exist."}; break; default: return {HTTP_STATUS_INTERNAL_SERVER_ERROR, "Internal server error"}; } } else if (error.domain == memcached_client_quark()) return {HTTP_STATUS_BAD_GATEWAY, "Cache server failed"}; else return {HTTP_STATUS_INTERNAL_SERVER_ERROR, "Internal server error"}; } gcc_pure static MessageHttpResponse ToResponse(struct pool &pool, std::exception_ptr ep) { try { FindRetrowNested<HttpMessageResponse>(ep); } catch (const HttpMessageResponse &e) { return Dup(pool, e.GetStatus(), e.what()); } try { FindRetrowNested<WidgetError>(ep); } catch (const WidgetError &e) { switch (e.GetCode()) { case WidgetErrorCode::UNSPECIFIED: break; case WidgetErrorCode::WRONG_TYPE: case WidgetErrorCode::UNSUPPORTED_ENCODING: return {HTTP_STATUS_BAD_GATEWAY, "Malformed widget response"}; case WidgetErrorCode::NO_SUCH_VIEW: return {HTTP_STATUS_NOT_FOUND, "No such view"}; case WidgetErrorCode::NOT_A_CONTAINER: return Dup(pool, HTTP_STATUS_NOT_FOUND, e.what()); case WidgetErrorCode::FORBIDDEN: return {HTTP_STATUS_FORBIDDEN, "Forbidden"}; } } return {HTTP_STATUS_INTERNAL_SERVER_ERROR, "Internal server error"}; } void response_dispatch_error(Request &request, GError *error) { auto response = ToResponse(request.pool, *error); if (request.instance.config.verbose_response) response.message = p_strdup(&request.pool, error->message); response_dispatch_message(request, response.status, response.message); } void response_dispatch_log(Request &request, http_status_t status, const char *msg, const char *log_msg) { daemon_log(2, "error on '%s': %s\n", request.request.uri, log_msg); if (request.instance.config.verbose_response) msg = p_strdup(&request.pool, log_msg); response_dispatch_message(request, status, msg); } void response_dispatch_log(Request &request, http_status_t status, const char *log_msg) { response_dispatch_log(request, status, http_status_to_string(status), log_msg); } void response_dispatch_log(Request &request, std::exception_ptr ep) { auto log_msg = GetFullMessage(ep); daemon_log(2, "error on '%s': %s\n", request.request.uri, log_msg.c_str()); auto response = ToResponse(request.pool, ep); if (request.instance.config.verbose_response) response.message = p_strdup(&request.pool, log_msg.c_str()); response_dispatch_message(request, response.status, response.message); } <commit_msg>rerror: translate NfsClientError<commit_after>/* * Convert GError to a HTTP response. * * author: Max Kellermann <mk@cm4all.com> */ #include "request.hxx" #include "bp_instance.hxx" #include "http_client.hxx" #include "nfs/Quark.hxx" #include "nfs/Error.hxx" #include "ajp/ajp_client.hxx" #include "memcached/memcached_client.hxx" #include "cgi/cgi_quark.h" #include "fcgi/Quark.hxx" #include "was/was_quark.h" #include "widget/Error.hxx" #include "http_response.hxx" #include "http_server/http_server.hxx" #include "http_server/Request.hxx" #include "http_quark.h" #include "http/MessageHttpResponse.hxx" #include "HttpMessageResponse.hxx" #include "gerrno.h" #include "pool.hxx" #include "util/Exception.hxx" #include <daemon/log.h> #include <nfsc/libnfs-raw-nfs.h> static MessageHttpResponse Dup(struct pool &pool, http_status_t status, const char *msg) { return {status, p_strdup(&pool, msg)}; } gcc_pure static MessageHttpResponse ToResponse(struct pool &pool, GError &error) { if (error.domain == http_response_quark()) return Dup(pool, http_status_t(error.code), error.message); if (error.domain == widget_quark()) { switch (WidgetErrorCode(error.code)) { case WidgetErrorCode::UNSPECIFIED: break; case WidgetErrorCode::WRONG_TYPE: case WidgetErrorCode::UNSUPPORTED_ENCODING: return {HTTP_STATUS_BAD_GATEWAY, "Malformed widget response"}; case WidgetErrorCode::NO_SUCH_VIEW: return {HTTP_STATUS_NOT_FOUND, "No such view"}; case WidgetErrorCode::NOT_A_CONTAINER: return Dup(pool, HTTP_STATUS_NOT_FOUND, error.message); case WidgetErrorCode::FORBIDDEN: return {HTTP_STATUS_FORBIDDEN, "Forbidden"}; } } if (error.domain == nfs_client_quark()) { switch (error.code) { case NFS3ERR_NOENT: case NFS3ERR_NOTDIR: return {HTTP_STATUS_NOT_FOUND, "The requested file does not exist."}; } } if (error.domain == http_client_quark() || error.domain == ajp_client_quark()) return {HTTP_STATUS_BAD_GATEWAY, "Upstream server failed"}; else if (error.domain == cgi_quark() || error.domain == fcgi_quark() || error.domain == was_quark()) return {HTTP_STATUS_BAD_GATEWAY, "Script failed"}; else if (error.domain == errno_quark()) { switch (error.code) { case ENOENT: case ENOTDIR: return {HTTP_STATUS_NOT_FOUND, "The requested file does not exist."}; break; default: return {HTTP_STATUS_INTERNAL_SERVER_ERROR, "Internal server error"}; } } else if (error.domain == memcached_client_quark()) return {HTTP_STATUS_BAD_GATEWAY, "Cache server failed"}; else return {HTTP_STATUS_INTERNAL_SERVER_ERROR, "Internal server error"}; } gcc_pure static MessageHttpResponse ToResponse(struct pool &pool, std::exception_ptr ep) { try { FindRetrowNested<HttpMessageResponse>(ep); } catch (const HttpMessageResponse &e) { return Dup(pool, e.GetStatus(), e.what()); } try { FindRetrowNested<WidgetError>(ep); } catch (const WidgetError &e) { switch (e.GetCode()) { case WidgetErrorCode::UNSPECIFIED: break; case WidgetErrorCode::WRONG_TYPE: case WidgetErrorCode::UNSUPPORTED_ENCODING: return {HTTP_STATUS_BAD_GATEWAY, "Malformed widget response"}; case WidgetErrorCode::NO_SUCH_VIEW: return {HTTP_STATUS_NOT_FOUND, "No such view"}; case WidgetErrorCode::NOT_A_CONTAINER: return Dup(pool, HTTP_STATUS_NOT_FOUND, e.what()); case WidgetErrorCode::FORBIDDEN: return {HTTP_STATUS_FORBIDDEN, "Forbidden"}; } } try { FindRetrowNested<NfsClientError>(ep); } catch (const NfsClientError &e) { switch (e.GetCode()) { case NFS3ERR_NOENT: case NFS3ERR_NOTDIR: return {HTTP_STATUS_NOT_FOUND, "The requested file does not exist."}; } } return {HTTP_STATUS_INTERNAL_SERVER_ERROR, "Internal server error"}; } void response_dispatch_error(Request &request, GError *error) { auto response = ToResponse(request.pool, *error); if (request.instance.config.verbose_response) response.message = p_strdup(&request.pool, error->message); response_dispatch_message(request, response.status, response.message); } void response_dispatch_log(Request &request, http_status_t status, const char *msg, const char *log_msg) { daemon_log(2, "error on '%s': %s\n", request.request.uri, log_msg); if (request.instance.config.verbose_response) msg = p_strdup(&request.pool, log_msg); response_dispatch_message(request, status, msg); } void response_dispatch_log(Request &request, http_status_t status, const char *log_msg) { response_dispatch_log(request, status, http_status_to_string(status), log_msg); } void response_dispatch_log(Request &request, std::exception_ptr ep) { auto log_msg = GetFullMessage(ep); daemon_log(2, "error on '%s': %s\n", request.request.uri, log_msg.c_str()); auto response = ToResponse(request.pool, ep); if (request.instance.config.verbose_response) response.message = p_strdup(&request.pool, log_msg.c_str()); response_dispatch_message(request, response.status, response.message); } <|endoftext|>
<commit_before>// RSHELL.CPP // Main source code for rshell #include "unistd.h" #include "sys/wait.h" #include "stdio.h" #include "errno.h" #include <iostream> #include <string> #include <vector> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/regex.hpp> #include <boost/regex.hpp> #include "rshell.h" #define RSHELL_DEBUG const char* CONN_AMP = "&&"; const char* CONN_PIPE = "||"; const char* CONN_SEMIC = ";"; /* Initialize environment */ void init() {} /* Main loop - controls command line, parsing, and execution logic */ int run() { std::vector<std::string> tokens_conn; std::vector<std::string> tokens_word; std::string usr_input; while(true) { usr_input = prompt(); tokens_conn = tokenize(usr_input, "(\\|\\||\\&\\&|;)"); for(unsigned int i = 0; i < tokens_conn.size(); i++) { #ifdef RSHELL_DEBUG std::cout << "<" << tokens_conn.at(i) << ">" << std::endl; #endif tokens_word = toksplit(tokens_conn.at(i), " "); for(unsigned int j = 0; j < tokens_word.size(); j++) { std::string word = tokens_word.at(j); // kill empty words if(word == "") tokens_word.erase(tokens_word.begin() + j); // using boost for convenience - this can be implemented manually boost::trim_if(word, boost::is_any_of(" \t")); } std::vector<char*> cmd_argv(tokens_word.size() + 1); for(unsigned int k = 0; k < tokens_word.size(); k++) { cmd_argv[k] = &tokens_word[k][0]; #ifdef RSHELL_DEBUG std::cout << "\t" << "<" << tokens_word.at(k) << ">" << std::endl; #endif } // exit only if first word is "exit", after formatting if(tokens_word.at(0) == "exit") return 0; execute(cmd_argv[0], cmd_argv.data()); } } return 0; } /* Prints the prompt symbol and takes in raw command line input */ std::string prompt() { std::cout << "$ " << std::flush; std::string input_raw; std::getline(std::cin, input_raw); return input_raw; } /* Basically a wrapper for execvp, has error checking */ int execute(const char* path, char* const argv[]) { #ifdef RSHELL_DEBUG std::cout << "executing " << path << std::endl; #endif int pid = fork(); if(pid == -1) { perror(NULL); return -1; } else if(pid == 0) { execvp(path, argv); perror(path); return 1; } else { if(waitpid(pid, NULL, 0) == -1) perror(NULL); } return 0; } /* Overload to tokenize by whitespace */ std::vector<std::string> tokenize(std::string s) { return tokenize(s, "\\s"); } /* Tokenize a string using boost regex */ std::vector<std::string> tokenize(std::string s, std::string r) { std::vector<std::string> token_vec; boost::algorithm::split_regex(token_vec, s, boost::regex(r)); return token_vec; } /* Tokenize a string using boost split */ std::vector<std::string> toksplit(std::string s, std::string toks) { std::vector<std::string> token_vec; boost::split(token_vec, s, boost::is_any_of(toks), boost::token_compress_on); return token_vec; } <commit_msg>fixed exit bug<commit_after>// RSHELL.CPP // Main source code for rshell #define RSHELL_DEBUG #include "unistd.h" #include "sys/wait.h" #include "stdio.h" #include "errno.h" #include <iostream> #include <string> #include <vector> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/regex.hpp> #include <boost/regex.hpp> #include "rshell.h" const char* CONN_AMP = "&&"; const char* CONN_PIPE = "||"; const char* CONN_SEMIC = ";"; /* Initialize environment */ void init() {} /* Main loop - controls command line, parsing, and execution logic */ int run() { std::vector<std::string> tokens_conn; std::vector<std::string> tokens_word; std::string usr_input; while(true) { usr_input = prompt(); tokens_conn = tokenize(usr_input, "(\\|\\||\\&\\&|;)"); for(unsigned int i = 0; i < tokens_conn.size(); i++) { #ifdef RSHELL_DEBUG std::cout << "<" << tokens_conn.at(i) << ">" << std::endl; #endif tokens_word = toksplit(tokens_conn.at(i), " "); for(unsigned int j = 0; j < tokens_word.size(); j++) { std::string word = tokens_word.at(j); // kill empty words if(word == "") tokens_word.erase(tokens_word.begin() + j); // using boost for convenience - this can be implemented manually boost::trim_if(word, boost::is_any_of(" \t")); } std::vector<char*> cmd_argv(tokens_word.size() + 1); for(unsigned int k = 0; k < tokens_word.size(); k++) { cmd_argv[k] = &tokens_word[k][0]; #ifdef RSHELL_DEBUG std::cout << "\t" << "<" << tokens_word.at(k) << ">" << std::endl; #endif } // exit only if first word is "exit", after formatting if(tokens_word.at(0) == "exit") return 0; int err_num = execute(cmd_argv[0], cmd_argv.data()); // if execvp returned and had error, stop the process if(err_num == 1) return 1; } } return 0; } /* Prints prompt text and takes in raw command line input */ std::string prompt() { char hostname[HOST_NAME_MAX]; if(gethostname(hostname, HOST_NAME_MAX) == -1) perror("gethostname"); std::cout << getlogin() << "@" << hostname; std::cout << "$ " << std::flush; std::string input_raw; std::getline(std::cin, input_raw); return input_raw; } /* fork and exec a program, complete error checking */ int execute(const char* path, char* const argv[]) { #ifdef RSHELL_DEBUG std::cout << "executing " << path << std::endl; #endif int pid = fork(); #ifdef RSHELL_DEBUG std::cout << "created process with id " << pid << std::endl; #endif if(pid == -1) { perror("fork"); return -1; } else if(pid == 0) { execvp(path, argv); perror(path); return 1; } else { if(waitpid(pid, NULL, 0) == -1) perror("waitpid"); } return 0; } /* Overload to tokenize by whitespace */ std::vector<std::string> tokenize(std::string s) { return tokenize(s, "\\s"); } /* Tokenize a string using boost regex */ std::vector<std::string> tokenize(std::string s, std::string r) { std::vector<std::string> token_vec; boost::algorithm::split_regex(token_vec, s, boost::regex(r)); return token_vec; } /* Tokenize a string using boost split */ std::vector<std::string> toksplit(std::string s, std::string toks) { std::vector<std::string> token_vec; boost::split(token_vec, s, boost::is_any_of(toks), boost::token_compress_on); return token_vec; } <|endoftext|>
<commit_before>#include <iostream> #include <string.h> #include <boost/tokenizer.hpp> #include <vector> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <algorithm> #include <ctype.h> #include <sys/types.h> #include <sys/stat.h> #include <time.h> #include <errno.h> using namespace std; using namespace boost; class Connector { public: Connector(); ~Connector(); bool run; int type; bool runNext(); bool precedence; }; Connector::Connector() { // the semicolon connector allows the next command to be execute always run = true; type = 0; // semicolon connector set to 0 precedence = false; } Connector::~Connector() { } bool Connector::runNext() { if (type == 1) // && connector { if (!run) // if the first command doesn't succeed it wont run the next command { return false; } } else if (type == 2) // || connector { if (run) // if the first command succeed it wont run the next command { return false; } } return true; } void parseinator(vector<string> input, string& command, string& argument, int& position, Connector& connect, string& flag); void commandifier(string command, string argument, Connector& connect, string flag); void test_function(string command, string & flag, string argument, Connector& connect); int main() { string flag; string str; string command; string argument; Connector connect; char hostname[100]; int position = 0; while (true) { printf("%s",getlogin()); // returns string containing name of user logged in gethostname(hostname, sizeof hostname); // returns the standard host name for the current machine cout << "@" << hostname << "$ "; getline(cin, str); if (str == "exit") // special command of exit { break; } vector<string> instruction; // vector of strings typedef tokenizer<boost::char_separator<char> > Tok; char_separator<char> sep; // default constructed Tok tok(str, sep);; for (Tok::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) // parses the input into a command and argument { instruction.push_back(*tok_iter); } if (instruction[0] != "#") // checks for user input except for comments (#) { parseinator(instruction, command, argument, position, connect, flag); // parses the input into a command and argument commandifier(command, argument, connect, flag); // runs a command with a given argument command = ""; argument = ""; int vector_size = instruction.size(); for (; position < vector_size;) // run until the end of the instruction { parseinator(instruction, command, argument, position, connect, flag); if (connect.runNext() && command != "") // checks connector to see if the next command should be ran { commandifier(command, argument, connect, flag); } else { while(connect.precedence && position < vector_size) { if(instruction[position] == ")") { connect.precedence = false; } position++; } connect.run = true; command = ""; } command = ""; argument = ""; } position = 0; } } return 0; } void parseinator(vector<string> input, string& command, string& argument, int& position, Connector& connect, string& flag) { if (input[position] == "&") // check if string is equal to & connector { connect.type = 1; // set & connector to 1 position += 2; // +=2 in order to take && connect } if (input[position] == "|") { connect.type = 2; // set | connector to 2 position += 2; // +=2 in order to take || connector } if (input[position] == ";") { connect.type = 0; // set ; connector to 0 position ++; } if (input[position] == "(") { connect.precedence = true; position++; } if (input[position] != "#") { command = input[position]; position++; } if (command == "test") { if(input[position] == "-") { position++; if (input[position] == "f") { flag = "-f"; position++; } else if (input[position] == "d") { flag = "-d"; position++; } else // DEFAULT E { flag = "-e"; position++; } } } int input_size = input.size(); for (; position < input_size; position++) { if (input[position] == ")") { connect.precedence = false; position++; break; } if(command == "echo" && input[position] == "\"") { position++; while(input[position] != "\"" && position <= input_size) { argument += input[position]; if(!isalnum(input[position].at(0)) && !isalnum(input[position+1].at(0))) { } else { argument += " "; } position++; } position++; break; } if (input[position] == "#") { position = input.size(); break; } if (input[position] == "&" || input[position] == "|" || input[position] == ";") { break; } argument += input[position]; int input_size1 = input.size(); if (position+1 != input_size1 && command == "echo") { //adds spaces when echoing argument += " "; } } } void commandifier(string command, string argument, Connector& connect, string flag) { const char * const_command = command.c_str(); char * char_command = new char[command.size()]; const char * const_argument = argument.c_str(); char * char_argument = new char[argument.size()]; strcpy (char_command, const_command); strcpy (char_argument, const_argument); char * args[2]; // char pointer array that holds command, and NULL char * args1[3]; // char pointer array that holds command, argument, and NULL bool no_arg = true; bool failed = false; if(command == "test" || command == "[") { test_function(command,flag,argument,connect); return; } // exit command if(command == "exit" || argument == "exit") { exit(1); } if (argument.size() == 0) // no arguments { args[0] = char_command; // args will contain the command args[1] = NULL; } else { no_arg = false; // sets bool no_arg to false args1[0] = char_command; // args1 contains command and argument args1[1] = char_argument; args1[2] = NULL; } pid_t c_pid, pid; // data type to reporesent process ID's int status; c_pid = fork(); // create our fork if (c_pid < 0) // indicates the fork has fail if its less than 0 { perror("fork failed"); exit(1); } else if (c_pid == 0) // in child process { if (no_arg) // no argument { execvp( args[0], args); // execvp the char pointer array that holds the command only if (execvp(args[0], args) == -1) // if it returns -1 it failed { perror("execvp failed"); connect.run = false; failed = true; } exit(3); } else // with command and argument { execvp(args1[0], args1); // execvp the char pointer array that holds the command, and argument if (execvp(args1[0], args1) == -1) // if it returns -1 it failed { perror("execvp failed"); connect.run = false; failed = true; } exit(3); } } else if (c_pid > 0) // parent process { if((pid = wait(&status)) < 0 ) { perror("wait"); exit(3); } if (WIFEXITED(status)) //Evaluates to a non-zero value if status was returned for a child process that terminated normally. { if (WEXITSTATUS(status) != 0) { connect.run = false; } else { connect.run = true; } } else { connect.run = true; } } } void test_function(string command, string & flag, string argument, Connector& connect) { const char * arg = argument.c_str(); struct stat sb; // struct for the stat function cout<<flag<<endl; if(flag == "-f") { if(stat(arg,&sb) == 0) { connect.run = true; if(S_ISREG(sb.st_mode)) { connect.run = true; } else { connect.run = false; } } else { connect.run = false; } } else if(flag == "-d") { if(stat(arg,&sb) == 0) { connect.run = true; if(S_ISDIR(sb.st_mode)) { connect.run = true; } else { connect.run = false; } } else { connect.run = false; } } else { if(stat(arg,&sb) == 0) { connect.run = true; } else { connect.run = false; } } } <commit_msg>Update rshell.cpp<commit_after>#include <iostream> #include <string.h> #include <boost/tokenizer.hpp> #include <vector> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <algorithm> #include <ctype.h> #include <sys/types.h> #include <sys/stat.h> #include <time.h> #include <errno.h> using namespace std; using namespace boost; class Connector { public: Connector(); ~Connector(); bool run; int type; bool runNext(); bool precedence; }; Connector::Connector() { // the semicolon connector allows the next command to be execute always run = true; type = 0; // semicolon connector set to 0 precedence = false; } Connector::~Connector() { } bool Connector::runNext() { if (type == 1) // && connector { if (!run) // if the first command doesn't succeed it wont run the next command { return false; } } else if (type == 2) // || connector { if (run) // if the first command succeed it wont run the next command { return false; } } return true; } void parseinator(vector<string> input, string& command, string& argument, int& position, Connector& connect, string& flag); void commandifier(string command, string argument, Connector& connect, string flag); void test_function(string command, string & flag, string argument, Connector& connect); int main() { string flag; string str; string command; string argument; Connector connect; char hostname[100]; int position = 0; while (true) { printf("%s",getlogin()); // returns string containing name of user logged in gethostname(hostname, sizeof hostname); // returns the standard host name for the current machine cout << "@" << hostname << "$ "; getline(cin, str); if (str == "exit") // special command of exit { break; } vector<string> instruction; // vector of strings typedef tokenizer<boost::char_separator<char> > Tok; char_separator<char> sep; // default constructed Tok tok(str, sep);; for (Tok::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) // parses the input into a command and argument { instruction.push_back(*tok_iter); } if (instruction[0] != "#") // checks for user input except for comments (#) { parseinator(instruction, command, argument, position, connect, flag); // parses the input into a command and argument commandifier(command, argument, connect, flag); // runs a command with a given argument command = ""; argument = ""; int vector_size = instruction.size(); for (; position < vector_size;) // run until the end of the instruction { parseinator(instruction, command, argument, position, connect, flag); if (connect.runNext() && command != "") // checks connector to see if the next command should be ran { commandifier(command, argument, connect, flag); } else { while(connect.precedence && position < vector_size) { if(instruction[position] == ")") { connect.precedence = false; } position++; } connect.run = true; command = ""; } command = ""; argument = ""; } position = 0; } } return 0; } void parseinator(vector<string> input, string& command, string& argument, int& position, Connector& connect, string& flag) { if (input[position] == "&") // check if string is equal to & connector { connect.type = 1; // set & connector to 1 position += 2; // +=2 in order to take && connect } if (input[position] == "|") { connect.type = 2; // set | connector to 2 position += 2; // +=2 in order to take || connector } if (input[position] == ";") { connect.type = 0; // set ; connector to 0 position ++; } if (input[position] == "(") { connect.precedence = true; position++; } if (input[position] != "#") { command = input[position]; position++; } if (command == "test") { if(input[position] == "-") { position++; if (input[position] == "f") { flag = "-f"; position++; } else if (input[position] == "d") { flag = "-d"; position++; } else // DEFAULT E { flag = "-e"; position++; } } } int input_size = input.size(); for (; position < input_size; position++) { if (input[position] == ")") { connect.precedence = false; position++; break; } if(command == "echo" && input[position] == "\"") { position++; while(input[position] != "\"" && position <= input_size) { argument += input[position]; if(!isalnum(input[position].at(0)) && !isalnum(input[position+1].at(0))) { } else { argument += " "; } position++; } position++; break; } if (input[position] == "#") { position = input.size(); break; } if (input[position] == "&" || input[position] == "|" || input[position] == ";") { break; } argument += input[position]; int input_size1 = input.size(); if (position+1 != input_size1 && command == "echo") { //adds spaces when echoing argument += " "; } } } void commandifier(string command, string argument, Connector& connect, string flag) { const char * const_command = command.c_str(); char * char_command = new char[command.size()]; const char * const_argument = argument.c_str(); char * char_argument = new char[argument.size()]; strcpy (char_command, const_command); strcpy (char_argument, const_argument); char * args[2]; // char pointer array that holds command, and NULL char * args1[3]; // char pointer array that holds command, argument, and NULL bool no_arg = true; bool failed = false; if(command == "test" || command == "[") { test_function(command,flag,argument,connect); return; } // exit command if(command == "exit" || argument == "exit") { exit(1); } if (argument.size() == 0) // no arguments { args[0] = char_command; // args will contain the command args[1] = NULL; } else { no_arg = false; // sets bool no_arg to false args1[0] = char_command; // args1 contains command and argument args1[1] = char_argument; args1[2] = NULL; } pid_t c_pid, pid; // data type to reporesent process ID's int status; c_pid = fork(); // create our fork if (c_pid < 0) // indicates the fork has fail if its less than 0 { perror("fork failed"); exit(1); } else if (c_pid == 0) // in child process { if (no_arg) // no argument { execvp( args[0], args); // execvp the char pointer array that holds the command only if (execvp(args[0], args) == -1) // if it returns -1 it failed { perror("execvp failed"); connect.run = false; failed = true; } exit(3); } else // with command and argument { execvp(args1[0], args1); // execvp the char pointer array that holds the command, and argument if (execvp(args1[0], args1) == -1) // if it returns -1 it failed { perror("execvp failed"); connect.run = false; failed = true; } exit(3); } } else if (c_pid > 0) // parent process { if((pid = wait(&status)) < 0 ) { perror("wait"); exit(3); } if (WIFEXITED(status)) //Evaluates to a non-zero value if status was returned for a child process that terminated normally. { if (WEXITSTATUS(status) != 0) { connect.run = false; } else { connect.run = true; } } else { connect.run = true; } } } void test_function(string command, string & flag, string argument, Connector& connect) { const char * arg = argument.c_str(); struct stat sb; // struct for the stat function if(flag == "-f") { if(stat(arg,&sb) == 0) { connect.run = true; if(S_ISREG(sb.st_mode)) { connect.run = true; } else { connect.run = false; } } else { connect.run = false; } } else if(flag == "-d") { if(stat(arg,&sb) == 0) { connect.run = true; if(S_ISDIR(sb.st_mode)) { connect.run = true; } else { connect.run = false; } } else { connect.run = false; } } else { if(stat(arg,&sb) == 0) { connect.run = true; } else { connect.run = false; } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: MABResultSet.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2001-10-17 18:18:52 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_MAB_RESULTSET_HXX_ #define _CONNECTIVITY_MAB_RESULTSET_HXX_ #ifndef _CONNECTIVITY_FILE_FRESULTSET_HXX_ #include "file/FResultSet.hxx" #endif #ifndef _CONNECTIVITY_MAB_TABLE_HXX_ #include "mozaddressbook/MABTable.hxx" #endif #ifndef _COM_SUN_STAR_SDBCX_XROWLOCATE_HPP_ #include <com/sun/star/sdbcx/XRowLocate.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XDELETEROWS_HPP_ #include <com/sun/star/sdbcx/XDeleteRows.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif namespace connectivity { namespace mozaddressbook { class OMozabResultSet; // these typedef's are only necessary for the compiler typedef ::cppu::ImplHelper2< ::com::sun::star::sdbcx::XRowLocate, ::com::sun::star::sdbcx::XDeleteRows> OMozabResultSet_BASE; typedef file::OResultSet OMozabResultSet_BASE2; typedef ::comphelper::OPropertyArrayUsageHelper<OMozabResultSet> OMozabResultSet_BASE3; class OMozabResultSet : public OMozabResultSet_BASE2, public OMozabResultSet_BASE, public OMozabResultSet_BASE3 { sal_Bool m_bBookmarkable; protected: OMozabTable *m_pMozTable; // OPropertyArrayUsageHelper virtual ::cppu::IPropertyArrayHelper* createArrayHelper() const; // OPropertySetHelper virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper(); virtual sal_Bool fillIndexValues(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier> &_xIndex); public: DECLARE_SERVICE_INFO(); OMozabResultSet( file::OStatement_Base* pStmt,connectivity::OSQLParseTreeIterator& _aSQLIterator); // XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire() throw(); virtual void SAL_CALL release() throw(); //XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException); // XPropertySet virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException); // XRowLocate virtual ::com::sun::star::uno::Any SAL_CALL getBookmark( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL moveToBookmark( const ::com::sun::star::uno::Any& bookmark ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL moveRelativeToBookmark( const ::com::sun::star::uno::Any& bookmark, sal_Int32 rows ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL compareBookmarks( const ::com::sun::star::uno::Any& first, const ::com::sun::star::uno::Any& second ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasOrderedBookmarks( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL hashBookmark( const ::com::sun::star::uno::Any& bookmark ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XDeleteRows virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL deleteRows( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& rows ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // special methods // virtual BOOL OpenImpl(); virtual void doTableSpecials(const OSQLTable& _xTable); }; } } #endif //_CONNECTIVITY_MAB_RESULTSET_HXX_ <commit_msg>INTEGRATION: CWS ooo19126 (1.8.342); FILE MERGED 2005/09/05 17:25:41 rt 1.8.342.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: MABResultSet.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2005-09-08 07:31:07 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CONNECTIVITY_MAB_RESULTSET_HXX_ #define _CONNECTIVITY_MAB_RESULTSET_HXX_ #ifndef _CONNECTIVITY_FILE_FRESULTSET_HXX_ #include "file/FResultSet.hxx" #endif #ifndef _CONNECTIVITY_MAB_TABLE_HXX_ #include "mozaddressbook/MABTable.hxx" #endif #ifndef _COM_SUN_STAR_SDBCX_XROWLOCATE_HPP_ #include <com/sun/star/sdbcx/XRowLocate.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_XDELETEROWS_HPP_ #include <com/sun/star/sdbcx/XDeleteRows.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif namespace connectivity { namespace mozaddressbook { class OMozabResultSet; // these typedef's are only necessary for the compiler typedef ::cppu::ImplHelper2< ::com::sun::star::sdbcx::XRowLocate, ::com::sun::star::sdbcx::XDeleteRows> OMozabResultSet_BASE; typedef file::OResultSet OMozabResultSet_BASE2; typedef ::comphelper::OPropertyArrayUsageHelper<OMozabResultSet> OMozabResultSet_BASE3; class OMozabResultSet : public OMozabResultSet_BASE2, public OMozabResultSet_BASE, public OMozabResultSet_BASE3 { sal_Bool m_bBookmarkable; protected: OMozabTable *m_pMozTable; // OPropertyArrayUsageHelper virtual ::cppu::IPropertyArrayHelper* createArrayHelper() const; // OPropertySetHelper virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper(); virtual sal_Bool fillIndexValues(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier> &_xIndex); public: DECLARE_SERVICE_INFO(); OMozabResultSet( file::OStatement_Base* pStmt,connectivity::OSQLParseTreeIterator& _aSQLIterator); // XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire() throw(); virtual void SAL_CALL release() throw(); //XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException); // XPropertySet virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException); // XRowLocate virtual ::com::sun::star::uno::Any SAL_CALL getBookmark( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL moveToBookmark( const ::com::sun::star::uno::Any& bookmark ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL moveRelativeToBookmark( const ::com::sun::star::uno::Any& bookmark, sal_Int32 rows ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL compareBookmarks( const ::com::sun::star::uno::Any& first, const ::com::sun::star::uno::Any& second ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasOrderedBookmarks( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL hashBookmark( const ::com::sun::star::uno::Any& bookmark ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XDeleteRows virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL deleteRows( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& rows ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // special methods // virtual BOOL OpenImpl(); virtual void doTableSpecials(const OSQLTable& _xTable); }; } } #endif //_CONNECTIVITY_MAB_RESULTSET_HXX_ <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkTextMapper.cxx Language: C++ Date: $Date$ Version: $Revision$ Thanks: Thanks to Matt Turek who developed this class. Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkTextMapper.h" #ifdef _WIN32 #include "vtkWin32OpenGLTextMapper.h" #include "vtkWin32TextMapper.h" #else #ifdef VTK_USE_OGLR #include "vtkXOpenGLTextMapper.h" #endif #include "vtkXTextMapper.h" #endif // Creates a new text mapper with Font size 12, bold off, italic off, // and Arial font vtkTextMapper::vtkTextMapper() { this->Input = (char*) NULL; this->FontSize = 12; this->Bold = 0; this->Italic = 0; this->Shadow = 0; this->FontFamily = VTK_ARIAL; this->Justification = VTK_TEXT_LEFT; this->VerticalJustification = VTK_TEXT_BOTTOM; this->TextLines = NULL; this->NumberOfLines = 0; this->NumberOfLinesAllocated = 0; this->LineOffset = 0.0; this->LineSpacing = 1.0; } vtkTextMapper *vtkTextMapper::New() { #ifdef _WIN32 #ifndef VTK_USE_NATIVE_IMAGING return vtkWin32OpenGLTextMapper::New(); #else return vtkWin32TextMapper::New(); #endif #else #ifdef VTK_USE_OGLR #ifndef VTK_USE_NATIVE_IMAGING return vtkXOpenGLTextMapper::New(); #else return vtkXTextMapper::New(); #endif #else return vtkXTextMapper::New(); #endif #endif } vtkTextMapper::~vtkTextMapper() { if (this->Input) { delete [] this->Input; this->Input = NULL; } if ( this->TextLines != NULL ) { for (int i=0; i < this->NumberOfLinesAllocated; i++) { this->TextLines[i]->Delete(); } delete [] this->TextLines; } } //---------------------------------------------------------------------------- void vtkTextMapper::PrintSelf(ostream& os, vtkIndent indent) { os << indent << "Line Offset: " << this->LineOffset; os << indent << "Line Spacing: " << this->LineSpacing; os << indent << "Bold: " << (this->Bold ? "On\n" : "Off\n"); os << indent << "Italic: " << (this->Italic ? "On\n" : "Off\n"); os << indent << "Shadow: " << (this->Shadow ? "On\n" : "Off\n"); os << indent << "FontFamily: " << this->FontFamily << "\n"; os << indent << "FontSize: " << this->FontSize << "\n"; os << indent << "Input: " << (this->Input ? this->Input : "(none)") << "\n"; os << indent << "Justification: "; switch (this->Justification) { case 0: os << "Left (0)" << endl; break; case 1: os << "Centered (1)" << endl; break; case 2: os << "Right (2)" << endl; break; } os << indent << "VerticalJustification: "; switch (this->VerticalJustification) { case VTK_TEXT_TOP: os << "Top" << endl; break; case VTK_TEXT_CENTERED: os << "Centered" << endl; break; case VTK_TEXT_BOTTOM: os << "Bottom" << endl; break; } vtkMapper2D::PrintSelf(os,indent); } int vtkTextMapper::GetWidth(vtkViewport* viewport) { int size[2]; this->GetSize(viewport, size); return size[0]; } int vtkTextMapper::GetHeight(vtkViewport* viewport) { int size[2]; this->GetSize(viewport, size); return size[1]; } // Parse the input and create multiple text mappers if multiple lines // (delimited by \n) are specified. void vtkTextMapper::SetInput(char *input) { if ( this->Input && input && (!strcmp(this->Input,input))) { return; } if (this->Input) { delete [] this->Input; } if (input) { this->Input = new char[strlen(input)+1]; strcpy(this->Input,input); } else { this->Input = NULL; } this->Modified(); int numLines = this->GetNumberOfLines(input); if ( numLines <= 1) // a line with no "\n" { this->NumberOfLines = numLines; this->LineOffset = 0.0; } else //multiple lines { char *line; int i; if ( numLines > this->NumberOfLinesAllocated ) { // delete old stuff if ( this->TextLines ) { for (i=0; i < this->NumberOfLinesAllocated; i++) { this->TextLines[i]->Delete(); } delete [] this->TextLines; } // allocate new text mappers this->NumberOfLinesAllocated = numLines; this->TextLines = new vtkTextMapper *[numLines]; for (i=0; i < numLines; i++) { this->TextLines[i] = vtkTextMapper::New(); } } //if we need to reallocate // set the input strings this->NumberOfLines = numLines; for (i=0; i < this->NumberOfLines; i++) { line = this->NextLine(input, i); this->TextLines[i]->SetInput( line ); delete [] line; } } } // Determine the number of lines in the Input string (delimited by "\n"). int vtkTextMapper::GetNumberOfLines(char *input) { if ( input == NULL ) { return 0; } int numLines=1; char *ptr = input; while ( ptr != NULL ) { if ( (ptr=strstr(ptr,"\n")) != NULL ) { numLines++; ptr++; //skip over \n } } return numLines; } // Get the next \n delimited line. Returns a string that // must be freed by the calling function. char *vtkTextMapper::NextLine(char *input, int lineNum) { char *line, *ptr, *ptrEnd; int strLen; ptr = input; for (int i=0; i != lineNum; i++) { ptr = strstr(ptr,"\n"); ptr++; } ptrEnd = strstr(ptr,"\n"); if ( ptrEnd == NULL ) { ptrEnd = strchr(ptr, '\0'); } strLen = ptrEnd - ptr; line = new char[strLen+1]; strncpy(line, ptr, strLen); line[strLen] = '\0'; return line; } // Get the size of a multi-line text string void vtkTextMapper::GetMultiLineSize(vtkViewport* viewport, int size[2]) { int i; int lineSize[2]; lineSize[0] = lineSize[1] = size[0] = size[1] = 0; for ( i=0; i < this->NumberOfLines; i++ ) { this->TextLines[i]->SetItalic(this->Italic); this->TextLines[i]->SetBold(this->Bold); this->TextLines[i]->SetShadow(this->Shadow); this->TextLines[i]->SetFontSize(this->FontSize); this->TextLines[i]->SetFontFamily(this->FontFamily); this->TextLines[i]->GetSize(viewport, lineSize); size[0] = (lineSize[0] > size[0] ? lineSize[0] : size[0]); size[1] = (lineSize[1] > size[1] ? lineSize[1] : size[1]); } // add in the line spacing this->LineSize = size[1]; size[1] = this->NumberOfLines* this->LineSpacing * size[1]; } void vtkTextMapper::RenderOverlayMultipleLines(vtkViewport *viewport, vtkActor2D *actor) { float offset; int size[2]; // make sure LineSize is up to date this->GetMultiLineSize(viewport,size); switch (this->VerticalJustification) { case VTK_TEXT_TOP: offset = 1.0; break; case VTK_TEXT_CENTERED: offset = -this->NumberOfLines/2.0 + 1; break; case VTK_TEXT_BOTTOM: offset = -(this->NumberOfLines - 1.0); break; } for (int lineNum=0; lineNum < this->NumberOfLines; lineNum++) { this->TextLines[lineNum]->SetItalic(this->Italic); this->TextLines[lineNum]->SetBold(this->Bold); this->TextLines[lineNum]->SetShadow(this->Shadow); this->TextLines[lineNum]->SetFontSize(this->FontSize); this->TextLines[lineNum]->SetFontFamily(this->FontFamily); this->TextLines[lineNum]->SetJustification(this->Justification); this->TextLines[lineNum]->SetLineOffset(this->LineSize*(lineNum+offset)); this->TextLines[lineNum]->SetLineSpacing(this->LineSpacing); this->TextLines[lineNum]->RenderOverlay(viewport,actor); } } void vtkTextMapper::RenderOpaqueGeometryMultipleLines(vtkViewport *viewport, vtkActor2D *actor) { float offset; int size[2]; // make sure LineSize is up to date this->GetMultiLineSize(viewport,size); switch (this->VerticalJustification) { case VTK_TEXT_TOP: offset = 1.0; break; case VTK_TEXT_CENTERED: offset = -this->NumberOfLines/2.0 + 1; break; case VTK_TEXT_BOTTOM: offset = -(this->NumberOfLines - 1.0); break; } for (int lineNum=0; lineNum < this->NumberOfLines; lineNum++) { this->TextLines[lineNum]->SetItalic(this->Italic); this->TextLines[lineNum]->SetBold(this->Bold); this->TextLines[lineNum]->SetShadow(this->Shadow); this->TextLines[lineNum]->SetFontSize(this->FontSize); this->TextLines[lineNum]->SetFontFamily(this->FontFamily); this->TextLines[lineNum]->SetJustification(this->Justification); this->TextLines[lineNum]->SetLineOffset(this->LineSize*(lineNum+offset)); this->TextLines[lineNum]->SetLineSpacing(this->LineSpacing); this->TextLines[lineNum]->RenderOpaqueGeometry(viewport,actor); } } <commit_msg>fixed print self<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkTextMapper.cxx Language: C++ Date: $Date$ Version: $Revision$ Thanks: Thanks to Matt Turek who developed this class. Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkTextMapper.h" #ifdef _WIN32 #include "vtkWin32OpenGLTextMapper.h" #include "vtkWin32TextMapper.h" #else #ifdef VTK_USE_OGLR #include "vtkXOpenGLTextMapper.h" #endif #include "vtkXTextMapper.h" #endif // Creates a new text mapper with Font size 12, bold off, italic off, // and Arial font vtkTextMapper::vtkTextMapper() { this->Input = (char*) NULL; this->FontSize = 12; this->Bold = 0; this->Italic = 0; this->Shadow = 0; this->FontFamily = VTK_ARIAL; this->Justification = VTK_TEXT_LEFT; this->VerticalJustification = VTK_TEXT_BOTTOM; this->TextLines = NULL; this->NumberOfLines = 0; this->NumberOfLinesAllocated = 0; this->LineOffset = 0.0; this->LineSpacing = 1.0; } vtkTextMapper *vtkTextMapper::New() { #ifdef _WIN32 #ifndef VTK_USE_NATIVE_IMAGING return vtkWin32OpenGLTextMapper::New(); #else return vtkWin32TextMapper::New(); #endif #else #ifdef VTK_USE_OGLR #ifndef VTK_USE_NATIVE_IMAGING return vtkXOpenGLTextMapper::New(); #else return vtkXTextMapper::New(); #endif #else return vtkXTextMapper::New(); #endif #endif } vtkTextMapper::~vtkTextMapper() { if (this->Input) { delete [] this->Input; this->Input = NULL; } if ( this->TextLines != NULL ) { for (int i=0; i < this->NumberOfLinesAllocated; i++) { this->TextLines[i]->Delete(); } delete [] this->TextLines; } } //---------------------------------------------------------------------------- void vtkTextMapper::PrintSelf(ostream& os, vtkIndent indent) { vtkMapper2D::PrintSelf(os,indent); os << indent << "Line Offset: " << this->LineOffset; os << indent << "Line Spacing: " << this->LineSpacing; os << indent << "Bold: " << (this->Bold ? "On\n" : "Off\n"); os << indent << "Italic: " << (this->Italic ? "On\n" : "Off\n"); os << indent << "Shadow: " << (this->Shadow ? "On\n" : "Off\n"); os << indent << "FontFamily: " << this->FontFamily << "\n"; os << indent << "FontSize: " << this->FontSize << "\n"; os << indent << "Input: " << (this->Input ? this->Input : "(none)") << "\n"; os << indent << "Justification: "; switch (this->Justification) { case 0: os << "Left (0)" << endl; break; case 1: os << "Centered (1)" << endl; break; case 2: os << "Right (2)" << endl; break; } os << indent << "VerticalJustification: "; switch (this->VerticalJustification) { case VTK_TEXT_TOP: os << "Top" << endl; break; case VTK_TEXT_CENTERED: os << "Centered" << endl; break; case VTK_TEXT_BOTTOM: os << "Bottom" << endl; break; } os << indent << "NumberOfLines: " << this->NumberOfLines << "\n"; } int vtkTextMapper::GetWidth(vtkViewport* viewport) { int size[2]; this->GetSize(viewport, size); return size[0]; } int vtkTextMapper::GetHeight(vtkViewport* viewport) { int size[2]; this->GetSize(viewport, size); return size[1]; } // Parse the input and create multiple text mappers if multiple lines // (delimited by \n) are specified. void vtkTextMapper::SetInput(char *input) { if ( this->Input && input && (!strcmp(this->Input,input))) { return; } if (this->Input) { delete [] this->Input; } if (input) { this->Input = new char[strlen(input)+1]; strcpy(this->Input,input); } else { this->Input = NULL; } this->Modified(); int numLines = this->GetNumberOfLines(input); if ( numLines <= 1) // a line with no "\n" { this->NumberOfLines = numLines; this->LineOffset = 0.0; } else //multiple lines { char *line; int i; if ( numLines > this->NumberOfLinesAllocated ) { // delete old stuff if ( this->TextLines ) { for (i=0; i < this->NumberOfLinesAllocated; i++) { this->TextLines[i]->Delete(); } delete [] this->TextLines; } // allocate new text mappers this->NumberOfLinesAllocated = numLines; this->TextLines = new vtkTextMapper *[numLines]; for (i=0; i < numLines; i++) { this->TextLines[i] = vtkTextMapper::New(); } } //if we need to reallocate // set the input strings this->NumberOfLines = numLines; for (i=0; i < this->NumberOfLines; i++) { line = this->NextLine(input, i); this->TextLines[i]->SetInput( line ); delete [] line; } } } // Determine the number of lines in the Input string (delimited by "\n"). int vtkTextMapper::GetNumberOfLines(char *input) { if ( input == NULL ) { return 0; } int numLines=1; char *ptr = input; while ( ptr != NULL ) { if ( (ptr=strstr(ptr,"\n")) != NULL ) { numLines++; ptr++; //skip over \n } } return numLines; } // Get the next \n delimited line. Returns a string that // must be freed by the calling function. char *vtkTextMapper::NextLine(char *input, int lineNum) { char *line, *ptr, *ptrEnd; int strLen; ptr = input; for (int i=0; i != lineNum; i++) { ptr = strstr(ptr,"\n"); ptr++; } ptrEnd = strstr(ptr,"\n"); if ( ptrEnd == NULL ) { ptrEnd = strchr(ptr, '\0'); } strLen = ptrEnd - ptr; line = new char[strLen+1]; strncpy(line, ptr, strLen); line[strLen] = '\0'; return line; } // Get the size of a multi-line text string void vtkTextMapper::GetMultiLineSize(vtkViewport* viewport, int size[2]) { int i; int lineSize[2]; lineSize[0] = lineSize[1] = size[0] = size[1] = 0; for ( i=0; i < this->NumberOfLines; i++ ) { this->TextLines[i]->SetItalic(this->Italic); this->TextLines[i]->SetBold(this->Bold); this->TextLines[i]->SetShadow(this->Shadow); this->TextLines[i]->SetFontSize(this->FontSize); this->TextLines[i]->SetFontFamily(this->FontFamily); this->TextLines[i]->GetSize(viewport, lineSize); size[0] = (lineSize[0] > size[0] ? lineSize[0] : size[0]); size[1] = (lineSize[1] > size[1] ? lineSize[1] : size[1]); } // add in the line spacing this->LineSize = size[1]; size[1] = this->NumberOfLines* this->LineSpacing * size[1]; } void vtkTextMapper::RenderOverlayMultipleLines(vtkViewport *viewport, vtkActor2D *actor) { float offset; int size[2]; // make sure LineSize is up to date this->GetMultiLineSize(viewport,size); switch (this->VerticalJustification) { case VTK_TEXT_TOP: offset = 1.0; break; case VTK_TEXT_CENTERED: offset = -this->NumberOfLines/2.0 + 1; break; case VTK_TEXT_BOTTOM: offset = -(this->NumberOfLines - 1.0); break; } for (int lineNum=0; lineNum < this->NumberOfLines; lineNum++) { this->TextLines[lineNum]->SetItalic(this->Italic); this->TextLines[lineNum]->SetBold(this->Bold); this->TextLines[lineNum]->SetShadow(this->Shadow); this->TextLines[lineNum]->SetFontSize(this->FontSize); this->TextLines[lineNum]->SetFontFamily(this->FontFamily); this->TextLines[lineNum]->SetJustification(this->Justification); this->TextLines[lineNum]->SetLineOffset(this->LineSize*(lineNum+offset)); this->TextLines[lineNum]->SetLineSpacing(this->LineSpacing); this->TextLines[lineNum]->RenderOverlay(viewport,actor); } } void vtkTextMapper::RenderOpaqueGeometryMultipleLines(vtkViewport *viewport, vtkActor2D *actor) { float offset; int size[2]; // make sure LineSize is up to date this->GetMultiLineSize(viewport,size); switch (this->VerticalJustification) { case VTK_TEXT_TOP: offset = 1.0; break; case VTK_TEXT_CENTERED: offset = -this->NumberOfLines/2.0 + 1; break; case VTK_TEXT_BOTTOM: offset = -(this->NumberOfLines - 1.0); break; } for (int lineNum=0; lineNum < this->NumberOfLines; lineNum++) { this->TextLines[lineNum]->SetItalic(this->Italic); this->TextLines[lineNum]->SetBold(this->Bold); this->TextLines[lineNum]->SetShadow(this->Shadow); this->TextLines[lineNum]->SetFontSize(this->FontSize); this->TextLines[lineNum]->SetFontFamily(this->FontFamily); this->TextLines[lineNum]->SetJustification(this->Justification); this->TextLines[lineNum]->SetLineOffset(this->LineSize*(lineNum+offset)); this->TextLines[lineNum]->SetLineSpacing(this->LineSpacing); this->TextLines[lineNum]->RenderOpaqueGeometry(viewport,actor); } } <|endoftext|>
<commit_before>/* Copyright (c) 2008-2019 the MRtrix3 contributors. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Covered Software is provided under this License on an "as is" * basis, without warranty of any kind, either expressed, implied, or * statutory, including, without limitation, warranties that the * Covered Software is free of defects, merchantable, fit for a * particular purpose or non-infringing. * See the Mozilla Public License v. 2.0 for more details. * * For more details, see http://www.mrtrix.org/. */ #include "command.h" #include "debug.h" #include "file/path.h" #include "file/dicom/element.h" #include "file/dicom/quick_scan.h" #include "file/dicom/definitions.h" using namespace MR; using namespace App; void usage () { AUTHOR = "J-Donald Tournier (jdtournier@gmail.com)"; SYNOPSIS = "Edit DICOM file in-place"; DESCRIPTION + "Note that this command simply replaces the existing " "values without modifying the DICOM structure in any way. Replacement text " "will be truncated if it is too long to fit inside the existing tag." + "WARNING: this command will modify existing data! It is recommended to run " "this command on a copy of the original data set to avoid loss of data."; ARGUMENTS + Argument ("file", "the DICOM file to be edited.").type_file_in(); OPTIONS + Option ("anonymise", "remove any identifiable information, by replacing the following tags:\n" "- any tag with Value Representation PN will be replaced with 'anonymous'\n" "- tag (0010,0030) PatientBirthDate will be replaced with an empty string\n\n" "WARNING: there is no guarantee that this command will remove all identiable " "information, since such information may be contained in any number " "of private vendor-specific tags. You will need to double-check the " "results independently if you " "need to ensure anonymity.") + Option ("id", "replace all ID tags with string supplied. This consists of tags " "(0010, 0020) PatientID and (0010, 1000) OtherPatientIDs") + Argument ("text").type_text() + Option ("tag", "replace specific tag.").allow_multiple() + Argument ("group") + Argument ("element") + Argument ("newvalue"); } class Tag { NOMEMALIGN public: Tag (uint16_t group, uint16_t element, const std::string& newvalue) : group (group), element (element), newvalue (newvalue) { } uint16_t group, element; std::string newvalue; }; inline std::string hex (uint16_t value) { std::ostringstream hex; hex << std::hex << value; return hex.str(); } inline uint16_t read_hex (const std::string& m) { uint16_t value; std::istringstream hex (m); hex >> std::hex >> value; return value; } void run () { vector<Tag> tags; vector<uint16_t> VRs; auto opt = get_options ("anonymise"); if (opt.size()) { tags.push_back (Tag (0x0010U, 0x0030U, "")); // PatientBirthDate VRs.push_back (VR_PN); } opt = get_options ("tag"); if (opt.size()) for (size_t n = 0; n < opt.size(); ++n) tags.push_back (Tag (read_hex (opt[n][0]), read_hex (opt[n][1]), opt[n][2])); opt = get_options ("id"); if (opt.size()) { std::string newid = opt[0][0]; tags.push_back (Tag (0x0010U, 0x0020U, newid)); // PatientID tags.push_back (Tag (0x0010U, 0x1000U, newid)); // OtherPatientIDs } for (size_t n = 0; n < VRs.size(); ++n) { union __VR { uint16_t i; char c[2]; } VR; VR.i = VRs[n]; INFO (std::string ("clearing entries with VR \"") + VR.c[1] + VR.c[0] + "\""); } for (size_t n = 0; n < tags.size(); ++n) INFO ("replacing tag (" + hex(tags[n].group) + "," + hex(tags[n].element) + ") with value \"" + tags[n].newvalue + "\""); File::Dicom::Element item; item.set (argument[0], true, true); while (item.read()) { for (size_t n = 0; n < VRs.size(); ++n) { if (item.VR == VRs[n]) { memset (item.data, 32, item.size); memcpy (item.data, "anonymous", std::min<int> (item.size, 9)); } } for (size_t n = 0; n < tags.size(); ++n) { if (item.is (tags[n].group, tags[n].element)) { memset (item.data, 32, item.size); memcpy (item.data, tags[n].newvalue.c_str(), std::min<int> (item.size, tags[n].newvalue.size())); } } } } <commit_msg>dcmedit: minor tweaks to docs<commit_after>/* Copyright (c) 2008-2019 the MRtrix3 contributors. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Covered Software is provided under this License on an "as is" * basis, without warranty of any kind, either expressed, implied, or * statutory, including, without limitation, warranties that the * Covered Software is free of defects, merchantable, fit for a * particular purpose or non-infringing. * See the Mozilla Public License v. 2.0 for more details. * * For more details, see http://www.mrtrix.org/. */ #include "command.h" #include "debug.h" #include "file/path.h" #include "file/dicom/element.h" #include "file/dicom/quick_scan.h" #include "file/dicom/definitions.h" using namespace MR; using namespace App; void usage () { AUTHOR = "J-Donald Tournier (jdtournier@gmail.com)"; SYNOPSIS = "Edit DICOM file in-place"; DESCRIPTION + "Note that this command simply replaces the existing " "values without modifying the DICOM structure in any way. Replacement text " "will be truncated if it is too long to fit inside the existing tag." + "WARNING: this command will modify existing data! It is recommended to run " "this command on a copy of the original data set to avoid loss of data."; ARGUMENTS + Argument ("file", "the DICOM file to be edited.").type_file_in(); OPTIONS + Option ("anonymise", "remove any identifiable information, by replacing the following tags:\n" "- any tag with Value Representation PN will be replaced with 'anonymous'\n" "- tag (0010,0030) PatientBirthDate will be replaced with an empty string\n" "WARNING: there is no guarantee that this command will remove all identiable " "information, since such information may be contained in any number " "of private vendor-specific tags. You will need to double-check the " "results independently if you " "need to ensure anonymity.") + Option ("id", "replace all ID tags with string supplied. This consists of tags " "(0010, 0020) PatientID and (0010, 1000) OtherPatientIDs") + Argument ("text").type_text() + Option ("tag", "replace specific tag.").allow_multiple() + Argument ("group") + Argument ("element") + Argument ("newvalue"); } class Tag { NOMEMALIGN public: Tag (uint16_t group, uint16_t element, const std::string& newvalue) : group (group), element (element), newvalue (newvalue) { } uint16_t group, element; std::string newvalue; }; inline std::string hex (uint16_t value) { std::ostringstream hex; hex << std::hex << value; return hex.str(); } inline uint16_t read_hex (const std::string& m) { uint16_t value; std::istringstream hex (m); hex >> std::hex >> value; return value; } void run () { vector<Tag> tags; vector<uint16_t> VRs; auto opt = get_options ("anonymise"); if (opt.size()) { tags.push_back (Tag (0x0010U, 0x0030U, "")); // PatientBirthDate VRs.push_back (VR_PN); } opt = get_options ("tag"); if (opt.size()) for (size_t n = 0; n < opt.size(); ++n) tags.push_back (Tag (read_hex (opt[n][0]), read_hex (opt[n][1]), opt[n][2])); opt = get_options ("id"); if (opt.size()) { std::string newid = opt[0][0]; tags.push_back (Tag (0x0010U, 0x0020U, newid)); // PatientID tags.push_back (Tag (0x0010U, 0x1000U, newid)); // OtherPatientIDs } for (size_t n = 0; n < VRs.size(); ++n) { union __VR { uint16_t i; char c[2]; } VR; VR.i = VRs[n]; INFO (std::string ("clearing entries with VR \"") + VR.c[1] + VR.c[0] + "\""); } for (size_t n = 0; n < tags.size(); ++n) INFO ("replacing tag (" + hex(tags[n].group) + "," + hex(tags[n].element) + ") with value \"" + tags[n].newvalue + "\""); File::Dicom::Element item; item.set (argument[0], true, true); while (item.read()) { for (size_t n = 0; n < VRs.size(); ++n) { if (item.VR == VRs[n]) { memset (item.data, 32, item.size); memcpy (item.data, "anonymous", std::min<int> (item.size, 9)); } } for (size_t n = 0; n < tags.size(); ++n) { if (item.is (tags[n].group, tags[n].element)) { memset (item.data, 32, item.size); memcpy (item.data, tags[n].newvalue.c_str(), std::min<int> (item.size, tags[n].newvalue.size())); } } } } <|endoftext|>
<commit_before>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/browser.h" #include <stdlib.h> #include "atom/browser/native_window.h" #include "atom/browser/window_list.h" #include "atom/common/atom_version.h" #include "brightray/common/application_info.h" #include "chrome/browser/ui/libgtk2ui/unity_service.h" namespace atom { void Browser::Focus() { // Focus on the first visible window. WindowList* list = WindowList::GetInstance(); for (WindowList::iterator iter = list->begin(); iter != list->end(); ++iter) { NativeWindow* window = *iter; if (window->IsVisible()) { window->Focus(true); break; } } } void Browser::AddRecentDocument(const base::FilePath& path) { } void Browser::ClearRecentDocuments() { } void Browser::SetAppUserModelID(const base::string16& name) { } bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol) { return false; } bool Browser::SetAsDefaultProtocolClient(const std::string& protocol) { return false; } bool Browser::IsDefaultProtocolClient(const std::string& protocol) { return false; } bool Browser::SetBadgeCount(int count) { if (IsUnityRunning()) { unity::SetDownloadCount(count); badge_count_ = count; return true; } else { return false; } } void Browser::SetLoginItemSettings(LoginItemSettings settings) { } LoginItemSettings Browser::GetLoginItemSettings() { return LoginItemSettings(); } std::string Browser::GetExecutableFileVersion() const { return brightray::GetApplicationVersion(); } std::string Browser::GetExecutableFileProductName() const { return brightray::GetApplicationName(); } bool Browser::IsUnityRunning() { return unity::IsRunning(); } } // namespace atom <commit_msg>Add Browser namespace<commit_after>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/browser.h" #include <stdlib.h> #include "atom/browser/native_window.h" #include "atom/browser/window_list.h" #include "atom/common/atom_version.h" #include "brightray/common/application_info.h" #include "chrome/browser/ui/libgtk2ui/unity_service.h" namespace atom { void Browser::Focus() { // Focus on the first visible window. WindowList* list = WindowList::GetInstance(); for (WindowList::iterator iter = list->begin(); iter != list->end(); ++iter) { NativeWindow* window = *iter; if (window->IsVisible()) { window->Focus(true); break; } } } void Browser::AddRecentDocument(const base::FilePath& path) { } void Browser::ClearRecentDocuments() { } void Browser::SetAppUserModelID(const base::string16& name) { } bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol) { return false; } bool Browser::SetAsDefaultProtocolClient(const std::string& protocol) { return false; } bool Browser::IsDefaultProtocolClient(const std::string& protocol) { return false; } bool Browser::SetBadgeCount(int count) { if (IsUnityRunning()) { unity::SetDownloadCount(count); badge_count_ = count; return true; } else { return false; } } void Browser::SetLoginItemSettings(LoginItemSettings settings) { } Browser::LoginItemSettings Browser::GetLoginItemSettings() { return LoginItemSettings(); } std::string Browser::GetExecutableFileVersion() const { return brightray::GetApplicationVersion(); } std::string Browser::GetExecutableFileProductName() const { return brightray::GetApplicationName(); } bool Browser::IsUnityRunning() { return unity::IsRunning(); } } // namespace atom <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #ifndef _Stroika_Foundation_Containers_Concrete_KeyedCollection_Factory_inl_ #define _Stroika_Foundation_Containers_Concrete_KeyedCollection_Factory_inl_ #include "../Concrete/KeyedCollection_LinkedList.h" namespace Stroika::Foundation::Containers::Factory { /* ******************************************************************************** ****** KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EQUALS_COMPARER> ******* ******************************************************************************** */ #if qCompiler_cpp17InlineStaticMemberOfClassDoubleDeleteAtExit_Buggy template <typename T, typename KEY_TYPE, typename TRAITS, typename KEY_EXTRACTOR, typename KEY_EQUALS_COMPARER> atomic<KeyedCollection<T, KEY_TYPE, TRAITS> (*) (KEY_EXTRACTOR&& keyExtractor, KEY_EQUALS_COMPARER&& keyComparer)> KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EXTRACTOR, KEY_EQUALS_COMPARER>::sFactory_ (nullptr); #endif template <typename T, typename KEY_TYPE, typename TRAITS, typename KEY_EXTRACTOR, typename KEY_EQUALS_COMPARER> inline KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EXTRACTOR, KEY_EQUALS_COMPARER>::KeyedCollection_Factory (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer) : fKeyExtractorType_{keyExtractor} , fKeyEqualsComparer_{keyComparer} { } template <typename T, typename KEY_TYPE, typename TRAITS, typename KEY_EXTRACTOR, typename KEY_EQUALS_COMPARER> inline KeyedCollection<T, KEY_TYPE, TRAITS> KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EXTRACTOR, KEY_EQUALS_COMPARER>::operator() () const { /* * Would have been more performant to just and assure always properly set, but to initialize * sFactory_ with a value other than nullptr requires waiting until after main() - so causes problems * with containers constructed before main. * * This works more generally (and with hopefully modest enough performance impact). */ if (auto f = sFactory_.load ()) { return f (fKeyExtractorType_, fKeyEqualsComparer_); } else { return Default_ (fKeyExtractorType_, fKeyEqualsComparer_); } } template <typename T, typename KEY_TYPE, typename TRAITS, typename KEY_EXTRACTOR, typename KEY_EQUALS_COMPARER> void KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EXTRACTOR, KEY_EQUALS_COMPARER>::Register (KeyedCollection<T, KEY_TYPE, TRAITS> (*factory) (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer)) { sFactory_ = factory; } template <typename T, typename KEY_TYPE, typename TRAITS, typename KEY_EXTRACTOR, typename KEY_EQUALS_COMPARER> inline KeyedCollection<T, KEY_TYPE, TRAITS> KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EXTRACTOR, KEY_EQUALS_COMPARER>::Default_ (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer) { /* * Note - though this is not an efficient implementation of KeyedCollection<> for large sizes, its probably the most * efficeint representation which adds no requirements to KEY_TYPE, such as operator< (or a traits less) or * a hash function. And its quite reasonable for small KeyedCollection's - which are often the case. * * Calls may use an explicit initializer of KeyedCollection_xxx<> to get better performance for large sized * maps. */ return Concrete::KeyedCollection_LinkedList<T, KEY_TYPE, TRAITS>{keyExtractor, keyComparer}; } } #endif /* _Stroika_Foundation_Containers_Concrete_KeyedCollection_Factory_inl_ */ <commit_msg>fix typo in vs2k17 BWA<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #ifndef _Stroika_Foundation_Containers_Concrete_KeyedCollection_Factory_inl_ #define _Stroika_Foundation_Containers_Concrete_KeyedCollection_Factory_inl_ #include "../Concrete/KeyedCollection_LinkedList.h" namespace Stroika::Foundation::Containers::Factory { /* ******************************************************************************** ****** KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EQUALS_COMPARER> ******* ******************************************************************************** */ #if qCompiler_cpp17InlineStaticMemberOfClassDoubleDeleteAtExit_Buggy template <typename T, typename KEY_TYPE, typename TRAITS, typename KEY_EXTRACTOR, typename KEY_EQUALS_COMPARER> atomic<KeyedCollection<T, KEY_TYPE, TRAITS> (*) (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer)> KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EXTRACTOR, KEY_EQUALS_COMPARER>::sFactory_ (nullptr); #endif template <typename T, typename KEY_TYPE, typename TRAITS, typename KEY_EXTRACTOR, typename KEY_EQUALS_COMPARER> inline KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EXTRACTOR, KEY_EQUALS_COMPARER>::KeyedCollection_Factory (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer) : fKeyExtractorType_{keyExtractor} , fKeyEqualsComparer_{keyComparer} { } template <typename T, typename KEY_TYPE, typename TRAITS, typename KEY_EXTRACTOR, typename KEY_EQUALS_COMPARER> inline KeyedCollection<T, KEY_TYPE, TRAITS> KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EXTRACTOR, KEY_EQUALS_COMPARER>::operator() () const { /* * Would have been more performant to just and assure always properly set, but to initialize * sFactory_ with a value other than nullptr requires waiting until after main() - so causes problems * with containers constructed before main. * * This works more generally (and with hopefully modest enough performance impact). */ if (auto f = sFactory_.load ()) { return f (fKeyExtractorType_, fKeyEqualsComparer_); } else { return Default_ (fKeyExtractorType_, fKeyEqualsComparer_); } } template <typename T, typename KEY_TYPE, typename TRAITS, typename KEY_EXTRACTOR, typename KEY_EQUALS_COMPARER> void KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EXTRACTOR, KEY_EQUALS_COMPARER>::Register (KeyedCollection<T, KEY_TYPE, TRAITS> (*factory) (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer)) { sFactory_ = factory; } template <typename T, typename KEY_TYPE, typename TRAITS, typename KEY_EXTRACTOR, typename KEY_EQUALS_COMPARER> inline KeyedCollection<T, KEY_TYPE, TRAITS> KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EXTRACTOR, KEY_EQUALS_COMPARER>::Default_ (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer) { /* * Note - though this is not an efficient implementation of KeyedCollection<> for large sizes, its probably the most * efficeint representation which adds no requirements to KEY_TYPE, such as operator< (or a traits less) or * a hash function. And its quite reasonable for small KeyedCollection's - which are often the case. * * Calls may use an explicit initializer of KeyedCollection_xxx<> to get better performance for large sized * maps. */ return Concrete::KeyedCollection_LinkedList<T, KEY_TYPE, TRAITS>{keyExtractor, keyComparer}; } } #endif /* _Stroika_Foundation_Containers_Concrete_KeyedCollection_Factory_inl_ */ <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 itkGradientDescentLineSearchOptimizerv4_hxx #define itkGradientDescentLineSearchOptimizerv4_hxx #include "itkGradientDescentLineSearchOptimizerv4.h" namespace itk { /** * Default constructor */ template<typename TInternalComputationValueType> GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> ::GradientDescentLineSearchOptimizerv4Template() { this->m_MaximumLineSearchIterations = 20; this->m_LineSearchIterations = NumericTraits<unsigned int>::ZeroValue(); this->m_LowerLimit = itk::NumericTraits< TInternalComputationValueType >::ZeroValue(); this->m_UpperLimit = 5.0; this->m_Phi = 1.618034; this->m_Resphi = 2 - this->m_Phi; this->m_Epsilon = 0.01; this->m_ReturnBestParametersAndValue = true; } /** * Destructor */ template<typename TInternalComputationValueType> GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> ::~GradientDescentLineSearchOptimizerv4Template() = default; /** *PrintSelf */ template<typename TInternalComputationValueType> void GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); } /** * Advance one Step following the gradient direction */ template<typename TInternalComputationValueType> void GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> ::AdvanceOneStep() { itkDebugMacro("AdvanceOneStep"); /* Modify the gradient by scales once at the begin */ this->ModifyGradientByScales(); /* This will estimate the learning rate (m_LearningRate) * if the options are set to do so. We only ever want to * estimate at the first step for this class. */ if ( this->m_CurrentIteration == 0 ) { this->EstimateLearningRate(); } this->m_LineSearchIterations = 0; this->m_LearningRate = this->GoldenSectionSearch( this->m_LearningRate * this->m_LowerLimit , this->m_LearningRate , this->m_LearningRate * this->m_UpperLimit ); /* Begin threaded gradient modification of m_Gradient variable. */ this->ModifyGradientByLearningRate(); try { /* Pass gradient to transform and let it do its own updating */ this->m_Metric->UpdateTransformParameters( this->m_Gradient ); } catch ( ExceptionObject & err ) { this->m_StopCondition = Superclass::UPDATE_PARAMETERS_ERROR; this->m_StopConditionDescription << "UpdateTransformParameters error"; this->StopOptimization(); // Pass exception to caller throw err; } this->InvokeEvent( IterationEvent() ); } // a and c are the current bounds; the minimum is between them. // b is a center point // f(x) is some mathematical function elsewhere defined // a corresponds to x1; b corresponds to x2; c corresponds to x3 // x corresponds to x4 template<typename TInternalComputationValueType> TInternalComputationValueType GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> ::GoldenSectionSearch( TInternalComputationValueType a, TInternalComputationValueType b, TInternalComputationValueType c ) { if ( this->m_LineSearchIterations > this->m_MaximumLineSearchIterations ) { return ( c + a ) / 2; } this->m_LineSearchIterations++; TInternalComputationValueType x; if ( c - b > b - a ) { x = b + this->m_Resphi * ( c - b ); } else { x = b - this->m_Resphi * ( b - a ); } if ( std::abs( c - a ) < this->m_Epsilon * ( std::abs( b ) + std::abs( x ) ) ) { return ( c + a ) / 2; } TInternalComputationValueType metricx, metricb; { // Cache the learning rate , parameters , gradient // Contain this in a block so these variables go out of // scope before we call recursively below. With dense transforms // we would otherwise eat up a lot of memory unnecessarily. TInternalComputationValueType baseLearningRate = this->m_LearningRate; DerivativeType baseGradient( this->m_Gradient ); ParametersType baseParameters( this->GetCurrentPosition() ); this->m_LearningRate = x; this->ModifyGradientByLearningRate(); this->m_Metric->UpdateTransformParameters( this->m_Gradient ); metricx = this->GetMetric()->GetValue( ); /** reset position of transform and gradient */ this->m_Metric->SetParameters( baseParameters ); this->m_Gradient = baseGradient; this->m_LearningRate = b; this->ModifyGradientByLearningRate(); this->m_Metric->UpdateTransformParameters( this->m_Gradient ); metricb = this->GetMetric()->GetValue( ); /** reset position of transform and learning rate */ this->m_Metric->SetParameters( baseParameters ); this->m_Gradient = baseGradient; this->m_LearningRate = baseLearningRate; } /** golden section */ if ( metricx < metricb ) { if (c - b > b - a) { return this->GoldenSectionSearch( b, x, c ); } else { return this->GoldenSectionSearch( a, x, b ); } } else { if ( c - b > b - a ) { return this->GoldenSectionSearch( a, b, x ); } else { return this->GoldenSectionSearch( x, b, c ); } } } }//namespace itk #endif <commit_msg>BUG: Handle boundary case with max metric<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 itkGradientDescentLineSearchOptimizerv4_hxx #define itkGradientDescentLineSearchOptimizerv4_hxx #include "itkGradientDescentLineSearchOptimizerv4.h" namespace itk { /** * Default constructor */ template<typename TInternalComputationValueType> GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> ::GradientDescentLineSearchOptimizerv4Template() { this->m_MaximumLineSearchIterations = 20; this->m_LineSearchIterations = NumericTraits<unsigned int>::ZeroValue(); this->m_LowerLimit = itk::NumericTraits< TInternalComputationValueType >::ZeroValue(); this->m_UpperLimit = 5.0; this->m_Phi = 1.618034; this->m_Resphi = 2 - this->m_Phi; this->m_Epsilon = 0.01; this->m_ReturnBestParametersAndValue = true; } /** * Destructor */ template<typename TInternalComputationValueType> GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> ::~GradientDescentLineSearchOptimizerv4Template() = default; /** *PrintSelf */ template<typename TInternalComputationValueType> void GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); } /** * Advance one Step following the gradient direction */ template<typename TInternalComputationValueType> void GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> ::AdvanceOneStep() { itkDebugMacro("AdvanceOneStep"); /* Modify the gradient by scales once at the begin */ this->ModifyGradientByScales(); /* This will estimate the learning rate (m_LearningRate) * if the options are set to do so. We only ever want to * estimate at the first step for this class. */ if ( this->m_CurrentIteration == 0 ) { this->EstimateLearningRate(); } this->m_LineSearchIterations = 0; this->m_LearningRate = this->GoldenSectionSearch( this->m_LearningRate * this->m_LowerLimit , this->m_LearningRate , this->m_LearningRate * this->m_UpperLimit ); /* Begin threaded gradient modification of m_Gradient variable. */ this->ModifyGradientByLearningRate(); try { /* Pass gradient to transform and let it do its own updating */ this->m_Metric->UpdateTransformParameters( this->m_Gradient ); } catch ( ExceptionObject & err ) { this->m_StopCondition = Superclass::UPDATE_PARAMETERS_ERROR; this->m_StopConditionDescription << "UpdateTransformParameters error"; this->StopOptimization(); // Pass exception to caller throw err; } this->InvokeEvent( IterationEvent() ); } // a and c are the current bounds; the minimum is between them. // b is a center point // f(x) is some mathematical function elsewhere defined // a corresponds to x1; b corresponds to x2; c corresponds to x3 // x corresponds to x4 template<typename TInternalComputationValueType> TInternalComputationValueType GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> ::GoldenSectionSearch( TInternalComputationValueType a, TInternalComputationValueType b, TInternalComputationValueType c ) { if ( this->m_LineSearchIterations > this->m_MaximumLineSearchIterations ) { return ( c + a ) / 2; } this->m_LineSearchIterations++; TInternalComputationValueType x; if ( c - b > b - a ) { x = b + this->m_Resphi * ( c - b ); } else { x = b - this->m_Resphi * ( b - a ); } if ( std::abs( c - a ) < this->m_Epsilon * ( std::abs( b ) + std::abs( x ) ) ) { return ( c + a ) / 2; } TInternalComputationValueType metricx, metricb; { // Cache the learning rate , parameters , gradient // Contain this in a block so these variables go out of // scope before we call recursively below. With dense transforms // we would otherwise eat up a lot of memory unnecessarily. TInternalComputationValueType baseLearningRate = this->m_LearningRate; DerivativeType baseGradient( this->m_Gradient ); ParametersType baseParameters( this->GetCurrentPosition() ); this->m_LearningRate = x; this->ModifyGradientByLearningRate(); this->m_Metric->UpdateTransformParameters( this->m_Gradient ); metricx = this->GetMetric()->GetValue( ); /** reset position of transform and gradient */ this->m_Metric->SetParameters( baseParameters ); this->m_Gradient = baseGradient; this->m_LearningRate = b; this->ModifyGradientByLearningRate(); this->m_Metric->UpdateTransformParameters( this->m_Gradient ); metricb = this->GetMetric()->GetValue( ); /** reset position of transform and learning rate */ this->m_Metric->SetParameters( baseParameters ); this->m_Gradient = baseGradient; this->m_LearningRate = baseLearningRate; } /** golden section */ if ( metricx < metricb ) { if (c - b > b - a) { return this->GoldenSectionSearch( b, x, c ); } else { return this->GoldenSectionSearch( a, x, b ); } } else { if ( c - b > b - a ) { return this->GoldenSectionSearch( a, b, x ); } else if ( metricx == NumericTraits<TInternalComputationValueType>::max() ) { // Keep the lower bounds when metricx and metricb are both max, // likely due to no valid sample points, from too large of a // learning rate. return this->GoldenSectionSearch( a, x, b ); } else { return this->GoldenSectionSearch( x, b, c ); } } } }//namespace itk #endif <|endoftext|>
<commit_before><commit_msg>Answer to question 5.5 is complete and close issue #46<commit_after><|endoftext|>
<commit_before>//===- fpcmp.cpp - A fuzzy "cmp" that permits floating point noise --------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // fpcmp is a tool that basically works like the 'cmp' tool, except that it can // tolerate errors due to floating point noise, with the -r option. // //===----------------------------------------------------------------------===// #include "Support/CommandLine.h" #include "Support/FileUtilities.h" #include "Config/fcntl.h" #include "Config/sys/mman.h" #include <iostream> #include <cmath> using namespace llvm; namespace { cl::opt<std::string> File1(cl::Positional, cl::desc("<input file #1>"), cl::Required); cl::opt<std::string> File2(cl::Positional, cl::desc("<input file #2>"), cl::Required); cl::opt<double> RelTolerance("r", cl::desc("Relative error tolerated"), cl::init(0)); cl::opt<double> AbsTolerance("a", cl::desc("Absolute error tolerated"), cl::init(0)); } /// OpenFile - mmap the specified file into the address space for reading, and /// return the length and address of the buffer. static void OpenFile(const std::string &Filename, unsigned &Len, char* &BufPtr){ int FD = open(Filename.c_str(), O_RDONLY); if (FD == -1 || (Len = getFileSize(Filename)) == ~0U) { std::cerr << "Error: cannot open file '" << Filename << "'\n"; exit(2); } // mmap in the file all at once... BufPtr = (char*)mmap(0, Len, PROT_READ, MAP_PRIVATE, FD, 0); if (BufPtr == (char*)MAP_FAILED) { std::cerr << "Error: cannot open file '" << Filename << "'\n"; exit(2); } } static bool isNumberChar(char C) { switch (C) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': case '+': case '-': case 'e': case 'E': return true; default: return false; } } static char *BackupNumber(char *Pos, char *FirstChar) { while (Pos > FirstChar && isNumberChar(Pos[-1])) --Pos; return Pos; } static void CompareNumbers(char *&F1P, char *&F2P, char *F1End, char *F2End) { char *F1NumEnd, *F2NumEnd; double V1 = strtod(F1P, &F1NumEnd); double V2 = strtod(F2P, &F2NumEnd); if (F1NumEnd == F1P || F2NumEnd == F2P) { std::cerr << "Comparison failed, not a numeric difference.\n"; exit(1); } // Check to see if these are inside the absolute tolerance if (AbsTolerance < std::abs(V1-V2)) { // Nope, check the relative tolerance... double Diff; if (V2) Diff = std::abs(V1/V2 - 1.0); else if (V1) Diff = std::abs(V2/V1 - 1.0); else Diff = 0; // Both zero. if (Diff > RelTolerance) { std::cerr << "Compared: " << V1 << " and " << V2 << ": diff = " << Diff << "\n"; std::cerr << "Out of tolerance: rel/abs: " << RelTolerance << "/" << AbsTolerance << "\n"; exit(1); } } // Otherwise, advance our read pointers to the end of the numbers. F1P = F1NumEnd; F2P = F2NumEnd; } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); // mmap in the files. unsigned File1Len, File2Len; char *File1Start, *File2Start; OpenFile(File1, File1Len, File1Start); OpenFile(File2, File2Len, File2Start); // Okay, now that we opened the files, scan them for the first difference. char *File1End = File1Start+File1Len; char *File2End = File2Start+File2Len; char *F1P = File1Start; char *F2P = File2Start; while (1) { // Scan for the end of file or first difference. while (F1P < File1End && F2P < File2End && *F1P == *F2P) ++F1P, ++F2P; if (F1P >= File1End || F2P >= File2End) break; // Okay, we must have found a difference. Backup to the start of the // current number each stream is at so that we can compare from the // beginning. F1P = BackupNumber(F1P, File1Start); F2P = BackupNumber(F2P, File2Start); // Now that we are at the start of the numbers, compare them, exiting if // they don't match. CompareNumbers(F1P, F2P, File1End, File2End); } // Okay, we reached the end of file. If both files are at the end, we // succeeded. if (F1P >= File1End && F2P >= File2End) return 0; // Otherwise, we might have run off the end due to a number, backup and retry. F1P = BackupNumber(F1P, File1Start); F2P = BackupNumber(F2P, File2Start); // Now that we are at the start of the numbers, compare them, exiting if // they don't match. CompareNumbers(F1P, F2P, File1End, File2End); // If we found the end, we succeeded. if (F1P >= File1End && F2P >= File2End) return 0; return 1; } <commit_msg>mmap of a zero length file returns null on some platforms, so hack around it.<commit_after>//===- fpcmp.cpp - A fuzzy "cmp" that permits floating point noise --------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // fpcmp is a tool that basically works like the 'cmp' tool, except that it can // tolerate errors due to floating point noise, with the -r option. // //===----------------------------------------------------------------------===// #include "Support/CommandLine.h" #include "Support/FileUtilities.h" #include "Config/fcntl.h" #include "Config/sys/mman.h" #include <iostream> #include <cmath> using namespace llvm; namespace { cl::opt<std::string> File1(cl::Positional, cl::desc("<input file #1>"), cl::Required); cl::opt<std::string> File2(cl::Positional, cl::desc("<input file #2>"), cl::Required); cl::opt<double> RelTolerance("r", cl::desc("Relative error tolerated"), cl::init(0)); cl::opt<double> AbsTolerance("a", cl::desc("Absolute error tolerated"), cl::init(0)); } /// OpenFile - mmap the specified file into the address space for reading, and /// return the length and address of the buffer. static void OpenFile(const std::string &Filename, unsigned &Len, char* &BufPtr){ int FD = open(Filename.c_str(), O_RDONLY); if (FD == -1 || (Len = getFileSize(Filename)) == ~0U) { std::cerr << "Error: cannot open file '" << Filename << "'\n"; exit(2); } // mmap in the file all at once... BufPtr = (char*)mmap(0, Len, PROT_READ, MAP_PRIVATE, FD, 0); if (BufPtr == (char*)MAP_FAILED) { std::cerr << "Error: cannot open file '" << Filename << "'\n"; exit(2); } // If mmap decided that the files were empty, it might have returned a // null pointer. If so, make a new, fake pointer -- it shouldn't matter // what it contains, because Len is 0, and it should never be read. if (BufPtr == 0 && Len == 0) BufPtr = new char[1]; } static bool isNumberChar(char C) { switch (C) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': case '+': case '-': case 'e': case 'E': return true; default: return false; } } static char *BackupNumber(char *Pos, char *FirstChar) { while (Pos > FirstChar && isNumberChar(Pos[-1])) --Pos; return Pos; } static void CompareNumbers(char *&F1P, char *&F2P, char *F1End, char *F2End) { char *F1NumEnd, *F2NumEnd; double V1 = strtod(F1P, &F1NumEnd); double V2 = strtod(F2P, &F2NumEnd); if (F1NumEnd == F1P || F2NumEnd == F2P) { std::cerr << "Comparison failed, not a numeric difference.\n"; exit(1); } // Check to see if these are inside the absolute tolerance if (AbsTolerance < std::abs(V1-V2)) { // Nope, check the relative tolerance... double Diff; if (V2) Diff = std::abs(V1/V2 - 1.0); else if (V1) Diff = std::abs(V2/V1 - 1.0); else Diff = 0; // Both zero. if (Diff > RelTolerance) { std::cerr << "Compared: " << V1 << " and " << V2 << ": diff = " << Diff << "\n"; std::cerr << "Out of tolerance: rel/abs: " << RelTolerance << "/" << AbsTolerance << "\n"; exit(1); } } // Otherwise, advance our read pointers to the end of the numbers. F1P = F1NumEnd; F2P = F2NumEnd; } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); // mmap in the files. unsigned File1Len, File2Len; char *File1Start, *File2Start; OpenFile(File1, File1Len, File1Start); OpenFile(File2, File2Len, File2Start); // Okay, now that we opened the files, scan them for the first difference. char *File1End = File1Start+File1Len; char *File2End = File2Start+File2Len; char *F1P = File1Start; char *F2P = File2Start; while (1) { // Scan for the end of file or first difference. while (F1P < File1End && F2P < File2End && *F1P == *F2P) ++F1P, ++F2P; if (F1P >= File1End || F2P >= File2End) break; // Okay, we must have found a difference. Backup to the start of the // current number each stream is at so that we can compare from the // beginning. F1P = BackupNumber(F1P, File1Start); F2P = BackupNumber(F2P, File2Start); // Now that we are at the start of the numbers, compare them, exiting if // they don't match. CompareNumbers(F1P, F2P, File1End, File2End); } // Okay, we reached the end of file. If both files are at the end, we // succeeded. if (F1P >= File1End && F2P >= File2End) return 0; // Otherwise, we might have run off the end due to a number, backup and retry. F1P = BackupNumber(F1P, File1Start); F2P = BackupNumber(F2P, File2Start); // Now that we are at the start of the numbers, compare them, exiting if // they don't match. CompareNumbers(F1P, F2P, File1End, File2End); // If we found the end, we succeeded. if (F1P >= File1End && F2P >= File2End) return 0; return 1; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ik_ce.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2006-06-19 11:48:55 $ * * 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 ARY_IDL_IK_CE_HXX #define ARY_IDL_IK_CE_HXX // USED SERVICES // BASE CLASSES // COMPONENTS // PARAMETERS #include <ary/idl/i_language.hxx> #include <ary/stdconstiter.hxx> namespace ary { namespace info { class Text; } namespace idl { namespace ifc_ce { typedef ::ary::Dyn_StdConstIterator<Ce_id> Dyn_CeIterator; typedef ::ary::Dyn_StdConstIterator<Type_id> Dyn_TypeIterator; typedef ::ary::info::Text DocText; struct attr { static Ce_id CeId( const CodeEntity & i_ce ); static const String & LocalName( const CodeEntity & i_ce ); static Ce_id NameRoom( const CodeEntity & i_ce ); static Rid Owner( const CodeEntity & i_ce ); static E_SightLevel SightLevel( const CodeEntity & i_ce ); static bool Search_Member( const CodeEntity & , const String & ) { return true; } // KORR_FUTURE }; struct xref { }; struct doc { static const DocText & ShortInfo( /// @return a short description of the CodeEntity const CodeEntity & i_ce ); static const DocText & TagAuthor( const CodeEntity & i_ce ); static const DocText & TagExample( const CodeEntity & i_ce ); static const DocText & TagDescr( const CodeEntity & i_ce ); static const DocText & TagGuarantees( const CodeEntity & i_ce ); static const DocText & TagKey( const CodeEntity & i_ce ); static const DocText & TagMissing( const CodeEntity & i_ce ); static const DocText & TagSee( const CodeEntity & i_ce ); static const DocText & TagShort( const CodeEntity & i_ce ); static const DocText & TagVersion( const CodeEntity & i_ce ); void Get_UnkownTags( Dyn_CeIterator & o_result, const CodeEntity & i_ce ); bool IsDeprecated( const CodeEntity & i_ce ); bool IsIncomplete( const CodeEntity & i_ce ); bool IsInternal( const CodeEntity & i_ce ); bool IsNodoc( const CodeEntity & i_ce ); bool IsOptional( const CodeEntity & i_ce ); bool IsSuspicious( const CodeEntity & i_ce ); }; } // namespace ifc_ce } // namspace idl } // namspace ary #endif <commit_msg>INTEGRATION: CWS adc18 (1.3.32); FILE MERGED 2007/10/18 13:06:37 np 1.3.32.1: #i81775#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ik_ce.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2007-11-02 15:13:20 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef ARY_IDL_IK_CE_HXX #define ARY_IDL_IK_CE_HXX // KORR_DEPRECATED_3.0 // USED SERVICES // BASE CLASSES // COMPONENTS // PARAMETERS #include <ary/idl/i_types4idl.hxx> #include <ary/stdconstiter.hxx> namespace ary { namespace info { class Text; } namespace idl { namespace ifc_ce { typedef ::ary::Dyn_StdConstIterator<Ce_id> Dyn_CeIterator; typedef ::ary::Dyn_StdConstIterator<Type_id> Dyn_TypeIterator; typedef ::ary::info::Text DocText; struct attr { static Ce_id CeId( const CodeEntity & i_ce ); static const String & LocalName( const CodeEntity & i_ce ); static Ce_id NameRoom( const CodeEntity & i_ce ); static Rid Owner( const CodeEntity & i_ce ); static E_SightLevel SightLevel( const CodeEntity & i_ce ); static bool Search_Member( const CodeEntity & , const String & ) { return true; } // KORR_FUTURE }; struct xref { }; struct doc { static const DocText & ShortInfo( /// @return a short description of the CodeEntity const CodeEntity & i_ce ); static const DocText & TagAuthor( const CodeEntity & i_ce ); static const DocText & TagExample( const CodeEntity & i_ce ); static const DocText & TagDescr( const CodeEntity & i_ce ); static const DocText & TagGuarantees( const CodeEntity & i_ce ); static const DocText & TagKey( const CodeEntity & i_ce ); static const DocText & TagMissing( const CodeEntity & i_ce ); static const DocText & TagSee( const CodeEntity & i_ce ); static const DocText & TagShort( const CodeEntity & i_ce ); static const DocText & TagVersion( const CodeEntity & i_ce ); void Get_UnkownTags( Dyn_CeIterator & o_result, const CodeEntity & i_ce ); bool IsDeprecated( const CodeEntity & i_ce ); bool IsIncomplete( const CodeEntity & i_ce ); bool IsInternal( const CodeEntity & i_ce ); bool IsNodoc( const CodeEntity & i_ce ); bool IsOptional( const CodeEntity & i_ce ); bool IsSuspicious( const CodeEntity & i_ce ); }; } // namespace ifc_ce } // namspace idl } // namspace ary #endif <|endoftext|>
<commit_before>//---------------------------- vertex_as_face_05.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2010 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- vertex_as_face_05.cc --------------------------- // verify that we can do things like cell->face() in 1d as well. here: // test DoFHandler accessors for the same thing as the _01 test #include "../tests.h" #include <grid/tria.h> #include <grid/tria_iterator.h> #include <grid/tria_accessor.h> #include <grid/grid_generator.h> #include <fe/fe_system.h> #include <fe/fe_q.h> #include <dofs/dof_handler.h> #include <dofs/dof_accessor.h> #include <fstream> template <int spacedim> void test () { Triangulation<1,spacedim> tria; GridGenerator::hyper_cube (tria); FESystem<1,spacedim> fe(FE_Q<1,spacedim>(2),2, FE_Q<1,spacedim>(1),1); DoFHandler<1,spacedim> dof_handler (tria); dof_handler.distribute_dofs (fe); deallog << "Coarse mesh:" << std::endl; deallog << "Left vertex=" << dof_handler.begin_active()->face(0)->vertex(0) << std::endl; deallog << "Right vertex=" << dof_handler.begin_active()->face(1)->vertex(0) << std::endl; tria.refine_global (2); dof_handler.distribute_dofs (fe); for (typename Triangulation<1,spacedim>::active_cell_iterator cell = dof_handler.begin_active(); cell != dof_handler.end(); ++cell) { deallog << "Cell: " << cell << std::endl; deallog << "Left vertex=" << cell->face(0)->vertex(0) << std::endl; deallog << "Right vertex=" << cell->face(1)->vertex(0) << std::endl; } } int main () { std::ofstream logfile("vertex_as_face_05/output"); deallog.attach(logfile); deallog.depth_console(0); test<1> (); test<2> (); return 0; } <commit_msg>Fix type of iterator.<commit_after>//---------------------------- vertex_as_face_05.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2010 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- vertex_as_face_05.cc --------------------------- // verify that we can do things like cell->face() in 1d as well. here: // test DoFHandler accessors for the same thing as the _01 test #include "../tests.h" #include <grid/tria.h> #include <grid/tria_iterator.h> #include <grid/tria_accessor.h> #include <grid/grid_generator.h> #include <fe/fe_system.h> #include <fe/fe_q.h> #include <dofs/dof_handler.h> #include <dofs/dof_accessor.h> #include <fstream> template <int spacedim> void test () { Triangulation<1,spacedim> tria; GridGenerator::hyper_cube (tria); FESystem<1,spacedim> fe(FE_Q<1,spacedim>(2),2, FE_Q<1,spacedim>(1),1); DoFHandler<1,spacedim> dof_handler (tria); dof_handler.distribute_dofs (fe); deallog << "Coarse mesh:" << std::endl; deallog << "Left vertex=" << dof_handler.begin_active()->face(0)->vertex(0) << std::endl; deallog << "Right vertex=" << dof_handler.begin_active()->face(1)->vertex(0) << std::endl; tria.refine_global (2); dof_handler.distribute_dofs (fe); for (typename DoFHandler<1,spacedim>::active_cell_iterator cell = dof_handler.begin_active(); cell != dof_handler.end(); ++cell) { deallog << "Cell: " << cell << std::endl; deallog << "Left vertex=" << cell->face(0)->vertex(0) << std::endl; deallog << "Right vertex=" << cell->face(1)->vertex(0) << std::endl; } } int main () { std::ofstream logfile("vertex_as_face_05/output"); deallog.attach(logfile); deallog.depth_console(0); test<1> (); test<2> (); return 0; } <|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the Avogadro project. Copyright 2013 Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "gromacsformat.h" #include <avogadro/core/avogadrocore.h> #include <avogadro/core/atom.h> #include <avogadro/core/matrix.h> #include <avogadro/core/molecule.h> #include <avogadro/core/unitcell.h> #include <avogadro/core/utilities.h> #include <string> #include <utility> using Avogadro::Core::Atom; using Avogadro::Core::Molecule; using Avogadro::Core::UnitCell; using Avogadro::Core::lexicalCast; using Avogadro::Core::trimmed; using Avogadro::Core::split; namespace Avogadro { namespace Io { GromacsFormat::GromacsFormat() { } GromacsFormat::~GromacsFormat() { } std::vector<std::string> GromacsFormat::fileExtensions() const { return std::vector<std::string>(1, std::string("gro")); } std::vector<std::string> GromacsFormat::mimeTypes() const { return std::vector<std::string>(1, std::string("chemical/x-gro")); } bool GromacsFormat::read(std::istream &in, Molecule &molecule) { std::string buffer; std::string value; // Title std::getline(in, buffer); if (!buffer.empty()) molecule.setData("name", trimmed(buffer)); // Atom count std::getline(in, buffer); buffer = trimmed(buffer); bool ok; size_t numAtoms = lexicalCast<size_t>(buffer, ok); if (buffer.empty() || !ok) { appendError("Number of atoms (line 2) invalid."); return false; } // read atom info: typedef std::map<std::string, unsigned char> AtomTypeMap; AtomTypeMap atomTypes; unsigned char customElementCounter = CustomElementMin; Vector3 pos; while (numAtoms-- > 0) { std::getline(in, buffer); if (buffer.size() < 44) { appendError("Error reading atom specification -- line too short: " + buffer); return false; } // Format of buffer is: (all indices start at 1) // Offset: 0 format: %5i value: Residue number // Offset: 5 format: %-5s value: Residue name // Offset: 10 format: %5s value: Atom name // Offset: 15 format: %5i value: Atom number // Offset: 20 format: %8.3f value: x coordinate (nm) // Offset: 28 format: %8.3f value: y coordinate (nm) // Offset: 36 format: %8.3f value: z coordinate (nm) // Offset: 44 format: %8.4f value: x velocity (nm/ps, a.k.a. km/s) // Offset: 52 format: %8.4f value: y velocity (nm/ps, a.k.a. km/s) // Offset: 60 format: %8.4f value: z velocity (nm/ps, a.k.a. km/s) // Atom name: value = trimmed(buffer.substr(10, 5)); AtomTypeMap::const_iterator it = atomTypes.find(value); if (it == atomTypes.end()) { atomTypes.insert(std::make_pair(value, customElementCounter++)); it = atomTypes.find(value); if (customElementCounter > CustomElementMax) { appendError("Custom element type limit exceeded."); return false; } } Atom atom = molecule.addAtom(it->second); // Coords for (int i = 0; i < 3; ++i) { value = trimmed(buffer.substr(20 + i * 8, 8)); pos[i] = lexicalCast<Real>(value, ok); if (!ok || value.empty()) { appendError("Error reading atom specification -- invalid coordinate: '" + buffer + "' (bad coord: '" + value + "')"); return false; } } atom.setPosition3d(pos * static_cast<Real>(10.0)); // nm --> Angstrom } // Set the custom element map if needed: if (!atomTypes.empty()) { Molecule::CustomElementMap elementMap; for (AtomTypeMap::const_iterator it = atomTypes.begin(), itEnd = atomTypes.end(); it != itEnd; ++it) { elementMap.insert(std::make_pair(it->second, it->first)); } molecule.setCustomElementMap(elementMap); } // Box description: // v1(x) v2(y) v3(z) [v1(y) v1(z) v2(x) v2(z) v3(x) v3(y)] // The last six values may be omitted, set all non-specified values to 0. // v1(y) == v1(z) == v2(z) == 0 always. std::getline(in, buffer); std::vector<std::string> tokens(split(buffer, ' ', true)); if (tokens.size() > 0) { if (tokens.size() != 3 && tokens.size() != 9) { appendError("Invalid box specification -- need either 3 or 9 values: '" + buffer + "'"); return false; } // Index arrays for parsing loop: const int rows[] = {0, 1, 2, 1, 2, 0, 2, 0, 1}; const int cols[] = {0, 1, 2, 0, 0, 1, 1, 2, 2}; Matrix3 cellMatrix = Matrix3::Zero(); for (size_t i = 0; i < tokens.size(); ++i) { cellMatrix(rows[i], cols[i]) = lexicalCast<Real>(tokens[i], ok); if (!ok || tokens[i].empty()) { appendError("Invalid box specification -- bad value: '" + tokens[i] + "'"); return false; } } UnitCell *cell = new UnitCell; cell->setCellMatrix(cellMatrix * static_cast<Real>(10)); // nm --> Angstrom molecule.setUnitCell(cell); } return true; } bool GromacsFormat::write(std::ostream &, const Core::Molecule &) { return false; } } // namespace Io } // namespace Avogadro <commit_msg>Added some code to deal with variable decimal places<commit_after>/****************************************************************************** This source file is part of the Avogadro project. Copyright 2013 Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "gromacsformat.h" #include <avogadro/core/avogadrocore.h> #include <avogadro/core/atom.h> #include <avogadro/core/matrix.h> #include <avogadro/core/molecule.h> #include <avogadro/core/unitcell.h> #include <avogadro/core/utilities.h> #include <iostream> #include <string> #include <utility> namespace Avogadro { namespace Io { using Core::Atom; using Core::Molecule; using Core::UnitCell; using Core::lexicalCast; using Core::trimmed; using Core::split; using std::string; using std::getline; using std::map; using std::vector; GromacsFormat::GromacsFormat() { } GromacsFormat::~GromacsFormat() { } std::vector<std::string> GromacsFormat::fileExtensions() const { return std::vector<std::string>(1, std::string("gro")); } std::vector<std::string> GromacsFormat::mimeTypes() const { return std::vector<std::string>(1, std::string("chemical/x-gro")); } bool GromacsFormat::read(std::istream &in, Molecule &molecule) { string buffer; string value; // Title getline(in, buffer); if (!buffer.empty()) molecule.setData("name", trimmed(buffer)); // Atom count getline(in, buffer); buffer = trimmed(buffer); bool ok; size_t numAtoms = lexicalCast<size_t>(buffer, ok); if (buffer.empty() || !ok) { appendError("Number of atoms (line 2) invalid."); return false; } // read atom info: typedef map<string, unsigned char> AtomTypeMap; AtomTypeMap atomTypes; unsigned char customElementCounter = CustomElementMin; Vector3 pos; while (numAtoms-- > 0) { getline(in, buffer); // Figure out the distance between decimal points, implement support for // variable precision as specified: // "any number of decimal places, the format will then be n+5 positions with // n decimal places (n+1 for velocities) in stead of 8 with 3 (with 4 for // velocities)". size_t decimal1 = buffer.find(".", 20); size_t decimal2 = string::npos; int decimalSep = 0; if (decimal1 != string::npos) decimal2 = buffer.find(".", decimal1 + 1); if (decimal2 != string::npos) decimalSep = decimal2 - decimal1; if (decimalSep == 0) { appendError("Decimal separation of 0 found in atom positions: " + buffer); return false; } if (buffer.size() < static_cast<size_t>(20 + 3 * decimalSep)) { appendError("Error reading atom specification -- line too short: " + buffer); return false; } // Format of buffer is: (all indices start at 1, variable dp throws this). // Offset: 0 format: %5i value: Residue number // Offset: 5 format: %-5s value: Residue name // Offset: 10 format: %5s value: Atom name // Offset: 15 format: %5i value: Atom number // Offset: 20 format: %8.3f value: x coordinate (nm) // Offset: 28 format: %8.3f value: y coordinate (nm) // Offset: 36 format: %8.3f value: z coordinate (nm) // Offset: 44 format: %8.4f value: x velocity (nm/ps, a.k.a. km/s) // Offset: 52 format: %8.4f value: y velocity (nm/ps, a.k.a. km/s) // Offset: 60 format: %8.4f value: z velocity (nm/ps, a.k.a. km/s) // Atom name: value = trimmed(buffer.substr(10, 5)); AtomTypeMap::const_iterator it = atomTypes.find(value); if (it == atomTypes.end()) { atomTypes.insert(std::make_pair(value, customElementCounter++)); it = atomTypes.find(value); if (customElementCounter > CustomElementMax) { appendError("Custom element type limit exceeded."); return false; } } Atom atom = molecule.addAtom(it->second); // Coords for (int i = 0; i < 3; ++i) { value = trimmed(buffer.substr(20 + i * decimalSep, decimalSep)); pos[i] = lexicalCast<Real>(value, ok); if (!ok || value.empty()) { appendError("Error reading atom specification -- invalid coordinate: '" + buffer + "' (bad coord: '" + value + "')"); return false; } } atom.setPosition3d(pos * static_cast<Real>(10.0)); // nm --> Angstrom } // Set the custom element map if needed: if (!atomTypes.empty()) { Molecule::CustomElementMap elementMap; for (AtomTypeMap::const_iterator it = atomTypes.begin(), itEnd = atomTypes.end(); it != itEnd; ++it) { elementMap.insert(std::make_pair(it->second, it->first)); } molecule.setCustomElementMap(elementMap); } // Box description: // v1(x) v2(y) v3(z) [v1(y) v1(z) v2(x) v2(z) v3(x) v3(y)] // The last six values may be omitted, set all non-specified values to 0. // v1(y) == v1(z) == v2(z) == 0 always. getline(in, buffer); vector<string> tokens(split(buffer, ' ', true)); if (tokens.size() > 0) { if (tokens.size() != 3 && tokens.size() != 9) { appendError("Invalid box specification -- need either 3 or 9 values: '" + buffer + "'"); return false; } // Index arrays for parsing loop: const int rows[] = {0, 1, 2, 1, 2, 0, 2, 0, 1}; const int cols[] = {0, 1, 2, 0, 0, 1, 1, 2, 2}; Matrix3 cellMatrix = Matrix3::Zero(); for (size_t i = 0; i < tokens.size(); ++i) { cellMatrix(rows[i], cols[i]) = lexicalCast<Real>(tokens[i], ok); if (!ok || tokens[i].empty()) { appendError("Invalid box specification -- bad value: '" + tokens[i] + "'"); return false; } } UnitCell *cell = new UnitCell; cell->setCellMatrix(cellMatrix * static_cast<Real>(10)); // nm --> Angstrom molecule.setUnitCell(cell); } return true; } bool GromacsFormat::write(std::ostream &, const Core::Molecule &) { return false; } } // namespace Io } // namespace Avogadro <|endoftext|>
<commit_before>#include <stdio.h> #include <sys/time.h> #include <iostream> #include <sstream> #include <fstream> #include <vector> #include <deque> #include <unordered_map> #include <algorithm> #include <omp.h> // Typedef for our primary data types typedef std::vector<std::string> pages_t; typedef std::unordered_map<std::string, int> page_ids_t; typedef std::unordered_map<int,std::vector<int>> page_links_t; /* Load in the page titles and page ids from a file. * * Each line of the file will represent the page ID, starting from line 1 until * the end of the file. The page titles will be stored into the pages vector. * The page titles => ids will be stored in the page_ids map * * Returns: The total number of pages loaded */ int load_page_titles(const std::string &file_path, pages_t &pages, page_ids_t &page_ids) { std::ifstream page_titles_file(file_path); std::string page_name; // We won't be using the first index of the vector for anything since // the page_id indexes start at 1 instead of 0. This should help to // prevent any errors during development pages.push_back(""); // Read the page name into the vector and into the hash-map int index = 1; while (std::getline(page_titles_file, page_name)) { pages.push_back(page_name); page_ids[page_name] = index++; } return index - 1; } /* Load in the page links from a file. * * Each line of the file should start with a page_id that represents a page, it * should then follow with a colon (':'). All numbers after the colon represent * page_ids that that page links to. * * Read all page links into the page_links hash map, where the key is the * page_id and the value is a vector of page_ids the page links to. * * Returns: The total number of links loaded */ int load_page_links(const std::string &file_path, page_links_t &page_links) { std::ifstream page_links_file(file_path); std::string link_id; int current_link = 0; int total_links = 0; while (page_links_file >> link_id) { if (link_id.back() == ':') { current_link = atoi(link_id.c_str()); } else { page_links[current_link].push_back(atoi(link_id.c_str())); total_links++; } } return total_links; } /* Given a hash map containing page_ids that represent a path back to a given * root node extract those Ids and order them so that we move from the root node * back to the tail_id. * * The root node is the node whos parent value is -1. * * Returns: A vector containing the page ids of the path in order. */ std::vector<int> path_from_parents(std::unordered_map<int, int> &parent_links, int target_id) { int current = target_id; std::vector<int> target_path; // Only fill the target_path vector if we have a parent link chain if (parent_links[target_id]) { // Traverse thrugh the parent_links till we reach the root node do { target_path.push_back(current); } while ((current = parent_links[current]) != -1); // Reverse the target path list to be in proper order std::reverse(target_path.begin(), target_path.end()); } return target_path; } /* Calculate the shortest path between two page_ids in the page links graph. * This uses the Depth First Search algorithm to travers through each of the * child nodes looking to see if they are the target id. If none are, then we * will traverse through all their children, up until we can find the target id. * * Returns: See the return value of `path_from_parents`. */ std::vector<int> path_between_pages(page_links_t &page_links, int start_id, int target_id) { // Keep track of parent nodes so we can traverse back through the path std::unordered_map<int, int> parent_links; // The starting node will always be considered 'visited' parent_links[start_id] = -1; // Queue of the current nodes to look at std::deque<int> current_nodes; current_nodes.push_back(start_id); bool found_target = false; // Search until we find our target node while ( ! found_target && ! current_nodes.empty()) { int available_nodes = current_nodes.size(); #pragma omp parallel for for (int i = 0; i < available_nodes; ++i) { // Since we can't break out of parallelize loops we just need to // finish off what evers left by continuing through them all #pragma omp flush (found_target) if (found_target) continue; int current; #pragma omp critical { current = current_nodes.front(); current_nodes.pop_front(); } // Iterate through all linked pages for (int page_id : page_links[current]) { // Keep track of how we traveled to this node #pragma omp critical if (parent_links[page_id] == 0) { parent_links[page_id] = current; if (target_id == page_id) { found_target = true; #pragma omp flush (found_target) } else { current_nodes.push_back(page_id); } } } } } return path_from_parents(parent_links, target_id); } int main(int argc, char* argv[]) { if (argc != 5) { std::cerr << "Path Finder only accepts 4 arguments\n"; exit(1); } // Used to store a list of page titles. Each index represents a page title pages_t pages; // Used to reverse lookup a page ID by it's title page_ids_t page_ids; // Used to store a list of page_ids that a given page_id links to page_links_t page_links; // Load in all page titles into a vector std::cout << "\033[92m==>\033[0m Reading in page titles as a vector & map\n"; { struct timeval start, end; gettimeofday(&start, 0); int total = load_page_titles(std::string(argv[1]), pages, page_ids); gettimeofday(&end, 0); double duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6; std::cout << "\033[94m -> \033[0mRead in " << total << " page titles\n"; std::cout << "\033[94m -> \033[0mTook " << duration << " seconds\n"; } // Load in all page links into a hash map std::cout << "\033[92m==>\033[0m Reading in page links as a map\n"; { struct timeval start, end; gettimeofday(&start, 0); int total = load_page_links(std::string(argv[2]), page_links); gettimeofday(&end, 0); double duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6; std::cout << "\033[94m -> \033[0mRead in " << total << " page links\n"; std::cout << "\033[94m -> \033[0mTook " << duration << " seconds\n"; } std::cout << "\033[92m==>\033[0m Beginning BFS on Wikipedia graph\n"; // Get the ID's of the start and target nodes int start_id = page_ids[argv[3]], target_id = page_ids[argv[4]]; if (start_id == target_id) { std::cout << "\n\033[92mNo clicks required. The page is the same!\n"; } std::vector<int> target_path; struct timeval start, end; gettimeofday(&start, 0); target_path = path_between_pages(page_links, start_id, target_id); gettimeofday(&end, 0); double duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6; std::cout << "\033[94m -> \033[0mTook " << duration << " seconds\n\n"; // Print out the path between the pages for (int page_id : target_path) { std::cout << " * " << pages[page_id] << '\n'; } return 0; } <commit_msg>Get data paths from relative bin location<commit_after>#include <stdio.h> #include <unistd.h> #include <libgen.h> #include <sys/time.h> #include <omp.h> #include <iostream> #include <sstream> #include <fstream> #include <vector> #include <deque> #include <unordered_map> #include <algorithm> // Typedef for our primary data types typedef std::vector<std::string> pages_t; typedef std::unordered_map<std::string, int> page_ids_t; typedef std::unordered_map<int,std::vector<int>> page_links_t; /* Load in the page titles and page ids from a file. * * Each line of the file will represent the page ID, starting from line 1 until * the end of the file. The page titles will be stored into the pages vector. * The page titles => ids will be stored in the page_ids map * * Returns: The total number of pages loaded */ int load_page_titles(const std::string &file_path, pages_t &pages, page_ids_t &page_ids) { std::ifstream page_titles_file(file_path); std::string page_name; // We won't be using the first index of the vector for anything since // the page_id indexes start at 1 instead of 0. This should help to // prevent any errors during development pages.push_back(""); // Read the page name into the vector and into the hash-map int index = 1; while (std::getline(page_titles_file, page_name)) { pages.push_back(page_name); page_ids[page_name] = index++; } return index - 1; } /* Load in the page links from a file. * * Each line of the file should start with a page_id that represents a page, it * should then follow with a colon (':'). All numbers after the colon represent * page_ids that that page links to. * * Read all page links into the page_links hash map, where the key is the * page_id and the value is a vector of page_ids the page links to. * * Returns: The total number of links loaded */ int load_page_links(const std::string &file_path, page_links_t &page_links) { std::ifstream page_links_file(file_path); std::string link_id; int current_link = 0; int total_links = 0; while (page_links_file >> link_id) { if (link_id.back() == ':') { current_link = atoi(link_id.c_str()); } else { page_links[current_link].push_back(atoi(link_id.c_str())); total_links++; } } return total_links; } /* Given a hash map containing page_ids that represent a path back to a given * root node extract those Ids and order them so that we move from the root node * back to the tail_id. * * The root node is the node whos parent value is -1. * * Returns: A vector containing the page ids of the path in order. */ std::vector<int> path_from_parents(std::unordered_map<int, int> &parent_links, int target_id) { int current = target_id; std::vector<int> target_path; // Only fill the target_path vector if we have a parent link chain if (parent_links[target_id]) { // Traverse thrugh the parent_links till we reach the root node do { target_path.push_back(current); } while ((current = parent_links[current]) != -1); // Reverse the target path list to be in proper order std::reverse(target_path.begin(), target_path.end()); } return target_path; } /* Calculate the shortest path between two page_ids in the page links graph. * This uses the Depth First Search algorithm to travers through each of the * child nodes looking to see if they are the target id. If none are, then we * will traverse through all their children, up until we can find the target id. * * Returns: See the return value of `path_from_parents`. */ std::vector<int> path_between_pages(page_links_t &page_links, int start_id, int target_id) { // Keep track of parent nodes so we can traverse back through the path std::unordered_map<int, int> parent_links; // The starting node will always be considered 'visited' parent_links[start_id] = -1; // Queue of the current nodes to look at std::deque<int> current_nodes; current_nodes.push_back(start_id); bool found_target = false; // Search until we find our target node while ( ! found_target && ! current_nodes.empty()) { int available_nodes = current_nodes.size(); #pragma omp parallel for for (int i = 0; i < available_nodes; ++i) { // Since we can't break out of parallelize loops we just need to // finish off what evers left by continuing through them all #pragma omp flush (found_target) if (found_target) continue; int current; #pragma omp critical { current = current_nodes.front(); current_nodes.pop_front(); } // Iterate through all linked pages for (int page_id : page_links[current]) { // Keep track of how we traveled to this node #pragma omp critical if (parent_links[page_id] == 0) { parent_links[page_id] = current; if (target_id == page_id) { found_target = true; #pragma omp flush (found_target) } else { current_nodes.push_back(page_id); } } } } } return path_from_parents(parent_links, target_id); } int main(int argc, char* argv[]) { // Used to store a list of page titles. Each index represents a page title pages_t pages; // Used to reverse lookup a page ID by it's title page_ids_t page_ids; // Used to store a list of page_ids that a given page_id links to page_links_t page_links; std::cout << "Welcome to Six-Degrees-of-Wikipedia path finder\n" << "Please while we load Wikipedia into memory.\n\n"; // Determine the base directory path char path_buffer[1024]; readlink("/proc/self/exe", path_buffer, sizeof(path_buffer) - 1); std::string base_path = std::string(dirname(path_buffer)) + "/../"; // Load in all page titles into a vector std::cout << "\033[92m==>\033[0m Reading in page titles as a vector & map\n"; { struct timeval start, end; gettimeofday(&start, 0); int total = load_page_titles(base_path + "data/titles-sorted", pages, page_ids); gettimeofday(&end, 0); double duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6; std::cout << "\033[94m -> \033[0mRead in " << total << " page titles\n"; std::cout << "\033[94m -> \033[0mTook " << duration << " seconds\n"; } // Load in all page links into a hash map std::cout << "\033[92m==>\033[0m Reading in page links as a map\n"; { struct timeval start, end; gettimeofday(&start, 0); int total = load_page_links(base_path + "data/links-simple-sorted", page_links); gettimeofday(&end, 0); double duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6; std::cout << "\033[94m -> \033[0mRead in " << total << " page links\n"; std::cout << "\033[94m -> \033[0mTook " << duration << " seconds\n"; } std::cout << "\033[92m==>\033[0m Beginning BFS on Wikipedia graph\n"; // Get the ID's of the start and target nodes int start_id = page_ids[argv[3]], target_id = page_ids[argv[4]]; if (start_id == target_id) { std::cout << "\n\033[92mNo clicks required. The page is the same!\n"; } std::vector<int> target_path; struct timeval start, end; gettimeofday(&start, 0); target_path = path_between_pages(page_links, start_id, target_id); gettimeofday(&end, 0); double duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6; std::cout << "\033[94m -> \033[0mTook " << duration << " seconds\n\n"; // Print out the path between the pages for (int page_id : target_path) { std::cout << " * " << pages[page_id] << '\n'; } return 0; } <|endoftext|>
<commit_before>#include <stdio.h> #include <unistd.h> #include <libgen.h> #include <sys/time.h> #include <omp.h> #include <iostream> #include <sstream> #include <fstream> #include <vector> #include <deque> #include <unordered_map> #include <algorithm> // Typedef for our primary data types typedef std::vector<std::string> pages_t; typedef std::unordered_map<std::string, int> page_ids_t; typedef std::unordered_map<int,std::vector<int>> page_links_t; /* Load in the page titles and page ids from a file. * * Each line of the file will represent the page ID, starting from line 1 until * the end of the file. The page titles will be stored into the pages vector. * The page titles => ids will be stored in the page_ids map * * Returns: The total number of pages loaded */ int load_page_titles(const std::string &file_path, pages_t &pages, page_ids_t &page_ids) { std::ifstream page_titles_file(file_path); std::string page_name; // We won't be using the first index of the vector for anything since // the page_id indexes start at 1 instead of 0. This should help to // prevent any errors during development pages.push_back(""); // Read the page name into the vector and into the hash-map int index = 1; while (std::getline(page_titles_file, page_name)) { pages.push_back(page_name); page_ids[page_name] = index++; } return index - 1; } /* Load in the page links from a file. * * Each line of the file should start with a page_id that represents a page, it * should then follow with a colon (':'). All numbers after the colon represent * page_ids that that page links to. * * Read all page links into the page_links hash map, where the key is the * page_id and the value is a vector of page_ids the page links to. * * Returns: The total number of links loaded */ int load_page_links(const std::string &file_path, page_links_t &page_links) { std::ifstream page_links_file(file_path); std::string link_id; int current_link = 0; int total_links = 0; while (page_links_file >> link_id) { if (link_id.back() == ':') { current_link = atoi(link_id.c_str()); } else { page_links[current_link].push_back(atoi(link_id.c_str())); total_links++; } } return total_links; } /* Given a hash map containing page_ids that represent a path back to a given * root node extract those Ids and order them so that we move from the root node * back to the tail_id. * * The root node is the node whos parent value is -1. * * Returns: A vector containing the page ids of the path in order. */ std::vector<int> path_from_parents(std::unordered_map<int, int> &parent_links, int target_id) { int current = target_id; std::vector<int> target_path; // Only fill the target_path vector if we have a parent link chain if (parent_links[target_id]) { // Traverse thrugh the parent_links till we reach the root node do { target_path.push_back(current); } while ((current = parent_links[current]) != -1); // Reverse the target path list to be in proper order std::reverse(target_path.begin(), target_path.end()); } return target_path; } /* Calculate the shortest path between two page_ids in the page links graph. * This uses the Depth First Search algorithm to travers through each of the * child nodes looking to see if they are the target id. If none are, then we * will traverse through all their children, up until we can find the target id. * * Returns: See the return value of `path_from_parents`. */ std::vector<int> path_between_pages(page_links_t &page_links, int start_id, int target_id) { // Keep track of parent nodes so we can traverse back through the path std::unordered_map<int, int> parent_links; // The starting node will always be considered 'visited' parent_links[start_id] = -1; // Queue of the current nodes to look at std::deque<int> current_nodes; current_nodes.push_back(start_id); bool found_target = false; // Search until we find our target node while ( ! found_target && ! current_nodes.empty()) { int available_nodes = current_nodes.size(); #pragma omp parallel for for (int i = 0; i < available_nodes; ++i) { // Since we can't break out of parallelize loops we just need to // finish off what evers left by continuing through them all #pragma omp flush (found_target) if (found_target) continue; int current; #pragma omp critical { current = current_nodes.front(); current_nodes.pop_front(); } // Iterate through all linked pages for (int page_id : page_links[current]) { // Keep track of how we traveled to this node #pragma omp critical if (parent_links[page_id] == 0) { parent_links[page_id] = current; if (target_id == page_id) { found_target = true; #pragma omp flush (found_target) } else { current_nodes.push_back(page_id); } } } } } return path_from_parents(parent_links, target_id); } /* Use the external python searcher script to find a given page by a search term * and output the resulting page name. * * Returns: Valid Wikipedia page name, or an empty string if one cannot be found */ std::string search_for_page(const std::string &py_searcher_bin, const std::string &search) { FILE *pipe = popen((py_searcher_bin + " \"" + search + "\"").c_str(), "r"); char buffer[255]; std::string page_name = ""; while ( ! feof(pipe)) { if (fgets(buffer, 255, pipe) != NULL) { page_name += buffer; } } return page_name; } std::string pretty_print_path(const std::vector<int> &path_ids, const pages_t &pages) { std::string path = ""; int left_padding = 2; for (int page_id : path_ids) { std::string page_title = pages[page_id]; std::string left_pad = std::string(left_padding, ' '); path += left_pad + page_title + '\n'; if (pages[page_id] != pages[path_ids.size() - 1]) { path += left_pad + "↓\n"; } } return path; } /* Kick off the main process: * * 1. Load in all of the wikipedia pages and page links into memory as a vector * and hash map. Do this in parallel if possible * 2. Begin reading user input for what pages they would like to path find * 3. Use an external python script to get the page names from wikis search * 4. Path find using the BFS algorithm (again, in parallel) * 5. Repeat 2 */ int main(int argc, char* argv[]) { // Used to store a list of page titles. Each index represents a page title pages_t pages; // Used to reverse lookup a page ID by it's title page_ids_t page_ids; // Used to store a list of page_ids that a given page_id links to page_links_t page_links; std::cout << "Welcome to Six-Degrees-of-Wikipedia path finder\n" << "Please while we load Wikipedia into memory.\n\n"; // Determine the base directory path char path_buffer[1024]; readlink("/proc/self/exe", path_buffer, sizeof(path_buffer) - 1); std::string base_path = std::string(dirname(path_buffer)) + "/../"; #pragma omp parallel sections { // Load in all data, in parallel std::cout << "\033[32m==>\033[0m Loading in page titles and page links\n"; #pragma omp section { struct timeval start, end; gettimeofday(&start, 0); int total = load_page_titles(base_path + "data/titles-sorted", pages, page_ids); gettimeofday(&end, 0); double duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6; std::cout << "\033[34m -> \033[0mRead in " << total << " page titles\n"; std::cout << "\033[34m -> \033[0mTook " << duration << " seconds\n"; } #pragma omp section { struct timeval start, end; gettimeofday(&start, 0); int total = load_page_links(base_path + "data/links-simple-sorted", page_links); gettimeofday(&end, 0); double duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6; std::cout << "\033[34m -> \033[0mRead in " << total << " page links\n"; std::cout << "\033[34m -> \033[0mTook " << duration << " seconds\n"; } } std::cout << "\033[32m==>\033[0m Wikipedia graph loaded! Ready to path find!\n\n"; while (true) { std::string start_page, target_page; std::cout << "Start Wikipedia Page: "; std::getline(std::cin, start_page); std::cout << "Target Wikipedia Page: "; std::getline(std::cin, target_page); // Use the the wiki_search.py script to lookup the wikipedia article name std::cout << "\n\033[32m==>\033[0m Looking up pages through Wikipedia search API\n"; start_page = search_for_page(base_path + "bin/wiki_search.py", start_page); target_page = search_for_page(base_path + "bin/wiki_search.py", target_page); // Ensure both pages exist if (start_page == "") { std::cout << "\033[31m==>\033[0m Start page is not a valid Wikipedia page\n\n"; continue; } if (target_page == "") { std::cout << "\033[31m==>\033[0m Target page is not a valid Wikipedia page\n\n"; continue; } // Remove newline from page names start_page.pop_back(); target_page.pop_back(); // Locate page Ids int start_id = page_ids[start_page], target_id = page_ids[target_page]; // Begin search std::cout << "\033[32m==>\033[0m Finding path from \033[35m" << start_page << "\033[0m → \033[34m" << target_page << "\033[0m\n"; std::vector<int> target_path; struct timeval start, end; gettimeofday(&start, 0); target_path = path_between_pages(page_links, start_id, target_id); gettimeofday(&end, 0); double duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6; std::cout << "\033[34m -> \033[0mFound path in \033[32m" << target_path.size() -1 << " clicks\033[0m\n"; std::cout << "\033[34m -> \033[0mTook " << duration << " seconds\n\n"; // Pretty print the page path for (int page_id : target_path) { std::cout << " \033[34m↓\033[0m " << pages[page_id] << "\n"; } std::cout << '\n'; } return 0; } <commit_msg>Time total boot process<commit_after>#include <stdio.h> #include <unistd.h> #include <libgen.h> #include <sys/time.h> #include <omp.h> #include <iostream> #include <sstream> #include <fstream> #include <vector> #include <deque> #include <unordered_map> #include <algorithm> // Typedef for our primary data types typedef std::vector<std::string> pages_t; typedef std::unordered_map<std::string, int> page_ids_t; typedef std::unordered_map<int,std::vector<int>> page_links_t; /* Load in the page titles and page ids from a file. * * Each line of the file will represent the page ID, starting from line 1 until * the end of the file. The page titles will be stored into the pages vector. * The page titles => ids will be stored in the page_ids map * * Returns: The total number of pages loaded */ int load_page_titles(const std::string &file_path, pages_t &pages, page_ids_t &page_ids) { std::ifstream page_titles_file(file_path); std::string page_name; // We won't be using the first index of the vector for anything since // the page_id indexes start at 1 instead of 0. This should help to // prevent any errors during development pages.push_back(""); // Read the page name into the vector and into the hash-map int index = 1; while (std::getline(page_titles_file, page_name)) { pages.push_back(page_name); page_ids[page_name] = index++; } return index - 1; } /* Load in the page links from a file. * * Each line of the file should start with a page_id that represents a page, it * should then follow with a colon (':'). All numbers after the colon represent * page_ids that that page links to. * * Read all page links into the page_links hash map, where the key is the * page_id and the value is a vector of page_ids the page links to. * * Returns: The total number of links loaded */ int load_page_links(const std::string &file_path, page_links_t &page_links) { std::ifstream page_links_file(file_path); std::string link_id; int current_link = 0; int total_links = 0; while (page_links_file >> link_id) { if (link_id.back() == ':') { current_link = atoi(link_id.c_str()); } else { page_links[current_link].push_back(atoi(link_id.c_str())); total_links++; } } return total_links; } /* Given a hash map containing page_ids that represent a path back to a given * root node extract those Ids and order them so that we move from the root node * back to the tail_id. * * The root node is the node whos parent value is -1. * * Returns: A vector containing the page ids of the path in order. */ std::vector<int> path_from_parents(std::unordered_map<int, int> &parent_links, int target_id) { int current = target_id; std::vector<int> target_path; // Only fill the target_path vector if we have a parent link chain if (parent_links[target_id]) { // Traverse thrugh the parent_links till we reach the root node do { target_path.push_back(current); } while ((current = parent_links[current]) != -1); // Reverse the target path list to be in proper order std::reverse(target_path.begin(), target_path.end()); } return target_path; } /* Calculate the shortest path between two page_ids in the page links graph. * This uses the Depth First Search algorithm to travers through each of the * child nodes looking to see if they are the target id. If none are, then we * will traverse through all their children, up until we can find the target id. * * Returns: See the return value of `path_from_parents`. */ std::vector<int> path_between_pages(page_links_t &page_links, int start_id, int target_id) { // Keep track of parent nodes so we can traverse back through the path std::unordered_map<int, int> parent_links; // The starting node will always be considered 'visited' parent_links[start_id] = -1; // Queue of the current nodes to look at std::deque<int> current_nodes; current_nodes.push_back(start_id); bool found_target = false; // Search until we find our target node while ( ! found_target && ! current_nodes.empty()) { int available_nodes = current_nodes.size(); #pragma omp parallel for for (int i = 0; i < available_nodes; ++i) { // Since we can't break out of parallelize loops we just need to // finish off what evers left by continuing through them all #pragma omp flush (found_target) if (found_target) continue; int current; #pragma omp critical { current = current_nodes.front(); current_nodes.pop_front(); } // Iterate through all linked pages for (int page_id : page_links[current]) { // Keep track of how we traveled to this node #pragma omp critical if (parent_links[page_id] == 0) { parent_links[page_id] = current; if (target_id == page_id) { found_target = true; #pragma omp flush (found_target) } else { current_nodes.push_back(page_id); } } } } } return path_from_parents(parent_links, target_id); } /* Use the external python searcher script to find a given page by a search term * and output the resulting page name. * * Returns: Valid Wikipedia page name, or an empty string if one cannot be found */ std::string search_for_page(const std::string &py_searcher_bin, const std::string &search) { FILE *pipe = popen((py_searcher_bin + " \"" + search + "\"").c_str(), "r"); char buffer[255]; std::string page_name = ""; while ( ! feof(pipe)) { if (fgets(buffer, 255, pipe) != NULL) { page_name += buffer; } } return page_name; } std::string pretty_print_path(const std::vector<int> &path_ids, const pages_t &pages) { std::string path = ""; int left_padding = 2; for (int page_id : path_ids) { std::string page_title = pages[page_id]; std::string left_pad = std::string(left_padding, ' '); path += left_pad + page_title + '\n'; if (pages[page_id] != pages[path_ids.size() - 1]) { path += left_pad + "↓\n"; } } return path; } /* Kick off the main process: * * 1. Load in all of the wikipedia pages and page links into memory as a vector * and hash map. Do this in parallel if possible * 2. Begin reading user input for what pages they would like to path find * 3. Use an external python script to get the page names from wikis search * 4. Path find using the BFS algorithm (again, in parallel) * 5. Repeat 2 */ int main(int argc, char* argv[]) { // Used to store a list of page titles. Each index represents a page title pages_t pages; // Used to reverse lookup a page ID by it's title page_ids_t page_ids; // Used to store a list of page_ids that a given page_id links to page_links_t page_links; std::cout << "Welcome to Six-Degrees-of-Wikipedia path finder\n" << "Please while we load Wikipedia into memory.\n\n"; // Determine the base directory path char path_buffer[1024]; readlink("/proc/self/exe", path_buffer, sizeof(path_buffer) - 1); std::string base_path = std::string(dirname(path_buffer)) + "/../"; struct timeval boot_start, boot_end; gettimeofday(&boot_start, 0); #pragma omp parallel sections { // Load in all data, in parallel std::cout << "\033[32m==>\033[0m Loading in page titles and page links\n"; #pragma omp section { struct timeval start, end; gettimeofday(&start, 0); int total = load_page_titles(base_path + "data/titles-sorted", pages, page_ids); gettimeofday(&end, 0); double duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6; std::cout << "\033[34m -> \033[0mRead in " << total << " page titles\n"; std::cout << "\033[34m -> \033[0mTook " << duration << " seconds\n"; } #pragma omp section { struct timeval start, end; gettimeofday(&start, 0); int total = load_page_links(base_path + "data/links-simple-sorted", page_links); gettimeofday(&end, 0); double duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6; std::cout << "\033[34m -> \033[0mRead in " << total << " page links\n"; std::cout << "\033[34m -> \033[0mTook " << duration << " seconds\n"; } } gettimeofday(&boot_end, 0); double duration = ((boot_end.tv_sec - boot_start.tv_sec) * 1000000u + boot_end.tv_usec - boot_start.tv_usec) / 1.e6; std::cout << "\033[32m==>\033[0m Wikipedia graph loaded in " << duration << " seconds. Ready to path find!\n\n"; while (true) { std::string start_page, target_page; std::cout << "Start Wikipedia Page: "; std::getline(std::cin, start_page); std::cout << "Target Wikipedia Page: "; std::getline(std::cin, target_page); // Use the the wiki_search.py script to lookup the wikipedia article name std::cout << "\n\033[32m==>\033[0m Looking up pages through Wikipedia search API\n"; start_page = search_for_page(base_path + "bin/wiki_search.py", start_page); target_page = search_for_page(base_path + "bin/wiki_search.py", target_page); // Ensure both pages exist if (start_page == "") { std::cout << "\033[31m==>\033[0m Start page is not a valid Wikipedia page\n\n"; continue; } if (target_page == "") { std::cout << "\033[31m==>\033[0m Target page is not a valid Wikipedia page\n\n"; continue; } // Remove newline from page names start_page.pop_back(); target_page.pop_back(); // Locate page Ids int start_id = page_ids[start_page], target_id = page_ids[target_page]; // Begin search std::cout << "\033[32m==>\033[0m Finding path from \033[35m" << start_page << "\033[0m → \033[34m" << target_page << "\033[0m\n"; std::vector<int> target_path; struct timeval start, end; gettimeofday(&start, 0); target_path = path_between_pages(page_links, start_id, target_id); gettimeofday(&end, 0); double duration = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6; std::cout << "\033[34m -> \033[0mFound path in \033[32m" << target_path.size() -1 << " clicks\033[0m\n"; std::cout << "\033[34m -> \033[0mTook " << duration << " seconds\n\n"; // Pretty print the page path for (int page_id : target_path) { std::cout << " \033[34m↓\033[0m " << pages[page_id] << "\n"; } std::cout << '\n'; } return 0; } <|endoftext|>
<commit_before>/* Copyright (C) 2015 Marcus Soll All rights reserved. You may use this file under the terms of BSD license as follows: 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 Jolla Ltd 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 HOLDERS 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 "search.h" #include <QDebug> namespace { void add_value(QString &s, QString value, QString key, QString &v_1, QString &v_2, QString &v_3, QString &v_4, QString &v_5, QString &v_6, QString &v_7, QString &v_8, int &count) { ++count; switch(count) { case 1: v_1 = value; s.append(" WHERE "); s.append(key); break; case 2: v_2 = value; s.append(" AND "); s.append(key); break; case 3: v_3 = value; s.append(" AND "); s.append(key); break; case 4: v_4 = value; s.append(" AND "); s.append(key); break; case 5: v_5 = value; s.append(" AND "); s.append(key); break; case 6: v_6 = value; s.append(" AND "); s.append(key); break; case 7: v_7 = value; s.append(" AND "); s.append(key); break; case 8: v_8 = value; s.append(" AND "); s.append(key); break; default: qDebug() << "ERROR in " __FILE__ << " " << __LINE__ << ": Too many search terms"; } } } search::search(QString settings_path, QObject *parent) : QObject(parent), _database(), _kanji_query(), _settings_query(), _literal_result(""), _meaning_result(""), _saved(""), _literal(""), _radical(-1), _strokecount(-1), _jlpt(-1), _meaning(""), _search_for_saved(false), _saved_search_value(false), _skip1(0), _skip2(0), _skip3(0), _search_started(false) { _database = QSqlDatabase::addDatabase("QSQLITE"); _database.setDatabaseName(":memory:"); if(!_database.open()) { qCritical() << "ERROR in " __FILE__ << " " << __LINE__ << ": Can not create database"; } _kanji_query = QSqlQuery(_database); _settings_query = QSqlQuery(_database); QString s = QString("ATTACH DATABASE '/usr/share/harbour-kanji/kanjidb.sqlite3' AS kanjidb"); if(!_kanji_query.exec(s)) { QString error = s.append(": ").append(_kanji_query.lastError().text()); qWarning() << error; } s = QString("ATTACH DATABASE ? AS settingsdb"); _kanji_query.clear(); _kanji_query.prepare(s); _kanji_query.addBindValue(settings_path); if(!_kanji_query.exec()) { QString error = s.append(": ").append(_kanji_query.lastError().text()); qWarning() << error; } _kanji_query.clear(); } void search::clear() { _kanji_query.clear(); _settings_query.clear(); _literal_result = ""; _meaning_result = ""; _saved = false; _literal = ""; _radical = -1; _strokecount = -1; _jlpt = -1; _meaning = ""; _search_for_saved = false; _saved_search_value = false; _skip1 = 0; _skip2 = 0; _skip3 = 0; _search_started = false; } void search::search_literal(QString literal) { _literal = literal; } void search::search_radical(int radical) { _radical = radical; } void search::search_strokecount(int strokecount) { _strokecount = strokecount; } void search::search_jlpt(int jlpt) { _jlpt = jlpt; } void search::search_meaning(QString meaning) { _meaning = meaning; } void search::search_saved(bool saved) { _search_for_saved = true; _saved_search_value = saved; } void search::search_skip(int skip1, int skip2, int skip3) { _skip1 = skip1; _skip2 = skip2; _skip3 = skip3; } bool search::start_search() { if(_literal == "" && _radical == 0 && _strokecount == 0 && _jlpt == 0 && _meaning == "") { // Get all kanji QString s = QString("SELECT literal,meaning FROM kanjidb.kanji"); if(!_kanji_query.exec(s)) { QString error = s.append(": ").append(_kanji_query.lastError().text()); qWarning() << error; _search_started = false; return false; } if(!_kanji_query.isSelect()) { QString error = s.append(": No SELECT"); qWarning() << error; _search_started = false; return false; } } else { // Search for all fitting kanji int count = 0; QString v_1; QString v_2; QString v_3; QString v_4; QString v_5; QString v_6; QString v_7; QString v_8; QString s = QString("SELECT literal,meaning FROM kanjidb.kanji"); if(_literal != "") { add_value(s,QString("\%%1\%").arg(_literal),QString("literal LIKE ?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count); } if(_radical != -1) { add_value(s,QString("%1").arg(_radical),QString("radical=?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count); } if(_strokecount != -1) { add_value(s,QString("%1").arg(_strokecount),QString("strokecount=?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count); } if(_jlpt != -1) { add_value(s,QString("%1").arg(_jlpt),QString("JLPT=?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count); } if(_meaning != "") { add_value(s,QString("\%%1\%").arg(_meaning),QString("meaning LIKE ?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count); } if(_skip1 != 0) { add_value(s,QString("%1").arg(_skip1),QString("skip_1=?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count); } if(_skip2 != 0) { add_value(s,QString("%1").arg(_skip2),QString("skip_2=?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count); } if(_skip3 != 0) { add_value(s,QString("%1").arg(_skip3),QString("skip_3=?"),v_1,v_2,v_3,v_4,v_5,v_6,v_7,v_8,count); } _kanji_query.clear(); _kanji_query.prepare(s); if(count >= 1) { _kanji_query.addBindValue(v_1); } if(count >= 2) { _kanji_query.addBindValue(v_2); } if(count >= 3) { _kanji_query.addBindValue(v_3); } if(count >= 4) { _kanji_query.addBindValue(v_4); } if(count >= 5) { _kanji_query.addBindValue(v_5); } if(count >= 6) { _kanji_query.addBindValue(v_6); } if(count >= 7) { _kanji_query.addBindValue(v_7); } if(count >= 8) { _kanji_query.addBindValue(v_8); } qDebug() << "DEBUG in " __FILE__ << " " << __LINE__ << ": SELECT statement:" << s; if(!_kanji_query.exec()) { QString error = s.append(": ").append(_kanji_query.lastError().text()); qWarning() << error; _search_started = false; return false; } if(!_kanji_query.isSelect()) { QString error = s.append(": No SELECT"); qWarning() << error; _search_started = false; return false; } } _search_started = true; return true; } bool search::next_hidden() { if(!_search_started) { return false; } if(_kanji_query.next()) { _literal_result = _kanji_query.value(0).toString(); _meaning_result = _kanji_query.value(1).toString(); QString s = QString("SELECT count(*) FROM settingsdb.saved_kanji WHERE literal=?"); _settings_query.prepare(s); _settings_query.addBindValue(_literal_result); if(_settings_query.exec() && _settings_query.isSelect() && _settings_query.next() && _settings_query.value(0).toInt() > 0) { _saved = true; } else { _saved = false; } _settings_query.finish(); return true; } else { _search_started = false; return false; } } bool search::next() { if(!_search_started) { return false; } if(!_search_for_saved) { return next_hidden(); } else { while(next_hidden()) { if(_saved_search_value == _saved) { return true; } } return false; } } QString search::literal() { return _literal_result; } QString search::meaning() { return _meaning_result; } bool search::kanji_is_saved() { return _saved; } <commit_msg>If "meaning" is selected for search both "meaning" and "custom_translation" will be considered.<commit_after>/* Copyright (C) 2015 Marcus Soll All rights reserved. You may use this file under the terms of BSD license as follows: 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 Jolla Ltd 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 HOLDERS 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 "search.h" #include <QDebug> #include <QVariant> #include <QVariantList> namespace { QString get_seperator(int &count) { ++count; if(count == 1) { return " WHERE "; } else { return " AND "; } } } search::search(QString settings_path, QObject *parent) : QObject(parent), _database(), _kanji_query(), _settings_query(), _literal_result(""), _meaning_result(""), _saved(""), _literal(""), _radical(-1), _strokecount(-1), _jlpt(-1), _meaning(""), _search_for_saved(false), _saved_search_value(false), _skip1(0), _skip2(0), _skip3(0), _search_started(false) { _database = QSqlDatabase::addDatabase("QSQLITE"); _database.setDatabaseName(":memory:"); if(!_database.open()) { qCritical() << "ERROR in " __FILE__ << " " << __LINE__ << ": Can not create database"; } _kanji_query = QSqlQuery(_database); _settings_query = QSqlQuery(_database); QString s = QString("ATTACH DATABASE '/usr/share/harbour-kanji/kanjidb.sqlite3' AS kanjidb"); if(!_kanji_query.exec(s)) { QString error = s.append(": ").append(_kanji_query.lastError().text()); qWarning() << error; } s = QString("ATTACH DATABASE ? AS settingsdb"); _kanji_query.clear(); _kanji_query.prepare(s); _kanji_query.addBindValue(settings_path); if(!_kanji_query.exec()) { QString error = s.append(": ").append(_kanji_query.lastError().text()); qWarning() << error; } _kanji_query.clear(); } void search::clear() { _kanji_query.clear(); _settings_query.clear(); _literal_result = ""; _meaning_result = ""; _saved = false; _literal = ""; _radical = -1; _strokecount = -1; _jlpt = -1; _meaning = ""; _search_for_saved = false; _saved_search_value = false; _skip1 = 0; _skip2 = 0; _skip3 = 0; _search_started = false; } void search::search_literal(QString literal) { _literal = literal; } void search::search_radical(int radical) { _radical = radical; } void search::search_strokecount(int strokecount) { _strokecount = strokecount; } void search::search_jlpt(int jlpt) { _jlpt = jlpt; } void search::search_meaning(QString meaning) { _meaning = meaning; } void search::search_saved(bool saved) { _search_for_saved = true; _saved_search_value = saved; } void search::search_skip(int skip1, int skip2, int skip3) { _skip1 = skip1; _skip2 = skip2; _skip3 = skip3; } bool search::start_search() { if(_literal == "" && _radical == -1 && _strokecount == -1 && _jlpt == -1 && _meaning == "" && _skip1 == 0 && _skip2 == 0 && _skip3 == 0) { // Get all kanji QString s = QString("SELECT literal,meaning FROM kanjidb.kanji"); if(!_kanji_query.exec(s)) { QString error = s.append(": ").append(_kanji_query.lastError().text()); qWarning() << error; _search_started = false; return false; } if(!_kanji_query.isSelect()) { QString error = s.append(": No SELECT"); qWarning() << error; _search_started = false; return false; } } else { // Search for all fitting kanji int count = 0; QVariantList search_list; QString s = QString("SELECT kanjidb.kanji.literal,meaning FROM kanjidb.kanji LEFT JOIN settingsdb.custom_translation ON kanjidb.kanji.literal=settingsdb.custom_translation.literal"); if(_literal != "") { s.append(get_seperator(count)); s.append("literal LIKE ?"); search_list.append(QString("\%%1\%").arg(_literal)); } if(_radical != -1) { s.append(get_seperator(count)); s.append("radical=?"); search_list.append(_radical); } if(_strokecount != -1) { s.append(get_seperator(count)); s.append("strokecount=?"); search_list.append(_strokecount); } if(_jlpt != -1) { s.append(get_seperator(count)); s.append("JLPT=?"); search_list.append(_jlpt); } if(_meaning != "") { s.append(get_seperator(count)); s.append("(meaning LIKE ? OR translation LIKE ?)"); search_list.append(QString("\%%1\%").arg(_meaning)); search_list.append(QString("\%%1\%").arg(_meaning)); } if(_skip1 != 0) { s.append(get_seperator(count)); s.append("skip_1=?"); search_list.append(_skip1); } if(_skip2 != 0) { s.append(get_seperator(count)); s.append("skip_2=?"); search_list.append(_skip2); } if(_skip3 != 0) { s.append(get_seperator(count)); s.append("skip_3=?"); search_list.append(_skip3); } _kanji_query.clear(); _kanji_query.prepare(s); foreach (QVariant var, search_list) { _kanji_query.addBindValue(var); } qDebug() << "DEBUG in " __FILE__ << " " << __LINE__ << ": SELECT statement:" << s; if(!_kanji_query.exec()) { QString error = s.append(": ").append(_kanji_query.lastError().text()); qWarning() << error; _search_started = false; return false; } if(!_kanji_query.isSelect()) { QString error = s.append(": No SELECT"); qWarning() << error; _search_started = false; return false; } } _search_started = true; return true; } bool search::next_hidden() { if(!_search_started) { return false; } if(_kanji_query.next()) { _literal_result = _kanji_query.value(0).toString(); _meaning_result = _kanji_query.value(1).toString(); QString s = QString("SELECT count(*) FROM settingsdb.saved_kanji WHERE literal=?"); _settings_query.prepare(s); _settings_query.addBindValue(_literal_result); if(_settings_query.exec() && _settings_query.isSelect() && _settings_query.next() && _settings_query.value(0).toInt() > 0) { _saved = true; } else { _saved = false; } _settings_query.finish(); return true; } else { _search_started = false; return false; } } bool search::next() { if(!_search_started) { return false; } if(!_search_for_saved) { return next_hidden(); } else { while(next_hidden()) { if(_saved_search_value == _saved) { return true; } } return false; } } QString search::literal() { return _literal_result; } QString search::meaning() { return _meaning_result; } bool search::kanji_is_saved() { return _saved; } <|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. */ #ifdef PADDLE_WITH_XPU #include "paddle/fluid/operators/sequence_ops/sequence_conv_op.h" #include "paddle/fluid/platform/device/device_wrapper.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; template <typename DeviceContext, typename T> class SequenceConvXPUKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& context) const override { auto* in = context.Input<LoDTensor>("X"); auto* out = context.Output<LoDTensor>("Out"); auto filter = *context.Input<Tensor>("Filter"); out->mutable_data<T>(context.GetPlace()); int context_start = context.Attr<int>("contextStart"); int context_length = context.Attr<int>("contextLength"); int context_stride = context.Attr<int>("contextStride"); bool padding_trainable = context.Attr<bool>("paddingTrainable"); PADDLE_ENFORCE_EQ( in->lod().empty(), false, platform::errors::InvalidArgument("Input(X) Tensor of SequenceConvOp " "does not contain LoD information.")); PADDLE_ENFORCE_EQ( in->lod().size(), 1UL, platform::errors::InvalidArgument( "Only support input sequence with lod level equal to 1 at " "present. But received: lod level %u.", in->lod().size())); PADDLE_ENFORCE_EQ( padding_trainable, false, platform::errors::InvalidArgument("Only support padding_trainable " "equal false.")); int up_pad = std::max(0, -context_start); int down_pad = std::max(0, context_start + context_length - 1); PADDLE_ENFORCE_EQ(up_pad, 2, platform::errors::InvalidArgument( "Only support up_pad equal 2.")); PADDLE_ENFORCE_EQ(down_pad, 2, platform::errors::InvalidArgument( "Only support down_pad equal 2.")); auto xpu_context = context.template device_context<DeviceContext>().x_context(); auto sequence_width = static_cast<int64_t>(in->dims()[1]); framework::DDim col_shape = {in->dims()[0], context_length * sequence_width}; xpu::ctx_guard RAII_GUARD(xpu_context); int col_numel = col_shape[0] * col_shape[1]; T* col_data = RAII_GUARD.alloc_l3_or_gm<T>(col_numel); PADDLE_ENFORCE_NOT_NULL( col_data, paddle::platform::errors::Fatal("XPU memory is not enough")); auto lod_level_0 = in->lod()[0]; int lod_size = lod_level_0.size(); // If batch size set to 256, the lod is {0, batch[0] - 0, // batch[1] - batch [0], ..., batch[255] - batch[254]}, // so the lod_size will be 257. PADDLE_ENFORCE_LE(lod_size, 257, platform::errors::InvalidArgument( "Only support batch size <= 256.")); std::vector<int> cpu_lodx(lod_size); for (int i = 0; i < lod_size; i++) { cpu_lodx[i] = lod_level_0[i]; } xpu::VectorParam<int> lodx = {cpu_lodx.data(), static_cast<int>(cpu_lodx.size()), nullptr}; int r = xpu::sequence_context_projection<T, int>( xpu_context, in->data<T>(), col_data, nullptr, lodx, sequence_width, context_start, context_length, context_stride, {2, 2}); PADDLE_ENFORCE_XDNN_SUCCESS(r, "sequence_context_projection"); bool trans_a = false; bool trans_b = false; int m = col_shape[0]; int k = col_shape[1]; int k1 = filter.dims()[0]; int n = filter.dims()[1]; PADDLE_ENFORCE_EQ(k, k1, platform::errors::InvalidArgument( "The shape of FC in SequenceConvOp is invalid." "The k of matrix A is %d, k1 of matrix B is %d." "But expect k == k1", k, k1)); int lda = (!trans_a) ? k : m; int ldb = (!trans_b) ? n : k; int ldc = n; T alpha = static_cast<T>(1.0); T beta = static_cast<T>(0.0); const T* data_a = col_data; const T* data_b = filter.data<T>(); T* data_c = out->data<T>(); r = xpu::fc_fusion<T, T, T, int32_t>( xpu_context, data_a, data_b, data_c, m, n, k, trans_a, trans_b, nullptr, nullptr, nullptr, lda, ldb, ldc, alpha, beta, nullptr, xpu::Activation_t::LINEAR); PADDLE_ENFORCE_XDNN_SUCCESS(r, "fc_fusion"); if (xpu_context->xpu_stream != nullptr) { xpu_wait(xpu_context->xpu_stream); } } }; template <typename DeviceContext, typename T> class SequenceConvGradXPUKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& context) const override { auto* in_g = context.Output<LoDTensor>(framework::GradVarName("X")); auto* out_g = context.Input<LoDTensor>(framework::GradVarName("Out")); auto* filter_g = context.Output<Tensor>(framework::GradVarName("Filter")); auto* in = context.Input<LoDTensor>("X"); auto* filter = context.Input<Tensor>("Filter"); int context_start = context.Attr<int>("contextStart"); int context_length = context.Attr<int>("contextLength"); int context_stride = context.Attr<int>("contextStride"); bool padding_trainable = context.Attr<bool>("paddingTrainable"); PADDLE_ENFORCE_EQ( in->lod().empty(), false, platform::errors::InvalidArgument("Input(X) Tensor of SequenceConvOp " "does not contain LoD information.")); PADDLE_ENFORCE_EQ( in->lod().size(), 1UL, platform::errors::InvalidArgument( "Only support input sequence with lod level equal to 1 at " "present. But received: lod level %u.", in->lod().size())); PADDLE_ENFORCE_EQ( padding_trainable, false, platform::errors::InvalidArgument("Only support padding_trainable " "equal false.")); int up_pad = std::max(0, -context_start); int down_pad = std::max(0, context_start + context_length - 1); PADDLE_ENFORCE_EQ(up_pad, 2, platform::errors::InvalidArgument( "Only support up_pad equal 2.")); PADDLE_ENFORCE_EQ(down_pad, 2, platform::errors::InvalidArgument( "Only support down_pad equal 2.")); auto lod_level_0 = in->lod()[0]; int lod_size = lod_level_0.size(); PADDLE_ENFORCE_LE(lod_size, 257, platform::errors::InvalidArgument( "Only support batch size <= 256.")); std::vector<int> cpu_lodx(lod_size); for (int i = 0; i < lod_size; i++) { cpu_lodx[i] = lod_level_0[i]; } xpu::VectorParam<int> lodx = {cpu_lodx.data(), static_cast<int>(cpu_lodx.size()), nullptr}; auto xpu_context = context.template device_context<DeviceContext>().x_context(); auto sequence_width = static_cast<int64_t>(in->dims()[1]); framework::DDim col_shape = {in->dims()[0], context_length * sequence_width}; xpu::ctx_guard RAII_GUARD(xpu_context); int col_numel = col_shape[0] * col_shape[1]; T* col_data = RAII_GUARD.alloc_l3_or_gm<T>(col_numel); PADDLE_ENFORCE_NOT_NULL( col_data, paddle::platform::errors::Fatal("XPU memory is not enough")); if (in_g || filter_g) { int r = xpu::constant<T>(xpu_context, col_data, col_numel, T(0)); PADDLE_ENFORCE_XDNN_SUCCESS(r, "constant"); bool trans_a = false; bool trans_b = true; int m = out_g->dims()[0]; int k = out_g->dims()[1]; int n = filter->dims()[0]; int k1 = filter->dims()[1]; PADDLE_ENFORCE_EQ(k, k1, platform::errors::InvalidArgument( "The shape of FC in SequenceConvGradOp is invalid." "The k of matrix A is %d, k1 of matrix B is %d." "But expect k == k1", k, k1)); int lda = (!trans_a) ? k : m; int ldb = (!trans_b) ? n : k; int ldc = n; T alpha = static_cast<T>(1.0); T beta = static_cast<T>(0.0); const T* data_a = out_g->data<T>(); const T* data_b = filter->data<T>(); T* data_c = col_data; r = xpu::fc_fusion<T, T, T, int32_t>( xpu_context, data_a, data_b, data_c, m, n, k, trans_a, trans_b, nullptr, nullptr, nullptr, lda, ldb, ldc, alpha, beta, nullptr, xpu::Activation_t::LINEAR); PADDLE_ENFORCE_XDNN_SUCCESS(r, "fc_fusion"); } if (in_g) { PADDLE_ENFORCE_LT(sequence_width, 512, platform::errors::InvalidArgument( "Only support sequence_width < 512.")); in_g->mutable_data<T>(context.GetPlace()); in_g->set_lod(in->lod()); xpu::constant<T>(xpu_context, in_g->data<T>(), in_g->numel(), T(0)); int r = xpu::sequence_context_projection_grad<T, int>( xpu_context, in_g->data<T>(), col_data, nullptr, lodx, sequence_width, context_start, context_length, context_stride, {2, 2}); PADDLE_ENFORCE_XDNN_SUCCESS(r, "sequence_context_projection_grad"); } if (filter_g) { filter_g->mutable_data<T>(context.GetPlace()); xpu::constant<T>(xpu_context, filter_g->data<T>(), filter_g->numel(), T(0)); int r = xpu::sequence_context_projection<T, int>( xpu_context, in->data<T>(), col_data, nullptr, lodx, sequence_width, context_start, context_length, context_stride, {2, 2}); PADDLE_ENFORCE_XDNN_SUCCESS(r, "sequence_context_projection"); bool trans_a = true; bool trans_b = false; int k = col_shape[0]; int m = col_shape[1]; int k1 = out_g->dims()[0]; int n = out_g->dims()[1]; PADDLE_ENFORCE_EQ(k, k1, platform::errors::InvalidArgument( "The shape of FC in SequenceConvGradOp is invalid." "The k of matrix A is %d, k1 of matrix B is %d." "But expect k == k1", k, k1)); int lda = (!trans_a) ? k : m; int ldb = (!trans_b) ? n : k; int ldc = n; T alpha = static_cast<T>(1.0); T beta = static_cast<T>(0.0); const T* data_a = col_data; const T* data_b = out_g->data<T>(); T* data_c = filter_g->data<T>(); r = xpu::fc_fusion<T, T, T, int32_t>( xpu_context, data_a, data_b, data_c, m, n, k, trans_a, trans_b, nullptr, nullptr, nullptr, lda, ldb, ldc, alpha, beta, nullptr, xpu::Activation_t::LINEAR); PADDLE_ENFORCE_XDNN_SUCCESS(r, "fc_fusion"); if (xpu_context->xpu_stream != nullptr) { xpu_wait(xpu_context->xpu_stream); } } } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_XPU_KERNEL( sequence_conv, ops::SequenceConvXPUKernel<paddle::platform::XPUDeviceContext, float>); REGISTER_OP_XPU_KERNEL( sequence_conv_grad, ops::SequenceConvGradXPUKernel<paddle::platform::XPUDeviceContext, float>); #endif <commit_msg>remove unnecessary constant fill in sequence conv test=kunlun. (#40126)<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. */ #ifdef PADDLE_WITH_XPU #include "paddle/fluid/operators/sequence_ops/sequence_conv_op.h" #include "paddle/fluid/platform/device/device_wrapper.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; template <typename DeviceContext, typename T> class SequenceConvXPUKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& context) const override { auto* in = context.Input<LoDTensor>("X"); auto* out = context.Output<LoDTensor>("Out"); auto filter = *context.Input<Tensor>("Filter"); out->mutable_data<T>(context.GetPlace()); int context_start = context.Attr<int>("contextStart"); int context_length = context.Attr<int>("contextLength"); int context_stride = context.Attr<int>("contextStride"); bool padding_trainable = context.Attr<bool>("paddingTrainable"); PADDLE_ENFORCE_EQ( in->lod().empty(), false, platform::errors::InvalidArgument("Input(X) Tensor of SequenceConvOp " "does not contain LoD information.")); PADDLE_ENFORCE_EQ( in->lod().size(), 1UL, platform::errors::InvalidArgument( "Only support input sequence with lod level equal to 1 at " "present. But received: lod level %u.", in->lod().size())); PADDLE_ENFORCE_EQ( padding_trainable, false, platform::errors::InvalidArgument("Only support padding_trainable " "equal false.")); int up_pad = std::max(0, -context_start); int down_pad = std::max(0, context_start + context_length - 1); PADDLE_ENFORCE_EQ(up_pad, 2, platform::errors::InvalidArgument( "Only support up_pad equal 2.")); PADDLE_ENFORCE_EQ(down_pad, 2, platform::errors::InvalidArgument( "Only support down_pad equal 2.")); auto xpu_context = context.template device_context<DeviceContext>().x_context(); auto sequence_width = static_cast<int64_t>(in->dims()[1]); framework::DDim col_shape = {in->dims()[0], context_length * sequence_width}; xpu::ctx_guard RAII_GUARD(xpu_context); int col_numel = col_shape[0] * col_shape[1]; T* col_data = RAII_GUARD.alloc_l3_or_gm<T>(col_numel); PADDLE_ENFORCE_NOT_NULL( col_data, paddle::platform::errors::Fatal("XPU memory is not enough")); auto lod_level_0 = in->lod()[0]; int lod_size = lod_level_0.size(); // If batch size set to 256, the lod is {0, batch[0] - 0, // batch[1] - batch [0], ..., batch[255] - batch[254]}, // so the lod_size will be 257. PADDLE_ENFORCE_LE(lod_size, 257, platform::errors::InvalidArgument( "Only support batch size <= 256.")); std::vector<int> cpu_lodx(lod_size); for (int i = 0; i < lod_size; i++) { cpu_lodx[i] = lod_level_0[i]; } xpu::VectorParam<int> lodx = {cpu_lodx.data(), static_cast<int>(cpu_lodx.size()), nullptr}; int r = xpu::sequence_context_projection<T, int>( xpu_context, in->data<T>(), col_data, nullptr, lodx, sequence_width, context_start, context_length, context_stride, {2, 2}); PADDLE_ENFORCE_XDNN_SUCCESS(r, "sequence_context_projection"); bool trans_a = false; bool trans_b = false; int m = col_shape[0]; int k = col_shape[1]; int k1 = filter.dims()[0]; int n = filter.dims()[1]; PADDLE_ENFORCE_EQ(k, k1, platform::errors::InvalidArgument( "The shape of FC in SequenceConvOp is invalid." "The k of matrix A is %d, k1 of matrix B is %d." "But expect k == k1", k, k1)); int lda = (!trans_a) ? k : m; int ldb = (!trans_b) ? n : k; int ldc = n; T alpha = static_cast<T>(1.0); T beta = static_cast<T>(0.0); const T* data_a = col_data; const T* data_b = filter.data<T>(); T* data_c = out->data<T>(); r = xpu::fc_fusion<T, T, T, int32_t>( xpu_context, data_a, data_b, data_c, m, n, k, trans_a, trans_b, nullptr, nullptr, nullptr, lda, ldb, ldc, alpha, beta, nullptr, xpu::Activation_t::LINEAR); PADDLE_ENFORCE_XDNN_SUCCESS(r, "fc_fusion"); if (xpu_context->xpu_stream != nullptr) { xpu_wait(xpu_context->xpu_stream); } } }; template <typename DeviceContext, typename T> class SequenceConvGradXPUKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& context) const override { auto* in_g = context.Output<LoDTensor>(framework::GradVarName("X")); auto* out_g = context.Input<LoDTensor>(framework::GradVarName("Out")); auto* filter_g = context.Output<Tensor>(framework::GradVarName("Filter")); auto* in = context.Input<LoDTensor>("X"); auto* filter = context.Input<Tensor>("Filter"); int context_start = context.Attr<int>("contextStart"); int context_length = context.Attr<int>("contextLength"); int context_stride = context.Attr<int>("contextStride"); bool padding_trainable = context.Attr<bool>("paddingTrainable"); PADDLE_ENFORCE_EQ( in->lod().empty(), false, platform::errors::InvalidArgument("Input(X) Tensor of SequenceConvOp " "does not contain LoD information.")); PADDLE_ENFORCE_EQ( in->lod().size(), 1UL, platform::errors::InvalidArgument( "Only support input sequence with lod level equal to 1 at " "present. But received: lod level %u.", in->lod().size())); PADDLE_ENFORCE_EQ( padding_trainable, false, platform::errors::InvalidArgument("Only support padding_trainable " "equal false.")); int up_pad = std::max(0, -context_start); int down_pad = std::max(0, context_start + context_length - 1); PADDLE_ENFORCE_EQ(up_pad, 2, platform::errors::InvalidArgument( "Only support up_pad equal 2.")); PADDLE_ENFORCE_EQ(down_pad, 2, platform::errors::InvalidArgument( "Only support down_pad equal 2.")); auto lod_level_0 = in->lod()[0]; int lod_size = lod_level_0.size(); PADDLE_ENFORCE_LE(lod_size, 257, platform::errors::InvalidArgument( "Only support batch size <= 256.")); std::vector<int> cpu_lodx(lod_size); for (int i = 0; i < lod_size; i++) { cpu_lodx[i] = lod_level_0[i]; } xpu::VectorParam<int> lodx = {cpu_lodx.data(), static_cast<int>(cpu_lodx.size()), nullptr}; auto xpu_context = context.template device_context<DeviceContext>().x_context(); auto sequence_width = static_cast<int64_t>(in->dims()[1]); framework::DDim col_shape = {in->dims()[0], context_length * sequence_width}; xpu::ctx_guard RAII_GUARD(xpu_context); int col_numel = col_shape[0] * col_shape[1]; T* col_data = RAII_GUARD.alloc_l3_or_gm<T>(col_numel); PADDLE_ENFORCE_NOT_NULL( col_data, paddle::platform::errors::Fatal("XPU memory is not enough")); if (in_g || filter_g) { bool trans_a = false; bool trans_b = true; int m = out_g->dims()[0]; int k = out_g->dims()[1]; int n = filter->dims()[0]; int k1 = filter->dims()[1]; PADDLE_ENFORCE_EQ(k, k1, platform::errors::InvalidArgument( "The shape of FC in SequenceConvGradOp is invalid." "The k of matrix A is %d, k1 of matrix B is %d." "But expect k == k1", k, k1)); int lda = (!trans_a) ? k : m; int ldb = (!trans_b) ? n : k; int ldc = n; T alpha = static_cast<T>(1.0); T beta = static_cast<T>(0.0); const T* data_a = out_g->data<T>(); const T* data_b = filter->data<T>(); T* data_c = col_data; int r = xpu::fc_fusion<T, T, T, int32_t>( xpu_context, data_a, data_b, data_c, m, n, k, trans_a, trans_b, nullptr, nullptr, nullptr, lda, ldb, ldc, alpha, beta, nullptr, xpu::Activation_t::LINEAR); PADDLE_ENFORCE_XDNN_SUCCESS(r, "fc_fusion"); } if (in_g) { PADDLE_ENFORCE_LT(sequence_width, 512, platform::errors::InvalidArgument( "Only support sequence_width < 512.")); in_g->mutable_data<T>(context.GetPlace()); in_g->set_lod(in->lod()); int r = xpu::sequence_context_projection_grad<T, int>( xpu_context, in_g->data<T>(), col_data, nullptr, lodx, sequence_width, context_start, context_length, context_stride, {2, 2}); PADDLE_ENFORCE_XDNN_SUCCESS(r, "sequence_context_projection_grad"); } if (filter_g) { filter_g->mutable_data<T>(context.GetPlace()); int r = xpu::sequence_context_projection<T, int>( xpu_context, in->data<T>(), col_data, nullptr, lodx, sequence_width, context_start, context_length, context_stride, {2, 2}); PADDLE_ENFORCE_XDNN_SUCCESS(r, "sequence_context_projection"); bool trans_a = true; bool trans_b = false; int k = col_shape[0]; int m = col_shape[1]; int k1 = out_g->dims()[0]; int n = out_g->dims()[1]; PADDLE_ENFORCE_EQ(k, k1, platform::errors::InvalidArgument( "The shape of FC in SequenceConvGradOp is invalid." "The k of matrix A is %d, k1 of matrix B is %d." "But expect k == k1", k, k1)); int lda = (!trans_a) ? k : m; int ldb = (!trans_b) ? n : k; int ldc = n; T alpha = static_cast<T>(1.0); T beta = static_cast<T>(0.0); const T* data_a = col_data; const T* data_b = out_g->data<T>(); T* data_c = filter_g->data<T>(); r = xpu::fc_fusion<T, T, T, int32_t>( xpu_context, data_a, data_b, data_c, m, n, k, trans_a, trans_b, nullptr, nullptr, nullptr, lda, ldb, ldc, alpha, beta, nullptr, xpu::Activation_t::LINEAR); PADDLE_ENFORCE_XDNN_SUCCESS(r, "fc_fusion"); if (xpu_context->xpu_stream != nullptr) { xpu_wait(xpu_context->xpu_stream); } } } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_XPU_KERNEL( sequence_conv, ops::SequenceConvXPUKernel<paddle::platform::XPUDeviceContext, float>); REGISTER_OP_XPU_KERNEL( sequence_conv_grad, ops::SequenceConvGradXPUKernel<paddle::platform::XPUDeviceContext, float>); #endif <|endoftext|>
<commit_before>//===--- XPCService.cpp ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "sourcekitd/Internal-XPC.h" #include "sourcekitd/Logging.h" #include "sourcekitd/XpcTracing.h" #include "SourceKit/Core/LLVM.h" #include "SourceKit/Support/Concurrency.h" #include "SourceKit/Support/UIdent.h" #include "SourceKit/Support/Logging.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Errno.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/Threading.h" #include <xpc/xpc.h> using namespace SourceKit; using namespace sourcekitd; static xpc_connection_t MainConnection = nullptr; void sourcekitd::postNotification(sourcekitd_response_t Notification) { xpc_connection_t peer = MainConnection; if (!peer) goto done; { xpc_object_t contents = xpc_array_create(nullptr, 0); xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, (uint64_t)xpc::Message::Notification); xpc_array_set_value(contents, XPC_ARRAY_APPEND, Notification); xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0); xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents); xpc_release(contents); xpc_connection_send_message(peer, msg); xpc_release(msg); } done: // The function accepted ownership. xpc_release(Notification); } namespace { /// \brief Associates sourcekitd_uid_t to a UIdent. class SKUIDToUIDMap { typedef llvm::DenseMap<void *, UIdent> MapTy; MapTy Map; WorkQueue Queue{ WorkQueue::Dequeuing::Concurrent, "UIDMap" }; public: UIdent get(sourcekitd_uid_t SKDUID); void set(sourcekitd_uid_t SKDUID, UIdent UID); }; } static SKUIDToUIDMap UIDMap; sourcekitd_uid_t sourcekitd::SKDUIDFromUIdent(UIdent UID) { if (void *Tag = UID.getTag()) return reinterpret_cast<sourcekitd_uid_t>(Tag); // FIXME: The following should run in the synchronous dispatch queue of the // connection. But does it matter, since if MainConnection is null or gets // destroyed it means the client crashed ? xpc_connection_t peer = MainConnection; if (!peer) return nullptr; xpc_object_t contents = xpc_array_create(nullptr, 0); xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, (uint64_t)xpc::Message::UIDSynchronization); xpc_array_set_string(contents, XPC_ARRAY_APPEND, UID.c_str()); xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0); xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents); xpc_release(contents); xpc_object_t reply = xpc_connection_send_message_with_reply_sync(peer, msg); xpc_release(msg); if (xpc_get_type(reply) == XPC_TYPE_ERROR) { xpc_release(reply); return nullptr; } assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY); uint64_t val = xpc_dictionary_get_uint64(reply, xpc::KeyMsgResponse); xpc_release(reply); sourcekitd_uid_t skduid = sourcekitd_uid_t(val); UID.setTag(skduid); UIDMap.set(skduid, UID); return skduid; } UIdent sourcekitd::UIdentFromSKDUID(sourcekitd_uid_t SKDUID) { // This should be used only for debugging/logging purposes. UIdent UID = UIDMap.get(SKDUID); if (UID.isValid()) return UID; xpc_connection_t Peer = MainConnection; if (!Peer) return UIdent(); xpc_object_t contents = xpc_array_create(nullptr, 0); xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, (uint64_t)xpc::Message::UIDSynchronization); xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, uintptr_t(SKDUID)); xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0); xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents); xpc_release(contents); xpc_object_t reply = xpc_connection_send_message_with_reply_sync(Peer, msg); xpc_release(msg); if (xpc_get_type(reply) == XPC_TYPE_ERROR) { xpc_release(reply); return UIdent(); } assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY); const char *Str = xpc_dictionary_get_string(reply, xpc::KeyMsgResponse); UID = UIdent(Str); UID.setTag(SKDUID); UIDMap.set(SKDUID, UID); xpc_release(reply); return UID; } void anchorForGetMainExecutableInXPCService() {} namespace { /// Responsible for replying to an XPC request. class XPCResponder { xpc_connection_t Peer; xpc_object_t Event; bool Responded = false; public: XPCResponder(xpc_object_t event, xpc_connection_t peer) : Peer(xpc_connection_t(xpc_retain(peer))), Event(xpc_retain(event)) {} ~XPCResponder() { if (!Responded) { LOG_WARN_FUNC("failed to respond to request"); sendReply(createErrorRequestFailed("Internal error: no response was " "provided for the request")); } xpc_release(Event); xpc_release(Peer); } /// Accepts ownership of the response object. void sendReply(sourcekitd_response_t response) { if (Responded) { LOG_WARN_FUNC("tried to respond to an already handled request"); return; } xpc_object_t reply = xpc_dictionary_create_reply(Event); xpc_dictionary_set_value(reply, xpc::KeyMsgResponse, response); xpc_release(response); xpc_connection_send_message(Peer, reply); xpc_release(reply); Responded = true; } }; } std::string sourcekitd::getRuntimeLibPath() { std::string MainExePath = llvm::sys::fs::getMainExecutable("sourcekit", reinterpret_cast<void *>(&anchorForGetMainExecutableInXPCService)); #ifdef SOURCEKIT_UNVERSIONED_FRAMEWORK_BUNDLE // MainExePath points to "lib/sourcekitd.framework/XPCServices/ // SourceKitService.xpc/SourceKitService" const unsigned MainExeLibNestingLevel = 4; #else // MainExePath points to "lib/sourcekitd.framework/Versions/Current/XPCServices/ // SourceKitService.xpc/Contents/MacOS/SourceKitService" const unsigned MainExeLibNestingLevel = 8; #endif // Get it to lib. StringRef Path = MainExePath; for (unsigned i = 0; i < MainExeLibNestingLevel; ++i) Path = llvm::sys::path::parent_path(Path); return Path; } static void sourcekitdServer_peer_event_handler(xpc_connection_t peer, xpc_object_t event) { xpc_type_t type = xpc_get_type(event); if (type == XPC_TYPE_ERROR) { if (event == XPC_ERROR_CONNECTION_INVALID) { // The client process on the other end of the connection has either // crashed or cancelled the connection. After receiving this error, // the connection is in an invalid state, and we do not need to // call xpc_connection_cancel(). Tear down any associated state // here. sourcekitd::shutdown(); xpc_transaction_end(); } else if (event == XPC_ERROR_TERMINATION_IMMINENT) { // Handle per-connection termination cleanup. xpc_connection_cancel(peer); } } else { assert(type == XPC_TYPE_DICTIONARY); // Handle the message xpc_retain(event); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{ xpc_object_t contents = xpc_dictionary_get_value(event, "msg"); if (!contents) { // Ping back. contents = xpc_dictionary_get_value(event, "ping"); assert(contents && "unexpected message"); xpc_object_t reply = xpc_dictionary_create_reply(event); assert(reply); xpc_connection_send_message(peer, reply); xpc_release(reply); return; } auto Responder = std::make_shared<XPCResponder>(event, peer); xpc_release(event); assert(xpc_get_type(contents) == XPC_TYPE_ARRAY); sourcekitd_object_t req = xpc_array_get_value(contents, 0); sourcekitd::handleRequest(req, [Responder](sourcekitd_response_t response) { Responder->sendReply(response); }); }); } } static void getInitializationInfo(xpc_connection_t peer) { xpc_object_t contents = xpc_array_create(nullptr, 0); xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, (uint64_t)xpc::Message::Initialization); xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0); xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents); xpc_release(contents); xpc_object_t reply = xpc_connection_send_message_with_reply_sync(peer, msg); xpc_release(msg); if (xpc_get_type(reply) == XPC_TYPE_ERROR) { xpc_release(reply); return; } assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY); uint64_t Delay = xpc_dictionary_get_uint64(reply, xpc::KeySemaEditorDelay); uint64_t TracingEnabled = xpc_dictionary_get_uint64(reply, xpc::KeyTracingEnabled); xpc_release(reply); if (Delay != 0) { llvm::SmallString<4> Buf; { llvm::raw_svector_ostream OS(Buf); OS << Delay; } setenv("SOURCEKIT_DELAY_SEMA_EDITOR", Buf.c_str(), /*overwrite=*/1); } if (TracingEnabled) { SourceKit::trace::enable(); } } static void sourcekitdServer_event_handler(xpc_connection_t peer) { // Keep the service alive even when idle. xpc_transaction_begin(); // By defaults, new connections will target the default dispatch // concurrent queue. xpc_connection_set_event_handler(peer, ^(xpc_object_t event) { sourcekitdServer_peer_event_handler(peer, event); }); MainConnection = peer; // This will tell the connection to begin listening for events. If you // have some other initialization that must be done asynchronously, then // you can defer this call until after that initialization is done. xpc_connection_resume(peer); dispatch_async(dispatch_get_main_queue(), ^{ getInitializationInfo(MainConnection); }); } static void fatal_error_handler(void *user_data, const std::string& reason, bool gen_crash_diag) { // Write the result out to stderr avoiding errs() because raw_ostreams can // call report_fatal_error. fprintf(stderr, "SOURCEKITD SERVER FATAL ERROR: %s\n", reason.c_str()); ::abort(); } int main(int argc, const char *argv[]) { llvm::install_fatal_error_handler(fatal_error_handler, 0); sourcekitd::enableLogging("sourcekit-serv"); sourcekitd::initialize(); sourcekitd::trace::initialize(); // Increase the file descriptor limit. // FIXME: Portability ? static const size_t FDLimit = 4096; struct rlimit l; if (getrlimit(RLIMIT_NOFILE, &l) == 0) { if (l.rlim_cur < FDLimit) { l.rlim_cur = FDLimit; if (setrlimit(RLIMIT_NOFILE, &l) == 0) { LOG_INFO_FUNC(Low, "bumped file descriptor limit to " << FDLimit); } else { LOG_WARN_FUNC("setrlimit failed: " << llvm::sys::StrError()); } } } else { LOG_WARN_FUNC("getrlimit failed: " << llvm::sys::StrError()); } xpc_main(sourcekitdServer_event_handler); return 0; } UIdent SKUIDToUIDMap::get(sourcekitd_uid_t SKDUID) { UIdent UID; Queue.dispatchSync([&]{ MapTy::iterator It = Map.find(SKDUID); if (It != Map.end()) UID = It->second; }); return UID; } void SKUIDToUIDMap::set(sourcekitd_uid_t SKDUID, UIdent UID) { Queue.dispatchBarrier([=]{ this->Map[SKDUID] = UID; }); } void sourcekitd::trace::sendTraceMessage(trace::sourcekitd_trace_message_t Msg) { if (!SourceKit::trace::enabled()) { xpc_release(Msg); return; } xpc_connection_t Peer = MainConnection; if (!Peer) { SourceKit::trace::disable(); xpc_release(Msg); return; } xpc_object_t Contents = xpc_array_create(nullptr, 0); xpc_array_set_uint64(Contents, XPC_ARRAY_APPEND, static_cast<uint64_t>(xpc::Message::TraceMessage)); xpc_array_set_uint64(Contents, XPC_ARRAY_APPEND, trace::getTracingSession()); xpc_array_set_value(Contents, XPC_ARRAY_APPEND, Msg); xpc_release(Msg); xpc_object_t Message = xpc_dictionary_create(nullptr, nullptr, 0); xpc_dictionary_set_value(Message, xpc::KeyInternalMsg, Contents); xpc_release(Contents); xpc_object_t Reply = xpc_connection_send_message_with_reply_sync(Peer, Message); xpc_release(Message); if (xpc_get_type(Reply) == XPC_TYPE_ERROR) { SourceKit::trace::disable(); xpc_release(Reply); return; } xpc_release(Reply); } <commit_msg>[SourceKit] Avoid calling "sourcekitd::shutdown()" on the service side, when the connection closes.<commit_after>//===--- XPCService.cpp ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "sourcekitd/Internal-XPC.h" #include "sourcekitd/Logging.h" #include "sourcekitd/XpcTracing.h" #include "SourceKit/Core/LLVM.h" #include "SourceKit/Support/Concurrency.h" #include "SourceKit/Support/UIdent.h" #include "SourceKit/Support/Logging.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Errno.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/Threading.h" #include <xpc/xpc.h> using namespace SourceKit; using namespace sourcekitd; static xpc_connection_t MainConnection = nullptr; void sourcekitd::postNotification(sourcekitd_response_t Notification) { xpc_connection_t peer = MainConnection; if (!peer) goto done; { xpc_object_t contents = xpc_array_create(nullptr, 0); xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, (uint64_t)xpc::Message::Notification); xpc_array_set_value(contents, XPC_ARRAY_APPEND, Notification); xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0); xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents); xpc_release(contents); xpc_connection_send_message(peer, msg); xpc_release(msg); } done: // The function accepted ownership. xpc_release(Notification); } namespace { /// \brief Associates sourcekitd_uid_t to a UIdent. class SKUIDToUIDMap { typedef llvm::DenseMap<void *, UIdent> MapTy; MapTy Map; WorkQueue Queue{ WorkQueue::Dequeuing::Concurrent, "UIDMap" }; public: UIdent get(sourcekitd_uid_t SKDUID); void set(sourcekitd_uid_t SKDUID, UIdent UID); }; } static SKUIDToUIDMap UIDMap; sourcekitd_uid_t sourcekitd::SKDUIDFromUIdent(UIdent UID) { if (void *Tag = UID.getTag()) return reinterpret_cast<sourcekitd_uid_t>(Tag); // FIXME: The following should run in the synchronous dispatch queue of the // connection. But does it matter, since if MainConnection is null or gets // destroyed it means the client crashed ? xpc_connection_t peer = MainConnection; if (!peer) return nullptr; xpc_object_t contents = xpc_array_create(nullptr, 0); xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, (uint64_t)xpc::Message::UIDSynchronization); xpc_array_set_string(contents, XPC_ARRAY_APPEND, UID.c_str()); xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0); xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents); xpc_release(contents); xpc_object_t reply = xpc_connection_send_message_with_reply_sync(peer, msg); xpc_release(msg); if (xpc_get_type(reply) == XPC_TYPE_ERROR) { xpc_release(reply); return nullptr; } assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY); uint64_t val = xpc_dictionary_get_uint64(reply, xpc::KeyMsgResponse); xpc_release(reply); sourcekitd_uid_t skduid = sourcekitd_uid_t(val); UID.setTag(skduid); UIDMap.set(skduid, UID); return skduid; } UIdent sourcekitd::UIdentFromSKDUID(sourcekitd_uid_t SKDUID) { // This should be used only for debugging/logging purposes. UIdent UID = UIDMap.get(SKDUID); if (UID.isValid()) return UID; xpc_connection_t Peer = MainConnection; if (!Peer) return UIdent(); xpc_object_t contents = xpc_array_create(nullptr, 0); xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, (uint64_t)xpc::Message::UIDSynchronization); xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, uintptr_t(SKDUID)); xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0); xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents); xpc_release(contents); xpc_object_t reply = xpc_connection_send_message_with_reply_sync(Peer, msg); xpc_release(msg); if (xpc_get_type(reply) == XPC_TYPE_ERROR) { xpc_release(reply); return UIdent(); } assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY); const char *Str = xpc_dictionary_get_string(reply, xpc::KeyMsgResponse); UID = UIdent(Str); UID.setTag(SKDUID); UIDMap.set(SKDUID, UID); xpc_release(reply); return UID; } void anchorForGetMainExecutableInXPCService() {} namespace { /// Responsible for replying to an XPC request. class XPCResponder { xpc_connection_t Peer; xpc_object_t Event; bool Responded = false; public: XPCResponder(xpc_object_t event, xpc_connection_t peer) : Peer(xpc_connection_t(xpc_retain(peer))), Event(xpc_retain(event)) {} ~XPCResponder() { if (!Responded) { LOG_WARN_FUNC("failed to respond to request"); sendReply(createErrorRequestFailed("Internal error: no response was " "provided for the request")); } xpc_release(Event); xpc_release(Peer); } /// Accepts ownership of the response object. void sendReply(sourcekitd_response_t response) { if (Responded) { LOG_WARN_FUNC("tried to respond to an already handled request"); return; } xpc_object_t reply = xpc_dictionary_create_reply(Event); xpc_dictionary_set_value(reply, xpc::KeyMsgResponse, response); xpc_release(response); xpc_connection_send_message(Peer, reply); xpc_release(reply); Responded = true; } }; } std::string sourcekitd::getRuntimeLibPath() { std::string MainExePath = llvm::sys::fs::getMainExecutable("sourcekit", reinterpret_cast<void *>(&anchorForGetMainExecutableInXPCService)); #ifdef SOURCEKIT_UNVERSIONED_FRAMEWORK_BUNDLE // MainExePath points to "lib/sourcekitd.framework/XPCServices/ // SourceKitService.xpc/SourceKitService" const unsigned MainExeLibNestingLevel = 4; #else // MainExePath points to "lib/sourcekitd.framework/Versions/Current/XPCServices/ // SourceKitService.xpc/Contents/MacOS/SourceKitService" const unsigned MainExeLibNestingLevel = 8; #endif // Get it to lib. StringRef Path = MainExePath; for (unsigned i = 0; i < MainExeLibNestingLevel; ++i) Path = llvm::sys::path::parent_path(Path); return Path; } static void sourcekitdServer_peer_event_handler(xpc_connection_t peer, xpc_object_t event) { xpc_type_t type = xpc_get_type(event); if (type == XPC_TYPE_ERROR) { if (event == XPC_ERROR_CONNECTION_INVALID) { // The client process on the other end of the connection has either // crashed or cancelled the connection. After receiving this error, // the connection is in an invalid state, and we do not need to // call xpc_connection_cancel(). // No need to call sourcekitd::shutdown() since the process is going down // anyway, plus if we get a new connection before the process closes then // we will fail to re-initialize properly since the initialize call is at // main. xpc_transaction_end(); } else if (event == XPC_ERROR_TERMINATION_IMMINENT) { // Handle per-connection termination cleanup. xpc_connection_cancel(peer); } } else { assert(type == XPC_TYPE_DICTIONARY); // Handle the message xpc_retain(event); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{ xpc_object_t contents = xpc_dictionary_get_value(event, "msg"); if (!contents) { // Ping back. contents = xpc_dictionary_get_value(event, "ping"); assert(contents && "unexpected message"); xpc_object_t reply = xpc_dictionary_create_reply(event); assert(reply); xpc_connection_send_message(peer, reply); xpc_release(reply); return; } auto Responder = std::make_shared<XPCResponder>(event, peer); xpc_release(event); assert(xpc_get_type(contents) == XPC_TYPE_ARRAY); sourcekitd_object_t req = xpc_array_get_value(contents, 0); sourcekitd::handleRequest(req, [Responder](sourcekitd_response_t response) { Responder->sendReply(response); }); }); } } static void getInitializationInfo(xpc_connection_t peer) { xpc_object_t contents = xpc_array_create(nullptr, 0); xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, (uint64_t)xpc::Message::Initialization); xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0); xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents); xpc_release(contents); xpc_object_t reply = xpc_connection_send_message_with_reply_sync(peer, msg); xpc_release(msg); if (xpc_get_type(reply) == XPC_TYPE_ERROR) { xpc_release(reply); return; } assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY); uint64_t Delay = xpc_dictionary_get_uint64(reply, xpc::KeySemaEditorDelay); uint64_t TracingEnabled = xpc_dictionary_get_uint64(reply, xpc::KeyTracingEnabled); xpc_release(reply); if (Delay != 0) { llvm::SmallString<4> Buf; { llvm::raw_svector_ostream OS(Buf); OS << Delay; } setenv("SOURCEKIT_DELAY_SEMA_EDITOR", Buf.c_str(), /*overwrite=*/1); } if (TracingEnabled) { SourceKit::trace::enable(); } } static void sourcekitdServer_event_handler(xpc_connection_t peer) { // Keep the service alive even when idle. xpc_transaction_begin(); // By defaults, new connections will target the default dispatch // concurrent queue. xpc_connection_set_event_handler(peer, ^(xpc_object_t event) { sourcekitdServer_peer_event_handler(peer, event); }); MainConnection = peer; // This will tell the connection to begin listening for events. If you // have some other initialization that must be done asynchronously, then // you can defer this call until after that initialization is done. xpc_connection_resume(peer); dispatch_async(dispatch_get_main_queue(), ^{ getInitializationInfo(MainConnection); }); } static void fatal_error_handler(void *user_data, const std::string& reason, bool gen_crash_diag) { // Write the result out to stderr avoiding errs() because raw_ostreams can // call report_fatal_error. fprintf(stderr, "SOURCEKITD SERVER FATAL ERROR: %s\n", reason.c_str()); ::abort(); } int main(int argc, const char *argv[]) { llvm::install_fatal_error_handler(fatal_error_handler, 0); sourcekitd::enableLogging("sourcekit-serv"); sourcekitd::initialize(); sourcekitd::trace::initialize(); // Increase the file descriptor limit. // FIXME: Portability ? static const size_t FDLimit = 4096; struct rlimit l; if (getrlimit(RLIMIT_NOFILE, &l) == 0) { if (l.rlim_cur < FDLimit) { l.rlim_cur = FDLimit; if (setrlimit(RLIMIT_NOFILE, &l) == 0) { LOG_INFO_FUNC(Low, "bumped file descriptor limit to " << FDLimit); } else { LOG_WARN_FUNC("setrlimit failed: " << llvm::sys::StrError()); } } } else { LOG_WARN_FUNC("getrlimit failed: " << llvm::sys::StrError()); } xpc_main(sourcekitdServer_event_handler); return 0; } UIdent SKUIDToUIDMap::get(sourcekitd_uid_t SKDUID) { UIdent UID; Queue.dispatchSync([&]{ MapTy::iterator It = Map.find(SKDUID); if (It != Map.end()) UID = It->second; }); return UID; } void SKUIDToUIDMap::set(sourcekitd_uid_t SKDUID, UIdent UID) { Queue.dispatchBarrier([=]{ this->Map[SKDUID] = UID; }); } void sourcekitd::trace::sendTraceMessage(trace::sourcekitd_trace_message_t Msg) { if (!SourceKit::trace::enabled()) { xpc_release(Msg); return; } xpc_connection_t Peer = MainConnection; if (!Peer) { SourceKit::trace::disable(); xpc_release(Msg); return; } xpc_object_t Contents = xpc_array_create(nullptr, 0); xpc_array_set_uint64(Contents, XPC_ARRAY_APPEND, static_cast<uint64_t>(xpc::Message::TraceMessage)); xpc_array_set_uint64(Contents, XPC_ARRAY_APPEND, trace::getTracingSession()); xpc_array_set_value(Contents, XPC_ARRAY_APPEND, Msg); xpc_release(Msg); xpc_object_t Message = xpc_dictionary_create(nullptr, nullptr, 0); xpc_dictionary_set_value(Message, xpc::KeyInternalMsg, Contents); xpc_release(Contents); xpc_object_t Reply = xpc_connection_send_message_with_reply_sync(Peer, Message); xpc_release(Message); if (xpc_get_type(Reply) == XPC_TYPE_ERROR) { SourceKit::trace::disable(); xpc_release(Reply); return; } xpc_release(Reply); } <|endoftext|>
<commit_before>#include <sender.hpp> #include <serialization.hpp> #include <boost/asio/io_service.hpp> using boost::asio::ip::tcp; NetworkSender::NetworkSender(std::shared_ptr<ReplicaSet> replicaset_) : io_service_(), socket_(io_service_), replicaset(replicaset_) { } NetworkSender::NetworkSender() : io_service_(), socket_(io_service_), replicaset(new ReplicaSet()) { } NetworkSender::~NetworkSender() { io_service_.post([this]() { socket_.close(); } ); } void NetworkSender::Reply(Message message) { tcp::resolver resolver(io_service_); auto endpoint = resolver.resolve( { message.to.hostname, std::to_string(message.to.port) }); boost::asio::async_connect(socket_, endpoint, [this, message](boost::system::error_code ec, tcp::resolver::iterator) { if (!ec) { // 1. serialize message std::string message_str = Serialize(message).str(); // 2. write message boost::asio::write( socket_, boost::asio::buffer( message_str.c_str(), message_str.size())); } }); } void NetworkSender::ReplyAll(Message message) { for (auto r : *replicaset) { Message m = message; m.to = r; Reply(m); } } <commit_msg>Update network sender to execute synchronous write operations<commit_after>#include <sender.hpp> #include <serialization.hpp> #include <boost/asio/io_service.hpp> using boost::asio::ip::tcp; NetworkSender::NetworkSender(std::shared_ptr<ReplicaSet> replicaset_) : io_service_(), socket_(io_service_), replicaset(replicaset_) { } NetworkSender::NetworkSender() : io_service_(), socket_(io_service_), replicaset(new ReplicaSet()) { } NetworkSender::~NetworkSender() { socket_.close(); } void NetworkSender::Reply(Message message) { tcp::resolver resolver(io_service_); auto endpoint = resolver.resolve( { message.to.hostname, std::to_string(message.to.port) }); boost::asio::connect(socket_, endpoint); // 1. serialize message std::string message_str = Serialize(message).str(); // 2. write message boost::asio::write(socket_, boost::asio::buffer(message_str.c_str(), message_str.size())); } void NetworkSender::ReplyAll(Message message) { for (auto r : *replicaset) { Message m = message; m.to = r; Reply(m); } } <|endoftext|>
<commit_before>#include "zonotope_halfspaces.hpp" #include <gmpxx.h> #include <iostream> int main() { using namespace std; typedef mpz_class NT; int n_tests; cin >> n_tests; for ( int t = 0; t < n_tests; ++t ) { int n, d; cin >> n >> d; vector<vector<NT> > generators ( n, vector<NT> ( d ) ); for ( int i = 0; i < n; ++i ) { for ( int j = 0; j < d; ++j ) { cin >> generators[i][j]; } } set<Hyperplane<NT> > halfspaces = zonotope_halfspaces<NT> (generators); cout << "n=" << n << " " << "d=" << d << " " << "ieqs=" << halfspaces.size() << "\n"; } return 0; } <commit_msg>Update the halfspaces test to also test `long` input/output<commit_after>#include "zonotope_halfspaces.hpp" #include <gmpxx.h> #include <iostream> int main() { using namespace std; int n_tests; cin >> n_tests; for ( int t = 0; t < n_tests; ++t ) { int n, d; cin >> n >> d; vector<vector<mpz_class> > generators_mpz ( n, vector<mpz_class> ( d ) ); vector<vector<long> > generators_long ( n, vector<long> ( d ) ); for ( int k = 0; k < n; ++k ) { for ( int i = 0; i < d; ++i ) { cin >> generators_long[k][i]; generators_mpz[k][i] = generators_long[k][i]; } } set<Hyperplane<mpz_class> > halfspaces_mpz; zonotope_halfspaces<mpz_class> (generators_mpz, halfspaces_mpz); set<Hyperplane<long> > halfspaces_long; zonotope_halfspaces<long> (generators_long, halfspaces_long); cout << "n=" << n << " " << "d=" << d << " " << "ieqs=" << halfspaces_mpz.size() << " " << "ieqs_long=" << halfspaces_long.size() << "\n"; } return 0; } <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Aki "lethalbit" Van Ness <aki@yosyshq.com> <aki@lethalbit.net> * * 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. * */ // MYAU - Metadata for Yosys-Assisted Utilities #include "kernel/rtlil.h" #include "kernel/register.h" #include "kernel/sigtools.h" #include "kernel/celltypes.h" #include "kernel/cellaigs.h" #include "kernel/log.h" #include <string> #include <unordered_map> #include <vector> USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct MetadataWriter { private: std::ostream &f; bool _use_selection; std::unordered_map<std::string, std::vector<Cell*>> _cells{}; // XXX(aki): this was pulled from the json backend, needs to be pulled // out possibly into some sort of utilities file, or integrated into rtlil.h // directly string get_string(string str) { string newstr = "\""; for (char c : str) { if (c == '\\') newstr += c; newstr += c; } return newstr + "\""; } // XXX(aki): I know this is far from ideal but i'm out of spoons and cant focus so // it'll have to do for now, void coalesce_cells(Module* mod) { for (auto cell : mod->cells()) { const auto cell_type = get_string(RTLIL::unescape_id(cell->type)); if (_cells.find(cell_type) == _cells.end()) _cells.emplace(cell_type, std::vector<Cell*>()); _cells.at(cell_type).push_back(cell); } } public: MetadataWriter(std::ostream &f, bool use_selection) noexcept: f(f), _use_selection(use_selection) { } void write_metadata(Design *design) { log_assert(design != nullptr); design->sort(); f << stringf("{\n"); f << stringf(" \"generator\": %s,\n", get_string(yosys_version_str).c_str()); // XXX(aki): Replace this with a proper version info eventually:tm: f << stringf(" \"version\": \"0.0.0\",\n"); f << stringf(" \"modules\": [\n"); bool first{true}; for (auto mod : _use_selection ? design->selected_modules() : design->modules()) { if (!first) f << stringf(",\n"); write_module(mod); f << stringf("\n"); first = false; } f << stringf(" ]\n"); f << stringf("}\n"); } void write_module(Module* mod) { log_assert(mod != nullptr); coalesce_cells(mod); f << stringf(" {\n"); f << stringf(" \"name\": %s,\n", get_string(RTLIL::unescape_id(mod->name)).c_str()); f << stringf(" \"cell_sorts\": [\n"); bool first_sort{true}; for (auto& sort : _cells) { if (!first_sort) f << stringf(",\n"); write_cell_sort(sort); first_sort = false; } f << stringf("\n"); f << stringf(" ],\n"); f << stringf(" \"connections\": [\n"); f << stringf(" ]\n"); f << stringf(" }"); } void write_cell_sort(std::pair<const std::string, std::vector<Cell*>>& sort) { const auto port_cell = sort.second.front(); f << stringf(" {\n"); f << stringf(" \"type\": %s,\n", sort.first.c_str()); f << stringf(" \"ports\": [\n"); bool first_port{true}; for (auto con : port_cell->connections()) { if (!first_port) f << stringf(",\n"); f << stringf(" {\n"); f << stringf(" \"name\": %s,\n", get_string(RTLIL::unescape_id(con.first)).c_str()); f << stringf(" \"direction\": \""); if (port_cell->input(con.first)) f << stringf("i"); if (port_cell->input(con.first)) f << stringf("o"); f << stringf("\",\n"); if (con.second.size() == 1) f << stringf(" \"range\": [0, 0]\n"); else f << stringf(" \"range\": [%d, %d]\n", con.second.size(), 0); f << stringf(" }"); first_port = false; } f << stringf("\n"); f << stringf(" ],\n \"cells\": [\n"); bool first_cell{true}; for (auto& cell : sort.second) { if (!first_cell) f << stringf(",\n"); write_cell(cell); first_cell = false; } f << stringf("\n"); f << stringf(" ]\n"); f << stringf(" }"); } void write_cell(Cell* cell) { log_assert(cell != nullptr); f << stringf(" {\n"); f << stringf(" \"name\": %s,\n", get_string(RTLIL::unescape_id(cell->name)).c_str()); f << stringf(" \"attributes\": {\n"); bool first_attr{true}; for (auto& attr : cell->attributes) { if (!first_attr) f << stringf(",\n"); const auto attr_val = attr.second.decode_string(); if (attr_val.size() > 0) f << stringf(" %s: \"%s\"\n", get_string(RTLIL::unescape_id(attr.first)).c_str(), attr_val.c_str()); else f << stringf(" %s: true\n", get_string(RTLIL::unescape_id(attr.first)).c_str()); first_attr = false; } f << stringf(" },\n"); f << stringf(" \"parameters\": {\n"); bool first_param{true}; for (auto& param : cell->parameters) { if (!first_param) f << stringf(",\n"); const auto param_val = param.second.decode_string(); if (param_val.size() > 0) f << stringf(" %s: \"%s\"\n", get_string(RTLIL::unescape_id(param.first)).c_str(), param_val.c_str()); else f << stringf(" %s: true\n", get_string(RTLIL::unescape_id(param.first)).c_str()); first_param = false; } f << stringf(" },\n"); f << stringf(" }"); } }; struct MetadataBackend : public Backend { MetadataBackend() : Backend("metadata", "generate design metadata") { } void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" metadata [options] [selection]\n"); log("\n"); log("Write a JSON metadata for the current design\n"); log("\n"); log("\n"); } void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) override { size_t argidx{1}; extra_args(f, filename, args, argidx); log_header(design, "Executing metadata backend.\n"); MetadataWriter metadata_writier(*f, false); metadata_writier.write_metadata(design); } } MetadataBackend; struct MetadataPass : public Pass { MetadataPass() : Pass("metadata", "write design metadata") { } void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" metadata [options] [selection]\n"); log("\n"); log("Write a JSON metadata for the current design\n"); log("\n"); log(" -o <filename>\n"); log(" write to the specified file.\n"); log("\n"); log("See 'help write_metadata' for a description of the JSON format used.\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) override { std::string filename{}; size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-o" && argidx+1 < args.size()) { filename = args[++argidx]; continue; } break; } extra_args(args, argidx, design); std::ostream *f; std::stringstream buf; if (!filename.empty()) { rewrite_filename(filename); std::ofstream *ff = new std::ofstream; ff->open(filename.c_str(), std::ofstream::trunc); if (ff->fail()) { delete ff; log_error("Can't open file `%s' for writing: %s\n", filename.c_str(), strerror(errno)); } f = ff; } else { f = &buf; } MetadataWriter metadata_writier(*f, false); metadata_writier.write_metadata(design); if (!filename.empty()) { delete f; } else { log("%s", buf.str().c_str()); } } } MetadataPass; PRIVATE_NAMESPACE_END <commit_msg>pass metadata: some more rough work on dumping the parameters and attributes<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Aki "lethalbit" Van Ness <aki@yosyshq.com> <aki@lethalbit.net> * * 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. * */ // MYAU - Metadata for Yosys-Assisted Utilities #include "kernel/rtlil.h" #include "kernel/register.h" #include "kernel/sigtools.h" #include "kernel/celltypes.h" #include "kernel/cellaigs.h" #include "kernel/log.h" #include <string> #include <unordered_map> #include <vector> USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct MetadataWriter { private: std::ostream &f; bool _use_selection; std::unordered_map<std::string, std::vector<Cell*>> _cells{}; // XXX(aki): this was pulled from the json backend, needs to be pulled // out possibly into some sort of utilities file, or integrated into rtlil.h // directly string get_string(string str) { string newstr = "\""; for (char c : str) { if (c == '\\') newstr += c; newstr += c; } return newstr + "\""; } // XXX(aki): I know this is far from ideal but i'm out of spoons and cant focus so // it'll have to do for now, void coalesce_cells(Module* mod) { for (auto cell : mod->cells()) { const auto cell_type = get_string(RTLIL::unescape_id(cell->type)); if (_cells.find(cell_type) == _cells.end()) _cells.emplace(cell_type, std::vector<Cell*>()); _cells.at(cell_type).push_back(cell); } } public: MetadataWriter(std::ostream &f, bool use_selection) noexcept: f(f), _use_selection(use_selection) { } void write_metadata(Design *design) { log_assert(design != nullptr); design->sort(); f << stringf("{\n"); f << stringf(" \"generator\": %s,\n", get_string(yosys_version_str).c_str()); // XXX(aki): Replace this with a proper version info eventually:tm: f << stringf(" \"version\": \"0.0.0\",\n"); f << stringf(" \"modules\": [\n"); bool first{true}; for (auto mod : _use_selection ? design->selected_modules() : design->modules()) { if (!first) f << stringf(",\n"); write_module(mod); f << stringf("\n"); first = false; } f << stringf(" ]\n"); f << stringf("}\n"); } void write_module(Module* mod) { log_assert(mod != nullptr); coalesce_cells(mod); f << stringf(" {\n"); f << stringf(" \"name\": %s,\n", get_string(RTLIL::unescape_id(mod->name)).c_str()); f << stringf(" \"cell_sorts\": [\n"); bool first_sort{true}; for (auto& sort : _cells) { if (!first_sort) f << stringf(",\n"); write_cell_sort(sort); first_sort = false; } f << stringf("\n"); f << stringf(" ],\n"); f << stringf(" \"connections\": [\n"); f << stringf(" ]\n"); f << stringf(" }"); } void write_cell_sort(std::pair<const std::string, std::vector<Cell*>>& sort) { const auto port_cell = sort.second.front(); f << stringf(" {\n"); f << stringf(" \"type\": %s,\n", sort.first.c_str()); f << stringf(" \"ports\": [\n"); bool first_port{true}; for (auto con : port_cell->connections()) { if (!first_port) f << stringf(",\n"); f << stringf(" {\n"); f << stringf(" \"name\": %s,\n", get_string(RTLIL::unescape_id(con.first)).c_str()); f << stringf(" \"direction\": \""); if (port_cell->input(con.first)) f << stringf("i"); if (port_cell->input(con.first)) f << stringf("o"); f << stringf("\",\n"); if (con.second.size() == 1) f << stringf(" \"range\": [0, 0]\n"); else f << stringf(" \"range\": [%d, %d]\n", con.second.size(), 0); f << stringf(" }"); first_port = false; } f << stringf("\n"); f << stringf(" ],\n \"cells\": [\n"); bool first_cell{true}; for (auto& cell : sort.second) { if (!first_cell) f << stringf(",\n"); write_cell(cell); first_cell = false; } f << stringf("\n"); f << stringf(" ]\n"); f << stringf(" }"); } void write_cell(Cell* cell) { log_assert(cell != nullptr); f << stringf(" {\n"); f << stringf(" \"name\": %s,\n", get_string(RTLIL::unescape_id(cell->name)).c_str()); f << stringf(" \"attributes\": {\n"); bool first_attr{true}; for (auto& attr : cell->attributes) { if (!first_attr) f << stringf(",\n"); const auto attr_val = attr.second; if (!attr_val.empty()) f << stringf(" %s: \"%s\"\n", get_string(RTLIL::unescape_id(attr.first)).c_str(), attr_val.decode_string().c_str()); else f << stringf(" %s: true\n", get_string(RTLIL::unescape_id(attr.first)).c_str()); first_attr = false; } f << stringf(" },\n"); f << stringf(" \"parameters\": {\n"); bool first_param{true}; for (auto& param : cell->parameters) { if (!first_param) f << stringf(",\n"); const auto param_val = param.second; if (!param_val.empty()) f << stringf(" %s: \"%s\"\n", get_string(RTLIL::unescape_id(param.first)).c_str(), param_val.decode_string().c_str()); else f << stringf(" %s: true\n", get_string(RTLIL::unescape_id(param.first)).c_str()); first_param = false; } f << stringf(" },\n"); f << stringf(" }"); } }; struct MetadataBackend : public Backend { MetadataBackend() : Backend("metadata", "generate design metadata") { } void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" metadata [options] [selection]\n"); log("\n"); log("Write a JSON metadata for the current design\n"); log("\n"); log("\n"); } void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) override { size_t argidx{1}; extra_args(f, filename, args, argidx); log_header(design, "Executing metadata backend.\n"); MetadataWriter metadata_writier(*f, false); metadata_writier.write_metadata(design); } } MetadataBackend; struct MetadataPass : public Pass { MetadataPass() : Pass("metadata", "write design metadata") { } void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" metadata [options] [selection]\n"); log("\n"); log("Write a JSON metadata for the current design\n"); log("\n"); log(" -o <filename>\n"); log(" write to the specified file.\n"); log("\n"); log("See 'help write_metadata' for a description of the JSON format used.\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) override { std::string filename{}; size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-o" && argidx+1 < args.size()) { filename = args[++argidx]; continue; } break; } extra_args(args, argidx, design); std::ostream *f; std::stringstream buf; if (!filename.empty()) { rewrite_filename(filename); std::ofstream *ff = new std::ofstream; ff->open(filename.c_str(), std::ofstream::trunc); if (ff->fail()) { delete ff; log_error("Can't open file `%s' for writing: %s\n", filename.c_str(), strerror(errno)); } f = ff; } else { f = &buf; } MetadataWriter metadata_writier(*f, false); metadata_writier.write_metadata(design); if (!filename.empty()) { delete f; } else { log("%s", buf.str().c_str()); } } } MetadataPass; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>/* Copyright 2002-2013 CEA LIST This file is part of LIMA. LIMA is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. LIMA 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 LIMA. If not, see <http://www.gnu.org/licenses/> */ /************************************************************************ * * @file ExternalProcessUnit.cpp * @author besancon (besanconr@zoe.cea.fr) * @date Mon Jan 17 2011 * copyright Copyright (C) 2011 by CEA LIST (LVIC) * ***********************************************************************/ #include "ExternalProcessUnit.h" #include "common/AbstractFactoryPattern/SimpleFactory.h" #include "linguisticProcessing/common/annotationGraph/AnnotationData.h" #include "common/XMLConfigurationFiles/xmlConfigurationFileExceptions.h" #include "common/time/traceUtils.h" #include "linguisticProcessing/core/LinguisticProcessors/LinguisticMetaData.h" #include "linguisticProcessing/core/LinguisticResources/AbstractResource.h" #include "linguisticProcessing/core/LinguisticResources/LinguisticResources.h" #include "linguisticProcessing/core/LinguisticAnalysisStructure/AnalysisGraph.h" #include "linguisticProcessing/core/TextSegmentation/SegmentationData.h" #include "linguisticProcessing/client/AnalysisHandlers/SimpleStreamHandler.h" //#include "boost/process.hpp" #include <QtCore/QProcess> #include <fstream> //namespace bp = ::boost::process; using namespace std; namespace Lima { namespace LinguisticProcessing { #define DEFAULT_TEMPFILE "/tmp/lp_external_tmp" SimpleFactory<MediaProcessUnit,ExternalProcessUnit> ExternalProcessUnitFactory(EXTERNALPROCESSUNIT_CLASSID); ExternalProcessUnit::ExternalProcessUnit(): MediaProcessUnit(), m_dumper(), m_loader(), m_commandLine(), m_useTemporaryFile(true), m_cleanTemporaryFile(true), m_tmpFileName(DEFAULT_TEMPFILE), m_handler(0), m_out(0), m_inputSuffix(), m_outputSuffix() { } ExternalProcessUnit::~ExternalProcessUnit() { } //************************************************************************ bool getBooleanParameter(Common::XMLConfigurationFiles::GroupConfigurationStructure& unitConfiguration, const std::string& param) { string value=unitConfiguration.getParamsValueAtKey(param); if (value == "yes" || value == "true" || value == "1") { return true; } return false; } void ExternalProcessUnit::init( Common::XMLConfigurationFiles::GroupConfigurationStructure& unitConfiguration, Manager* manager) { LOGINIT("LP:External"); LDEBUG << "Initialization"; MediaId language=manager->getInitializationParameters().media; try { string dumperName=unitConfiguration.getParamsValueAtKey("dumper"); // create the dumper m_dumper=manager->getObject(dumperName); } catch (Common::XMLConfigurationFiles::NoSuchParam& ) { LERROR << "Missing 'dumper' parameter in ExternalProcessUnit group for language " << (int)language << " !"; throw InvalidConfiguration(); } try { string loaderName=unitConfiguration.getParamsValueAtKey("loader"); // create the loader m_loader=manager->getObject(loaderName); } catch (InvalidConfiguration& ) { m_loader = 0; } catch (Common::XMLConfigurationFiles::NoSuchParam& ) { LERROR << "Missing 'loader' parameter in ExternalProcessUnit group for language " << (int)language << " !"; throw InvalidConfiguration(); } try { m_inputSuffix=QString::fromUtf8(unitConfiguration.getParamsValueAtKey("inputSuffix").c_str()); } catch (Common::XMLConfigurationFiles::NoSuchParam& ) { // optional parameter: keep default value } try { m_outputSuffix=QString::fromUtf8(unitConfiguration.getParamsValueAtKey("outputSuffix").c_str()); } catch (Common::XMLConfigurationFiles::NoSuchParam& ) { // optional parameter: keep default value } try { m_useTemporaryFile=getBooleanParameter(unitConfiguration,"useTmpFile"); } catch (Common::XMLConfigurationFiles::NoSuchParam& ) { // optional parameter: keep default value } try { m_cleanTemporaryFile=getBooleanParameter(unitConfiguration,"cleanTmpFile"); } catch (Common::XMLConfigurationFiles::NoSuchParam& ) { // optional parameter: keep default value } try { m_tmpFileName=unitConfiguration.getParamsValueAtKey("tmpFileName"); } catch (Common::XMLConfigurationFiles::NoSuchParam& ) { // optional parameter: keep default value } try { m_commandLine=QString::fromUtf8(unitConfiguration.getParamsValueAtKey("command").c_str()); } catch (Common::XMLConfigurationFiles::NoSuchParam& ) { LERROR << "Missing 'command' parameter in ExternalProcessUnit group for language " << (int)language << " !"; throw InvalidConfiguration(); } } LimaStatusCode ExternalProcessUnit::process(AnalysisContent& analysis) const { TimeUtils::updateCurrentTime(); LOGINIT("LP:External"); LINFO << "ExternalProcessUnit: start"; LinguisticMetaData* metadata=static_cast<LinguisticMetaData*>(analysis.getData("LinguisticMetaData")); if (metadata == 0) { LERROR << "no LinguisticMetaData ! abort"; return MISSING_DATA; } LimaStatusCode returnCode(SUCCESS_ID); // produce temporary file with the given dumper LDEBUG << "ExternalProcessUnit: write tmp file"; returnCode=m_dumper->process(analysis); if (returnCode!=SUCCESS_ID) { LERROR << "ExternalProcessUnit: failed to dump data to temporary file"; return returnCode; } QString fileName = QString::fromUtf8(metadata->getMetaData("FileName").c_str()); QString inputFilename, outputFilename; // apply command line LDEBUG << "ExternalProcessUnit: apply external program"; QString commandLine = m_commandLine; if (!m_inputSuffix.isEmpty()) { inputFilename = fileName+ m_inputSuffix; } if (!m_outputSuffix.isEmpty()) { outputFilename = fileName + m_outputSuffix; } // commandLine = commandLine.arg(inputFilename).arg(outputFilename); LDEBUG << "Launching " << commandLine; QProcess::execute(commandLine); if (m_loader != 0) { // load results from the external program with the given loader LDEBUG << "ExternalProcessUnit: read results"; returnCode=m_loader->process(analysis); if (returnCode!=SUCCESS_ID) { LERROR << "ExternalProcessUnit: failed to load data from temporary file"; return returnCode; } } else { LWARN << "ExternalProcessUnit: no loader defined for the current external process unit"; } TimeUtils::logElapsedTime("ExternalProcessUnit"); return returnCode; } } // end namespace } // end namespace <commit_msg>Uncomment the line to launch the srl command with arguments<commit_after>/* Copyright 2002-2013 CEA LIST This file is part of LIMA. LIMA is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. LIMA 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 LIMA. If not, see <http://www.gnu.org/licenses/> */ /************************************************************************ * * @file ExternalProcessUnit.cpp * @author besancon (besanconr@zoe.cea.fr) * @date Mon Jan 17 2011 * copyright Copyright (C) 2011 by CEA LIST (LVIC) * ***********************************************************************/ #include "ExternalProcessUnit.h" #include "common/AbstractFactoryPattern/SimpleFactory.h" #include "linguisticProcessing/common/annotationGraph/AnnotationData.h" #include "common/XMLConfigurationFiles/xmlConfigurationFileExceptions.h" #include "common/time/traceUtils.h" #include "linguisticProcessing/core/LinguisticProcessors/LinguisticMetaData.h" #include "linguisticProcessing/core/LinguisticResources/AbstractResource.h" #include "linguisticProcessing/core/LinguisticResources/LinguisticResources.h" #include "linguisticProcessing/core/LinguisticAnalysisStructure/AnalysisGraph.h" #include "linguisticProcessing/core/TextSegmentation/SegmentationData.h" #include "linguisticProcessing/client/AnalysisHandlers/SimpleStreamHandler.h" //#include "boost/process.hpp" #include <QtCore/QProcess> #include <fstream> //namespace bp = ::boost::process; using namespace std; namespace Lima { namespace LinguisticProcessing { #define DEFAULT_TEMPFILE "/tmp/lp_external_tmp" SimpleFactory<MediaProcessUnit,ExternalProcessUnit> ExternalProcessUnitFactory(EXTERNALPROCESSUNIT_CLASSID); ExternalProcessUnit::ExternalProcessUnit(): MediaProcessUnit(), m_dumper(), m_loader(), m_commandLine(), m_useTemporaryFile(true), m_cleanTemporaryFile(true), m_tmpFileName(DEFAULT_TEMPFILE), m_handler(0), m_out(0), m_inputSuffix(), m_outputSuffix() { } ExternalProcessUnit::~ExternalProcessUnit() { } //************************************************************************ bool getBooleanParameter(Common::XMLConfigurationFiles::GroupConfigurationStructure& unitConfiguration, const std::string& param) { string value=unitConfiguration.getParamsValueAtKey(param); if (value == "yes" || value == "true" || value == "1") { return true; } return false; } void ExternalProcessUnit::init( Common::XMLConfigurationFiles::GroupConfigurationStructure& unitConfiguration, Manager* manager) { LOGINIT("LP:External"); LDEBUG << "Initialization"; MediaId language=manager->getInitializationParameters().media; try { string dumperName=unitConfiguration.getParamsValueAtKey("dumper"); // create the dumper m_dumper=manager->getObject(dumperName); } catch (Common::XMLConfigurationFiles::NoSuchParam& ) { LERROR << "Missing 'dumper' parameter in ExternalProcessUnit group for language " << (int)language << " !"; throw InvalidConfiguration(); } try { string loaderName=unitConfiguration.getParamsValueAtKey("loader"); // create the loader m_loader=manager->getObject(loaderName); } catch (InvalidConfiguration& ) { m_loader = 0; } catch (Common::XMLConfigurationFiles::NoSuchParam& ) { LERROR << "Missing 'loader' parameter in ExternalProcessUnit group for language " << (int)language << " !"; throw InvalidConfiguration(); } try { m_inputSuffix=QString::fromUtf8(unitConfiguration.getParamsValueAtKey("inputSuffix").c_str()); } catch (Common::XMLConfigurationFiles::NoSuchParam& ) { // optional parameter: keep default value } try { m_outputSuffix=QString::fromUtf8(unitConfiguration.getParamsValueAtKey("outputSuffix").c_str()); } catch (Common::XMLConfigurationFiles::NoSuchParam& ) { // optional parameter: keep default value } try { m_useTemporaryFile=getBooleanParameter(unitConfiguration,"useTmpFile"); } catch (Common::XMLConfigurationFiles::NoSuchParam& ) { // optional parameter: keep default value } try { m_cleanTemporaryFile=getBooleanParameter(unitConfiguration,"cleanTmpFile"); } catch (Common::XMLConfigurationFiles::NoSuchParam& ) { // optional parameter: keep default value } try { m_tmpFileName=unitConfiguration.getParamsValueAtKey("tmpFileName"); } catch (Common::XMLConfigurationFiles::NoSuchParam& ) { // optional parameter: keep default value } try { m_commandLine=QString::fromUtf8(unitConfiguration.getParamsValueAtKey("command").c_str()); } catch (Common::XMLConfigurationFiles::NoSuchParam& ) { LERROR << "Missing 'command' parameter in ExternalProcessUnit group for language " << (int)language << " !"; throw InvalidConfiguration(); } } LimaStatusCode ExternalProcessUnit::process(AnalysisContent& analysis) const { TimeUtils::updateCurrentTime(); LOGINIT("LP:External"); LINFO << "ExternalProcessUnit: start"; LinguisticMetaData* metadata=static_cast<LinguisticMetaData*>(analysis.getData("LinguisticMetaData")); if (metadata == 0) { LERROR << "no LinguisticMetaData ! abort"; return MISSING_DATA; } LimaStatusCode returnCode(SUCCESS_ID); // produce temporary file with the given dumper LDEBUG << "ExternalProcessUnit: write tmp file"; returnCode=m_dumper->process(analysis); if (returnCode!=SUCCESS_ID) { LERROR << "ExternalProcessUnit: failed to dump data to temporary file"; return returnCode; } QString fileName = QString::fromUtf8(metadata->getMetaData("FileName").c_str()); QString inputFilename, outputFilename; // apply command line LDEBUG << "ExternalProcessUnit: apply external program"; QString commandLine = m_commandLine; if (!m_inputSuffix.isEmpty()) { inputFilename = fileName+ m_inputSuffix; } if (!m_outputSuffix.isEmpty()) { outputFilename = fileName + m_outputSuffix; } commandLine = commandLine.arg(inputFilename).arg(outputFilename); LDEBUG << "Launching " << commandLine; QProcess::execute(commandLine); if (m_loader != 0) { // load results from the external program with the given loader LDEBUG << "ExternalProcessUnit: read results"; returnCode=m_loader->process(analysis); if (returnCode!=SUCCESS_ID) { LERROR << "ExternalProcessUnit: failed to load data from temporary file"; return returnCode; } } else { LWARN << "ExternalProcessUnit: no loader defined for the current external process unit"; } TimeUtils::logElapsedTime("ExternalProcessUnit"); return returnCode; } } // end namespace } // end namespace <|endoftext|>
<commit_before>#include "server.h" #include "unique_fd.h" #include <iostream> #include <cstdlib> #include <iomanip> #include <cstring> #include <sstream> #include <fstream> #include <thread> #include <sys/time.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <signal.h> #include <errno.h> namespace { const int fail = -1; const int inet_aton_fail = 0; static bool terminated = false; void termination(int signum) { terminated = true; } bool setSignalsHandlers() { struct sigaction sa; sa.sa_handler = termination; sigaddset(&sa.sa_mask, SIGTERM); sigaddset(&sa.sa_mask, SIGINT); sa.sa_flags = 0; if (sigaction(SIGTERM, &sa, nullptr) == fail) { perror("sigaction"); return false; } if (sigaction(SIGINT, &sa, nullptr) == fail) { perror("sigaction"); return false; } return true; } bool init(const http_server::Options& options) { if (options.daemon()) { if (daemon(0, 1) == fail) { perror("daemon"); return false; } } if (options.verbose()) { std::cout << "The server started as " << (options.daemon()? "daemon": "application") << std::endl; std::cout << "pid = " << getpid() << std::endl; } return setSignalsHandlers(); } aux::UniqueFd makeListeningSocket() { //aux::UniqueFd sd {socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0)}; aux::UniqueFd sockfd {socket(AF_INET, SOCK_STREAM, 0)}; if (!sockfd) { perror("socket"); return aux::UniqueFd(); } const int yes = 1; if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == fail) { perror("setsockopt"); return aux::UniqueFd(); } return sockfd; } bool startListen(const aux::UniqueFd& sockfd, const http_server::Options& options) { struct sockaddr_in addr_in; addr_in.sin_family = AF_INET; addr_in.sin_port = htons(options.port()); if (inet_aton(options.ip(), &addr_in.sin_addr) == inet_aton_fail) { std::cerr << "inet_aton: " << "The address '" << options.ip() << "' is wrong" << std::endl; return false; } if (options.verbose()) { std::cout << "Listening: " << inet_ntoa(addr_in.sin_addr) << ":" << ntohs(addr_in.sin_port) << std::endl; } if (bind(sockfd, reinterpret_cast<struct sockaddr*>(&addr_in), sizeof(addr_in)) == fail) { perror("bind"); return false; } if (listen(sockfd, SOMAXCONN) == fail) { perror("listen"); return false; } return true; } void outputBinaryData(const char * data, size_t size) { std::cout << std::setfill('0'); for(size_t i = 0; i < size; ++i) std::cout << std::setw(2) << std::hex << static_cast<int>(data[i]) << " "; std::cout << std::setfill(' '); std::cout << std::dec; std::cout << std::endl; std::cout << std::endl; } int sendData(int sockfd, const char * data, size_t size, bool verbose, std::ofstream& logout) { logout << std::string(data, size); if (verbose) { std::cout << "Send: "; outputBinaryData(data, size); } int res = send(sockfd, data, size, 0); if (res == -1) perror("send"); return res; } int sendBadRequest(int sockfd, bool verbose, std::ofstream& logout) { static const char badRequest[] = "HTTP/1.0 400 Bad Request\r\n" "Content-Type: text/html\r\n" "Content-Length: 43\r\n" "\r\n" "<html><body>400 Bad Request</body></html>\r\n"; return sendData(sockfd, badRequest, sizeof(badRequest) - 1, verbose, logout); } int sendNotFound(int sockfd, bool verbose, std::ofstream& logout) { static const char notFound[] = "HTTP/1.0 404 Not Found\r\n" "Content-Type: text/html\r\n" "Content-Length: 41\r\n" "\r\n" "<html><body>404 Not Found</body></html>\r\n"; return sendData(sockfd, notFound, sizeof(notFound) - 1, verbose, logout); } int sendAnswer(int sockfd, const std::string& data, bool verbose, std::ofstream& logout) { std::ostringstream os; os << "HTTP/1.0 200 OK\r\n" << "Content-Type: text/html\r\n" << "Content-Length: " << data.length() << "\r\n" << "\r\n" << data; return sendData(sockfd, os.str().c_str(), os.str().length(), verbose, logout); } void clientWorker(aux::UniqueFd&& sockfd, const sockaddr_in peerAddr, const http_server::Options& options) { aux::UniqueFd clientfd(std::move(sockfd)); std::string logName; { struct timeval tv; gettimeofday(&tv, NULL); std::ostringstream os; os << "/tmp/" << tv.tv_sec << "_" << tv.tv_usec << ".log"; logName = os.str(); os.str(""); } std::ofstream logout(logName); if (options.verbose()) { std::cout << "Connection with: " << inet_ntoa(peerAddr.sin_addr) << ":" << ntohs(peerAddr.sin_port) << std::endl; } logout << "Connection with: " << inet_ntoa(peerAddr.sin_addr) << ":" << ntohs(peerAddr.sin_port) << "\n" << std::endl; char buf[1024]; ssize_t received = recv(clientfd, &buf, sizeof(buf), 0); switch (received) { case -1: perror("recv"); break; case 0: break; default: if (options.verbose()) { std::cout << "Received: "; outputBinaryData(buf, received); } logout << std::string(buf, received); logout.flush(); const char* getLine = std::strtok(buf, "\r\n"); if ((getLine == NULL) || (strncmp(getLine, "GET ", 4) != 0)) { sendBadRequest(clientfd, options.verbose(), logout); return; } const char* protocolStr = std::strrchr(getLine, 'H'); if ((protocolStr == NULL) || (std::strncmp(protocolStr, "HTTP/", 5) != 0)) { sendBadRequest(clientfd, options.verbose(), logout); return; } std::string filename(getLine + 4, protocolStr - getLine - 5); std::filebuf file; if (file.open(options.directory() + filename, std::ios_base::in) == nullptr) { sendNotFound(clientfd, options.verbose(), logout); return; } using std::ios_base; auto posEnd = file.pubseekoff(0, ios_base::end); file.pubseekpos(0); //sendAnswer(clientfd, filename, options.verbose()); if (options.verbose()) std::cout << "Sending header..." << std::endl; std::ostringstream os; int fileSize = posEnd; os << "HTTP/1.0 200 OK\r\n" << "Content-Type: text/html\r\n" << "Content-Length: " << (fileSize - 1) << "\r\n" << "\r\n"; int read = 0; do { read = file.sgetn(buf, sizeof(buf)); os << std::string(buf, read); } while(read == sizeof(buf)); if (sendData(clientfd, os.str().c_str(), os.str().length(), options.verbose(), logout) == -1) return; /* if (options.verbose()) std::cout << "Sending content..." << std::endl; int read = 0; do { read = file.sgetn(buf, sizeof(buf)); if (sendData(clientfd, buf, read, options.verbose()) == -1) return; } while(read == sizeof(buf)); */ break; } } } /* anonymous namespace */ int http_server::run(const http_server::Options& options) { if (!init(options)) return EXIT_FAILURE; aux::UniqueFd sockfd { makeListeningSocket() }; if (!sockfd) return EXIT_FAILURE; if (!startListen(sockfd, options)) return EXIT_FAILURE; std::ofstream logout("/tmp/mainfinal.log"); logout << "start" << std::endl; while(!terminated) { struct sockaddr_in peerAddr; socklen_t peerAddrSize = sizeof(peerAddr); aux::UniqueFd clientfd { accept(sockfd, reinterpret_cast<sockaddr*>(&peerAddr), &peerAddrSize) }; if (clientfd) { //clientWorker(std::move(clientfd), peerAddr, options); logout << "Connection with: " << inet_ntoa(peerAddr.sin_addr) << ":" << ntohs(peerAddr.sin_port) << "\n" << std::endl; std::thread t(clientWorker, std::move(clientfd), peerAddr, options); t.detach(); } else { perror("accept"); } } if (options.verbose()) std::cout << "The server stoped" << std::endl; logout << "stop\n"; logout.close(); return 0; } <commit_msg>single log<commit_after>#include "server.h" #include "unique_fd.h" #include <iostream> #include <cstdlib> #include <iomanip> #include <cstring> #include <sstream> #include <fstream> #include <thread> #include <sys/time.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <signal.h> #include <errno.h> namespace { const int fail = -1; const int inet_aton_fail = 0; static bool terminated = false; void termination(int signum) { terminated = true; } bool setSignalsHandlers() { struct sigaction sa; sa.sa_handler = termination; sigaddset(&sa.sa_mask, SIGTERM); sigaddset(&sa.sa_mask, SIGINT); sa.sa_flags = 0; if (sigaction(SIGTERM, &sa, nullptr) == fail) { perror("sigaction"); return false; } if (sigaction(SIGINT, &sa, nullptr) == fail) { perror("sigaction"); return false; } return true; } bool init(const http_server::Options& options) { if (options.daemon()) { if (daemon(0, 1) == fail) { perror("daemon"); return false; } } if (options.verbose()) { std::cout << "The server started as " << (options.daemon()? "daemon": "application") << std::endl; std::cout << "pid = " << getpid() << std::endl; } return setSignalsHandlers(); } aux::UniqueFd makeListeningSocket() { //aux::UniqueFd sd {socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0)}; aux::UniqueFd sockfd {socket(AF_INET, SOCK_STREAM, 0)}; if (!sockfd) { perror("socket"); return aux::UniqueFd(); } const int yes = 1; if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == fail) { perror("setsockopt"); return aux::UniqueFd(); } return sockfd; } bool startListen(const aux::UniqueFd& sockfd, const http_server::Options& options) { struct sockaddr_in addr_in; addr_in.sin_family = AF_INET; addr_in.sin_port = htons(options.port()); if (inet_aton(options.ip(), &addr_in.sin_addr) == inet_aton_fail) { std::cerr << "inet_aton: " << "The address '" << options.ip() << "' is wrong" << std::endl; return false; } if (options.verbose()) { std::cout << "Listening: " << inet_ntoa(addr_in.sin_addr) << ":" << ntohs(addr_in.sin_port) << std::endl; } if (bind(sockfd, reinterpret_cast<struct sockaddr*>(&addr_in), sizeof(addr_in)) == fail) { perror("bind"); return false; } if (listen(sockfd, SOMAXCONN) == fail) { perror("listen"); return false; } return true; } void outputBinaryData(const char * data, size_t size) { std::cout << std::setfill('0'); for(size_t i = 0; i < size; ++i) std::cout << std::setw(2) << std::hex << static_cast<int>(data[i]) << " "; std::cout << std::setfill(' '); std::cout << std::dec; std::cout << std::endl; std::cout << std::endl; } int sendData(int sockfd, const char * data, size_t size, bool verbose, std::ofstream& logout) { logout << std::string(data, size); if (verbose) { std::cout << "Send: "; outputBinaryData(data, size); } int res = send(sockfd, data, size, 0); if (res == -1) perror("send"); return res; } int sendBadRequest(int sockfd, bool verbose, std::ofstream& logout) { static const char badRequest[] = "HTTP/1.0 400 Bad Request\r\n" "Content-Type: text/html\r\n" "Content-Length: 43\r\n" "\r\n" "<html><body>400 Bad Request</body></html>\r\n"; return sendData(sockfd, badRequest, sizeof(badRequest) - 1, verbose, logout); } int sendNotFound(int sockfd, bool verbose, std::ofstream& logout) { static const char notFound[] = "HTTP/1.0 404 Not Found\r\n" "Content-Type: text/html\r\n" "Content-Length: 41\r\n" "\r\n" "<html><body>404 Not Found</body></html>\r\n"; return sendData(sockfd, notFound, sizeof(notFound) - 1, verbose, logout); } int sendAnswer(int sockfd, const std::string& data, bool verbose, std::ofstream& logout) { std::ostringstream os; os << "HTTP/1.0 200 OK\r\n" << "Content-Type: text/html\r\n" << "Content-Length: " << data.length() << "\r\n" << "\r\n" << data; return sendData(sockfd, os.str().c_str(), os.str().length(), verbose, logout); } void clientWorker(aux::UniqueFd&& sockfd, const sockaddr_in peerAddr, const http_server::Options& options, std::ofstream& logout ) { aux::UniqueFd clientfd(std::move(sockfd)); std::string logName; { struct timeval tv; gettimeofday(&tv, NULL); std::ostringstream os; os << "/tmp/" << tv.tv_sec << "_" << tv.tv_usec << ".log"; logName = os.str(); os.str(""); } //std::ofstream logout(logName); if (options.verbose()) { std::cout << "Connection with: " << inet_ntoa(peerAddr.sin_addr) << ":" << ntohs(peerAddr.sin_port) << std::endl; } logout << "Connection with: " << inet_ntoa(peerAddr.sin_addr) << ":" << ntohs(peerAddr.sin_port) << "\n" << std::endl; char buf[1024]; ssize_t received = recv(clientfd, &buf, sizeof(buf), 0); switch (received) { case -1: perror("recv"); break; case 0: break; default: if (options.verbose()) { std::cout << "Received: "; outputBinaryData(buf, received); } logout << std::string(buf, received); logout.flush(); const char* getLine = std::strtok(buf, "\r\n"); if ((getLine == NULL) || (strncmp(getLine, "GET ", 4) != 0)) { sendBadRequest(clientfd, options.verbose(), logout); return; } const char* protocolStr = std::strrchr(getLine, 'H'); if ((protocolStr == NULL) || (std::strncmp(protocolStr, "HTTP/", 5) != 0)) { sendBadRequest(clientfd, options.verbose(), logout); return; } std::string filename(getLine + 4, protocolStr - getLine - 5); std::filebuf file; if (file.open(options.directory() + filename, std::ios_base::in) == nullptr) { sendNotFound(clientfd, options.verbose(), logout); return; } using std::ios_base; auto posEnd = file.pubseekoff(0, ios_base::end); file.pubseekpos(0); //sendAnswer(clientfd, filename, options.verbose()); if (options.verbose()) std::cout << "Sending header..." << std::endl; std::ostringstream os; int fileSize = posEnd; os << "HTTP/1.0 200 OK\r\n" << "Content-Type: text/html\r\n" << "Content-Length: " << (fileSize - 1) << "\r\n" << "\r\n"; int read = 0; do { read = file.sgetn(buf, sizeof(buf)); os << std::string(buf, read); } while(read == sizeof(buf)); if (sendData(clientfd, os.str().c_str(), os.str().length(), options.verbose(), logout) == -1) return; /* if (options.verbose()) std::cout << "Sending content..." << std::endl; int read = 0; do { read = file.sgetn(buf, sizeof(buf)); if (sendData(clientfd, buf, read, options.verbose()) == -1) return; } while(read == sizeof(buf)); */ break; } } } /* anonymous namespace */ int http_server::run(const http_server::Options& options) { if (!init(options)) return EXIT_FAILURE; aux::UniqueFd sockfd { makeListeningSocket() }; if (!sockfd) return EXIT_FAILURE; if (!startListen(sockfd, options)) return EXIT_FAILURE; std::ofstream logout("/tmp/mainfinal.log"); logout << "start" << std::endl; while(!terminated) { struct sockaddr_in peerAddr; socklen_t peerAddrSize = sizeof(peerAddr); aux::UniqueFd clientfd { accept(sockfd, reinterpret_cast<sockaddr*>(&peerAddr), &peerAddrSize) }; if (clientfd) { //clientWorker(std::move(clientfd), peerAddr, options); logout << "Connection with: " << inet_ntoa(peerAddr.sin_addr) << ":" << ntohs(peerAddr.sin_port) << "\n" << std::endl; std::thread t(clientWorker, std::move(clientfd), peerAddr, options, std::ref(logout)); t.detach(); } else { perror("accept"); } } if (options.verbose()) std::cout << "The server stoped" << std::endl; logout << "stop\n"; logout.close(); return 0; } <|endoftext|>
<commit_before>#ifndef SAVE_STATE_H # define SAVE_STATE_H # pragma once struct statebuf { void* sp; void* label; }; #if defined(__GNUC__) inline bool __attribute__((always_inline)) savestate(statebuf& ssb) noexcept { bool r; #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ( "movl %%esp, %0\n\t" // store sp "movl $1f, %1\n\t" // store label "movb $0, %2\n\t" // return false "jmp 2f\n\t" "1:movb $1, %2\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ( "movq %%rsp, %0\n\t" // store sp "movq $1f, %1\n\t" // store label "movb $0, %2\n\t" // return false "jmp 2f\n\t" "1:movb $1, %2\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #elif defined(__arm__) asm volatile ( "str sp, %0" "b 2f\n\t" "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #endif return r; } #elif defined(_MSC_VER) __forceinline bool savestate(statebuf& ssb) noexcept { bool r; __asm { push ebp mov ebx, ssb mov [ebx]ssb.sp, esp mov [ebx]ssb.label, offset _1f mov r, 0x0 jmp _2f _1f: pop ebp mov r, 0x1 _2f: } return r; } #else # error "unsupported compiler" #endif #if defined(__GNUC__) #if defined(i386) || defined(__i386) || defined(__i386__) #define restorestate(SSB) \ asm volatile ( \ "movl %0, %%esp\n\t" \ "jmp *%1" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) #define restorestate(SSB) \ asm volatile ( \ "movq %0, %%rsp\n\t" \ "jmp *%1" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #elif defined(__arm__) #define restorestate(SSB) \ asm volatile ( \ "ldr sp, %0\n\t" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #else # error "unsupported architecture" #endif #elif defined(_MSC_VER) #define restorestate(SSB) \ __asm mov ebx, this \ __asm add ebx, [SSB] \ __asm mov esp, [ebx]SSB.sp\ __asm jmp [ebx]SSB.label #else # error "unsupported compiler" #endif #endif // SAVE_STATE_H <commit_msg>some fixes<commit_after>#ifndef SAVE_STATE_H # define SAVE_STATE_H # pragma once struct statebuf { void* sp; void* label; }; #if defined(__GNUC__) inline bool __attribute__((always_inline)) savestate(statebuf& ssb) noexcept { bool r; #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ( "movl %%esp, %0\n\t" // store sp "movl $1f, %1\n\t" // store label "movb $0, %2\n\t" // return false "jmp 2f\n\t" "1:movb $1, %2\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ( "movq %%rsp, %0\n\t" // store sp "movq $1f, %1\n\t" // store label "movb $0, %2\n\t" // return false "jmp 2f\n\t" "1:movb $1, %2\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #elif defined(__arm__) asm volatile ( "str sp, %0\n\t" "b 2f\n\t" "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #endif return r; } #elif defined(_MSC_VER) __forceinline bool savestate(statebuf& ssb) noexcept { bool r; __asm { push ebp mov ebx, ssb mov [ebx]ssb.sp, esp mov [ebx]ssb.label, offset _1f mov r, 0x0 jmp _2f _1f: pop ebp mov r, 0x1 _2f: } return r; } #else # error "unsupported compiler" #endif #if defined(__GNUC__) #if defined(i386) || defined(__i386) || defined(__i386__) #define restorestate(SSB) \ asm volatile ( \ "movl %0, %%esp\n\t" \ "jmp *%1" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) #define restorestate(SSB) \ asm volatile ( \ "movq %0, %%rsp\n\t" \ "jmp *%1" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #elif defined(__arm__) #define restorestate(SSB) \ asm volatile ( \ "ldr sp, %0\n\t" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #else # error "unsupported architecture" #endif #elif defined(_MSC_VER) #define restorestate(SSB) \ __asm mov ebx, this \ __asm add ebx, [SSB] \ __asm mov esp, [ebx]SSB.sp\ __asm jmp [ebx]SSB.label #else # error "unsupported compiler" #endif #endif // SAVE_STATE_H <|endoftext|>
<commit_before>#ifdef SHRINK #include "internal.hpp" #include "macros.hpp" #include <algorithm> namespace CaDiCaL { // This is an extended minimization which goes over all alternative reasons // as first explored in PrecoSAT and discussed by Allen Van Gelder later. // The most important observation in PrecoSAT was that alternative reasons // for resolution need to have all literals but one set to false and thus // the true literal will be watched. It subsumes clause minimization, but // is more expensive and thus should be called only on clauses for which // shrinking is useful (such as small clauses with small glue). As in // PrecoSAT we restrict traversal to follow the topological assignment order // to avoid cycles (which would yield unsound removals). bool Internal::shrink_literal (int lit, int depth) { assert (val (lit) > 0); Flags & f = flags (lit); Var & v = var (lit); if (!v.level || f.removable || f.clause) return true; if (!v.reason || f.poison || v.level == level) return false; const Level & l = control[v.level]; if (!depth && l.seen < 2) return false; if (v.trail <= l.trail) return false; if (depth > opts.shrinkdepth) return false; bool remove = false; Watches & ws = watches (lit); // The difference to 'minimize_literal' is here, where we iterate over all // clauses watches by 'lit' instead of 'just' the reason clause except for // '(!!!)' where we have to make sure that we respect assignment order in // resolutions to avoid cyclic derivations. For the actual reason this // test is not necessary. const const_watch_iterator eow = ws.end (); const_watch_iterator i; for (i = ws.begin (); !remove && i != eow; i++) { Clause * c = i->clause; const const_literal_iterator eoc = c->end (); const_literal_iterator j; bool failed = false; int lit_trail = var (lit).trail; for (j = c->begin (); !failed && j != eoc; j++) { int other = *j; if (other == lit) continue; else if (val (other) >= 0) failed = true; else if (var (other).trail > lit_trail) failed = true; // (!!!) else failed = !shrink_literal (-other, depth+1); } if (!failed) remove = true; } if (remove) f.removable = true; else f.poison = true; minimized.push_back (lit); if (!depth) LOG ("shrinking %d %s", lit, remove ? "succeeded" : "failed"); return remove; } void Internal::shrink_clause () { START (shrink); LOG (clause, "shrinking minimized first UIP clause"); stats.shrinktried += clause.size (); sort (clause.begin (), clause.end (), trail_smaller (this)); assert (minimized.empty ()); int_iterator j = clause.begin (); for (const_int_iterator i = j; i != clause.end (); i++) if (shrink_literal (-*i)) stats.shrunken++; else flags (*j++ = *i).clause = true; LOG ("shrunken %d literals", (long)(clause.end () - j)); clause.resize (j - clause.begin ()); clear_minimized (); check_learned_clause (); STOP (shrink); } }; #endif <commit_msg>shrink<commit_after>#ifdef SHRINK #include "internal.hpp" #include "macros.hpp" #include <algorithm> namespace CaDiCaL { // This is an extended minimization which goes over all alternative reasons // as first explored in PrecoSAT and discussed by Allen Van Gelder later. // The most important observation in PrecoSAT was that alternative reasons // for resolution need to have all literals but one set to false and thus // the true literal will be watched. It subsumes clause minimization, but // is more expensive and thus should be called only on clauses for which // shrinking is useful (such as small clauses with small glue). As in // PrecoSAT we restrict traversal to follow the topological assignment order // to avoid cycles (which could yield unsound removals). bool Internal::shrink_literal (int lit, int depth) { assert (val (lit) > 0); Flags & f = flags (lit); Var & v = var (lit); if (!v.level || f.removable || f.clause) return true; if (!v.reason || f.poison || v.level == level) return false; const Level & l = control[v.level]; if (!depth && l.seen < 2) return false; if (v.trail <= l.trail) return false; if (depth > opts.shrinkdepth) return false; bool remove = false; Watches & ws = watches (lit); // The difference to 'minimize_literal' is here, where we iterate over all // clauses watched by 'lit' instead of 'just' the reason clause except for // '(!!!)' where we have to make sure that we respect assignment order in // resolutions to avoid cyclic derivations. For the actual reason this // test is not necessary. const const_watch_iterator eow = ws.end (); const_watch_iterator i; for (i = ws.begin (); !remove && i != eow; i++) { Clause * c = i->clause; const const_literal_iterator eoc = c->end (); const_literal_iterator j; bool failed = false; int lit_trail = var (lit).trail; for (j = c->begin (); !failed && j != eoc; j++) { int other = *j; if (other == lit) continue; else if (val (other) >= 0) failed = true; else if (var (other).trail > lit_trail) failed = true; // (!!!) else failed = !shrink_literal (-other, depth+1); } if (!failed) remove = true; } if (remove) f.removable = true; else f.poison = true; minimized.push_back (lit); if (!depth) LOG ("shrinking %d %s", lit, remove ? "succeeded" : "failed"); return remove; } void Internal::shrink_clause () { START (shrink); LOG (clause, "shrinking minimized first UIP clause"); stats.shrinktried += clause.size (); sort (clause.begin (), clause.end (), trail_smaller (this)); assert (minimized.empty ()); int_iterator j = clause.begin (); for (const_int_iterator i = j; i != clause.end (); i++) if (shrink_literal (-*i)) stats.shrunken++; else flags (*j++ = *i).clause = true; LOG ("shrunken %d literals", (long)(clause.end () - j)); clause.resize (j - clause.begin ()); clear_minimized (); check_learned_clause (); STOP (shrink); } }; #endif <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl> * Copyright (c) 2011 Laszlo Papp <djszapi@archlinux.us> * * 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 */ #include "propertiesdock.h" #include "widgets/propertywidget.h" #include "objectmanager.h" #include "historymanager.h" #include <engine/game.h> #include <engine/component.h> using namespace GluonCreator; class PropertiesDock::PropertiesDockPrivate { public: PropertiesDockPrivate() { } PropertyWidget* widget; }; PropertiesDock::PropertiesDock( const QString& title, QWidget* parent, Qt::WindowFlags flags ) : QDockWidget( title, parent, flags ), d( new PropertiesDockPrivate ) { setObjectName( "PropertiesDock" ); d->widget = new PropertyWidget( this ); setWidget( d->widget ); connect( SelectionManager::instance(), SIGNAL( selectionChanged( SelectionManager::SelectionList ) ), SLOT( selectionChanged( SelectionManager::SelectionList ) ) ); connect( d->widget, SIGNAL( propertyChanged( QObject*, QString, QVariant, QVariant ) ), SLOT( propertyChanged( QObject*, QString, QVariant, QVariant ) ) ); connect( ObjectManager::instance(), SIGNAL( newComponent( GluonEngine::Component* ) ), SLOT( newComponent( GluonEngine::Component* ) ) ); } PropertiesDock::~PropertiesDock() { delete d; } void PropertiesDock::selectionChanged( SelectionManager::SelectionList selection ) { if( selection.empty() ) d->widget->clear(); else d->widget->setObject( selection.at( 0 ) ); } void PropertiesDock::newComponent( GluonEngine::Component* comp ) { if( comp->parent() == d->widget->object() ) { d->widget->setObject( d->widget->object() ); } } void PropertiesDock::propertyChanged( QObject* object, QString property, QVariant oldValue, QVariant newValue ) { GluonCore::GluonObject* obj = qobject_cast<GluonCore::GluonObject*>( object ); if( obj ) ObjectManager::instance()->changeProperty( obj, property, oldValue, newValue ); } <commit_msg>A little cleanup in the properties dock<commit_after>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl> * Copyright (c) 2011 Laszlo Papp <djszapi@archlinux.us> * * 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 */ #include "propertiesdock.h" #include "widgets/propertywidget.h" #include "objectmanager.h" #include "historymanager.h" #include <engine/game.h> #include <engine/component.h> using namespace GluonCreator; class PropertiesDock::PropertiesDockPrivate { public: PropertiesDockPrivate(PropertyWidget* widget) : widget(widget) { } PropertyWidget* widget; }; PropertiesDock::PropertiesDock( const QString& title, QWidget* parent, Qt::WindowFlags flags ) : QDockWidget( title, parent, flags ) , d( new PropertiesDockPrivate( new PropertyWidget( this ) ) ) { setObjectName( "PropertiesDock" ); setWidget( d->widget ); connect( SelectionManager::instance(), SIGNAL( selectionChanged( SelectionManager::SelectionList ) ), SLOT( selectionChanged( SelectionManager::SelectionList ) ) ); connect( d->widget, SIGNAL( propertyChanged( QObject*, QString, QVariant, QVariant ) ), SLOT( propertyChanged( QObject*, QString, QVariant, QVariant ) ) ); connect( ObjectManager::instance(), SIGNAL( newComponent( GluonEngine::Component* ) ), SLOT( newComponent( GluonEngine::Component* ) ) ); } PropertiesDock::~PropertiesDock() { delete d; } void PropertiesDock::selectionChanged( SelectionManager::SelectionList selection ) { d->widget->clear(); if( !selection.empty() ) d->widget->setObject( selection.at( 0 ) ); } void PropertiesDock::newComponent( GluonEngine::Component* comp ) { if( comp->parent() == d->widget->object() ) { d->widget->setObject( d->widget->object() ); } } void PropertiesDock::propertyChanged( QObject* object, QString property, QVariant oldValue, QVariant newValue ) { GluonCore::GluonObject* obj = qobject_cast<GluonCore::GluonObject*>( object ); if( obj ) ObjectManager::instance()->changeProperty( obj, property, oldValue, newValue ); } <|endoftext|>
<commit_before>#ifndef SAVE_STATE_H # define SAVE_STATE_H # pragma once struct statebuf { void* sp; void* label; }; #if defined(__GNUC__) inline bool __attribute__((always_inline)) savestate(statebuf& ssb) noexcept { bool volatile r; #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ( "movl %%esp, %0\n\t" // store sp "movl $1f, %1\n\t" // store label "movb $0, %2\n\t" // return false "jmp 2f\n\t" "1:movb $1, %2\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ( "movq %%rsp, %0\n\t" // store sp "movq $1f, %1\n\t" // store label "movb $0, %2\n\t" // return false "jmp 2f\n\t" "1:movb $1, %2\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #elif defined(__arm__) asm volatile ( "push {r11}\n\t" // push r0 "str sp, %0\n\t" // store sp "ldr r0, =1f\n\t" // load label into r0 "str r0, %1\n\t" // store r0 into label "mov %2, $0\n\t" // store 0 into result "b 2f\n\t" "1:pop {r11}\n\t" "mov %2, $1\n\t" // store 1 into result "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #endif return r; } #elif defined(_MSC_VER) __forceinline bool savestate(statebuf& ssb) noexcept { bool volatile r; __asm { push ebp mov ebx, ssb mov [ebx]ssb.sp, esp mov [ebx]ssb.label, offset _1f mov r, 0x0 jmp _2f _1f: pop ebp mov r, 0x1 _2f: } return r; } #else # error "unsupported compiler" #endif #if defined(__GNUC__) #if defined(i386) || defined(__i386) || defined(__i386__) #define restorestate(SSB) \ asm volatile ( \ "movl %0, %%esp\n\t" \ "jmp *%1" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) #define restorestate(SSB) \ asm volatile ( \ "movq %0, %%rsp\n\t" \ "jmp *%1" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #elif defined(__arm__) #define restorestate(SSB) \ asm volatile ( \ "ldr sp, %0\n\t" \ "ldr pc, %1" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #else # error "unsupported architecture" #endif #elif defined(_MSC_VER) #define restorestate(SSB) \ __asm mov ebx, this \ __asm add ebx, [SSB] \ __asm mov esp, [ebx]SSB.sp\ __asm jmp [ebx]SSB.label #else # error "unsupported compiler" #endif #endif // SAVE_STATE_H <commit_msg>some fixes<commit_after>#ifndef SAVE_STATE_H # define SAVE_STATE_H # pragma once struct statebuf { void* sp; void* label; }; #if defined(__GNUC__) inline bool __attribute__((always_inline)) savestate(statebuf& ssb) noexcept { bool r; #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ( "movl %%esp, %0\n\t" // store sp "movl $1f, %1\n\t" // store label "movb $0, %2\n\t" // return false "jmp 2f\n\t" "1:movb $1, %2\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ( "movq %%rsp, %0\n\t" // store sp "movq $1f, %1\n\t" // store label "movb $0, %2\n\t" // return false "jmp 2f\n\t" "1:movb $1, %2\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #elif defined(__arm__) asm volatile ( "push {r11}\n\t" // push r0 "str sp, %0\n\t" // store sp "ldr r0, =1f\n\t" // load label into r0 "str r0, %1\n\t" // store r0 into label "mov %2, $0\n\t" // store 0 into result "b 2f\n\t" "1:pop {r11}\n\t" "mov %2, $1\n\t" // store 1 into result "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #endif return r; } #elif defined(_MSC_VER) __forceinline bool savestate(statebuf& ssb) noexcept { bool r; __asm { push ebp mov ebx, ssb mov [ebx]ssb.sp, esp mov [ebx]ssb.label, offset _1f mov r, 0x0 jmp _2f _1f: pop ebp mov r, 0x1 _2f: } return r; } #else # error "unsupported compiler" #endif #if defined(__GNUC__) #if defined(i386) || defined(__i386) || defined(__i386__) #define restorestate(SSB) \ asm volatile ( \ "movl %0, %%esp\n\t" \ "jmp *%1" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) #define restorestate(SSB) \ asm volatile ( \ "movq %0, %%rsp\n\t" \ "jmp *%1" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #elif defined(__arm__) #define restorestate(SSB) \ asm volatile ( \ "ldr sp, %0\n\t" \ "ldr pc, %1" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #else # error "unsupported architecture" #endif #elif defined(_MSC_VER) #define restorestate(SSB) \ __asm mov ebx, this \ __asm add ebx, [SSB] \ __asm mov esp, [ebx]SSB.sp\ __asm jmp [ebx]SSB.label #else # error "unsupported compiler" #endif #endif // SAVE_STATE_H <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ /// \file string.cpp //------------------------------------------------------------------------------ /// \brief Implementation of general purpose functions for string processing //------------------------------------------------------------------------------ // Copyright (c) 2010 Serge Aleynikov <saleyn@gmail.com> // Created: 2010-05-06 //------------------------------------------------------------------------------ /* ***** BEGIN LICENSE BLOCK ***** This file is part of the utxx open-source project. Copyright (C) 2010 Serge Aleynikov <saleyn@gmail.com> 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***** END LICENSE BLOCK ***** */ #include <utxx/string.hpp> #include <utxx/print_opts.hpp> namespace utxx { std::string to_bin_string(const char* buf, size_t sz, bool hex, bool readable, bool eol) { std::stringstream out; const char* begin = buf, *end = buf + sz; print_opts opts = hex ? (readable ? print_opts::printable_or_hex : print_opts::hex) : (readable ? print_opts::printable_or_dec : print_opts::dec); output(out, begin, end, opts, ",", "", "\"", "<<", ">>"); if (eol) out << std::endl; return out.str(); } bool wildcard_match(const char* a_input, const char* a_pattern) { const char* ip = nullptr, *pp = nullptr; // Match until the first '*' or '?': for(; *a_input && *a_pattern != '*'; ++a_pattern, ++a_input) if ((*a_pattern != *a_input) && (*a_pattern != '?')) return false; // Pattern match on everything that follows '*', and exit // at the end of the input string while (*a_input) { if (*a_pattern == '*') { if (!*++a_pattern) return true; // Store state after '*': pp = a_pattern; ip = a_input+1; } else if ((*a_pattern == *a_input) || (*a_pattern == '?')) { // Continue successful match a_pattern++; a_input++; } else { // Match failed - restore state of pattern after '*': a_pattern = pp; a_input = ip++; } } // Skip trailing '*' in the pattern, since they don't affect the outcome: while (*a_pattern == '*') a_pattern++; // Are both input and pattern complete? return !*a_pattern; } } // namespace utxx <commit_msg>Move closer to use<commit_after>//------------------------------------------------------------------------------ /// \file string.cpp //------------------------------------------------------------------------------ /// \brief Implementation of general purpose functions for string processing //------------------------------------------------------------------------------ // Copyright (c) 2010 Serge Aleynikov <saleyn@gmail.com> // Created: 2010-05-06 //------------------------------------------------------------------------------ /* ***** BEGIN LICENSE BLOCK ***** This file is part of the utxx open-source project. Copyright (C) 2010 Serge Aleynikov <saleyn@gmail.com> 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***** END LICENSE BLOCK ***** */ #include <utxx/string.hpp> #include <utxx/print_opts.hpp> namespace utxx { std::string to_bin_string(const char* buf, size_t sz, bool hex, bool readable, bool eol) { std::stringstream out; const char* begin = buf, *end = buf + sz; print_opts opts = hex ? (readable ? print_opts::printable_or_hex : print_opts::hex) : (readable ? print_opts::printable_or_dec : print_opts::dec); output(out, begin, end, opts, ",", "", "\"", "<<", ">>"); if (eol) out << std::endl; return out.str(); } bool wildcard_match(const char* a_input, const char* a_pattern) { // Match until the first '*' or '?': for(; *a_input && *a_pattern != '*'; ++a_pattern, ++a_input) if ((*a_pattern != *a_input) && (*a_pattern != '?')) return false; const char* ip = nullptr, *pp = nullptr; // Pattern match on everything that follows '*', and exit // at the end of the input string while (*a_input) { if (*a_pattern == '*') { if (!*++a_pattern) return true; // Store state after '*': pp = a_pattern; ip = a_input+1; } else if ((*a_pattern == *a_input) || (*a_pattern == '?')) { // Continue successful match a_pattern++; a_input++; } else { // Match failed - restore state of pattern after '*': a_pattern = pp; a_input = ip++; } } // Skip trailing '*' in the pattern, since they don't affect the outcome: while (*a_pattern == '*') a_pattern++; // Are both input and pattern complete? return !*a_pattern; } } // namespace utxx <|endoftext|>
<commit_before>#include "subcommand.hpp" #include "../vg.hpp" #include "../utility.hpp" #include "../counter.hpp" #include "../stream.hpp" #include <unistd.h> #include <getopt.h> using namespace vg; using namespace vg::subcommand; void help_count(char** argv) { cerr << "usage: " << argv[0] << " count [options]" << endl << "options:" << endl << " -x, --xg FILE use this basis graph" << endl << " -o, --counts-out FILE write compressed coverage counts to this output file" << endl << " -i, --counts-in FILE begin by summing coverage counts from each provided FILE" << endl << " -g, --gam FILE read alignments from this file (could be '-' for stdin)" << endl << " -d, --as-table write table on stdout representing counts" << endl << " -n, --no-edits don't record or write edits, just graph-matching coverage" << endl << " -t, --threads N use N threads (defaults to numCPUs)" << endl; } int main_count(int argc, char** argv) { string xg_name; vector<string> counts_in; string counts_out; string gam_in; bool write_table = false; int thread_count = 1; bool record_edits = true; if (argc == 2) { help_count(argv); return 1; } int c; optind = 2; // force optind past command positional argument while (true) { static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"xg", required_argument,0, 'x'}, {"counts-out", required_argument,0, 'o'}, {"count-in", required_argument, 0, 'i'}, {"gam", required_argument, 0, 'g'}, {"as-table", no_argument, 0, 'd'}, {"threads", required_argument, 0, 't'}, {"no-edits", no_argument, 0, 'n'}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long (argc, argv, "hx:o:i:g:dt:n", long_options, &option_index); // Detect the end of the options. if (c == -1) break; switch (c) { case '?': case 'h': help_count(argv); return 1; case 'x': xg_name = optarg; break; case 'o': counts_out = optarg; break; case 'i': counts_in.push_back(optarg); break; case 'g': gam_in = optarg; break; case 'd': write_table = true; break; case 'n': record_edits = false; break; case 't': thread_count = atoi(optarg); break; default: abort(); } } omp_set_num_threads(thread_count); xg::XG xgidx; if (xg_name.empty()) { cerr << "No XG index given. An XG index must be provided." << endl; exit(1); } else { ifstream in(xg_name.c_str()); xgidx.load(in); } // todo one counter per thread and merge vg::Counter counter(&xgidx); if (!counts_in.empty()) { counter.load_from_file(counts_in.front()); } if (!gam_in.empty()) { ifstream gam_stream(gam_in); std::function<void(Alignment&)> lambda = [&counter,&record_edits](Alignment& aln) { counter.add(aln, record_edits); }; stream::for_each(gam_stream, lambda); gam_stream.close(); } if (!counts_out.empty()) { counter.save_to_file(counts_out); } if (write_table) { counter.make_compact(); counter.as_table(cout, record_edits); } return 0; } // Register subcommand static Subcommand vg_count("count", "count features on the graph", main_count); <commit_msg>count: enable reading gam from stdin<commit_after>#include "subcommand.hpp" #include "../vg.hpp" #include "../utility.hpp" #include "../counter.hpp" #include "../stream.hpp" #include <unistd.h> #include <getopt.h> using namespace vg; using namespace vg::subcommand; void help_count(char** argv) { cerr << "usage: " << argv[0] << " count [options]" << endl << "options:" << endl << " -x, --xg FILE use this basis graph" << endl << " -o, --counts-out FILE write compressed coverage counts to this output file" << endl << " -i, --counts-in FILE begin by summing coverage counts from each provided FILE" << endl << " -g, --gam FILE read alignments from this file (could be '-' for stdin)" << endl << " -d, --as-table write table on stdout representing counts" << endl << " -n, --no-edits don't record or write edits, just graph-matching coverage" << endl << " -t, --threads N use N threads (defaults to numCPUs)" << endl; } int main_count(int argc, char** argv) { string xg_name; vector<string> counts_in; string counts_out; string gam_in; bool write_table = false; int thread_count = 1; bool record_edits = true; if (argc == 2) { help_count(argv); return 1; } int c; optind = 2; // force optind past command positional argument while (true) { static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"xg", required_argument,0, 'x'}, {"counts-out", required_argument,0, 'o'}, {"count-in", required_argument, 0, 'i'}, {"gam", required_argument, 0, 'g'}, {"as-table", no_argument, 0, 'd'}, {"threads", required_argument, 0, 't'}, {"no-edits", no_argument, 0, 'n'}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long (argc, argv, "hx:o:i:g:dt:n", long_options, &option_index); // Detect the end of the options. if (c == -1) break; switch (c) { case '?': case 'h': help_count(argv); return 1; case 'x': xg_name = optarg; break; case 'o': counts_out = optarg; break; case 'i': counts_in.push_back(optarg); break; case 'g': gam_in = optarg; break; case 'd': write_table = true; break; case 'n': record_edits = false; break; case 't': thread_count = atoi(optarg); break; default: abort(); } } omp_set_num_threads(thread_count); xg::XG xgidx; if (xg_name.empty()) { cerr << "No XG index given. An XG index must be provided." << endl; exit(1); } else { ifstream in(xg_name.c_str()); xgidx.load(in); } // todo one counter per thread and merge vg::Counter counter(&xgidx); if (!counts_in.empty()) { counter.load_from_file(counts_in.front()); } if (!gam_in.empty()) { std::function<void(Alignment&)> lambda = [&counter,&record_edits](Alignment& aln) { counter.add(aln, record_edits); }; if (gam_in == "-") { stream::for_each(std::cin, lambda); } else { ifstream gam_stream(gam_in); stream::for_each(gam_stream, lambda); gam_stream.close(); } } if (!counts_out.empty()) { counter.save_to_file(counts_out); } if (write_table) { counter.make_compact(); counter.as_table(cout, record_edits); } return 0; } // Register subcommand static Subcommand vg_count("count", "count features on the graph", main_count); <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // File: cmnserver.hpp // // Desc: Common HTTP server - HTTP server for all application // // Copyright (c) 2014-2018 opencvr.com. All rights reserved. //------------------------------------------------------------------------------ #ifndef __VSC_CMN_SERVER__H_ #define __VSC_CMN_SERVER__H_ #include "utility.hpp" #include "debug.hpp" #include <QThread> #include "XSDK/XHash.h" #include "XSDK/TimeUtils.h" #include "XSDK/XSocket.h" #include "XSDK/XSSLSocket.h" #include "Webby/ClientSideRequest.h" #include "Webby/ClientSideResponse.h" #include "Webby/ServerSideRequest.h" #include "Webby/ServerSideResponse.h" #include "Webby/WebbyException.h" using namespace std; using namespace XSDK; using namespace WEBBY; /* each app can register a http REST path can move the socket to itself, for streaming, it it for performance. */ using namespace UtilityLib; class CmnHttpServer:public QThread { Q_OBJECT public: inline CmnHttpServer(u16 port); inline ~CmnHttpServer(); public: void Lock() { m_Lock.lock(); } void UnLock() { m_Lock.unlock(); } public: inline void run(); private: fast_mutex m_Lock; u16 m_port; }; class CmnHttpsServer:public QThread { Q_OBJECT public: inline CmnHttpsServer(u16 port); inline ~CmnHttpsServer(); public: void Lock() { m_Lock.lock(); } void UnLock() { m_Lock.unlock(); } public: inline void run(); private: fast_mutex m_Lock; u16 m_port; }; typedef CmnHttpServer* LPCmnHttpServer; typedef CmnHttpsServer* LPCmnHttpsServer; #include "cmnserverimpl.hpp" #endif /* __VSC_CMN_SERVER__H_ */ <commit_msg>add oapi.hpp<commit_after>//------------------------------------------------------------------------------ // File: cmnserver.hpp // // Desc: Common HTTP server - HTTP server for all application // // Copyright (c) 2014-2018 opencvr.com. All rights reserved. //------------------------------------------------------------------------------ #ifndef __VSC_CMN_SERVER__H_ #define __VSC_CMN_SERVER__H_ #include "utility.hpp" #include "debug.hpp" #include <QThread> #include "XSDK/XHash.h" #include "XSDK/TimeUtils.h" #include "XSDK/XSocket.h" #include "XSDK/XSSLSocket.h" #include "Webby/ClientSideRequest.h" #include "Webby/ClientSideResponse.h" #include "Webby/ServerSideRequest.h" #include "Webby/ServerSideResponse.h" #include "Webby/WebbyException.h" #include "oapi.hpp" using namespace std; using namespace XSDK; using namespace WEBBY; /* each app can register a http REST path can move the socket to itself, for streaming, it it for performance. */ using namespace UtilityLib; class CmnHttpServer:public QThread { Q_OBJECT public: inline CmnHttpServer(u16 port); inline ~CmnHttpServer(); public: void Lock() { m_Lock.lock(); } void UnLock() { m_Lock.unlock(); } public: inline void run(); private: fast_mutex m_Lock; u16 m_port; }; class CmnHttpsServer:public QThread { Q_OBJECT public: inline CmnHttpsServer(u16 port); inline ~CmnHttpsServer(); public: void Lock() { m_Lock.lock(); } void UnLock() { m_Lock.unlock(); } public: inline void run(); private: fast_mutex m_Lock; u16 m_port; }; typedef CmnHttpServer* LPCmnHttpServer; typedef CmnHttpsServer* LPCmnHttpsServer; #include "cmnserverimpl.hpp" #endif /* __VSC_CMN_SERVER__H_ */ <|endoftext|>
<commit_before>// Prints the tag of a audio file // mp3, m4a ogg and flac supported // Bilal Hussain // install: // g++ `taglib-config --cflags --libs` taginfo.cpp -o taginfo // or // g++ -ltag -I/usr/local/include/taglib -L/usr/local/lib taginfo.cpp -o taginfo // if no taglib-config #include <stdio.h> #include <stdlib.h> #include <string.h> #include <tag.h> #include <fileref.h> void usage() { fprintf(stderr, "taginfo \n"); fprintf(stderr, "Usage: taginfo <file(s)>\n"); fprintf(stderr, "Usage: taginfo --short <file>\n"); fprintf(stderr, "Usage: taginfo --info <file>\n"); fprintf(stderr, "Usage: taginfo --details <file> <current_secs>\n"); fprintf(stderr, "Usage: taginfo --details-colour <file> <current_secs>\n"); } int main(int argc, char *argv[]) { if(argc < 2) { usage(); exit(1); } if (argc == 3 && strcmp("--short", argv[1]) == 0){ TagLib::FileRef f(argv[2]); printf("%s\n", f.tag()->title().toCString(true)); printf("%s\n", f.tag()->album().toCString(true)); printf("%s\n", f.tag()->artist().toCString(true)); int time = f.audioProperties()->length(); printf("%d:%d\n", (time%3600/60), (time%60) ); exit(0); } else if (argc == 3 && strcmp("--info", argv[1]) == 0){ TagLib::FileRef f(argv[2]); printf("%s - %02d %s - %s\n", f.tag()->artist().toCString(true), f.tag()->track(), f.tag()->title().toCString(true), f.tag()->album().toCString(true) ); exit(0); } else if (argc == 4 && strcmp("--details", argv[1]) == 0){ TagLib::FileRef f(argv[2]); long start_time = strtol(argv[3],NULL,10); const int end_time = f.audioProperties()->length(); printf("%s - %02d %s - %s - %ld:%02ld/%d:%02d\n", f.tag()->artist().toCString(true), f.tag()->track(), f.tag()->title().toCString(true), f.tag()->album().toCString(true), (start_time%3600/60), (start_time%60), (end_time%3600/60), (end_time%60) ); exit(0); } else if (argc == 4 && strcmp("--details-colour", argv[1]) == 0){ TagLib::FileRef f(argv[2]); long start_time = strtol(argv[3],NULL,10); const int end_time = f.audioProperties()->length(); // adds %s before and after #define SSS(str) "%s" str "%s" #define BLUE "\033[34m" // Blue #define RED "\033[31m" // Red #define GREEN "\033[32m" // Green #define RESET "\033[0m" // Need before and after #define COLOUR(string, colour) RESET colour, string, RESET printf("%s - %02d " SSS("%s") " - %s - %ld:%02ld/%d:%02d\n", f.tag()->artist().toCString(true), f.tag()->track(), COLOUR(f.tag()->title().toCString(true),BLUE), f.tag()->album().toCString(true), (start_time%3600/60), (start_time%60), (end_time%3600/60), (end_time%60) ); exit(0); } for(int i = 1; i < argc; i++) { TagLib::FileRef f(argv[i]); if(!f.isNull() && f.tag()) { printf("FILE=\"%s\"\n", argv[i]); printf("ALBUM=\"%s\"\n", f.tag()->album().toCString(true)); printf("TRACK=\"%d\"\n", f.tag()->track()); printf("ARTIST=\"%s\"\n", f.tag()->artist().toCString(true)); printf("TITLE=\"%s\"\n", f.tag()->title().toCString(true)); printf("GENRE=\"%s\"\n", f.tag()->genre().toCString(true)); printf("YEAR=\"%d\"\n", f.tag()->year()); printf("COMMENT=\"%s\"\n", f.tag()->comment().toCString(true)); printf("LENGTH=\"%d\"\n", f.audioProperties()->length()); printf("BITRATE=\"%d\"\n", f.audioProperties()->bitrate()); printf("SAMPLERATE=\"%d\"\n", f.audioProperties()->sampleRate()); printf("CHANNELS=\"%d\"\n\n", f.audioProperties()->channels()); } else { fprintf(stderr, "Error opening file: %s\n", argv[i]); } } return 0; } <commit_msg>pretty print<commit_after>// Prints the tag of a audio file // mp3, m4a ogg and flac supported // Bilal Hussain // install: // g++ `taglib-config --cflags --libs` taginfo.cpp -o taginfo // or // g++ -ltag -I/usr/local/include/taglib -L/usr/local/lib taginfo.cpp -o taginfo // if no taglib-config #include <stdio.h> #include <stdlib.h> #include <string.h> #include <tag.h> #include <fileref.h> void usage() { fprintf(stderr, "taginfo \n"); fprintf(stderr, "Usage: taginfo <file(s)>\n"); fprintf(stderr, "Usage: taginfo --short <file>\n"); fprintf(stderr, "Usage: taginfo --info <file>\n"); fprintf(stderr, "Usage: taginfo --pretty <file> \n"); fprintf(stderr, "Usage: taginfo --pretty <file> <current_secs>\n"); fprintf(stderr, "Usage: taginfo --details <file> <current_secs>\n"); fprintf(stderr, "Usage: taginfo --details-colour <file> <current_secs>\n"); } // adds %s before and after #define SSS(str) "%s" str "%s" #define S3 "%s%s%s" #define BLUE "\033[34m" // Blue #define RED "\033[31m" // Red #define GREEN "\033[32m" // Green #define RESET "\033[0m" // Need before and after #define COLOUR(string, colour) RESET colour, string, RESET #define COLOURN(string, colour) string int main(int argc, char *argv[]) { if(argc < 2) { usage(); exit(1); } if (argc == 3 && strcmp("--short", argv[1]) == 0){ TagLib::FileRef f(argv[2]); printf("%s\n", f.tag()->title().toCString(true)); printf("%s\n", f.tag()->album().toCString(true)); printf("%s\n", f.tag()->artist().toCString(true)); int time = f.audioProperties()->length(); printf("%d:%d\n", (time%3600/60), (time%60) ); exit(0); } else if (argc == 3 && strcmp("--info", argv[1]) == 0){ TagLib::FileRef f(argv[2]); printf("%s - %02d %s - %s\n", f.tag()->artist().toCString(true), f.tag()->track(), f.tag()->title().toCString(true), f.tag()->album().toCString(true) ); exit(0); } else if (argc == 4 && strcmp("--details", argv[1]) == 0){ TagLib::FileRef f(argv[2]); long start_time = strtol(argv[3],NULL,10); const int end_time = f.audioProperties()->length(); printf("%s - %02d %s - %s - %ld:%02ld/%d:%02d\n", f.tag()->artist().toCString(true), f.tag()->track(), f.tag()->title().toCString(true), f.tag()->album().toCString(true), (start_time%3600/60), (start_time%60), (end_time%3600/60), (end_time%60) ); exit(0); } else if (argc == 4 && strcmp("--details-colour", argv[1]) == 0){ TagLib::FileRef f(argv[2]); long start_time = strtol(argv[3],NULL,10); const int end_time = f.audioProperties()->length(); printf("%s - %02d " SSS("%s") " - %s - %ld:%02ld/%d:%02d\n", f.tag()->artist().toCString(true), f.tag()->track(), COLOUR(f.tag()->title().toCString(true),BLUE), f.tag()->album().toCString(true), (start_time%3600/60), (start_time%60), (end_time%3600/60), (end_time%60) ); exit(0); } else if (argc == 4 && strcmp("--pretty", argv[1]) == 0){ TagLib::FileRef f(argv[2]); long start_time = strtol(argv[3],NULL,10); const int end_time = f.audioProperties()->length(); // Track : Faraway ★★★★★ // Album : Day After Tomorrow // Artist: Day After Tomorrow // Time : 5:00/5:84 printf( "Track : %d - " S3 "\n" "Album : %s\n" "Artist : %s\n" "Time : %ld:%02ld/%d:%02d\n", f.tag()->track(), COLOUR(f.tag()->title().toCString(true),BLUE), f.tag()->artist().toCString(true), f.tag()->album().toCString(true), (start_time%3600/60), (start_time%60), (end_time%3600/60), (end_time%60) ); exit(0); } else if (argc == 3 && strcmp("--pretty", argv[1]) == 0){ TagLib::FileRef f(argv[2]); const int end_time = f.audioProperties()->length(); // Track : Faraway ★★★★★ // Album : Day After Tomorrow // Artist: Day After Tomorrow // Time : 5:00/5:84 printf( "Track : %d - " S3 "\n" "Album : %s\n" "Artist : %s\n" "Time : %d:%02d\n", f.tag()->track(), COLOUR(f.tag()->title().toCString(true),BLUE), f.tag()->artist().toCString(true), f.tag()->album().toCString(true), (end_time%3600/60), (end_time%60) ); exit(0); } for(int i = 1; i < argc; i++) { TagLib::FileRef f(argv[i]); if(!f.isNull() && f.tag()) { printf("FILE=\"%s\"\n", argv[i]); printf("ALBUM=\"%s\"\n", f.tag()->album().toCString(true)); printf("TRACK=\"%d\"\n", f.tag()->track()); printf("ARTIST=\"%s\"\n", f.tag()->artist().toCString(true)); printf("TITLE=\"%s\"\n", f.tag()->title().toCString(true)); printf("GENRE=\"%s\"\n", f.tag()->genre().toCString(true)); printf("YEAR=\"%d\"\n", f.tag()->year()); printf("COMMENT=\"%s\"\n", f.tag()->comment().toCString(true)); printf("LENGTH=\"%d\"\n", f.audioProperties()->length()); printf("BITRATE=\"%d\"\n", f.audioProperties()->bitrate()); printf("SAMPLERATE=\"%d\"\n", f.audioProperties()->sampleRate()); printf("CHANNELS=\"%d\"\n\n", f.audioProperties()->channels()); } else { fprintf(stderr, "Error opening file: %s\n", argv[i]); } } return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin * * Permission to use, copy, modify, and 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 <Spinlock.h> #include <processor/Processor.h> #ifdef TRACK_LOCKS #include <LocksCommand.h> #endif #include <panic.h> void Spinlock::acquire() { // Save the current irq status. // This save to local variable prevents a heinous race condition where the thread is // preempted between the getInterrupts and setInterrupts, then this same spinlock is called // in the new thread with interrupts disabled. It gets back to us, and m_bInterrupts==false. // Oh dear, hanging time. // // We write to a local so the interrupt value is saved onto the stack until interrupts are // definately disabled; then we can write it back to the member variable. bool bInterrupts = Processor::getInterrupts(); // Disable irqs if not already done if (bInterrupts) Processor::setInterrupts(false); if (m_Magic != 0xdeadbaba) { FATAL("Wrong magic in acquire."); } while (m_Atom.compareAndSwap(true, false) == false) { #ifndef MULTIPROCESSOR /// \note When we hit this breakpoint, we're not able to backtrace as backtracing /// depends on the log spinlock, which may have deadlocked. So we actually /// force the spinlock to release here, then hit the breakpoint. size_t atom = m_Atom; m_Atom = true; // Break into the debugger, with the return address in EAX to make debugging easier #ifdef X86 FATAL_NOLOCK("Spinlock has deadlocked, return address of other locker is " << m_Ra << ", spinlock is " << reinterpret_cast<uintptr_t>(this) << ", atom is " << atom << "."); // asm volatile("mov %0, %%eax; mov %1, %%ebx; int3" : : "r"(reinterpret_cast<uintptr_t>(this)), "r"(atom)); #endif #ifdef X64 asm volatile("mov %0, %%rax; mov %1, %%rbx; int3" : : "r"(reinterpret_cast<uintptr_t>(this)), "r"(atom)); #endif // Panic in case there's a return from the debugger (or the debugger isn't available) panic("Spinlock has deadlocked"); #endif } m_Ra = reinterpret_cast<uintptr_t>(__builtin_return_address(0)); #ifdef TRACK_LOCKS // if (!m_bAvoidTracking) g_LocksCommand.lockAcquired(this); #endif m_bInterrupts = bInterrupts; } void Spinlock::release() { bool bWasInterrupts = Processor::getInterrupts(); if (bWasInterrupts == true) { FATAL("Spinlock: release() called with interrupts enabled."); } bool bInterrupts = m_bInterrupts; if (m_Magic != 0xdeadbaba) { FATAL("Wrong magic in release."); } if (m_Atom.compareAndSwap(false, true) == false) { /// \note When we hit this breakpoint, we're not able to backtrace as backtracing /// depends on the log spinlock, which may have deadlocked. So we actually /// force the spinlock to release here, then hit the breakpoint. m_Atom = true; // Break into the debugger, with the return address in EAX to make debugging easier #ifdef X86 asm volatile("mov %0, %%eax; mov %1, %%ebx; int3" : : "r"(reinterpret_cast<uintptr_t>(this)), "m"(m_Atom)); #endif #ifdef X64 asm volatile("mov %0, %%rax; mov %1, %%rbx; int3" : : "r"(reinterpret_cast<uintptr_t>(this)), "m"(m_Atom)); #endif // Panic in case there's a return from the debugger (or the debugger isn't available) panic("Spinlock has deadlocked"); } #ifdef TRACK_LOCKS // if (!m_bAvoidTracking) g_LocksCommand.lockReleased(this); #endif // Reenable irqs if they were enabled before if (bInterrupts) { Processor::setInterrupts(true); } } <commit_msg>Add Log.h to list of includes in Spinlock.cc. Previously assumed that other headers would indirectly include Log.h<commit_after>/* * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin * * Permission to use, copy, modify, and 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 <Spinlock.h> #include <processor/Processor.h> #ifdef TRACK_LOCKS #include <LocksCommand.h> #endif #include <Log.h> #include <panic.h> void Spinlock::acquire() { // Save the current irq status. // This save to local variable prevents a heinous race condition where the thread is // preempted between the getInterrupts and setInterrupts, then this same spinlock is called // in the new thread with interrupts disabled. It gets back to us, and m_bInterrupts==false. // Oh dear, hanging time. // // We write to a local so the interrupt value is saved onto the stack until interrupts are // definately disabled; then we can write it back to the member variable. bool bInterrupts = Processor::getInterrupts(); // Disable irqs if not already done if (bInterrupts) Processor::setInterrupts(false); if (m_Magic != 0xdeadbaba) { FATAL("Wrong magic in acquire."); } while (m_Atom.compareAndSwap(true, false) == false) { #ifndef MULTIPROCESSOR /// \note When we hit this breakpoint, we're not able to backtrace as backtracing /// depends on the log spinlock, which may have deadlocked. So we actually /// force the spinlock to release here, then hit the breakpoint. size_t atom = m_Atom; m_Atom = true; // Break into the debugger, with the return address in EAX to make debugging easier #ifdef X86 FATAL_NOLOCK("Spinlock has deadlocked, return address of other locker is " << m_Ra << ", spinlock is " << reinterpret_cast<uintptr_t>(this) << ", atom is " << atom << "."); // asm volatile("mov %0, %%eax; mov %1, %%ebx; int3" : : "r"(reinterpret_cast<uintptr_t>(this)), "r"(atom)); #endif #ifdef X64 asm volatile("mov %0, %%rax; mov %1, %%rbx; int3" : : "r"(reinterpret_cast<uintptr_t>(this)), "r"(atom)); #endif // Panic in case there's a return from the debugger (or the debugger isn't available) panic("Spinlock has deadlocked"); #endif } m_Ra = reinterpret_cast<uintptr_t>(__builtin_return_address(0)); #ifdef TRACK_LOCKS // if (!m_bAvoidTracking) g_LocksCommand.lockAcquired(this); #endif m_bInterrupts = bInterrupts; } void Spinlock::release() { bool bWasInterrupts = Processor::getInterrupts(); if (bWasInterrupts == true) { FATAL("Spinlock: release() called with interrupts enabled."); } bool bInterrupts = m_bInterrupts; if (m_Magic != 0xdeadbaba) { FATAL("Wrong magic in release."); } if (m_Atom.compareAndSwap(false, true) == false) { /// \note When we hit this breakpoint, we're not able to backtrace as backtracing /// depends on the log spinlock, which may have deadlocked. So we actually /// force the spinlock to release here, then hit the breakpoint. m_Atom = true; // Break into the debugger, with the return address in EAX to make debugging easier #ifdef X86 asm volatile("mov %0, %%eax; mov %1, %%ebx; int3" : : "r"(reinterpret_cast<uintptr_t>(this)), "m"(m_Atom)); #endif #ifdef X64 asm volatile("mov %0, %%rax; mov %1, %%rbx; int3" : : "r"(reinterpret_cast<uintptr_t>(this)), "m"(m_Atom)); #endif // Panic in case there's a return from the debugger (or the debugger isn't available) panic("Spinlock has deadlocked"); } #ifdef TRACK_LOCKS // if (!m_bAvoidTracking) g_LocksCommand.lockReleased(this); #endif // Reenable irqs if they were enabled before if (bInterrupts) { Processor::setInterrupts(true); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * 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: Steve Reinhardt */ #include "arch/utility.hh" #include "arch/faults.hh" #include "base/cprintf.hh" #include "base/inifile.hh" #include "base/loader/symtab.hh" #include "base/misc.hh" #include "base/pollevent.hh" #include "base/range.hh" #include "base/stats/events.hh" #include "base/trace.hh" #include "cpu/base.hh" #include "cpu/exetrace.hh" #include "cpu/profile.hh" #include "cpu/simple/base.hh" #include "cpu/simple_thread.hh" #include "cpu/smt.hh" #include "cpu/static_inst.hh" #include "cpu/thread_context.hh" #include "mem/packet.hh" #include "sim/builder.hh" #include "sim/byteswap.hh" #include "sim/debug.hh" #include "sim/host.hh" #include "sim/sim_events.hh" #include "sim/sim_object.hh" #include "sim/stats.hh" #include "sim/system.hh" #if FULL_SYSTEM #include "arch/kernel_stats.hh" #include "arch/stacktrace.hh" #include "arch/tlb.hh" #include "arch/vtophys.hh" #include "base/remote_gdb.hh" #else // !FULL_SYSTEM #include "mem/mem_object.hh" #endif // FULL_SYSTEM using namespace std; using namespace TheISA; BaseSimpleCPU::BaseSimpleCPU(Params *p) : BaseCPU(p), traceData(NULL), thread(NULL), predecoder(NULL) { #if FULL_SYSTEM thread = new SimpleThread(this, 0, p->system, p->itb, p->dtb); #else thread = new SimpleThread(this, /* thread_num */ 0, p->process, /* asid */ 0); #endif // !FULL_SYSTEM thread->setStatus(ThreadContext::Unallocated); tc = thread->getTC(); numInst = 0; startNumInst = 0; numLoad = 0; startNumLoad = 0; lastIcacheStall = 0; lastDcacheStall = 0; threadContexts.push_back(tc); fetchOffset = 0; stayAtPC = false; } BaseSimpleCPU::~BaseSimpleCPU() { } void BaseSimpleCPU::deallocateContext(int thread_num) { // for now, these are equivalent suspendContext(thread_num); } void BaseSimpleCPU::haltContext(int thread_num) { // for now, these are equivalent suspendContext(thread_num); } void BaseSimpleCPU::regStats() { using namespace Stats; BaseCPU::regStats(); numInsts .name(name() + ".num_insts") .desc("Number of instructions executed") ; numMemRefs .name(name() + ".num_refs") .desc("Number of memory references") ; notIdleFraction .name(name() + ".not_idle_fraction") .desc("Percentage of non-idle cycles") ; idleFraction .name(name() + ".idle_fraction") .desc("Percentage of idle cycles") ; icacheStallCycles .name(name() + ".icache_stall_cycles") .desc("ICache total stall cycles") .prereq(icacheStallCycles) ; dcacheStallCycles .name(name() + ".dcache_stall_cycles") .desc("DCache total stall cycles") .prereq(dcacheStallCycles) ; icacheRetryCycles .name(name() + ".icache_retry_cycles") .desc("ICache total retry cycles") .prereq(icacheRetryCycles) ; dcacheRetryCycles .name(name() + ".dcache_retry_cycles") .desc("DCache total retry cycles") .prereq(dcacheRetryCycles) ; idleFraction = constant(1.0) - notIdleFraction; } void BaseSimpleCPU::resetStats() { // startNumInst = numInst; // notIdleFraction = (_status != Idle); } void BaseSimpleCPU::serialize(ostream &os) { BaseCPU::serialize(os); // SERIALIZE_SCALAR(inst); nameOut(os, csprintf("%s.xc.0", name())); thread->serialize(os); } void BaseSimpleCPU::unserialize(Checkpoint *cp, const string &section) { BaseCPU::unserialize(cp, section); // UNSERIALIZE_SCALAR(inst); thread->unserialize(cp, csprintf("%s.xc.0", section)); } void change_thread_state(int thread_number, int activate, int priority) { } Fault BaseSimpleCPU::copySrcTranslate(Addr src) { #if 0 static bool no_warn = true; int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64; // Only support block sizes of 64 atm. assert(blk_size == 64); int offset = src & (blk_size - 1); // Make sure block doesn't span page if (no_warn && (src & PageMask) != ((src + blk_size) & PageMask) && (src >> 40) != 0xfffffc) { warn("Copied block source spans pages %x.", src); no_warn = false; } memReq->reset(src & ~(blk_size - 1), blk_size); // translate to physical address Fault fault = thread->translateDataReadReq(req); if (fault == NoFault) { thread->copySrcAddr = src; thread->copySrcPhysAddr = memReq->paddr + offset; } else { assert(!fault->isAlignmentFault()); thread->copySrcAddr = 0; thread->copySrcPhysAddr = 0; } return fault; #else return NoFault; #endif } Fault BaseSimpleCPU::copy(Addr dest) { #if 0 static bool no_warn = true; int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64; // Only support block sizes of 64 atm. assert(blk_size == 64); uint8_t data[blk_size]; //assert(thread->copySrcAddr); int offset = dest & (blk_size - 1); // Make sure block doesn't span page if (no_warn && (dest & PageMask) != ((dest + blk_size) & PageMask) && (dest >> 40) != 0xfffffc) { no_warn = false; warn("Copied block destination spans pages %x. ", dest); } memReq->reset(dest & ~(blk_size -1), blk_size); // translate to physical address Fault fault = thread->translateDataWriteReq(req); if (fault == NoFault) { Addr dest_addr = memReq->paddr + offset; // Need to read straight from memory since we have more than 8 bytes. memReq->paddr = thread->copySrcPhysAddr; thread->mem->read(memReq, data); memReq->paddr = dest_addr; thread->mem->write(memReq, data); if (dcacheInterface) { memReq->cmd = Copy; memReq->completionEvent = NULL; memReq->paddr = thread->copySrcPhysAddr; memReq->dest = dest_addr; memReq->size = 64; memReq->time = curTick; memReq->flags &= ~INST_READ; dcacheInterface->access(memReq); } } else assert(!fault->isAlignmentFault()); return fault; #else panic("copy not implemented"); return NoFault; #endif } #if FULL_SYSTEM Addr BaseSimpleCPU::dbg_vtophys(Addr addr) { return vtophys(tc, addr); } #endif // FULL_SYSTEM #if FULL_SYSTEM void BaseSimpleCPU::post_interrupt(int int_num, int index) { BaseCPU::post_interrupt(int_num, index); if (thread->status() == ThreadContext::Suspended) { DPRINTF(Quiesce,"Suspended Processor awoke\n"); thread->activate(); } } #endif // FULL_SYSTEM void BaseSimpleCPU::checkForInterrupts() { #if FULL_SYSTEM if (check_interrupts(tc)) { Fault interrupt = interrupts.getInterrupt(tc); if (interrupt != NoFault) { interrupts.updateIntrInfo(tc); interrupt->invoke(tc); } } #endif } Fault BaseSimpleCPU::setupFetchRequest(Request *req) { uint64_t threadPC = thread->readPC(); // set up memory request for instruction fetch #if ISA_HAS_DELAY_SLOT DPRINTF(Fetch,"Fetch: PC:%08p NPC:%08p NNPC:%08p\n",threadPC, thread->readNextPC(),thread->readNextNPC()); #else DPRINTF(Fetch,"Fetch: PC:%08p NPC:%08p",threadPC, thread->readNextPC()); #endif const Addr PCMask = ~(sizeof(MachInst) - 1); Addr fetchPC = thread->readPC() + fetchOffset; req->setVirt(0, fetchPC & PCMask, sizeof(MachInst), 0, threadPC()); Fault fault = thread->translateInstReq(req); return fault; } void BaseSimpleCPU::preExecute() { // maintain $r0 semantics thread->setIntReg(ZeroReg, 0); #if THE_ISA == ALPHA_ISA thread->setFloatReg(ZeroReg, 0.0); #endif // ALPHA_ISA // keep an instruction count numInst++; numInsts++; thread->funcExeInst++; // check for instruction-count-based events comInstEventQueue[0]->serviceEvents(numInst); // decode the instruction inst = gtoh(inst); //If we're not in the middle of a macro instruction if (!curMacroStaticInst) { StaticInstPtr instPtr = NULL; //Predecode, ie bundle up an ExtMachInst //This should go away once the constructor can be set up properly predecoder.setTC(thread->getTC()); //If more fetch data is needed, pass it in. const Addr PCMask = ~(sizeof(MachInst) - 1); if(predecoder.needMoreBytes()) predecoder.moreBytes((thread->readPC() & PCMask) + fetchOffset, 0, inst); else predecoder.process(); //If an instruction is ready, decode it. Otherwise, we'll have to //fetch beyond the MachInst at the current pc. if (predecoder.extMachInstReady()) { #if THE_ISA == X86_ISA thread->setNextPC(thread->readPC() + predecoder.getInstSize()); #endif // X86_ISA stayAtPC = false; instPtr = StaticInst::decode(predecoder.getExtMachInst()); } else { stayAtPC = true; fetchOffset += sizeof(MachInst); } //If we decoded an instruction and it's microcoded, start pulling //out micro ops if (instPtr && instPtr->isMacroOp()) { curMacroStaticInst = instPtr; curStaticInst = curMacroStaticInst-> fetchMicroOp(thread->readMicroPC()); } else { curStaticInst = instPtr; } } else { //Read the next micro op from the macro op curStaticInst = curMacroStaticInst-> fetchMicroOp(thread->readMicroPC()); } #if TRACING_ON //If we decoded an instruction this "tick", record information about it. if(curStaticInst) { traceData = Trace::getInstRecord(curTick, tc, curStaticInst, thread->readPC()); DPRINTF(Decode,"Decode: Decoded %s instruction: 0x%x\n", curStaticInst->getName(), curStaticInst->machInst); #if FULL_SYSTEM thread->setInst(inst); #endif // FULL_SYSTEM } #endif // TRACING_ON } void BaseSimpleCPU::postExecute() { #if FULL_SYSTEM if (thread->profile) { bool usermode = TheISA::inUserMode(tc); thread->profilePC = usermode ? 1 : thread->readPC(); StaticInstPtr si(inst); ProfileNode *node = thread->profile->consume(tc, si); if (node) thread->profileNode = node; } #endif if (curStaticInst->isMemRef()) { numMemRefs++; } if (curStaticInst->isLoad()) { ++numLoad; comLoadEventQueue[0]->serviceEvents(numLoad); } traceFunctions(thread->readPC()); if (traceData) { traceData->dump(); delete traceData; traceData = NULL; } } void BaseSimpleCPU::advancePC(Fault fault) { //Since we're moving to a new pc, zero out the offset fetchOffset = 0; if (fault != NoFault) { curMacroStaticInst = StaticInst::nullStaticInstPtr; fault->invoke(tc); thread->setMicroPC(0); thread->setNextMicroPC(1); } else { //If we're at the last micro op for this instruction if (curStaticInst && curStaticInst->isLastMicroOp()) { //We should be working with a macro op assert(curMacroStaticInst); //Close out this macro op, and clean up the //microcode state curMacroStaticInst = StaticInst::nullStaticInstPtr; thread->setMicroPC(0); thread->setNextMicroPC(1); } //If we're still in a macro op if (curMacroStaticInst) { //Advance the micro pc thread->setMicroPC(thread->readNextMicroPC()); //Advance the "next" micro pc. Note that there are no delay //slots, and micro ops are "word" addressed. thread->setNextMicroPC(thread->readNextMicroPC() + 1); } else { // go to the next instruction thread->setPC(thread->readNextPC()); thread->setNextPC(thread->readNextNPC()); thread->setNextNPC(thread->readNextNPC() + sizeof(MachInst)); assert(thread->readNextPC() != thread->readNextNPC()); } } #if FULL_SYSTEM Addr oldpc; do { oldpc = thread->readPC(); system->pcEventQueue.service(tc); } while (oldpc != thread->readPC()); #endif } <commit_msg>Minor error. Forgotten to remove brackets for threadPC.<commit_after>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * 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: Steve Reinhardt */ #include "arch/utility.hh" #include "arch/faults.hh" #include "base/cprintf.hh" #include "base/inifile.hh" #include "base/loader/symtab.hh" #include "base/misc.hh" #include "base/pollevent.hh" #include "base/range.hh" #include "base/stats/events.hh" #include "base/trace.hh" #include "cpu/base.hh" #include "cpu/exetrace.hh" #include "cpu/profile.hh" #include "cpu/simple/base.hh" #include "cpu/simple_thread.hh" #include "cpu/smt.hh" #include "cpu/static_inst.hh" #include "cpu/thread_context.hh" #include "mem/packet.hh" #include "sim/builder.hh" #include "sim/byteswap.hh" #include "sim/debug.hh" #include "sim/host.hh" #include "sim/sim_events.hh" #include "sim/sim_object.hh" #include "sim/stats.hh" #include "sim/system.hh" #if FULL_SYSTEM #include "arch/kernel_stats.hh" #include "arch/stacktrace.hh" #include "arch/tlb.hh" #include "arch/vtophys.hh" #include "base/remote_gdb.hh" #else // !FULL_SYSTEM #include "mem/mem_object.hh" #endif // FULL_SYSTEM using namespace std; using namespace TheISA; BaseSimpleCPU::BaseSimpleCPU(Params *p) : BaseCPU(p), traceData(NULL), thread(NULL), predecoder(NULL) { #if FULL_SYSTEM thread = new SimpleThread(this, 0, p->system, p->itb, p->dtb); #else thread = new SimpleThread(this, /* thread_num */ 0, p->process, /* asid */ 0); #endif // !FULL_SYSTEM thread->setStatus(ThreadContext::Unallocated); tc = thread->getTC(); numInst = 0; startNumInst = 0; numLoad = 0; startNumLoad = 0; lastIcacheStall = 0; lastDcacheStall = 0; threadContexts.push_back(tc); fetchOffset = 0; stayAtPC = false; } BaseSimpleCPU::~BaseSimpleCPU() { } void BaseSimpleCPU::deallocateContext(int thread_num) { // for now, these are equivalent suspendContext(thread_num); } void BaseSimpleCPU::haltContext(int thread_num) { // for now, these are equivalent suspendContext(thread_num); } void BaseSimpleCPU::regStats() { using namespace Stats; BaseCPU::regStats(); numInsts .name(name() + ".num_insts") .desc("Number of instructions executed") ; numMemRefs .name(name() + ".num_refs") .desc("Number of memory references") ; notIdleFraction .name(name() + ".not_idle_fraction") .desc("Percentage of non-idle cycles") ; idleFraction .name(name() + ".idle_fraction") .desc("Percentage of idle cycles") ; icacheStallCycles .name(name() + ".icache_stall_cycles") .desc("ICache total stall cycles") .prereq(icacheStallCycles) ; dcacheStallCycles .name(name() + ".dcache_stall_cycles") .desc("DCache total stall cycles") .prereq(dcacheStallCycles) ; icacheRetryCycles .name(name() + ".icache_retry_cycles") .desc("ICache total retry cycles") .prereq(icacheRetryCycles) ; dcacheRetryCycles .name(name() + ".dcache_retry_cycles") .desc("DCache total retry cycles") .prereq(dcacheRetryCycles) ; idleFraction = constant(1.0) - notIdleFraction; } void BaseSimpleCPU::resetStats() { // startNumInst = numInst; // notIdleFraction = (_status != Idle); } void BaseSimpleCPU::serialize(ostream &os) { BaseCPU::serialize(os); // SERIALIZE_SCALAR(inst); nameOut(os, csprintf("%s.xc.0", name())); thread->serialize(os); } void BaseSimpleCPU::unserialize(Checkpoint *cp, const string &section) { BaseCPU::unserialize(cp, section); // UNSERIALIZE_SCALAR(inst); thread->unserialize(cp, csprintf("%s.xc.0", section)); } void change_thread_state(int thread_number, int activate, int priority) { } Fault BaseSimpleCPU::copySrcTranslate(Addr src) { #if 0 static bool no_warn = true; int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64; // Only support block sizes of 64 atm. assert(blk_size == 64); int offset = src & (blk_size - 1); // Make sure block doesn't span page if (no_warn && (src & PageMask) != ((src + blk_size) & PageMask) && (src >> 40) != 0xfffffc) { warn("Copied block source spans pages %x.", src); no_warn = false; } memReq->reset(src & ~(blk_size - 1), blk_size); // translate to physical address Fault fault = thread->translateDataReadReq(req); if (fault == NoFault) { thread->copySrcAddr = src; thread->copySrcPhysAddr = memReq->paddr + offset; } else { assert(!fault->isAlignmentFault()); thread->copySrcAddr = 0; thread->copySrcPhysAddr = 0; } return fault; #else return NoFault; #endif } Fault BaseSimpleCPU::copy(Addr dest) { #if 0 static bool no_warn = true; int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64; // Only support block sizes of 64 atm. assert(blk_size == 64); uint8_t data[blk_size]; //assert(thread->copySrcAddr); int offset = dest & (blk_size - 1); // Make sure block doesn't span page if (no_warn && (dest & PageMask) != ((dest + blk_size) & PageMask) && (dest >> 40) != 0xfffffc) { no_warn = false; warn("Copied block destination spans pages %x. ", dest); } memReq->reset(dest & ~(blk_size -1), blk_size); // translate to physical address Fault fault = thread->translateDataWriteReq(req); if (fault == NoFault) { Addr dest_addr = memReq->paddr + offset; // Need to read straight from memory since we have more than 8 bytes. memReq->paddr = thread->copySrcPhysAddr; thread->mem->read(memReq, data); memReq->paddr = dest_addr; thread->mem->write(memReq, data); if (dcacheInterface) { memReq->cmd = Copy; memReq->completionEvent = NULL; memReq->paddr = thread->copySrcPhysAddr; memReq->dest = dest_addr; memReq->size = 64; memReq->time = curTick; memReq->flags &= ~INST_READ; dcacheInterface->access(memReq); } } else assert(!fault->isAlignmentFault()); return fault; #else panic("copy not implemented"); return NoFault; #endif } #if FULL_SYSTEM Addr BaseSimpleCPU::dbg_vtophys(Addr addr) { return vtophys(tc, addr); } #endif // FULL_SYSTEM #if FULL_SYSTEM void BaseSimpleCPU::post_interrupt(int int_num, int index) { BaseCPU::post_interrupt(int_num, index); if (thread->status() == ThreadContext::Suspended) { DPRINTF(Quiesce,"Suspended Processor awoke\n"); thread->activate(); } } #endif // FULL_SYSTEM void BaseSimpleCPU::checkForInterrupts() { #if FULL_SYSTEM if (check_interrupts(tc)) { Fault interrupt = interrupts.getInterrupt(tc); if (interrupt != NoFault) { interrupts.updateIntrInfo(tc); interrupt->invoke(tc); } } #endif } Fault BaseSimpleCPU::setupFetchRequest(Request *req) { uint64_t threadPC = thread->readPC(); // set up memory request for instruction fetch #if ISA_HAS_DELAY_SLOT DPRINTF(Fetch,"Fetch: PC:%08p NPC:%08p NNPC:%08p\n",threadPC, thread->readNextPC(),thread->readNextNPC()); #else DPRINTF(Fetch,"Fetch: PC:%08p NPC:%08p",threadPC, thread->readNextPC()); #endif const Addr PCMask = ~(sizeof(MachInst) - 1); Addr fetchPC = thread->readPC() + fetchOffset; req->setVirt(0, fetchPC & PCMask, sizeof(MachInst), 0, threadPC); Fault fault = thread->translateInstReq(req); return fault; } void BaseSimpleCPU::preExecute() { // maintain $r0 semantics thread->setIntReg(ZeroReg, 0); #if THE_ISA == ALPHA_ISA thread->setFloatReg(ZeroReg, 0.0); #endif // ALPHA_ISA // keep an instruction count numInst++; numInsts++; thread->funcExeInst++; // check for instruction-count-based events comInstEventQueue[0]->serviceEvents(numInst); // decode the instruction inst = gtoh(inst); //If we're not in the middle of a macro instruction if (!curMacroStaticInst) { StaticInstPtr instPtr = NULL; //Predecode, ie bundle up an ExtMachInst //This should go away once the constructor can be set up properly predecoder.setTC(thread->getTC()); //If more fetch data is needed, pass it in. const Addr PCMask = ~(sizeof(MachInst) - 1); if(predecoder.needMoreBytes()) predecoder.moreBytes((thread->readPC() & PCMask) + fetchOffset, 0, inst); else predecoder.process(); //If an instruction is ready, decode it. Otherwise, we'll have to //fetch beyond the MachInst at the current pc. if (predecoder.extMachInstReady()) { #if THE_ISA == X86_ISA thread->setNextPC(thread->readPC() + predecoder.getInstSize()); #endif // X86_ISA stayAtPC = false; instPtr = StaticInst::decode(predecoder.getExtMachInst()); } else { stayAtPC = true; fetchOffset += sizeof(MachInst); } //If we decoded an instruction and it's microcoded, start pulling //out micro ops if (instPtr && instPtr->isMacroOp()) { curMacroStaticInst = instPtr; curStaticInst = curMacroStaticInst-> fetchMicroOp(thread->readMicroPC()); } else { curStaticInst = instPtr; } } else { //Read the next micro op from the macro op curStaticInst = curMacroStaticInst-> fetchMicroOp(thread->readMicroPC()); } #if TRACING_ON //If we decoded an instruction this "tick", record information about it. if(curStaticInst) { traceData = Trace::getInstRecord(curTick, tc, curStaticInst, thread->readPC()); DPRINTF(Decode,"Decode: Decoded %s instruction: 0x%x\n", curStaticInst->getName(), curStaticInst->machInst); #if FULL_SYSTEM thread->setInst(inst); #endif // FULL_SYSTEM } #endif // TRACING_ON } void BaseSimpleCPU::postExecute() { #if FULL_SYSTEM if (thread->profile) { bool usermode = TheISA::inUserMode(tc); thread->profilePC = usermode ? 1 : thread->readPC(); StaticInstPtr si(inst); ProfileNode *node = thread->profile->consume(tc, si); if (node) thread->profileNode = node; } #endif if (curStaticInst->isMemRef()) { numMemRefs++; } if (curStaticInst->isLoad()) { ++numLoad; comLoadEventQueue[0]->serviceEvents(numLoad); } traceFunctions(thread->readPC()); if (traceData) { traceData->dump(); delete traceData; traceData = NULL; } } void BaseSimpleCPU::advancePC(Fault fault) { //Since we're moving to a new pc, zero out the offset fetchOffset = 0; if (fault != NoFault) { curMacroStaticInst = StaticInst::nullStaticInstPtr; fault->invoke(tc); thread->setMicroPC(0); thread->setNextMicroPC(1); } else { //If we're at the last micro op for this instruction if (curStaticInst && curStaticInst->isLastMicroOp()) { //We should be working with a macro op assert(curMacroStaticInst); //Close out this macro op, and clean up the //microcode state curMacroStaticInst = StaticInst::nullStaticInstPtr; thread->setMicroPC(0); thread->setNextMicroPC(1); } //If we're still in a macro op if (curMacroStaticInst) { //Advance the micro pc thread->setMicroPC(thread->readNextMicroPC()); //Advance the "next" micro pc. Note that there are no delay //slots, and micro ops are "word" addressed. thread->setNextMicroPC(thread->readNextMicroPC() + 1); } else { // go to the next instruction thread->setPC(thread->readNextPC()); thread->setNextPC(thread->readNextNPC()); thread->setNextNPC(thread->readNextNPC() + sizeof(MachInst)); assert(thread->readNextPC() != thread->readNextNPC()); } } #if FULL_SYSTEM Addr oldpc; do { oldpc = thread->readPC(); system->pcEventQueue.service(tc); } while (oldpc != thread->readPC()); #endif } <|endoftext|>
<commit_before>/* Siconos-Kernel version 3.0.0, Copyright INRIA 2005-2008. * Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * Siconos is a free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * Siconos 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 Siconos; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Contact: Vincent ACARY vincent.acary@inrialpes.fr */ #include "Relay.h" #include <iostream> #include <assert.h> #include "Tools.hpp" #include "Simulation.h" #include "RelayNSL.h" using namespace std; using namespace RELATION; /* nslaw dispatch on bounds */ struct Relay::_BoundsNSLEffect : public SiconosVisitor { Relay *parent; unsigned int pos; SP::UnitaryRelation UR; _BoundsNSLEffect(Relay *p, SP::UnitaryRelation UR, unsigned int pos) : parent(p), UR(UR), pos(pos) {}; void visit(RelayNSL& nslaw) { // cout << "Relay::_BoundsNSLEffect visit" << endl; for (int i = 0; i < UR->getNonSmoothLawSize(); i++) { (*(parent->lb()))(pos + i) = nslaw.lb(); (*(parent->ub()))(pos + i) = nslaw.ub(); } } void visit(ComplementarityConditionNSL& nslaw) { for (int i = 0; i < UR->getNonSmoothLawSize(); i++) { (*(parent->lb()))(pos + i) = 0.0; (*(parent->ub()))(pos + i) = 1e+24; } // \warning Introduce the infinte double symbol rather 1e+24 } }; void Relay::initialize(SP::Simulation sim) { LinearOSNS::initialize(sim); //cout << "Relay::initialize" << endl; // initialize memory for _lb and _ub if (! _lb) _lb.reset(new SimpleVector(maxSize())); else { if (_lb->size() != maxSize()) _lb->resize(maxSize()); } if (! _ub) _ub.reset(new SimpleVector(maxSize())); else { if (_ub->size() != maxSize()) _ub->resize(maxSize()); } // fill _lb and _ub wiht the value of the NonSmooth Law SP::UnitaryRelationsGraph indexSet = simulation()->indexSet(levelMin()); //cout << " _sizeOutput =" <<_sizeOutput << endl; if (_lb->size() != _sizeOutput) { _lb->resize(_sizeOutput, false); _lb->zero(); } if (_ub->size() != _sizeOutput) { _ub->resize(_sizeOutput, false); _ub->zero(); } unsigned int pos = 0; UnitaryRelationsGraph::VIterator ui, uiend; for (boost::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui) { SP::UnitaryRelation ur = indexSet->bundle(*ui); // Compute q, this depends on the type of non smooth problem, on // the relation type and on the non smooth law pos = _M->getPositionOfUnitaryBlock(ur); SP::SiconosVisitor NSLEffect(new _BoundsNSLEffect(this, ur, pos)); ur->interaction()->nonSmoothLaw()->accept(*NSLEffect); } } int Relay::compute(double time) { // --- Prepare data for Relay computing --- preCompute(time); int info = 0; // --- Call Numerics driver --- // Inputs: // - the problem (M,q ...) // - the unknowns (z,w) // - the options for the solver (name, max iteration number ...) // - the global options for Numerics (verbose mode ...) if (_sizeOutput != 0) { // The Relay in Numerics format Relay_Problem numerics_problem; numerics_problem.M = &*_M->getNumericsMatrix(); numerics_problem.q = _q->getArray(); numerics_problem.lb = _lb->getArray(); numerics_problem.ub = _ub->getArray(); numerics_problem.size = _sizeOutput; int nbSolvers = 1; // Call Relay Driver info = relay_driver(&numerics_problem, _z->getArray() , _w->getArray() , &*_solver->numericsSolverOptions(), &*_numerics_options); // --- Recovering of the desired variables from Relay output --- postCompute(); } return info; } void Relay::display() const { cout << "======= Relay of size " << _sizeOutput << " with: " << endl; LinearOSNS::display(); } Relay* Relay::convert(OneStepNSProblem* osnsp) { Relay* lcp = dynamic_cast<Relay*>(osnsp); return lcp; } <commit_msg>new Relay.cpp<commit_after>/* Siconos-Kernel version 3.0.0, Copyright INRIA 2005-2008. * Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * Siconos is a free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * Siconos 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 Siconos; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Contact: Vincent ACARY vincent.acary@inrialpes.fr */ #include "Relay.h" #include <iostream> #include <assert.h> #include "Tools.hpp" #include "Simulation.h" #include "RelayNSL.h" using namespace std; using namespace RELATION; /* nslaw dispatch on bounds */ struct Relay::_BoundsNSLEffect : public SiconosVisitor { Relay *parent; unsigned int pos; SP::UnitaryRelation UR; _BoundsNSLEffect(Relay *p, SP::UnitaryRelation UR, unsigned int pos) : parent(p), UR(UR), pos(pos) {}; void visit(RelayNSL& nslaw) { // cout << "Relay::_BoundsNSLEffect visit" << endl; for (int i = 0; i < UR->getNonSmoothLawSize(); i++) { (*(parent->lb()))(pos + i) = nslaw.lb(); (*(parent->ub()))(pos + i) = nslaw.ub(); } } void visit(ComplementarityConditionNSL& nslaw) { for (int i = 0; i < UR->getNonSmoothLawSize(); i++) { (*(parent->lb()))(pos + i) = 0.0; (*(parent->ub()))(pos + i) = 1e+24; } // \warning Introduce the infinte double symbol rather 1e+24 } }; void Relay::initialize(SP::Simulation sim) { LinearOSNS::initialize(sim); //cout << "Relay::initialize" << endl; // initialize memory for _lb and _ub if (! _lb) _lb.reset(new SimpleVector(maxSize())); else { if (_lb->size() != maxSize()) _lb->resize(maxSize()); } if (! _ub) _ub.reset(new SimpleVector(maxSize())); else { if (_ub->size() != maxSize()) _ub->resize(maxSize()); } // fill _lb and _ub wiht the value of the NonSmooth Law SP::UnitaryRelationsGraph indexSet = simulation()->indexSet(levelMin()); //cout << " _sizeOutput =" <<_sizeOutput << endl; if (_lb->size() != _sizeOutput) { _lb->resize(_sizeOutput, false); _lb->zero(); } if (_ub->size() != _sizeOutput) { _ub->resize(_sizeOutput, false); _ub->zero(); } unsigned int pos = 0; UnitaryRelationsGraph::VIterator ui, uiend; for (boost::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui) { SP::UnitaryRelation ur = indexSet->bundle(*ui); // Compute q, this depends on the type of non smooth problem, on // the relation type and on the non smooth law pos = _M->getPositionOfUnitaryBlock(ur); SP::SiconosVisitor NSLEffect(new _BoundsNSLEffect(this, ur, pos)); ur->interaction()->nonSmoothLaw()->accept(*NSLEffect); } } int Relay::compute(double time) { // --- Prepare data for Relay computing --- preCompute(time); int info = 0; // --- Call Numerics driver --- // Inputs: // - the problem (M,q ...) // - the unknowns (z,w) // - the options for the solver (name, max iteration number ...) // - the global options for Numerics (verbose mode ...) if (_sizeOutput != 0) { // The Relay in Numerics format Relay_Problem numerics_problem; numerics_problem.M = &*_M->getNumericsMatrix(); numerics_problem.q = _q->getArray(); numerics_problem.lb = _lb->getArray(); numerics_problem.ub = _ub->getArray(); numerics_problem.size = _sizeOutput; int nbSolvers = 1; // Call Relay Driver Relay_display(&numerics_problem); info = relay_driver(&numerics_problem, _z->getArray() , _w->getArray() , &*_solver->numericsSolverOptions(), nbSolvers, &*_numerics_options); if (info != 0) { cout << "Warning : Problem in Relay resolution" << endl; } // --- Recovering of the desired variables from Relay output --- postCompute(); } return info; } void Relay::display() const { cout << "======= Relay of size " << _sizeOutput << " with: " << endl; LinearOSNS::display(); } Relay* Relay::convert(OneStepNSProblem* osnsp) { Relay* lcp = dynamic_cast<Relay*>(osnsp); return lcp; } <|endoftext|>
<commit_before>/* * Licensed under Apache License v2. See LICENSE for more information. */ #include <CppUTest/TestHarness.h> #include "CppUTest/CommandLineTestRunner.h" extern "C" { #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "dyn_function.h" static int g_count; static void stdLog(void *handle, int level, const char *file, int line, const char *msg, ...) { va_list ap; const char *levels[5] = {"NIL", "ERROR", "WARNING", "INFO", "DEBUG"}; fprintf(stderr, "%s: FILE:%s, LINE:%i, MSG:",levels[level], file, line); va_start(ap, msg); vfprintf(stderr, msg, ap); fprintf(stderr, "\n"); } #define EXAMPLE1_SCHEMA "example(III)I" static void example1_binding(void *userData, void* args[], void *out) { printf("example1 closure called\n"); int32_t a = *((int32_t *)args[0]); int32_t b = *((int32_t *)args[1]); int32_t c = *((int32_t *)args[2]); int32_t *ret = (int32_t *)out; *ret = a + b + c; g_count += 1; } #define EXAMPLE2_SCHEMA "example(I{DDD val1 val2 val3}I)D" struct example2_arg2 { double val1; double val2; double val3; }; void example2_binding(void *userData, void* args[], void *out) { printf("example2 closure called\n"); int32_t a = *((int32_t *)args[0]); struct example2_arg2 b = *((struct example2_arg2 *)args[1]); int32_t c = *((int32_t *)args[2]); int32_t *ret = (int32_t *)out; *ret = a + b.val1 + b.val2 + b.val3 + c; g_count += 1; } #define EXAMPLE3_SCHEMA "example(III){III sum max min}" struct example3_ret { int32_t sum; int32_t max; int32_t min; }; static void example3_binding(void *userData, void* args[], void *out) { printf("example closure called\n"); int32_t a = *((int32_t *)args[0]); int32_t b = *((int32_t *)args[1]); int32_t c = *((int32_t *)args[2]); struct example3_ret *result = (struct example3_ret *)calloc(1,sizeof(struct example3_ret)); result->sum = a + b + c; result->min = a <= b ? a : b; result->max = a >= b ? a : b; result->min = result->min <= c ? result->min : c; result->max = result->max >= c ? result->max : c; struct example3_ret **ret = (struct example3_ret **)out; (*ret) = result; g_count += 1; } static void tests() { dyn_closure_type *dynClosure = NULL; int rc; { rc = dynClosure_create(EXAMPLE1_SCHEMA, example1_binding, NULL, &dynClosure); CHECK_EQUAL(0, rc); int32_t (*func)(int32_t a, int32_t b, int32_t c) = NULL; int rc = dynClosure_getFnPointer(dynClosure, (void(**)(void))&func); CHECK_EQUAL(0, rc); int32_t ret = func(2,3,4); printf("Return value for example1 is %i\n", ret); CHECK_EQUAL(1, g_count); dynClosure_destroy(dynClosure); } { dynClosure = NULL; rc = dynClosure_create(EXAMPLE2_SCHEMA, example2_binding, NULL, &dynClosure); CHECK_EQUAL(0, rc); double (*func)(int32_t a, struct example2_arg2 b, int32_t c) = NULL; rc = dynClosure_getFnPointer(dynClosure, (void(**)(void))&func); CHECK_EQUAL(0, rc); struct example2_arg2 b = { .val1 = 1.0, .val2 = 1.5, .val3 = 2.0 }; double ret = func(2,b,4); printf("Return value for example2 is %f\n", ret); CHECK_EQUAL(2, g_count); dynClosure_destroy(dynClosure); } { dynClosure = NULL; rc = dynClosure_create(EXAMPLE3_SCHEMA, example3_binding, NULL, &dynClosure); CHECK_EQUAL(0, rc); struct example3_ret * (*func)(int32_t a, int32_t b, int32_t c) = NULL; rc = dynClosure_getFnPointer(dynClosure, (void(**)(void))&func); CHECK_EQUAL(0, rc); struct example3_ret *ret = func(2,8,4); printf("Return value for example3 is {sum:%i, max:%i, min:%i}\n", ret->sum, ret->max, ret->min); CHECK_EQUAL(3, g_count); dynClosure_destroy(dynClosure); free(ret); } } } TEST_GROUP(DynClosureTests) { void setup() { dynFunction_logSetup(stdLog, NULL, 4); //TODO dynType_logSetup(stdLog, NULL, 4); g_count = 0; } }; TEST(DynClosureTests, DynCLosureTest1) { //TODO split up tests(); } <commit_msg>CELIX-237: change struct assigment in ccputest.<commit_after>/* * Licensed under Apache License v2. See LICENSE for more information. */ #include <CppUTest/TestHarness.h> #include "CppUTest/CommandLineTestRunner.h" extern "C" { #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "dyn_function.h" static int g_count; static void stdLog(void *handle, int level, const char *file, int line, const char *msg, ...) { va_list ap; const char *levels[5] = {"NIL", "ERROR", "WARNING", "INFO", "DEBUG"}; fprintf(stderr, "%s: FILE:%s, LINE:%i, MSG:",levels[level], file, line); va_start(ap, msg); vfprintf(stderr, msg, ap); fprintf(stderr, "\n"); } #define EXAMPLE1_SCHEMA "example(III)I" static void example1_binding(void *userData, void* args[], void *out) { printf("example1 closure called\n"); int32_t a = *((int32_t *)args[0]); int32_t b = *((int32_t *)args[1]); int32_t c = *((int32_t *)args[2]); int32_t *ret = (int32_t *)out; *ret = a + b + c; g_count += 1; } #define EXAMPLE2_SCHEMA "example(I{DDD val1 val2 val3}I)D" struct example2_arg2 { double val1; double val2; double val3; }; void example2_binding(void *userData, void* args[], void *out) { printf("example2 closure called\n"); int32_t a = *((int32_t *)args[0]); struct example2_arg2 b = *((struct example2_arg2 *)args[1]); int32_t c = *((int32_t *)args[2]); int32_t *ret = (int32_t *)out; *ret = a + b.val1 + b.val2 + b.val3 + c; g_count += 1; } #define EXAMPLE3_SCHEMA "example(III){III sum max min}" struct example3_ret { int32_t sum; int32_t max; int32_t min; }; static void example3_binding(void *userData, void* args[], void *out) { printf("example closure called\n"); int32_t a = *((int32_t *)args[0]); int32_t b = *((int32_t *)args[1]); int32_t c = *((int32_t *)args[2]); struct example3_ret *result = (struct example3_ret *)calloc(1,sizeof(struct example3_ret)); result->sum = a + b + c; result->min = a <= b ? a : b; result->max = a >= b ? a : b; result->min = result->min <= c ? result->min : c; result->max = result->max >= c ? result->max : c; struct example3_ret **ret = (struct example3_ret **)out; (*ret) = result; g_count += 1; } static void tests() { dyn_closure_type *dynClosure = NULL; int rc; { rc = dynClosure_create(EXAMPLE1_SCHEMA, example1_binding, NULL, &dynClosure); CHECK_EQUAL(0, rc); int32_t (*func)(int32_t a, int32_t b, int32_t c) = NULL; int rc = dynClosure_getFnPointer(dynClosure, (void(**)(void))&func); CHECK_EQUAL(0, rc); int32_t ret = func(2,3,4); printf("Return value for example1 is %i\n", ret); CHECK_EQUAL(1, g_count); dynClosure_destroy(dynClosure); } { dynClosure = NULL; rc = dynClosure_create(EXAMPLE2_SCHEMA, example2_binding, NULL, &dynClosure); CHECK_EQUAL(0, rc); double (*func)(int32_t a, struct example2_arg2 b, int32_t c) = NULL; rc = dynClosure_getFnPointer(dynClosure, (void(**)(void))&func); CHECK_EQUAL(0, rc); struct example2_arg2 b; b.val1 = 1.0; b.val2 = 1.5; b.val3 = 2.0; double ret = func(2,b,4); printf("Return value for example2 is %f\n", ret); CHECK_EQUAL(2, g_count); dynClosure_destroy(dynClosure); } { dynClosure = NULL; rc = dynClosure_create(EXAMPLE3_SCHEMA, example3_binding, NULL, &dynClosure); CHECK_EQUAL(0, rc); struct example3_ret * (*func)(int32_t a, int32_t b, int32_t c) = NULL; rc = dynClosure_getFnPointer(dynClosure, (void(**)(void))&func); CHECK_EQUAL(0, rc); struct example3_ret *ret = func(2,8,4); printf("Return value for example3 is {sum:%i, max:%i, min:%i}\n", ret->sum, ret->max, ret->min); CHECK_EQUAL(3, g_count); dynClosure_destroy(dynClosure); free(ret); } } } TEST_GROUP(DynClosureTests) { void setup() { dynFunction_logSetup(stdLog, NULL, 4); //TODO dynType_logSetup(stdLog, NULL, 4); g_count = 0; } }; TEST(DynClosureTests, DynCLosureTest1) { //TODO split up tests(); } <|endoftext|>
<commit_before>/* * Copyright 2008-2011 NVIDIA Corporation * * 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 <thrust/detail/config.h> #include <thrust/detail/tagged_allocator.h> #include <thrust/detail/backend/generic/select_system.h> #include <thrust/system/detail/bad_alloc.h> #include <limits> namespace thrust { namespace detail { template<typename T, typename Tag, typename Pointer> tagged_allocator<T,Tag,Pointer> ::tagged_allocator() {} template<typename T, typename Tag, typename Pointer> tagged_allocator<T,Tag,Pointer> ::tagged_allocator(const tagged_allocator<T,Tag,Pointer> &) {} template<typename T, typename Tag, typename Pointer> template<typename U, typename OtherPointer> tagged_allocator<T,Tag,Pointer> ::tagged_allocator(const tagged_allocator<U,Tag,OtherPointer> &) {} template<typename T, typename Tag, typename Pointer> tagged_allocator<T,Tag,Pointer> ::~tagged_allocator() {} template<typename T, typename Tag, typename Pointer> typename tagged_allocator<T,Tag,Pointer>::pointer tagged_allocator<T,Tag,Pointer> ::address(reference x) const { return &x; } template<typename T, typename Tag, typename Pointer> typename tagged_allocator<T,Tag,Pointer>::const_pointer tagged_allocator<T,Tag,Pointer> ::address(const_reference x) const { return &x; } template<typename T, typename Tag, typename Pointer> template<typename OtherPointer> typename thrust::detail::pointer_traits<OtherPointer>::raw_pointer tagged_allocator<T,Tag,Pointer> ::get(OtherPointer ptr) { return thrust::detail::pointer_traits<OtherPointer>::get(ptr); } template<typename T, typename Tag, typename Pointer> typename tagged_allocator<T,Tag,Pointer>::pointer tagged_allocator<T,Tag,Pointer> ::allocate(size_type cnt) { using thrust::detail::backend::generic::select_system; using thrust::detail::backend::generic::malloc; // XXX should use a hypothetical thrust::static_pointer_cast here T* result = static_cast<T*>(get(malloc(select_system(Tag()), sizeof(value_type) * cnt))); if(result == 0) { throw thrust::system::detail::bad_alloc("tagged_allocator::allocate: malloc failed"); } // end if return pointer(result); } template<typename T, typename Tag, typename Pointer> void tagged_allocator<T,Tag,Pointer> ::deallocate(pointer p, size_type n) { using thrust::detail::backend::generic::select_system; // XXX should probably have a using generic::free here // which would be an automatic failure if selected free(select_system(Tag()), p); } template<typename T, typename Tag, typename Pointer> typename tagged_allocator<T,Tag,Pointer>::size_type tagged_allocator<T,Tag,Pointer> ::max_size() const { return (std::numeric_limits<size_type>::max)() / sizeof(T); } template<typename T1, typename Pointer1, typename T2, typename Pointer2, typename Tag> __host__ __device__ bool operator==(const tagged_allocator<T1,Pointer1,Tag> &, const tagged_allocator<T2,Pointer2,Tag> &) { return true; } template<typename T1, typename Pointer1, typename T2, typename Pointer2, typename Tag> __host__ __device__ bool operator!=(const tagged_allocator<T1,Pointer1,Tag> &, const tagged_allocator<T2,Pointer2,Tag> &) { return false; } } // end detail } // end thrust <commit_msg>Add a using thrust::detail::backend::generic::free to tagged_allocator::deallocate<commit_after>/* * Copyright 2008-2011 NVIDIA Corporation * * 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 <thrust/detail/config.h> #include <thrust/detail/tagged_allocator.h> #include <thrust/detail/backend/generic/select_system.h> #include <thrust/detail/backend/generic/memory.h> #include <thrust/system/detail/bad_alloc.h> #include <limits> namespace thrust { namespace detail { template<typename T, typename Tag, typename Pointer> tagged_allocator<T,Tag,Pointer> ::tagged_allocator() {} template<typename T, typename Tag, typename Pointer> tagged_allocator<T,Tag,Pointer> ::tagged_allocator(const tagged_allocator<T,Tag,Pointer> &) {} template<typename T, typename Tag, typename Pointer> template<typename U, typename OtherPointer> tagged_allocator<T,Tag,Pointer> ::tagged_allocator(const tagged_allocator<U,Tag,OtherPointer> &) {} template<typename T, typename Tag, typename Pointer> tagged_allocator<T,Tag,Pointer> ::~tagged_allocator() {} template<typename T, typename Tag, typename Pointer> typename tagged_allocator<T,Tag,Pointer>::pointer tagged_allocator<T,Tag,Pointer> ::address(reference x) const { return &x; } template<typename T, typename Tag, typename Pointer> typename tagged_allocator<T,Tag,Pointer>::const_pointer tagged_allocator<T,Tag,Pointer> ::address(const_reference x) const { return &x; } template<typename T, typename Tag, typename Pointer> template<typename OtherPointer> typename thrust::detail::pointer_traits<OtherPointer>::raw_pointer tagged_allocator<T,Tag,Pointer> ::get(OtherPointer ptr) { return thrust::detail::pointer_traits<OtherPointer>::get(ptr); } template<typename T, typename Tag, typename Pointer> typename tagged_allocator<T,Tag,Pointer>::pointer tagged_allocator<T,Tag,Pointer> ::allocate(size_type cnt) { using thrust::detail::backend::generic::select_system; using thrust::detail::backend::generic::malloc; // XXX should use a hypothetical thrust::static_pointer_cast here T* result = static_cast<T*>(get(malloc(select_system(Tag()), sizeof(value_type) * cnt))); if(result == 0) { throw thrust::system::detail::bad_alloc("tagged_allocator::allocate: malloc failed"); } // end if return pointer(result); } template<typename T, typename Tag, typename Pointer> void tagged_allocator<T,Tag,Pointer> ::deallocate(pointer p, size_type n) { using thrust::detail::backend::generic::select_system; using thrust::detail::backend::generic::free; free(select_system(Tag()), p); } template<typename T, typename Tag, typename Pointer> typename tagged_allocator<T,Tag,Pointer>::size_type tagged_allocator<T,Tag,Pointer> ::max_size() const { return (std::numeric_limits<size_type>::max)() / sizeof(T); } template<typename T1, typename Pointer1, typename T2, typename Pointer2, typename Tag> __host__ __device__ bool operator==(const tagged_allocator<T1,Pointer1,Tag> &, const tagged_allocator<T2,Pointer2,Tag> &) { return true; } template<typename T1, typename Pointer1, typename T2, typename Pointer2, typename Tag> __host__ __device__ bool operator!=(const tagged_allocator<T1,Pointer1,Tag> &, const tagged_allocator<T2,Pointer2,Tag> &) { return false; } } // end detail } // end thrust <|endoftext|>
<commit_before>#ifndef __FUTURE_HPP__ #define __FUTURE_HPP__ #include "SoftXMT.hpp" #include "Delegate.hpp" #include "Cache.hpp" //TODO: special ArgsCache acquire, which //uses args pointer field as a global address //to the future and either //1. flip the started bit //2. or simply acquire RW instead of RO (and Cached not Incoherent) // idea: if we had a need for futures that // only mutate their arguments (essentially functional but could change the inputs as well) // then we could allow multiple copies of // the future to execute RW-shared mode, where only the first release writeback wins // TODO: do something like this to force users to have // the future fields but make them invisible /* class FutureArgs { private: GlobalAddress<Future> futurePtr; void (* user_fn_p)(A *); }; class MyArgs : public FutureArgs { int i; int j; } // Additional possibility is method #2 above */ ////////////////////////////////////////// #if DEBUG static int64_t count_ = 0; #endif template < typename ArgsStruct > class Future { private: int64_t started; Thread * waiter; bool done; ArgsStruct * userArgs_lp; struct future_args { GlobalAddress<Future> futureAddr; void (* user_fn_p)(ArgsStruct *); GlobalAddress< ArgsStruct > userArgs; future_args( Future< ArgsStruct > * future, ArgsStruct * userArgs, void (* fn_p)(ArgsStruct *) ) : futureAddr( make_global( future ) ) , userArgs( make_global( userArgs ) ) , user_fn_p( fn_p ) { } }; future_args task_args; struct future_done_args { Future< ArgsStruct > * futurePtr; }; static void future_done_am( future_done_args * args, size_t args_size, void * payload, size_t payload_size ) { args->futurePtr->done = true; if ( args->futurePtr->waiter != NULL ) { SoftXMT_wake( args->futurePtr->waiter ); args->futurePtr->waiter = NULL; } } ///////////////// //Custom delegate operation //TODO: use a generalized mechanism that abstracts all but function ///////////////// struct started_memory_descriptor { Thread * t; GlobalAddress< Future<ArgsStruct> > address; int64_t data; bool done; }; struct started_reply_args { GlobalAddress<started_memory_descriptor> descriptor; }; static void started_reply_am( started_reply_args * args, size_t size, void * payload, size_t payload_size ) { assert( payload_size == sizeof(int64_t ) ); args->descriptor.pointer()->data = *(static_cast<int64_t*>(payload)); args->descriptor.pointer()->done = true; SoftXMT_wake( args->descriptor.pointer()->t ); } struct started_request_args { GlobalAddress<started_memory_descriptor> descriptor; GlobalAddress< Future<ArgsStruct> > address; }; static void started_request_am( started_request_args * args, size_t size, void * payload, size_t payload_size ) { Future< ArgsStruct > * fptr = args->address.pointer(); DVLOG(5) << "Future(IN_AM) FID "<< fptr->getId(); CHECK((int64_t)fptr>0x1000) << "dequeued request (descriptor gaddress:" << args->descriptor << "): future ptr:" << (void*)fptr << "(future gaddress:"<<args->address; int64_t data = fptr->started; fptr->started = data + 1; // If future was already started in this case, it must have been started by touching thread. // Incrementing started again will tell the touching thread it can deallocate the Future if ( data > 0 ) { DVLOG(5) << "already started:(id:"<<fptr->getId(); if ( fptr->done ) { //if it is done then toucher is waiting for the dequeue DVLOG(5) << "need to wake:(id:"<<fptr->getId(); CHECK ( fptr->waiter!=NULL ) << "future ptr:" << (void*)fptr <<"\n done="<<fptr->done<<" (id:"<<fptr->getId()<<") data="<<data<< " (AM from "<<args->descriptor.node(); SoftXMT_wake( fptr->waiter ); fptr->waiter = NULL; } else { DVLOG(5) << "not need to wake:(id:"<<fptr->getId(); } } else { DVLOG(5) << "not already started:(id:"<<fptr->getId(); } started_reply_args reply_args; reply_args.descriptor = args->descriptor; SoftXMT_call_on( args->descriptor.node(), &started_reply_am, &reply_args, sizeof(reply_args), &data, sizeof(data) ); } static int64_t future_delegate_started( GlobalAddress< Future<ArgsStruct> > address ) { started_memory_descriptor md; md.address = address; md.data = 0; md.done = false; md.t = CURRENT_THREAD; started_request_args args; args.descriptor = make_global(&md); args.address = address; SoftXMT_call_on( address.node(), &started_request_am, &args ); while( !md.done ) { SoftXMT_suspend(); } return md.data; } ////////////////////////////////////// static void future_function( future_args * args ) { DVLOG(4) << "Future(other) "<< args->futureAddr; // TODO #1: the make_global is just calculating location of Future->started //if ( SoftXMT_delegate_fetch_and_add_word( make_global( args->startedAddr, args->futureAddr.node() ), 1 ) == 0 ) { DVLOG(5) << CURRENT_THREAD->id << "args("<<(void*)args<<") will call started am " << args->futureAddr.pointer(); if ( future_delegate_started( args->futureAddr ) == 0 ) { DVLOG(5) << CURRENT_THREAD->id << "user_args="<<args->userArgs<<" for ftraddr="<< args->futureAddr.pointer(); // grab the user arguments size_t args_size = sizeof(ArgsStruct); ArgsStruct argsbuf; typename Incoherent<ArgsStruct>::RO cached_args( args->userArgs, args_size, &argsbuf ); cached_args.block_until_acquired(); // call the user task args->user_fn_p( &argsbuf ); cached_args.block_until_released(); // call wake up AM on Node that has the Future future_done_args done_args = { args->futureAddr.pointer() }; SoftXMT_call_on( args->futureAddr.node(), &future_done_am, &done_args ); } } int64_t getId() { #if DEBUG return id; #else return -1; #endif } public: #if DEBUG int64_t id; #endif // TODO: NOTE that this does not copy user arguments because we want to // preserve the same semantics as normal tasks. // --Unfortunately this means there are three communications to start // 1) Task.execute fetches args // 2) Future atomic started // 3) Bring in user arguments and start Future ( void (* fn_p)(ArgsStruct *), ArgsStruct * userArgs ) : started( 0 ) , waiter( NULL ) , done( false ) , userArgs_lp( userArgs ) #if DEBUG , id( SoftXMT_mynode() + ((count_++)*SoftXMT_nodes() ) ) #endif , task_args( this, userArgs, fn_p ) { DVLOG(5) << CURRENT_THREAD->id << " creates Future:"<< (void*)this << " id:"<< getId() << " args:"<< &task_args; } void touch( ) { DVLOG(4) << "Future(touch) FID "<< this->getId() << " ga:"<<task_args.futureAddr; // start if not started if ( SoftXMT_delegate_fetch_and_add_word( make_global(&started), 1 )==0 ) { DVLOG(5) << CURRENT_THREAD->id << " gets to touch-go " << getId(); task_args.user_fn_p( userArgs_lp ); CHECK( started <= 2 ) << "started=" << started << " (at most one additional increment should occur)"; done = true; while ( started < 2 ) { // wait until dequeued DVLOG(5) << CURRENT_THREAD->id << " has to wait on dequeue " << getId(); waiter = CURRENT_THREAD; SoftXMT_suspend( ); DVLOG(5) << CURRENT_THREAD->id << " has woke on dequeue " << getId(); } } else { // otherwise block on done event while ( !done ) { waiter = CURRENT_THREAD; SoftXMT_suspend( ); } } } void addAsPublicTask( ) { DVLOG(4) << "Future(spawn) " << this->getId() << " ga:"<<task_args.futureAddr; SoftXMT_publicTask( &future_function, &task_args ); } }; #endif <commit_msg>FIXED: future was fetching count:args_size, instead of count=1 userArgs<commit_after>#ifndef __FUTURE_HPP__ #define __FUTURE_HPP__ #include "SoftXMT.hpp" #include "Delegate.hpp" #include "Cache.hpp" //TODO: special ArgsCache acquire, which //uses args pointer field as a global address //to the future and either //1. flip the started bit //2. or simply acquire RW instead of RO (and Cached not Incoherent) // idea: if we had a need for futures that // only mutate their arguments (essentially functional but could change the inputs as well) // then we could allow multiple copies of // the future to execute RW-shared mode, where only the first release writeback wins // TODO: do something like this to force users to have // the future fields but make them invisible /* class FutureArgs { private: GlobalAddress<Future> futurePtr; void (* user_fn_p)(A *); }; class MyArgs : public FutureArgs { int i; int j; } // Additional possibility is method #2 above */ ////////////////////////////////////////// #if DEBUG static int64_t count_ = 0; #endif template < typename ArgsStruct > class Future { private: int64_t started; Thread * waiter; bool done; ArgsStruct * userArgs_lp; struct future_args { GlobalAddress<Future> futureAddr; void (* user_fn_p)(ArgsStruct *); GlobalAddress< ArgsStruct > userArgs; future_args( Future< ArgsStruct > * future, ArgsStruct * userArgs, void (* fn_p)(ArgsStruct *) ) : futureAddr( make_global( future ) ) , userArgs( make_global( userArgs ) ) , user_fn_p( fn_p ) { } }; future_args task_args; struct future_done_args { Future< ArgsStruct > * futurePtr; }; static void future_done_am( future_done_args * args, size_t args_size, void * payload, size_t payload_size ) { args->futurePtr->done = true; if ( args->futurePtr->waiter != NULL ) { SoftXMT_wake( args->futurePtr->waiter ); args->futurePtr->waiter = NULL; } } ///////////////// //Custom delegate operation //TODO: use a generalized mechanism that abstracts all but function ///////////////// struct started_memory_descriptor { Thread * t; GlobalAddress< Future<ArgsStruct> > address; int64_t data; bool done; }; struct started_reply_args { GlobalAddress<started_memory_descriptor> descriptor; }; static void started_reply_am( started_reply_args * args, size_t size, void * payload, size_t payload_size ) { assert( payload_size == sizeof(int64_t ) ); args->descriptor.pointer()->data = *(static_cast<int64_t*>(payload)); args->descriptor.pointer()->done = true; SoftXMT_wake( args->descriptor.pointer()->t ); } struct started_request_args { GlobalAddress<started_memory_descriptor> descriptor; GlobalAddress< Future<ArgsStruct> > address; }; static void started_request_am( started_request_args * args, size_t size, void * payload, size_t payload_size ) { Future< ArgsStruct > * fptr = args->address.pointer(); DVLOG(5) << "Future(IN_AM) FID "<< fptr->getId(); CHECK((int64_t)fptr>0x1000) << "dequeued request (descriptor gaddress:" << args->descriptor << "): future ptr:" << (void*)fptr << "(future gaddress:"<<args->address; int64_t data = fptr->started; fptr->started = data + 1; // If future was already started in this case, it must have been started by touching thread. // Incrementing started again will tell the touching thread it can deallocate the Future if ( data > 0 ) { DVLOG(5) << "already started:(id:"<<fptr->getId(); if ( fptr->done ) { //if it is done then toucher is waiting for the dequeue DVLOG(5) << "need to wake:(id:"<<fptr->getId(); CHECK ( fptr->waiter!=NULL ) << "future ptr:" << (void*)fptr <<"\n done="<<fptr->done<<" (id:"<<fptr->getId()<<") data="<<data<< " (AM from "<<args->descriptor.node(); SoftXMT_wake( fptr->waiter ); fptr->waiter = NULL; } else { DVLOG(5) << "not need to wake:(id:"<<fptr->getId(); } } else { DVLOG(5) << "not already started:(id:"<<fptr->getId(); } started_reply_args reply_args; reply_args.descriptor = args->descriptor; SoftXMT_call_on( args->descriptor.node(), &started_reply_am, &reply_args, sizeof(reply_args), &data, sizeof(data) ); } static int64_t future_delegate_started( GlobalAddress< Future<ArgsStruct> > address ) { started_memory_descriptor md; md.address = address; md.data = 0; md.done = false; md.t = CURRENT_THREAD; started_request_args args; args.descriptor = make_global(&md); args.address = address; SoftXMT_call_on( address.node(), &started_request_am, &args ); while( !md.done ) { SoftXMT_suspend(); } return md.data; } ////////////////////////////////////// static void future_function( future_args * args ) { DVLOG(4) << "Future(other) "<< args->futureAddr; // TODO #1: the make_global is just calculating location of Future->started //if ( SoftXMT_delegate_fetch_and_add_word( make_global( args->startedAddr, args->futureAddr.node() ), 1 ) == 0 ) { DVLOG(5) << CURRENT_THREAD->id << "args("<<(void*)args<<") will call started am " << args->futureAddr.pointer(); if ( future_delegate_started( args->futureAddr ) == 0 ) { DVLOG(5) << CURRENT_THREAD->id << "user_args="<<args->userArgs<<" for ftraddr="<< args->futureAddr.pointer(); // grab the user arguments size_t args_size = sizeof(ArgsStruct); ArgsStruct argsbuf; typename Incoherent<ArgsStruct>::RO cached_args( args->userArgs, 1, &argsbuf ); cached_args.block_until_acquired(); // call the user task args->user_fn_p( &argsbuf ); cached_args.block_until_released(); // call wake up AM on Node that has the Future future_done_args done_args = { args->futureAddr.pointer() }; SoftXMT_call_on( args->futureAddr.node(), &future_done_am, &done_args ); } } int64_t getId() { #if DEBUG return id; #else return -1; #endif } public: #if DEBUG int64_t id; #endif // TODO: NOTE that this does not copy user arguments because we want to // preserve the same semantics as normal tasks. // --Unfortunately this means there are three communications to start // 1) Task.execute fetches args // 2) Future atomic started // 3) Bring in user arguments and start Future ( void (* fn_p)(ArgsStruct *), ArgsStruct * userArgs ) : started( 0 ) , waiter( NULL ) , done( false ) , userArgs_lp( userArgs ) #if DEBUG , id( SoftXMT_mynode() + ((count_++)*SoftXMT_nodes() ) ) #endif , task_args( this, userArgs, fn_p ) { DVLOG(5) << CURRENT_THREAD->id << " creates Future:"<< (void*)this << " id:"<< getId() << " args:"<< &task_args; } void touch( ) { DVLOG(4) << "Future(touch) FID "<< this->getId() << " ga:"<<task_args.futureAddr; // start if not started if ( SoftXMT_delegate_fetch_and_add_word( make_global(&started), 1 )==0 ) { DVLOG(5) << CURRENT_THREAD->id << " gets to touch-go " << getId(); task_args.user_fn_p( userArgs_lp ); CHECK( started <= 2 ) << "started=" << started << " (at most one additional increment should occur)"; done = true; while ( started < 2 ) { // wait until dequeued DVLOG(5) << CURRENT_THREAD->id << " has to wait on dequeue " << getId(); waiter = CURRENT_THREAD; SoftXMT_suspend( ); DVLOG(5) << CURRENT_THREAD->id << " has woke on dequeue " << getId(); } } else { // otherwise block on done event while ( !done ) { waiter = CURRENT_THREAD; SoftXMT_suspend( ); } } } void addAsPublicTask( ) { DVLOG(4) << "Future(spawn) " << this->getId() << " ga:"<<task_args.futureAddr; SoftXMT_publicTask( &future_function, &task_args ); } }; #endif <|endoftext|>
<commit_before>#include "pch.h" #include "aiMeshOps.h" namespace impl { template<class Indices, class Counts> inline void BuildConnection( MeshConnectionInfo& connection, const Indices& indices, const Counts& counts, const IArray<float3>& vertices) { size_t num_points = vertices.size(); size_t num_faces = counts.size(); size_t num_indices = indices.size(); connection.v2f_offsets.resize_discard(num_points); connection.v2f_faces.resize_discard(num_indices); connection.v2f_indices.resize_discard(num_indices); connection.v2f_counts.resize_zeroclear(num_points); { int ii = 0; for (size_t fi = 0; fi < num_faces; ++fi) { int c = counts[fi]; for (int ci = 0; ci < c; ++ci) { connection.v2f_counts[indices[ii + ci]]++; } ii += c; } int offset = 0; for (size_t i = 0; i < num_points; ++i) { connection.v2f_offsets[i] = offset; offset += connection.v2f_counts[i]; } } connection.v2f_counts.zeroclear(); { int i = 0; for (int fi = 0; fi < (int)num_faces; ++fi) { int c = counts[fi]; for (int ci = 0; ci < c; ++ci) { int vi = indices[i + ci]; int ti = connection.v2f_offsets[vi] + connection.v2f_counts[vi]++; connection.v2f_faces[ti] = fi; connection.v2f_indices[ti] = i + ci; } i += c; } } } } void MeshConnectionInfo::clear() { v2f_counts.clear(); v2f_offsets.clear(); v2f_faces.clear(); v2f_indices.clear(); weld_map.clear(); weld_counts.clear(); weld_offsets.clear(); weld_indices.clear(); } void MeshConnectionInfo::buildConnection( const IArray<int>& indices, const IArray<int>& counts, const IArray<float3>& vertices) { size_t num_points = vertices.size(); size_t num_faces = counts.size(); size_t num_indices = indices.size(); v2f_offsets.resize_discard(num_points); v2f_faces.resize_discard(num_indices); v2f_indices.resize_discard(num_indices); v2f_counts.resize_zeroclear(num_points); { int ii = 0; for (size_t fi = 0; fi < num_faces; ++fi) { int c = counts[fi]; for (int ci = 0; ci < c; ++ci) { v2f_counts[indices[ii + ci]]++; } ii += c; } int offset = 0; for (size_t i = 0; i < num_points; ++i) { v2f_offsets[i] = offset; offset += v2f_counts[i]; } } v2f_counts.zeroclear(); { int i = 0; for (int fi = 0; fi < (int)num_faces; ++fi) { int c = counts[fi]; for (int ci = 0; ci < c; ++ci) { int vi = indices[i + ci]; int ti = v2f_offsets[vi] + v2f_counts[vi]++; v2f_faces[ti] = fi; v2f_indices[ti] = i + ci; } i += c; } } } static inline int next_power_of_two(uint32_t v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v + (v == 0); } void MeshWelder::prepare(abcV3 * points, int count) { m_points = points; m_count = count; m_hash_size = next_power_of_two(m_count); m_hash_table.resize_discard(m_hash_size + m_count); memset(m_hash_table.data(), NIL, m_hash_size * sizeof(int)); m_remap.resize_discard(m_count); } const RawVector<int>& MeshWelder::getRemapTable() const { return m_remap; } void MeshRefiner::triangulate(bool swap_faces, bool turn_quads) { auto& dst = new_indices_triangulated; dst.resize(num_new_indices); const int i1 = swap_faces ? 2 : 1; const int i2 = swap_faces ? 1 : 2; size_t num_faces = counts.size(); int n = 0; int i = 0; if (turn_quads) { for (size_t fi = 0; fi < num_faces; ++fi) { int count = counts[fi]; if (count == 4) { int quad[4] = { new_indices[n + 3], new_indices[n + 0], new_indices[n + 1], new_indices[n + 2], }; for (int ni = 0; ni < count - 2; ++ni) { dst[i + 0] = quad[0]; dst[i + 1] = quad[ni + i1]; dst[i + 2] = quad[ni + i2]; i += 3; } n += count; } else { for (int ni = 0; ni < count - 2; ++ni) { dst[i + 0] = new_indices[n + 0]; dst[i + 1] = new_indices[n + ni + i1]; dst[i + 2] = new_indices[n + ni + i2]; i += 3; } n += count; } } } else { for (size_t fi = 0; fi < num_faces; ++fi) { int count = counts[fi]; for (int ni = 0; ni < count - 2; ++ni) { dst[i + 0] = new_indices[n + 0]; dst[i + 1] = new_indices[n + ni + i1]; dst[i + 2] = new_indices[n + ni + i2]; i += 3; } n += count; } } } void MeshRefiner::genSubmeshes(IArray<int> material_ids) { submeshes.clear(); new_indices_submeshes.resize(new_indices_triangulated.size()); const int *indices_read = new_indices_triangulated.data(); int *indices_write = new_indices_submeshes.data(); int num_splits = (int)splits.size(); int offset_faces = 0; RawVector<Submesh> tmp_submeshes; for (int spi = 0; spi < num_splits; ++spi) { auto& split = splits[spi]; int offset_vertices = split.vertex_offset; // count triangle indices for (int fi = 0; fi < split.face_count; ++fi) { int mid = material_ids[offset_faces + fi] + 1; // -1 == no material. adjust to zero based while (mid >= (int)tmp_submeshes.size()) { int id = (int)tmp_submeshes.size(); tmp_submeshes.push_back({}); tmp_submeshes.back().material_id = id - 1; } tmp_submeshes[mid].index_count += (counts[fi] - 2) * 3; } for (int mi = 0; mi < (int)tmp_submeshes.size(); ++mi) { auto& sm = tmp_submeshes[mi]; sm.indices_write = indices_write; sm.index_offset = (int)std::distance(new_indices_submeshes.data(), indices_write); indices_write += sm.index_count; } // copy indices for (int fi = 0; fi < split.face_count; ++fi) { int mid = material_ids[offset_faces + fi] + 1; int count = counts[offset_faces + fi]; int nidx = (count - 2) * 3; for (int i = 0; i < nidx; ++i) { *(tmp_submeshes[mid].indices_write++) = *(indices_read++) - offset_vertices; } } for (int mi = 0; mi < (int)tmp_submeshes.size(); ++mi) { auto& sm = tmp_submeshes[mi]; if (sm.index_count > 0) { ++split.submesh_count; submeshes.push_back(sm); } } offset_faces += split.face_count; tmp_submeshes.clear(); } setupSubmeshes(); } void MeshRefiner::genSubmeshes() { submeshes.clear(); new_indices_submeshes.resize(new_indices_triangulated.size()); const int *indices_read = new_indices_triangulated.data(); int *indices_write = new_indices_submeshes.data(); int num_splits = (int)splits.size(); for (int spi = 0; spi < num_splits; ++spi) { auto& split = splits[spi]; int offset_vertices = split.vertex_offset; Submesh sm; sm.index_count = split.triangulated_index_count; sm.index_offset = (int)std::distance(new_indices_submeshes.data(), indices_write); for (int ii = 0; ii < sm.index_count; ++ii) { *(indices_write++) = *(indices_read++) - offset_vertices; } ++split.submesh_count; submeshes.push_back(sm); } setupSubmeshes(); } void MeshRefiner::setupSubmeshes() { int num_splits = (int)splits.size(); int total_submeshes = 0; for (int spi = 0; spi < num_splits; ++spi) { auto& split = splits[spi]; split.submesh_offset = total_submeshes; total_submeshes += split.submesh_count; for (int smi = 0; smi < split.submesh_count; ++smi) { auto& sm = submeshes[smi + split.submesh_offset]; sm.split_index = spi; sm.submesh_index = smi; } } } void MeshRefiner::clear() { split_unit = 0; counts.reset(); indices.reset(); points.reset(); for (auto& attr : attributes) { attr->clear(); // attributes are placement new-ed, so need to call destructor manually attr->~IAttribute(); } attributes.clear(); old2new_indices.clear(); new2old_points.clear(); new_indices.clear(); new_indices_triangulated.clear(); new_indices_submeshes.clear(); new_points.clear(); splits.clear(); submeshes.clear(); num_new_indices = 0; } void MeshRefiner::refine() { if (connection.v2f_counts.size() != points.size()) { connection.buildConnection(indices, counts, points); } int num_indices = (int)indices.size(); new_points.reserve(num_indices); new_indices.reserve(num_indices); for (auto& attr : attributes) { attr->prepare((int)points.size(), (int)indices.size()); } old2new_indices.resize(num_indices, -1); int num_faces_total = (int)counts.size(); int offset_faces = 0; int offset_indices = 0; int offset_vertices = 0; int num_faces = 0; int num_indices_triangulated = 0; auto add_new_split = [&]() { auto split = Split{}; split.face_offset = offset_faces; split.index_offset = offset_indices; split.vertex_offset = offset_vertices; split.face_count = num_faces; split.triangulated_index_count = num_indices_triangulated; split.vertex_count = (int)new_points.size() - offset_vertices; split.index_count = (int)new_indices.size() - offset_indices; splits.push_back(split); offset_faces += split.face_count; offset_indices += split.index_count; offset_vertices += split.vertex_count; num_new_indices += num_indices_triangulated; num_faces = 0; num_indices_triangulated = 0; }; auto compare_all_attributes = [&](int ni, int ii) -> bool { for (auto& attr : attributes) if (!attr->compare(ni, ii)) { return false; } return true; }; auto find_or_emit_vertex = [&](int vi, int ii) -> int { int offset = connection.v2f_offsets[vi]; int connection_count = connection.v2f_counts[vi]; for (int ci = 0; ci < connection_count; ++ci) { int& ni = old2new_indices[connection.v2f_indices[offset + ci]]; if (ni != -1 && compare_all_attributes(ni, ii)) { return ni; } else if (ni == -1) { ni = (int)new_points.size(); new_points.push_back(points[vi]); new2old_points.push_back(vi); for (auto& attr : attributes) { attr->emit(ii); } return ni; } } return 0; }; int offset = 0; for (int fi = 0; fi < num_faces_total; ++fi) { int count = counts[fi]; if (split_unit > 0 && (int)new_points.size() - offset_vertices + count > split_unit) { add_new_split(); // clear vertex cache memset(old2new_indices.data(), -1, old2new_indices.size() * sizeof(int)); } for (int ci = 0; ci < count; ++ci) { int ii = offset + ci; int vi = indices[ii]; new_indices.push_back(find_or_emit_vertex(vi, ii)); } ++num_faces; num_indices_triangulated += (count - 2) * 3; offset += count; } add_new_split(); } <commit_msg>fix a bug in MeshRefiner #58<commit_after>#include "pch.h" #include "aiMeshOps.h" namespace impl { template<class Indices, class Counts> inline void BuildConnection( MeshConnectionInfo& connection, const Indices& indices, const Counts& counts, const IArray<float3>& vertices) { size_t num_points = vertices.size(); size_t num_faces = counts.size(); size_t num_indices = indices.size(); connection.v2f_offsets.resize_discard(num_points); connection.v2f_faces.resize_discard(num_indices); connection.v2f_indices.resize_discard(num_indices); connection.v2f_counts.resize_zeroclear(num_points); { int ii = 0; for (size_t fi = 0; fi < num_faces; ++fi) { int c = counts[fi]; for (int ci = 0; ci < c; ++ci) { connection.v2f_counts[indices[ii + ci]]++; } ii += c; } int offset = 0; for (size_t i = 0; i < num_points; ++i) { connection.v2f_offsets[i] = offset; offset += connection.v2f_counts[i]; } } connection.v2f_counts.zeroclear(); { int i = 0; for (int fi = 0; fi < (int)num_faces; ++fi) { int c = counts[fi]; for (int ci = 0; ci < c; ++ci) { int vi = indices[i + ci]; int ti = connection.v2f_offsets[vi] + connection.v2f_counts[vi]++; connection.v2f_faces[ti] = fi; connection.v2f_indices[ti] = i + ci; } i += c; } } } } void MeshConnectionInfo::clear() { v2f_counts.clear(); v2f_offsets.clear(); v2f_faces.clear(); v2f_indices.clear(); weld_map.clear(); weld_counts.clear(); weld_offsets.clear(); weld_indices.clear(); } void MeshConnectionInfo::buildConnection( const IArray<int>& indices, const IArray<int>& counts, const IArray<float3>& vertices) { size_t num_points = vertices.size(); size_t num_faces = counts.size(); size_t num_indices = indices.size(); v2f_offsets.resize_discard(num_points); v2f_faces.resize_discard(num_indices); v2f_indices.resize_discard(num_indices); v2f_counts.resize_zeroclear(num_points); { int ii = 0; for (size_t fi = 0; fi < num_faces; ++fi) { int c = counts[fi]; for (int ci = 0; ci < c; ++ci) { v2f_counts[indices[ii + ci]]++; } ii += c; } int offset = 0; for (size_t i = 0; i < num_points; ++i) { v2f_offsets[i] = offset; offset += v2f_counts[i]; } } v2f_counts.zeroclear(); { int i = 0; for (int fi = 0; fi < (int)num_faces; ++fi) { int c = counts[fi]; for (int ci = 0; ci < c; ++ci) { int vi = indices[i + ci]; int ti = v2f_offsets[vi] + v2f_counts[vi]++; v2f_faces[ti] = fi; v2f_indices[ti] = i + ci; } i += c; } } } static inline int next_power_of_two(uint32_t v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v + (v == 0); } void MeshWelder::prepare(abcV3 * points, int count) { m_points = points; m_count = count; m_hash_size = next_power_of_two(m_count); m_hash_table.resize_discard(m_hash_size + m_count); memset(m_hash_table.data(), NIL, m_hash_size * sizeof(int)); m_remap.resize_discard(m_count); } const RawVector<int>& MeshWelder::getRemapTable() const { return m_remap; } void MeshRefiner::triangulate(bool swap_faces, bool turn_quads) { auto& dst = new_indices_triangulated; dst.resize(num_new_indices); const int i1 = swap_faces ? 2 : 1; const int i2 = swap_faces ? 1 : 2; size_t num_faces = counts.size(); int n = 0; int i = 0; if (turn_quads) { for (size_t fi = 0; fi < num_faces; ++fi) { int count = counts[fi]; if (count == 4) { int quad[4] = { new_indices[n + 3], new_indices[n + 0], new_indices[n + 1], new_indices[n + 2], }; for (int ni = 0; ni < count - 2; ++ni) { dst[i + 0] = quad[0]; dst[i + 1] = quad[ni + i1]; dst[i + 2] = quad[ni + i2]; i += 3; } n += count; } else { for (int ni = 0; ni < count - 2; ++ni) { dst[i + 0] = new_indices[n + 0]; dst[i + 1] = new_indices[n + ni + i1]; dst[i + 2] = new_indices[n + ni + i2]; i += 3; } n += count; } } } else { for (size_t fi = 0; fi < num_faces; ++fi) { int count = counts[fi]; for (int ni = 0; ni < count - 2; ++ni) { dst[i + 0] = new_indices[n + 0]; dst[i + 1] = new_indices[n + ni + i1]; dst[i + 2] = new_indices[n + ni + i2]; i += 3; } n += count; } } } void MeshRefiner::genSubmeshes(IArray<int> material_ids) { submeshes.clear(); new_indices_submeshes.resize(new_indices_triangulated.size()); const int *indices_read = new_indices_triangulated.data(); int *indices_write = new_indices_submeshes.data(); int num_splits = (int)splits.size(); int offset_faces = 0; RawVector<Submesh> tmp_submeshes; for (int spi = 0; spi < num_splits; ++spi) { auto& split = splits[spi]; int offset_vertices = split.vertex_offset; // count triangle indices for (int fi = 0; fi < split.face_count; ++fi) { int mid = material_ids[offset_faces + fi] + 1; // -1 == no material. adjust to zero based while (mid >= (int)tmp_submeshes.size()) { int id = (int)tmp_submeshes.size(); tmp_submeshes.push_back({}); tmp_submeshes.back().material_id = id - 1; } tmp_submeshes[mid].index_count += (counts[fi] - 2) * 3; } for (int mi = 0; mi < (int)tmp_submeshes.size(); ++mi) { auto& sm = tmp_submeshes[mi]; sm.indices_write = indices_write; sm.index_offset = (int)std::distance(new_indices_submeshes.data(), indices_write); indices_write += sm.index_count; } // copy indices for (int fi = 0; fi < split.face_count; ++fi) { int mid = material_ids[offset_faces + fi] + 1; int count = counts[offset_faces + fi]; int nidx = (count - 2) * 3; for (int i = 0; i < nidx; ++i) { *(tmp_submeshes[mid].indices_write++) = *(indices_read++) - offset_vertices; } } for (int mi = 0; mi < (int)tmp_submeshes.size(); ++mi) { auto& sm = tmp_submeshes[mi]; if (sm.index_count > 0) { ++split.submesh_count; submeshes.push_back(sm); } } offset_faces += split.face_count; tmp_submeshes.clear(); } setupSubmeshes(); } void MeshRefiner::genSubmeshes() { submeshes.clear(); new_indices_submeshes.resize(new_indices_triangulated.size()); const int *indices_read = new_indices_triangulated.data(); int *indices_write = new_indices_submeshes.data(); int num_splits = (int)splits.size(); for (int spi = 0; spi < num_splits; ++spi) { auto& split = splits[spi]; int offset_vertices = split.vertex_offset; Submesh sm; sm.index_count = split.triangulated_index_count; sm.index_offset = (int)std::distance(new_indices_submeshes.data(), indices_write); for (int ii = 0; ii < sm.index_count; ++ii) { *(indices_write++) = *(indices_read++) - offset_vertices; } ++split.submesh_count; submeshes.push_back(sm); } setupSubmeshes(); } void MeshRefiner::setupSubmeshes() { int num_splits = (int)splits.size(); int total_submeshes = 0; for (int spi = 0; spi < num_splits; ++spi) { auto& split = splits[spi]; split.submesh_offset = total_submeshes; total_submeshes += split.submesh_count; for (int smi = 0; smi < split.submesh_count; ++smi) { auto& sm = submeshes[smi + split.submesh_offset]; sm.split_index = spi; sm.submesh_index = smi; } } } void MeshRefiner::clear() { split_unit = 0; counts.reset(); indices.reset(); points.reset(); for (auto& attr : attributes) { attr->clear(); // attributes are placement new-ed, so need to call destructor manually attr->~IAttribute(); } attributes.clear(); old2new_indices.clear(); new2old_points.clear(); new_indices.clear(); new_indices_triangulated.clear(); new_indices_submeshes.clear(); new_points.clear(); splits.clear(); submeshes.clear(); num_new_indices = 0; } void MeshRefiner::refine() { if (connection.v2f_counts.size() != points.size()) { connection.buildConnection(indices, counts, points); } int num_indices = (int)indices.size(); new_points.reserve(num_indices); new_indices.reserve(num_indices); for (auto& attr : attributes) { attr->prepare((int)points.size(), (int)indices.size()); } old2new_indices.resize(num_indices, -1); int num_faces_total = (int)counts.size(); int offset_faces = 0; int offset_indices = 0; int offset_vertices = 0; int num_faces = 0; int num_indices_triangulated = 0; auto add_new_split = [&]() { auto split = Split{}; split.face_offset = offset_faces; split.index_offset = offset_indices; split.vertex_offset = offset_vertices; split.face_count = num_faces; split.triangulated_index_count = num_indices_triangulated; split.vertex_count = (int)new_points.size() - offset_vertices; split.index_count = (int)new_indices.size() - offset_indices; splits.push_back(split); offset_faces += split.face_count; offset_indices += split.index_count; offset_vertices += split.vertex_count; num_new_indices += num_indices_triangulated; num_faces = 0; num_indices_triangulated = 0; }; auto compare_all_attributes = [&](int ni, int ii) -> bool { for (auto& attr : attributes) if (!attr->compare(ni, ii)) { return false; } return true; }; auto find_or_emit_vertex = [&](int vi, int ii) -> int { int offset = connection.v2f_offsets[vi]; int connection_count = connection.v2f_counts[vi]; for (int ci = 0; ci < connection_count; ++ci) { int& ni = old2new_indices[connection.v2f_indices[offset + ci]]; if (ni != -1 && compare_all_attributes(ni, ii)) { return ni; } else { ni = (int)new_points.size(); new_points.push_back(points[vi]); new2old_points.push_back(vi); for (auto& attr : attributes) { attr->emit(ii); } return ni; } } return 0; }; int offset = 0; for (int fi = 0; fi < num_faces_total; ++fi) { int count = counts[fi]; if (split_unit > 0 && (int)new_points.size() - offset_vertices + count > split_unit) { add_new_split(); // clear vertex cache memset(old2new_indices.data(), -1, old2new_indices.size() * sizeof(int)); } for (int ci = 0; ci < count; ++ci) { int ii = offset + ci; int vi = indices[ii]; new_indices.push_back(find_or_emit_vertex(vi, ii)); } ++num_faces; num_indices_triangulated += (count - 2) * 3; offset += count; } add_new_split(); } <|endoftext|>
<commit_before>/*************************************************************************/ /* audio_driver_ao.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* 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 "audio_driver_ao.h" #include "globals.h" #include "os/os.h" Error AudioDriverAO::init() { active = false; thread_exited = false; exit_thread = false; pcm_open = false; samples_in = NULL; mix_rate = 44100; output_format = OUTPUT_STEREO; channels = 2; ao_sample_format format; format.bits = 16; format.rate = mix_rate; format.channels = channels; format.byte_format = AO_FMT_LITTLE; format.matrix = "L,R"; device = ao_open_live(ao_default_driver_id(), &format, NULL); ERR_FAIL_COND_V(device == NULL, ERR_CANT_OPEN); int latency = GLOBAL_DEF("audio/output_latency", 25); buffer_size = nearest_power_of_2( latency * mix_rate / 1000 ); samples_in = memnew_arr(int32_t, buffer_size * channels); mutex = Mutex::create(); thread = Thread::create(AudioDriverAO::thread_func, this); return OK; }; void AudioDriverAO::thread_func(void* p_udata) { AudioDriverAO* ad = (AudioDriverAO*)p_udata; int16_t* samples_out = ad->samples_in; // Overwrite samples on conversion unsigned int n_samples = ad->buffer_size * ad->channels; unsigned int n_bytes = n_samples * sizeof(int16_t); while (!ad->exit_thread) { if (ad->active) { ad->lock(); ad->audio_server_process(ad->buffer_size, ad->samples_in); ad->unlock(); for (unsigned int i = 0; i < n_samples; i++) { samples_out[i] = ad->samples_in[i] >> 16; } } else { memset(samples_out, 0, n_bytes); } if (ad->exit_thread) break; if (!ao_play(ad->device, reinterpret_cast<char*>(samples_out), n_bytes)) { ERR_PRINT("ao_play() failed"); } }; ad->thread_exited = true; }; void AudioDriverAO::start() { active = true; }; int AudioDriverAO::get_mix_rate() const { return mix_rate; }; AudioDriverSW::OutputFormat AudioDriverAO::get_output_format() const { return output_format; }; void AudioDriverAO::lock() { if (!thread || !mutex) return; mutex->lock(); }; void AudioDriverAO::unlock() { if (!thread || !mutex) return; mutex->unlock(); }; void AudioDriverAO::finish() { if (!thread) return; exit_thread = true; Thread::wait_to_finish(thread); if (samples_in) { memdelete_arr(samples_in); }; memdelete(thread); if (mutex) memdelete(mutex); if (device) ao_close(device); thread = NULL; }; AudioDriverAO::AudioDriverAO() { mutex = NULL; thread = NULL; ao_initialize(); }; AudioDriverAO::~AudioDriverAO() { ao_shutdown(); }; <commit_msg>Cast samples_in to samples_out with reinterpret_cast<int16_t*><commit_after>/*************************************************************************/ /* audio_driver_ao.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* 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 "audio_driver_ao.h" #include "globals.h" #include "os/os.h" Error AudioDriverAO::init() { active = false; thread_exited = false; exit_thread = false; pcm_open = false; samples_in = NULL; mix_rate = 44100; output_format = OUTPUT_STEREO; channels = 2; ao_sample_format format; format.bits = 16; format.rate = mix_rate; format.channels = channels; format.byte_format = AO_FMT_LITTLE; format.matrix = "L,R"; device = ao_open_live(ao_default_driver_id(), &format, NULL); ERR_FAIL_COND_V(device == NULL, ERR_CANT_OPEN); int latency = GLOBAL_DEF("audio/output_latency", 25); buffer_size = nearest_power_of_2( latency * mix_rate / 1000 ); samples_in = memnew_arr(int32_t, buffer_size * channels); mutex = Mutex::create(); thread = Thread::create(AudioDriverAO::thread_func, this); return OK; }; void AudioDriverAO::thread_func(void* p_udata) { AudioDriverAO* ad = (AudioDriverAO*)p_udata; // Overwrite samples on conversion int16_t* samples_out = reinterpret_cast<int16_t*>(ad->samples_in); unsigned int n_samples = ad->buffer_size * ad->channels; unsigned int n_bytes = n_samples * sizeof(int16_t); while (!ad->exit_thread) { if (ad->active) { ad->lock(); ad->audio_server_process(ad->buffer_size, ad->samples_in); ad->unlock(); for (unsigned int i = 0; i < n_samples; i++) { samples_out[i] = ad->samples_in[i] >> 16; } } else { memset(samples_out, 0, n_bytes); } if (ad->exit_thread) break; if (!ao_play(ad->device, reinterpret_cast<char*>(samples_out), n_bytes)) { ERR_PRINT("ao_play() failed"); } }; ad->thread_exited = true; }; void AudioDriverAO::start() { active = true; }; int AudioDriverAO::get_mix_rate() const { return mix_rate; }; AudioDriverSW::OutputFormat AudioDriverAO::get_output_format() const { return output_format; }; void AudioDriverAO::lock() { if (!thread || !mutex) return; mutex->lock(); }; void AudioDriverAO::unlock() { if (!thread || !mutex) return; mutex->unlock(); }; void AudioDriverAO::finish() { if (!thread) return; exit_thread = true; Thread::wait_to_finish(thread); if (samples_in) { memdelete_arr(samples_in); }; memdelete(thread); if (mutex) memdelete(mutex); if (device) ao_close(device); thread = NULL; }; AudioDriverAO::AudioDriverAO() { mutex = NULL; thread = NULL; ao_initialize(); }; AudioDriverAO::~AudioDriverAO() { ao_shutdown(); }; <|endoftext|>
<commit_before>{ // //This macro produces the flowchart of TFormula::Analyze //Author: Rene Brun gROOT->Reset(); c1 = new TCanvas("c1","Analyze.mac",620,790); c1->Range(-1,0,19,30); TPaveLabel pl1(0,27,3.5,29,"Analyze"); pl1.SetFillColor(42); pl1.Draw(); TPaveText pt1(0,22.8,4,25.2); TText *t1=pt1.AddText("Parenthesis matching"); TText *t2=pt1.AddText("Remove unnecessary"); TText *t2a=pt1.AddText("parenthesis"); pt1.Draw(); TPaveText pt2(6,23,10,25); TText *t3=pt2.AddText("break of"); TText *t4=pt2.AddText("Analyze"); pt2.Draw(); TPaveText pt3(0,19,4,21); TText *t4=pt3.AddText("look for simple"); TText *t5=pt3.AddText("operators"); pt3.Draw(); TPaveText pt4(0,15,4,17); TText *t6=pt4.AddText("look for an already"); TText *t7=pt4.AddText("defined expression"); pt4.Draw(); TPaveText pt5(0,11,4,13); TText *t8=pt5.AddText("look for usual"); TText *t9=pt5.AddText("functions :cos sin .."); pt5.Draw(); TPaveText pt6(0,7,4,9); TText *t10=pt6.AddText("look for a"); TText *t11=pt6.AddText("numeric value"); pt6.Draw(); TPaveText pt7(6,18.5,10,21.5); TText *t12=pt7.AddText("Analyze left and"); TText *t13=pt7.AddText("right part of"); TText *t14=pt7.AddText("the expression"); pt7.Draw(); TPaveText pt8(6,15,10,17); TText *t15=pt8.AddText("Replace expression"); pt8.Draw(); TPaveText pt9(6,11,10,13); TText *t16=pt9.AddText("Analyze"); pt9.SetFillColor(42); pt9.Draw(); TPaveText pt10(6,7,10,9); TText *t17=pt10.AddText("Error"); TText *t18=pt10.AddText("Break of Analyze"); pt10.Draw(); TPaveText pt11(14,22,17,24); pt11.SetFillColor(42); TText *t19=pt11.AddText("Analyze"); TText *t19a=pt11.AddText("Left"); pt11.Draw(); TPaveText pt12(14,19,17,21); pt12.SetFillColor(42); TText *t20=pt12.AddText("Analyze"); TText *t20a=pt12.AddText("Right"); pt12.Draw(); TPaveText pt13(14,15,18,18); TText *t21=pt13.AddText("StackNumber++"); TText *t22=pt13.AddText("operator[StackNumber]"); TText *t23=pt13.AddText("= operator found"); pt13.Draw(); TPaveText pt14(12,10.8,17,13.2); TText *t24=pt14.AddText("StackNumber++"); TText *t25=pt14.AddText("operator[StackNumber]"); TText *t26=pt14.AddText("= function found"); pt14.Draw(); TPaveText pt15(6,7,10,9); TText *t27=pt15.AddText("Error"); TText *t28=pt15.AddText("break of Analyze"); pt15.Draw(); TPaveText pt16(0,2,7,5); TText *t29=pt16.AddText("StackNumber++"); TText *t30=pt16.AddText("operator[StackNumber] = 0"); TText *t31=pt16.AddText("value[StackNumber] = value found"); pt16.Draw(); TArrow ar(2,27,2,25.4,0.012,"|>"); ar.SetFillColor(1); ar.Draw(); ar.DrawArrow(2,22.8,2,21.2,0.012,"|>"); ar.DrawArrow(2,19,2,17.2,0.012,"|>"); ar.DrawArrow(2,15,2,13.2,0.012,"|>"); ar.DrawArrow(2,11,2, 9.2,0.012,"|>"); ar.DrawArrow(2, 7,2, 5.2,0.012,"|>"); ar.DrawArrow(4,24,6,24,0.012,"|>"); ar.DrawArrow(4,20,6,20,0.012,"|>"); ar.DrawArrow(4,16,6,16,0.012,"|>"); ar.DrawArrow(4,12,6,12,0.012,"|>"); ar.DrawArrow(4, 8,6, 8,0.012,"|>"); ar.DrawArrow(10,20,14,20,0.012,"|>"); ar.DrawArrow(12,23,14,23,0.012,"|>"); ar.DrawArrow(12,16.5,14,16.5,0.012,"|>"); ar.DrawArrow(10,12,12,12,0.012,"|>"); TText ta(2.2,22.2,"err = 0"); ta.SetTextFont(71); ta.SetTextSize(0.015); ta.SetTextColor(4); ta.SetTextAlign(12); ta.Draw(); ta.DrawText(2.2,18.2,"not found"); ta.DrawText(2.2,6.2,"found"); TText tb(4.2,24.1,"err != 0"); tb.SetTextFont(71); tb.SetTextSize(0.015); tb.SetTextColor(4); tb.SetTextAlign(11); tb.Draw(); tb.DrawText(4.2,20.1,"found"); tb.DrawText(4.2,16.1,"found"); tb.DrawText(4.2,12.1,"found"); tb.DrawText(4.2, 8.1,"not found"); TLine l1(12,16.5,12,23); l1.Draw(); } <commit_msg>Fix a redefinition.<commit_after>{ // //This macro produces the flowchart of TFormula::Analyze //Author: Rene Brun gROOT->Reset(); c1 = new TCanvas("c1","Analyze.mac",620,790); c1->Range(-1,0,19,30); TPaveLabel pl1(0,27,3.5,29,"Analyze"); pl1.SetFillColor(42); pl1.Draw(); TPaveText pt1(0,22.8,4,25.2); TText *t1=pt1.AddText("Parenthesis matching"); TText *t2=pt1.AddText("Remove unnecessary"); TText *t2a=pt1.AddText("parenthesis"); pt1.Draw(); TPaveText pt2(6,23,10,25); TText *t3=pt2.AddText("break of"); TText *t4=pt2.AddText("Analyze"); pt2.Draw(); TPaveText pt3(0,19,4,21); t4=pt3.AddText("look for simple"); TText *t5=pt3.AddText("operators"); pt3.Draw(); TPaveText pt4(0,15,4,17); TText *t6=pt4.AddText("look for an already"); TText *t7=pt4.AddText("defined expression"); pt4.Draw(); TPaveText pt5(0,11,4,13); TText *t8=pt5.AddText("look for usual"); TText *t9=pt5.AddText("functions :cos sin .."); pt5.Draw(); TPaveText pt6(0,7,4,9); TText *t10=pt6.AddText("look for a"); TText *t11=pt6.AddText("numeric value"); pt6.Draw(); TPaveText pt7(6,18.5,10,21.5); TText *t12=pt7.AddText("Analyze left and"); TText *t13=pt7.AddText("right part of"); TText *t14=pt7.AddText("the expression"); pt7.Draw(); TPaveText pt8(6,15,10,17); TText *t15=pt8.AddText("Replace expression"); pt8.Draw(); TPaveText pt9(6,11,10,13); TText *t16=pt9.AddText("Analyze"); pt9.SetFillColor(42); pt9.Draw(); TPaveText pt10(6,7,10,9); TText *t17=pt10.AddText("Error"); TText *t18=pt10.AddText("Break of Analyze"); pt10.Draw(); TPaveText pt11(14,22,17,24); pt11.SetFillColor(42); TText *t19=pt11.AddText("Analyze"); TText *t19a=pt11.AddText("Left"); pt11.Draw(); TPaveText pt12(14,19,17,21); pt12.SetFillColor(42); TText *t20=pt12.AddText("Analyze"); TText *t20a=pt12.AddText("Right"); pt12.Draw(); TPaveText pt13(14,15,18,18); TText *t21=pt13.AddText("StackNumber++"); TText *t22=pt13.AddText("operator[StackNumber]"); TText *t23=pt13.AddText("= operator found"); pt13.Draw(); TPaveText pt14(12,10.8,17,13.2); TText *t24=pt14.AddText("StackNumber++"); TText *t25=pt14.AddText("operator[StackNumber]"); TText *t26=pt14.AddText("= function found"); pt14.Draw(); TPaveText pt15(6,7,10,9); TText *t27=pt15.AddText("Error"); TText *t28=pt15.AddText("break of Analyze"); pt15.Draw(); TPaveText pt16(0,2,7,5); TText *t29=pt16.AddText("StackNumber++"); TText *t30=pt16.AddText("operator[StackNumber] = 0"); TText *t31=pt16.AddText("value[StackNumber] = value found"); pt16.Draw(); TArrow ar(2,27,2,25.4,0.012,"|>"); ar.SetFillColor(1); ar.Draw(); ar.DrawArrow(2,22.8,2,21.2,0.012,"|>"); ar.DrawArrow(2,19,2,17.2,0.012,"|>"); ar.DrawArrow(2,15,2,13.2,0.012,"|>"); ar.DrawArrow(2,11,2, 9.2,0.012,"|>"); ar.DrawArrow(2, 7,2, 5.2,0.012,"|>"); ar.DrawArrow(4,24,6,24,0.012,"|>"); ar.DrawArrow(4,20,6,20,0.012,"|>"); ar.DrawArrow(4,16,6,16,0.012,"|>"); ar.DrawArrow(4,12,6,12,0.012,"|>"); ar.DrawArrow(4, 8,6, 8,0.012,"|>"); ar.DrawArrow(10,20,14,20,0.012,"|>"); ar.DrawArrow(12,23,14,23,0.012,"|>"); ar.DrawArrow(12,16.5,14,16.5,0.012,"|>"); ar.DrawArrow(10,12,12,12,0.012,"|>"); TText ta(2.2,22.2,"err = 0"); ta.SetTextFont(71); ta.SetTextSize(0.015); ta.SetTextColor(4); ta.SetTextAlign(12); ta.Draw(); ta.DrawText(2.2,18.2,"not found"); ta.DrawText(2.2,6.2,"found"); TText tb(4.2,24.1,"err != 0"); tb.SetTextFont(71); tb.SetTextSize(0.015); tb.SetTextColor(4); tb.SetTextAlign(11); tb.Draw(); tb.DrawText(4.2,20.1,"found"); tb.DrawText(4.2,16.1,"found"); tb.DrawText(4.2,12.1,"found"); tb.DrawText(4.2, 8.1,"not found"); TLine l1(12,16.5,12,23); l1.Draw(); } <|endoftext|>
<commit_before>/// \file /// \ingroup tutorial_math /// Demo for quantiles (with highlight mode) /// /// \macro_image /// \macro_code /// /// \authors Rene Brun, Eddy Offermann TList *lq = 0; TGraph *gr = 0; void hlquantiles() { const Int_t nq = 100; const Int_t nshots = 10; Double_t xq[nq]; // position where to compute the quantiles in [0,1] Double_t yq[nq]; // array to contain the quantiles for (Int_t i=0;i<nq;i++) xq[i] = Float_t(i+1)/nq; TGraph *gr70 = new TGraph(nshots); TGraph *gr90 = new TGraph(nshots); TGraph *gr98 = new TGraph(nshots); TGraph *grq[nq]; for (Int_t ig = 0; ig < nq; ig++) grq[ig] = new TGraph(nshots); TH1F *h = new TH1F("h","demo quantiles",50,-3,3); for (Int_t shot=0;shot<nshots;shot++) { h->FillRandom("gaus",50); h->GetQuantiles(nq,yq,xq); gr70->SetPoint(shot,shot+1,yq[70]); gr90->SetPoint(shot,shot+1,yq[90]); gr98->SetPoint(shot,shot+1,yq[98]); for (Int_t ig = 0; ig < nq; ig++) grq[ig]->SetPoint(shot,shot+1,yq[ig]); } //show the original histogram in the top pad TCanvas *c1 = new TCanvas("c1","demo quantiles",10,10,600,900); c1->SetFillColor(41); c1->Divide(1,3); c1->cd(1); h->SetFillColor(38); h->Draw(); // show the final quantiles in the middle pad c1->cd(2); gPad->SetFrameFillColor(33); gPad->SetGrid(); gr = new TGraph(nq,xq,yq); gr->SetTitle("final quantiles"); gr->SetMarkerStyle(21); gr->SetMarkerColor(kRed); gr->SetMarkerSize(0.3); gr->Draw("ap"); // prepare quantiles lq = new TList(); for (Int_t ig = 0; ig < nq; ig++) { grq[ig]->SetMinimum(gr->GetYaxis()->GetXmin()); grq[ig]->SetMaximum(gr->GetYaxis()->GetXmax()); grq[ig]->SetMarkerStyle(23); grq[ig]->SetMarkerColor(ig%100); grq[ig]->SetTitle(TString::Format("q%02d", ig)); lq->Add(grq[ig]); } TText *info = new TText(0.1, 2.4, "please move the mouse over the graph"); info->SetTextSize(0.08); info->SetTextColor(gr->GetMarkerColor()); info->SetBit(kCannotPick); info->Draw(); gr->SetHighlight(); c1->HighlightConnect("HighlightQuantile(TVirtualPad*,TObject*,Int_t,Int_t)"); // show the evolution of some quantiles in the bottom pad c1->cd(3); gPad->SetFrameFillColor(17); gPad->DrawFrame(0,0,nshots+1,3.2); gPad->SetGrid(); gr98->SetMarkerStyle(22); gr98->SetMarkerColor(kRed); gr98->Draw("lp"); gr90->SetMarkerStyle(21); gr90->SetMarkerColor(kBlue); gr90->Draw("lp"); gr70->SetMarkerStyle(20); gr70->SetMarkerColor(kMagenta); gr70->Draw("lp"); // add a legend TLegend *legend = new TLegend(0.85,0.74,0.95,0.95); legend->SetTextFont(72); legend->SetTextSize(0.05); legend->AddEntry(gr98," q98","lp"); legend->AddEntry(gr90," q90","lp"); legend->AddEntry(gr70," q70","lp"); legend->Draw(); } void HighlightQuantile(TVirtualPad *pad, TObject *obj, Int_t ihp, Int_t y) { // show the evolution of all quantiles in the bottom pad if (obj != gr) return; if (ihp == -1) return; TVirtualPad *savepad = gPad; pad->GetCanvas()->cd(3); lq->At(ihp)->Draw("alp"); gPad->Update(); savepad->cd(); } <commit_msg>Change authors<commit_after>/// \file /// \ingroup tutorial_math /// Demo for quantiles (with highlight mode) /// /// \macro_image /// \macro_code /// /// \authors Rene Brun, Eddy Offermann, Jan Musinsky TList *lq = 0; TGraph *gr = 0; void hlquantiles() { const Int_t nq = 100; const Int_t nshots = 10; Double_t xq[nq]; // position where to compute the quantiles in [0,1] Double_t yq[nq]; // array to contain the quantiles for (Int_t i=0;i<nq;i++) xq[i] = Float_t(i+1)/nq; TGraph *gr70 = new TGraph(nshots); TGraph *gr90 = new TGraph(nshots); TGraph *gr98 = new TGraph(nshots); TGraph *grq[nq]; for (Int_t ig = 0; ig < nq; ig++) grq[ig] = new TGraph(nshots); TH1F *h = new TH1F("h","demo quantiles",50,-3,3); for (Int_t shot=0;shot<nshots;shot++) { h->FillRandom("gaus",50); h->GetQuantiles(nq,yq,xq); gr70->SetPoint(shot,shot+1,yq[70]); gr90->SetPoint(shot,shot+1,yq[90]); gr98->SetPoint(shot,shot+1,yq[98]); for (Int_t ig = 0; ig < nq; ig++) grq[ig]->SetPoint(shot,shot+1,yq[ig]); } //show the original histogram in the top pad TCanvas *c1 = new TCanvas("c1","demo quantiles",10,10,600,900); c1->SetFillColor(41); c1->Divide(1,3); c1->cd(1); h->SetFillColor(38); h->Draw(); // show the final quantiles in the middle pad c1->cd(2); gPad->SetFrameFillColor(33); gPad->SetGrid(); gr = new TGraph(nq,xq,yq); gr->SetTitle("final quantiles"); gr->SetMarkerStyle(21); gr->SetMarkerColor(kRed); gr->SetMarkerSize(0.3); gr->Draw("ap"); // prepare quantiles lq = new TList(); for (Int_t ig = 0; ig < nq; ig++) { grq[ig]->SetMinimum(gr->GetYaxis()->GetXmin()); grq[ig]->SetMaximum(gr->GetYaxis()->GetXmax()); grq[ig]->SetMarkerStyle(23); grq[ig]->SetMarkerColor(ig%100); grq[ig]->SetTitle(TString::Format("q%02d", ig)); lq->Add(grq[ig]); } TText *info = new TText(0.1, 2.4, "please move the mouse over the graph"); info->SetTextSize(0.08); info->SetTextColor(gr->GetMarkerColor()); info->SetBit(kCannotPick); info->Draw(); gr->SetHighlight(); c1->HighlightConnect("HighlightQuantile(TVirtualPad*,TObject*,Int_t,Int_t)"); // show the evolution of some quantiles in the bottom pad c1->cd(3); gPad->SetFrameFillColor(17); gPad->DrawFrame(0,0,nshots+1,3.2); gPad->SetGrid(); gr98->SetMarkerStyle(22); gr98->SetMarkerColor(kRed); gr98->Draw("lp"); gr90->SetMarkerStyle(21); gr90->SetMarkerColor(kBlue); gr90->Draw("lp"); gr70->SetMarkerStyle(20); gr70->SetMarkerColor(kMagenta); gr70->Draw("lp"); // add a legend TLegend *legend = new TLegend(0.85,0.74,0.95,0.95); legend->SetTextFont(72); legend->SetTextSize(0.05); legend->AddEntry(gr98," q98","lp"); legend->AddEntry(gr90," q90","lp"); legend->AddEntry(gr70," q70","lp"); legend->Draw(); } void HighlightQuantile(TVirtualPad *pad, TObject *obj, Int_t ihp, Int_t y) { // show the evolution of all quantiles in the bottom pad if (obj != gr) return; if (ihp == -1) return; TVirtualPad *savepad = gPad; pad->GetCanvas()->cd(3); lq->At(ihp)->Draw("alp"); gPad->Update(); savepad->cd(); } <|endoftext|>
<commit_before>#include "updaterbody.hpp" #include "usbshell.hpp" using namespace Updater; using namespace UpdaterAPI; UpdaterBody *GetBody(bool flag, UPDATER_ACTION_MODE mode, firmware_information_t::information *info) { return new UpdaterBodyImpl; } void ReleaseBody(UpdaterBody *body) { delete body; } bool UpdaterBodyImpl::Execute(RingBuffer *buffer, CallbackInterface *interface) { usbshell_loop(); return true; } <commit_msg>UpdaterBody: Catch exceptions<commit_after>#include "updaterbody.hpp" #include "usbshell.hpp" using namespace Updater; using namespace UpdaterAPI; UpdaterBody *GetBody(bool flag, UPDATER_ACTION_MODE mode, firmware_information_t::information *info) { return new UpdaterBodyImpl; } void ReleaseBody(UpdaterBody *body) { delete body; } bool UpdaterBodyImpl::Execute(RingBuffer *buffer, CallbackInterface *interface) { try { usbshell_loop(); } catch (...) { // ignore } return true; } <|endoftext|>
<commit_before>#include <fstream> #include <cstring> #include <iostream> #include <vector> #include <unordered_map> #include <algorithm> #include "detectJumps.h" #include "utils.h" using namespace std; uint64_t transformRegionInReadToHash(regionInRead region){ hash<int> regionHash; return regionHash(region.read + region.firstWindow + region.lastWindow); } void detectJumps(const vector<pairOfIndexWindow>& vec, uint indexReadT, uint indexReadQ, unordered_map <regionInRead, vector<regionInRead>>& correspondance){ uint indexT(0); uint indexQ(0); for (uint i(0); i<vec.size(); ++i){ //~ cout << vec[i].target << " " << vec[i].query << endl; regionInRead regionTarget({indexT, vec[i].target, indexReadT}); if (i != vec.size()-1 and absolute(int(vec[i].target)-int(vec[i+1].target))>2){ cout << "jump" << endl; //~ if (correspondance.count(regionTarget)){ //~ correspondance[regionTarget].push_back({indexQ, vec[i].query, indexReadQ}); //~ } else { //~ regionInRead r({indexQ, vec[i].query, indexReadQ}); //~ vector <regionInRead> v; //~ v.push_back(r); //~ correspondance[regionTarget] = v; //~ } //~ cout << "jump in target" << indexT << "to" << vec[i+1].target << endl; indexT = vec[i+1].target; indexQ = vec[i+1].query; } else if (i != vec.size()-1 and absolute(int(vec[i].query)-int(vec[i+1].query))>2){ cout << "jump" << endl; //~ if (correspondance.count(regionTarget)){ //~ correspondance[regionTarget].push_back({indexQ, vec[i].query, indexReadQ}); //~ } else { //~ regionInRead r({indexQ, vec[i].query, indexReadQ}); //~ vector <regionInRead> v; //~ v.push_back(r); //~ correspondance[regionTarget] = v; //~ } //~ cout << "jump in query" << indexQ << "to" << vec[i+1].query << endl; indexT = vec[i+1].target; indexQ = vec[i+1].query; } } if (indexT==0){ cout << "no jump" << endl; //~ regionInRead regionTarget({vec[0].target, vec.back().target, indexReadT}); //~ if (correspondance.count(regionTarget)){ //~ correspondance[regionTarget].push_back({vec[0].query, vec.back().query, indexReadQ}); //~ } else { //~ regionInRead r({vec[0].query, vec.back().query, indexReadQ}); //~ vector <regionInRead> v; //~ v.push_back(r); //~ correspondance[regionTarget] = v; //~ } } } <commit_msg>first simple jump detection<commit_after>#include <fstream> #include <cstring> #include <iostream> #include <vector> #include <unordered_map> #include <algorithm> #include "detectJumps.h" #include "utils.h" using namespace std; uint64_t transformRegionInReadToHash(regionInRead region){ hash<int> regionHash; return regionHash(region.read + region.firstWindow + region.lastWindow); } void detectJumps(const vector<pairOfIndexWindow>& vec, uint indexReadT, uint indexReadQ, unordered_map <regionInRead, vector<regionInRead>>& correspondance){ uint indexT(0); uint indexQ(0); for (uint i(0); i<vec.size(); ++i){ //~ cout << vec[i].target << " " << vec[i].query << endl; regionInRead regionTarget({indexT, vec[i].target, indexReadT}); if (i != vec.size()-1 and absolute(int(vec[i].target)-int(vec[i+1].target))>2){ //~ cout << "jump" << endl; //~ if (correspondance.count(regionTarget)){ //~ correspondance[regionTarget].push_back({indexQ, vec[i].query, indexReadQ}); //~ } else { //~ regionInRead r({indexQ, vec[i].query, indexReadQ}); //~ vector <regionInRead> v; //~ v.push_back(r); //~ correspondance[regionTarget] = v; //~ } cout << "jump in target" << indexT << "to" << vec[i+1].target << endl; indexT = vec[i+1].target; indexQ = vec[i+1].query; } else if (i != vec.size()-1 and absolute(int(vec[i].query)-int(vec[i+1].query))>2){ //~ cout << "jump" << endl; //~ if (correspondance.count(regionTarget)){ //~ correspondance[regionTarget].push_back({indexQ, vec[i].query, indexReadQ}); //~ } else { //~ regionInRead r({indexQ, vec[i].query, indexReadQ}); //~ vector <regionInRead> v; //~ v.push_back(r); //~ correspondance[regionTarget] = v; //~ } cout << "jump in query" << indexQ << "to" << vec[i+1].query << endl; indexT = vec[i+1].target; indexQ = vec[i+1].query; } } if (indexT==0){ cout << "no jump" << endl; //~ regionInRead regionTarget({vec[0].target, vec.back().target, indexReadT}); //~ if (correspondance.count(regionTarget)){ //~ correspondance[regionTarget].push_back({vec[0].query, vec.back().query, indexReadQ}); //~ } else { //~ regionInRead r({vec[0].query, vec.back().query, indexReadQ}); //~ vector <regionInRead> v; //~ v.push_back(r); //~ correspondance[regionTarget] = v; //~ } } } <|endoftext|>
<commit_before>#include "combat/combat.h" #include "random.h" #include "logconsole.h" #include "dataconsts.h" #include "entity_system.h" #include "srv_attack.h" #include "srv_damage.h" #include "srv_hp_reply.h" #include "components/basic_info.h" #include "components/destination.h" #include "components/life.h" #include "components/magic.h" #include "components/player_spawn.h" #include "components/position.h" #include "components/target.h" #include "components/damage.h" #include "components/skills.h" #include "components/stamina.h" #include "components/stats.h" #include <cmath> using namespace RoseCommon; using namespace RoseCommon::Packet; void Combat::hp_request(EntitySystem& entitySystem, Entity entity, const CliHpReq& packet) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); if (packet.get_targetId()) { Entity t = entitySystem.get_entity_from_id(packet.get_targetId()); if (t != entt::null) { const auto& life = entitySystem.get_component<Component::Life>(t); auto p = SrvHpReply::create(packet.get_targetId(), life.hp); entitySystem.send_to(entity, p); } } } std::pair<float, float> Combat::get_range_position(const EntitySystem& entitySystem, Entity character, Entity target, float range) { const auto& char_pos = entitySystem.get_component<Component::Position>(character); const auto& target_pos = entitySystem.get_component<Component::Position>(target); std::pair<float, float> vector{char_pos.x - target_pos.x, char_pos.y - target_pos.y}; const float length = sqrt(vector.first * vector.first + vector.second * vector.second); vector.first /= length; vector.second /= length; return {vector.first * range, vector.second * range}; } float Combat::get_range_to(const EntitySystem& entitySystem, Entity character, Entity target) { const auto& char_pos = entitySystem.get_component<Component::Position>(character); const auto& target_pos = entitySystem.get_component<Component::Position>(target); const float dx = char_pos.x - target_pos.x; const float dy = char_pos.y - target_pos.y; return std::sqrt(dx * dx + dy * dy); } void Combat::attack(EntitySystem& entitySystem, Entity entity, const CliAttack& packet) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("Combat::attack"); logger->trace("entity {}, target {}", entity, packet.get_targetId()); const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity); const auto& pos = entitySystem.get_component<Component::Position>(entity); const auto& stats = entitySystem.get_component<Component::Stats>(entity); if (packet.get_targetId()) { Entity t = entitySystem.get_entity_from_id(packet.get_targetId()); if (t != entt::null) { auto& target = entitySystem.add_or_replace_component<Component::Target>(entity); target.target = t; //TODO: Check distance to target, if not in attack range, move into max attack range if(get_range_to(entitySystem, entity, t) > 1) { auto& dest = entitySystem.add_or_replace_component<Component::Destination>(entity); auto npos = get_range_position(entitySystem, entity, t); dest.x = npos.first; dest.y = npos.second; dest.z = 0; const float dx = pos.x - dest.x; const float dy = pos.y - dest.y; dest.dist = std::sqrt(dx * dx + dy * dy); } // This packet acts as an attack and mouse_cmd all in one, we don't want the mouse_cmd portion // of it as it can cause some issues with attack animations going off before it should // auto p = SrvAttack::create(basicInfo.id, packet.get_targetId()); // p.set_x(dest.x); // p.set_y(dest.y); // p.set_distance(dest.dist); // entitySystem.send_nearby(entity, p); } } } void Combat::update(EntitySystem& entitySystem, Entity entity) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity); const auto& pos = entitySystem.get_component<Component::Position>(entity); auto& life = entitySystem.get_component<Component::Life>(entity); //TODO:: Update buffs //TODO:: Update HP if(entitySystem.has_component<Component::Damage>(entity) == true) { auto& queuedDamage = entitySystem.get_component<Component::Damage>(entity); int32_t adjusted_hp = life.hp; uint32_t total_applied_damage = 0; for(auto attack : queuedDamage.damage_) { if(attack.apply_) { // We waited at least one update before applying damage, apply it now //TODO:: Apply damage to this entity Entity attacker = entitySystem.get_entity_from_id(attack.attacker_); logger->debug("Applying damage to entity {} {}", basicInfo.name, basicInfo.id); if((adjusted_hp - attack.value_) <= 0) { logger->debug("Entity {} {} will die from {} damage", basicInfo.name, basicInfo.id, attack.value_); total_applied_damage = attack.value_ + adjusted_hp; adjusted_hp = 0; //TODO: Credit this attacker as the one who killed this entity. } else { total_applied_damage += attack.value_; adjusted_hp -= attack.value_; } if(adjusted_hp <= 0) { //TODO: Get dropped item data here and send it with the DAMAGE packet attack.action_ &= ~DAMAGE_ACTION_HIT; attack.action_ |= DAMAGE_ACTION_DEAD; auto p = SrvDamage::create(attack.attacker_, basicInfo.id, attack.value_ + 30000, attack.action_); entitySystem.send_nearby(entity, p); // remove components that we can't have if we are dead! entitySystem.remove_component<Component::Damage>(entity); entitySystem.remove_component<Component::Destination>(entity); entitySystem.remove_component<Component::Target>(entity); } else { logger->debug("applied {} damage to entity {} {}.", attack.value_, basicInfo.name, basicInfo.id); auto p = SrvDamage::create(attack.attacker_, basicInfo.id, attack.value_, attack.action_); entitySystem.send_to(entity, p); entitySystem.send_to(attacker, p); } // Reset the damage value to 0 for next pass attack.value_ = 0; } else { // Apply any new damage on next update attack.apply_ = true; } } } // Check to see if we have a target component if(entitySystem.has_component<Component::Target>(entity) == true) { auto& target = entitySystem.get_component<Component::Target>(entity); // Are we in attack range? //TODO:: Update apply damage to target } } RoseCommon::Entity Combat::get_closest_spawn(EntitySystem& entitySystem, RoseCommon::Entity player) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("Combat::get_closest_spawn start"); const auto& position = entitySystem.get_component<Component::Position>(player); RoseCommon::Entity closest = {}; float closestDist = 999999999999; for (RoseCommon::Entity entity : entitySystem.get_entities_with_components<Component::BasicInfo, Component::Position, Component::PlayerSpawn>()) { const auto& spawnPosition = entitySystem.get_component<Component::Position>(entity); if(spawnPosition.map != position.map) continue; float dx = spawnPosition.x - position.x; float dy = spawnPosition.y - position.y; float distance = std::sqrt(dx * dx + dy * dy); if(distance < closestDist) { closest = entity; closestDist = distance; } } logger->trace("Combat::get_closest_spawn end"); return closest; } RoseCommon::Entity Combat::get_saved_spawn(EntitySystem& entitySystem, RoseCommon::Entity player) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("Combat::get_saved_spawn start"); const auto& position = entitySystem.get_component<Component::Position>(player); for (RoseCommon::Entity entity : entitySystem.get_entities_with_components<Component::BasicInfo, Component::Position, Component::PlayerSpawn>()) { const auto& spawninfo = entitySystem.get_component<Component::PlayerSpawn>(entity); if(spawninfo.type == Component::PlayerSpawn::RESPAWN_POINT) { const auto& spawnPosition = entitySystem.get_component<Component::Position>(entity); if(spawnPosition.map == position.spawn) return entity; } } logger->trace("Combat::get_saved_spawn unable to find the saved spawn point"); return {}; } RoseCommon::Entity Combat::get_start_spawn(EntitySystem& entitySystem) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("Combat::get_start_spawn start"); for (RoseCommon::Entity entity : entitySystem.get_entities_with_components<Component::BasicInfo, Component::Position, Component::PlayerSpawn>()) { const auto& spawninfo = entitySystem.get_component<Component::PlayerSpawn>(entity); if(spawninfo.type == Component::PlayerSpawn::START_POINT) return entity; } return {}; } void Combat::revive(EntitySystem& entitySystem, Entity entity, const RoseCommon::Packet::CliReviveReq& packet) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("Combat::revive"); const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity); const auto& pos = entitySystem.get_component<Component::Position>(entity); auto& life = entitySystem.get_component<Component::Life>(entity); auto& magic = entitySystem.get_component<Component::Magic>(entity); uint16_t map_id = pos.map; float x = 0.f, y = 0.f; switch(packet.get_reviveType()) { case CliReviveReq::ReviveRequest::REVIVE_POSITION: { if (Entity e = get_closest_spawn(entitySystem, entity); e) { auto& dest = entitySystem.get_component<Component::Position>(e); x = dest.x + (Core::Random::getInstance().get_uniform(0, 1001) - 500); y = dest.y + (Core::Random::getInstance().get_uniform(0, 1001) - 500); } break; } case CliReviveReq::ReviveRequest::SAVE_POSITION: { if (Entity e = get_saved_spawn(entitySystem, entity); e) { auto& dest = entitySystem.get_component<Component::Position>(e); if(dest.map == 20 && basicInfo.job) { if (Entity e = get_closest_spawn(entitySystem, entity); e) { auto& dest = entitySystem.get_component<Component::Position>(e); x = dest.x + (Core::Random::getInstance().get_uniform(0, 1001) - 500); y = dest.y + (Core::Random::getInstance().get_uniform(0, 1001) - 500); } break; } if(pos.map != dest.map) { map_id = dest.map; } x = dest.x + (Core::Random::getInstance().get_uniform(0, 1001) - 500); y = dest.y + (Core::Random::getInstance().get_uniform(0, 1001) - 500); } break; } case CliReviveReq::ReviveRequest::START_POSITION: { if (Entity e = get_start_spawn(entitySystem); e) { auto& dest = entitySystem.get_component<Component::Position>(e); x = dest.x + (Core::Random::getInstance().get_uniform(0, 1001) - 500); y = dest.y + (Core::Random::getInstance().get_uniform(0, 1001) - 500); } break; } case CliReviveReq::ReviveRequest::CURRENT_POSITION: { x = pos.x; y = pos.y; break; } default: { logger->warn("Combat::revive player {} sent a revive type that doesn't exist...", basicInfo.name); break; } } life.hp = (life.maxHp * 0.3f); magic.mp = 0; entitySystem.teleport_entity(entity, x, y, map_id); }<commit_msg>Cleanup queued damage that has been applied already<commit_after>#include <algorithm> #include "combat/combat.h" #include "random.h" #include "logconsole.h" #include "dataconsts.h" #include "entity_system.h" #include "srv_attack.h" #include "srv_damage.h" #include "srv_hp_reply.h" #include "components/basic_info.h" #include "components/destination.h" #include "components/life.h" #include "components/magic.h" #include "components/player_spawn.h" #include "components/position.h" #include "components/target.h" #include "components/damage.h" #include "components/skills.h" #include "components/stamina.h" #include "components/stats.h" #include <cmath> using namespace RoseCommon; using namespace RoseCommon::Packet; void Combat::hp_request(EntitySystem& entitySystem, Entity entity, const CliHpReq& packet) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); if (packet.get_targetId()) { Entity t = entitySystem.get_entity_from_id(packet.get_targetId()); if (t != entt::null) { const auto& life = entitySystem.get_component<Component::Life>(t); auto p = SrvHpReply::create(packet.get_targetId(), life.hp); entitySystem.send_to(entity, p); } } } std::pair<float, float> Combat::get_range_position(const EntitySystem& entitySystem, Entity character, Entity target, float range) { const auto& char_pos = entitySystem.get_component<Component::Position>(character); const auto& target_pos = entitySystem.get_component<Component::Position>(target); std::pair<float, float> vector{char_pos.x - target_pos.x, char_pos.y - target_pos.y}; const float length = sqrt(vector.first * vector.first + vector.second * vector.second); vector.first /= length; vector.second /= length; return {vector.first * range, vector.second * range}; } float Combat::get_range_to(const EntitySystem& entitySystem, Entity character, Entity target) { const auto& char_pos = entitySystem.get_component<Component::Position>(character); const auto& target_pos = entitySystem.get_component<Component::Position>(target); const float dx = char_pos.x - target_pos.x; const float dy = char_pos.y - target_pos.y; return std::sqrt(dx * dx + dy * dy); } void Combat::attack(EntitySystem& entitySystem, Entity entity, const CliAttack& packet) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("Combat::attack"); logger->trace("entity {}, target {}", entity, packet.get_targetId()); const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity); const auto& pos = entitySystem.get_component<Component::Position>(entity); const auto& stats = entitySystem.get_component<Component::Stats>(entity); if (packet.get_targetId()) { Entity t = entitySystem.get_entity_from_id(packet.get_targetId()); if (t != entt::null) { auto& target = entitySystem.add_or_replace_component<Component::Target>(entity); target.target = t; //TODO: Check distance to target, if not in attack range, move into max attack range if(get_range_to(entitySystem, entity, t) > 1) { auto& dest = entitySystem.add_or_replace_component<Component::Destination>(entity); auto npos = get_range_position(entitySystem, entity, t); dest.x = npos.first; dest.y = npos.second; dest.z = 0; const float dx = pos.x - dest.x; const float dy = pos.y - dest.y; dest.dist = std::sqrt(dx * dx + dy * dy); } // This packet acts as an attack and mouse_cmd all in one, we don't want the mouse_cmd portion // of it as it can cause some issues with attack animations going off before it should // auto p = SrvAttack::create(basicInfo.id, packet.get_targetId()); // p.set_x(dest.x); // p.set_y(dest.y); // p.set_distance(dest.dist); // entitySystem.send_nearby(entity, p); } } } void Combat::update(EntitySystem& entitySystem, Entity entity) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity); const auto& pos = entitySystem.get_component<Component::Position>(entity); auto& life = entitySystem.get_component<Component::Life>(entity); //TODO:: Update buffs //TODO:: Update HP if(entitySystem.has_component<Component::Damage>(entity) == true) { auto& queuedDamage = entitySystem.get_component<Component::Damage>(entity); int32_t adjusted_hp = life.hp; uint32_t total_applied_damage = 0; for(auto attack : queuedDamage.damage_) { if(attack.apply_) { // We waited at least one update before applying damage, apply it now //TODO:: Apply damage to this entity Entity attacker = entitySystem.get_entity_from_id(attack.attacker_); logger->debug("Applying damage to entity {} {}", basicInfo.name, basicInfo.id); if((adjusted_hp - attack.value_) <= 0) { logger->debug("Entity {} {} will die from {} damage", basicInfo.name, basicInfo.id, attack.value_); total_applied_damage = attack.value_ + adjusted_hp; adjusted_hp = 0; //TODO: Credit this attacker as the one who killed this entity. } else { total_applied_damage += attack.value_; adjusted_hp -= attack.value_; } if(adjusted_hp <= 0) { //TODO: Get dropped item data here and send it with the DAMAGE packet attack.action_ &= ~DAMAGE_ACTION_HIT; attack.action_ |= DAMAGE_ACTION_DEAD; auto p = SrvDamage::create(attack.attacker_, basicInfo.id, attack.value_ + 30000, attack.action_); entitySystem.send_nearby(entity, p); // remove components that we can't have if we are dead! entitySystem.remove_component<Component::Damage>(entity); entitySystem.remove_component<Component::Destination>(entity); entitySystem.remove_component<Component::Target>(entity); } else { logger->debug("applied {} damage to entity {} {}.", attack.value_, basicInfo.name, basicInfo.id); auto p = SrvDamage::create(attack.attacker_, basicInfo.id, attack.value_, attack.action_); entitySystem.send_to(entity, p); entitySystem.send_to(attacker, p); } // Reset the damage value to 0 for next pass attack.value_ = 0; } else { // Apply any new damage on next update attack.apply_ = true; } } std::remove_if(queuedDamage.damage_.begin(), queuedDamage.damage_.end(), [] (auto &i) { return (true == i.apply_ && 0 == i.value_); }); } // Check to see if we have a target component if(entitySystem.has_component<Component::Target>(entity) == true) { auto& target = entitySystem.get_component<Component::Target>(entity); // Are we in attack range? //TODO:: Update apply damage to target } } RoseCommon::Entity Combat::get_closest_spawn(EntitySystem& entitySystem, RoseCommon::Entity player) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("Combat::get_closest_spawn start"); const auto& position = entitySystem.get_component<Component::Position>(player); RoseCommon::Entity closest = {}; float closestDist = 999999999999; for (RoseCommon::Entity entity : entitySystem.get_entities_with_components<Component::BasicInfo, Component::Position, Component::PlayerSpawn>()) { const auto& spawnPosition = entitySystem.get_component<Component::Position>(entity); if(spawnPosition.map != position.map) continue; float dx = spawnPosition.x - position.x; float dy = spawnPosition.y - position.y; float distance = std::sqrt(dx * dx + dy * dy); if(distance < closestDist) { closest = entity; closestDist = distance; } } logger->trace("Combat::get_closest_spawn end"); return closest; } RoseCommon::Entity Combat::get_saved_spawn(EntitySystem& entitySystem, RoseCommon::Entity player) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("Combat::get_saved_spawn start"); const auto& position = entitySystem.get_component<Component::Position>(player); for (RoseCommon::Entity entity : entitySystem.get_entities_with_components<Component::BasicInfo, Component::Position, Component::PlayerSpawn>()) { const auto& spawninfo = entitySystem.get_component<Component::PlayerSpawn>(entity); if(spawninfo.type == Component::PlayerSpawn::RESPAWN_POINT) { const auto& spawnPosition = entitySystem.get_component<Component::Position>(entity); if(spawnPosition.map == position.spawn) return entity; } } logger->trace("Combat::get_saved_spawn unable to find the saved spawn point"); return {}; } RoseCommon::Entity Combat::get_start_spawn(EntitySystem& entitySystem) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("Combat::get_start_spawn start"); for (RoseCommon::Entity entity : entitySystem.get_entities_with_components<Component::BasicInfo, Component::Position, Component::PlayerSpawn>()) { const auto& spawninfo = entitySystem.get_component<Component::PlayerSpawn>(entity); if(spawninfo.type == Component::PlayerSpawn::START_POINT) return entity; } return {}; } void Combat::revive(EntitySystem& entitySystem, Entity entity, const RoseCommon::Packet::CliReviveReq& packet) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("Combat::revive"); const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity); const auto& pos = entitySystem.get_component<Component::Position>(entity); auto& life = entitySystem.get_component<Component::Life>(entity); auto& magic = entitySystem.get_component<Component::Magic>(entity); uint16_t map_id = pos.map; float x = 0.f, y = 0.f; switch(packet.get_reviveType()) { case CliReviveReq::ReviveRequest::REVIVE_POSITION: { if (Entity e = get_closest_spawn(entitySystem, entity); e) { auto& dest = entitySystem.get_component<Component::Position>(e); x = dest.x + (Core::Random::getInstance().get_uniform(0, 1001) - 500); y = dest.y + (Core::Random::getInstance().get_uniform(0, 1001) - 500); } break; } case CliReviveReq::ReviveRequest::SAVE_POSITION: { if (Entity e = get_saved_spawn(entitySystem, entity); e) { auto& dest = entitySystem.get_component<Component::Position>(e); if(dest.map == 20 && basicInfo.job) { if (Entity e = get_closest_spawn(entitySystem, entity); e) { auto& dest = entitySystem.get_component<Component::Position>(e); x = dest.x + (Core::Random::getInstance().get_uniform(0, 1001) - 500); y = dest.y + (Core::Random::getInstance().get_uniform(0, 1001) - 500); } break; } if(pos.map != dest.map) { map_id = dest.map; } x = dest.x + (Core::Random::getInstance().get_uniform(0, 1001) - 500); y = dest.y + (Core::Random::getInstance().get_uniform(0, 1001) - 500); } break; } case CliReviveReq::ReviveRequest::START_POSITION: { if (Entity e = get_start_spawn(entitySystem); e) { auto& dest = entitySystem.get_component<Component::Position>(e); x = dest.x + (Core::Random::getInstance().get_uniform(0, 1001) - 500); y = dest.y + (Core::Random::getInstance().get_uniform(0, 1001) - 500); } break; } case CliReviveReq::ReviveRequest::CURRENT_POSITION: { x = pos.x; y = pos.y; break; } default: { logger->warn("Combat::revive player {} sent a revive type that doesn't exist...", basicInfo.name); break; } } life.hp = (life.maxHp * 0.3f); magic.mp = 0; entitySystem.teleport_entity(entity, x, y, map_id); }<|endoftext|>
<commit_before>/* Resembla: Word-based Japanese similar sentence search library https://github.com/tuem/resembla Copyright 2017 Takashi Uemura 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 RESEMBLA_LETTER_WEIGHT_HPP #define RESEMBLA_LETTER_WEIGHT_HPP #include <string> #include <fstream> #include <exception> #include <unordered_map> #include "../string_util.hpp" namespace resembla { // simple weight function for sets of letters template<typename string_type> struct LetterWeight { using value_type = typename string_type::value_type; LetterWeight(double base_weight, double delete_insert_ratio, const std::string& letter_weight_file_path): base_weight(base_weight), delete_insert_ratio(delete_insert_ratio) { if(letter_weight_file_path.empty()){ return; } std::basic_ifstream<value_type> ifs(letter_weight_file_path); if(ifs.fail()){ throw std::runtime_error("input file is not available: " + letter_weight_file_path); } while(ifs.good()){ string_type line; std::getline(ifs, line); if(ifs.eof() || line.length() == 0){ break; } auto columns = split(line, column_delimiter<value_type>()); if(columns.size() < 2){ throw std::runtime_error("invalid line in " + letter_weight_file_path + ": " + cast_string<std::string>(line)); } auto letters= columns[0]; auto weight = std::stod(columns[1]); for(size_t i = 0; i < letters.size(); ++i){ letter_weights[letters[i]] = weight; } } } double operator()(const value_type c, bool is_original = false, size_t total = -1, size_t position = -1) const { (void)total; (void)position; double w = base_weight; if(is_original){ w *= delete_insert_ratio; } auto p = letter_weights.find(c); if(p != std::end(letter_weights)){ w *= p->second; } return w; } protected: double base_weight; double delete_insert_ratio; std::unordered_map<value_type, double> letter_weights; }; } #endif <commit_msg>use csv_reader in letter_weight<commit_after>/* Resembla: Word-based Japanese similar sentence search library https://github.com/tuem/resembla Copyright 2017 Takashi Uemura 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 RESEMBLA_LETTER_WEIGHT_HPP #define RESEMBLA_LETTER_WEIGHT_HPP #include <string> #include <exception> #include <unordered_map> #include "../string_util.hpp" #include "../csv_reader.hpp" namespace resembla { // simple weight function for sets of letters template<typename string_type> struct LetterWeight { using value_type = typename string_type::value_type; LetterWeight(double base_weight, double delete_insert_ratio, const std::string& letter_weight_file_path): base_weight(base_weight), delete_insert_ratio(delete_insert_ratio) { if(letter_weight_file_path.empty()){ return; } for(const auto& columns: CsvReader<>(letter_weight_file_path, 2)){ auto letters = cast_string<string_type>(columns[0]); auto weight = std::stod(columns[1]); for(auto c: letters){ letter_weights[c] = weight; } } } double operator()(const value_type c, bool is_original = false, size_t total = -1, size_t position = -1) const { (void)total; (void)position; double w = base_weight; if(is_original){ w *= delete_insert_ratio; } auto p = letter_weights.find(c); if(p != std::end(letter_weights)){ w *= p->second; } return w; } protected: double base_weight; double delete_insert_ratio; std::unordered_map<value_type, double> letter_weights; }; } #endif <|endoftext|>
<commit_before>#include <aikido/statespace/RealVectorStateSpace.hpp> #include <aikido/statespace/SO2StateSpace.hpp> #include <aikido/statespace/SO3StateSpace.hpp> #include <aikido/statespace/SE2StateSpace.hpp> #include <aikido/statespace/SE3StateSpace.hpp> #include <aikido/statespace/CompoundStateSpace.hpp> #include <aikido/statespace/StateSpace.hpp> #include <dart/math/Geometry.h> #include <gtest/gtest.h> #include <Eigen/Dense> #include <typeinfo> // std::bad_cast using namespace aikido::statespace; using namespace std; TEST(RealVectorStateSpace, Compose) { RealVectorStateSpace rvss(3); RealVectorStateSpace::ScopedState s1 = rvss.createState(); s1.getValue() = Eigen::Vector3d(1, 2, 3); RealVectorStateSpace::ScopedState s2 = rvss.createState(); s2.getValue() = Eigen::Vector3d(2, 3, 4); RealVectorStateSpace::ScopedState out = rvss.createState(); rvss.compose(*s1, *s2, *out); EXPECT_TRUE(out.getValue().isApprox(Eigen::Vector3d(3, 5, 7))); } TEST(SO2StateSpace, Compose) { SO2StateSpace::State s1(M_PI/4); SO2StateSpace::State s2(M_PI/2); SO2StateSpace::State out; SO2StateSpace::State expected(3.0/4.0*M_PI); SO2StateSpace so2; so2.compose(s1, s2, out); EXPECT_TRUE(out.getRotation().isApprox(expected.getRotation())); } TEST(SO3StateSpace, Compose) { SO3StateSpace::State identity; EXPECT_TRUE(identity.getQuaternion().isApprox( Eigen::Quaterniond::Identity())); SO3StateSpace::State s2(Eigen::Quaterniond( Eigen::AngleAxisd(M_PI_2, Eigen::Vector3d::UnitZ()))); SO3StateSpace::State s3(Eigen::Quaterniond( Eigen::AngleAxisd(M_PI_2, Eigen::Vector3d::UnitZ()))); SO3StateSpace::State expected(Eigen::Quaterniond( Eigen::AngleAxisd(M_PI, Eigen::Vector3d::UnitZ()))); SO3StateSpace::State out; SO3StateSpace so3; so3.compose(s2, s3, out); EXPECT_TRUE(expected.getQuaternion().isApprox(out.getQuaternion())); } TEST(SE2StateSpace, Compose) { SE2StateSpace space; SE2StateSpace::ScopedState identity(&space); EXPECT_TRUE(identity.getIsometry().isApprox(Eigen::Isometry2d::Identity())); Eigen::Isometry2d pose2 = Eigen::Isometry2d::Identity(); pose2.rotate(Eigen::Rotation2Dd(M_PI_2)); SE2StateSpace::ScopedState state2(&space); state2.setIsometry(pose2); Eigen::Isometry2d pose3 = Eigen::Isometry2d::Identity(); pose3.rotate(Eigen::Rotation2Dd(M_PI_4)); SE2StateSpace::ScopedState state3(&space); state3.setIsometry(pose3); Eigen::Isometry2d expected_pose = Eigen::Isometry2d::Identity(); expected_pose.rotate(Eigen::Rotation2Dd(3. * M_PI_4)); SE2StateSpace::ScopedState out(&space); space.compose(*state2, *state3, *out); EXPECT_TRUE(expected_pose.isApprox(out.getIsometry())); } TEST(SE3StateSpace, Compose) { SE3StateSpace space; SE3StateSpace::ScopedState identity(&space); EXPECT_TRUE(identity.getIsometry().isApprox(Eigen::Isometry3d::Identity())); Eigen::Isometry3d pose2 = Eigen::Isometry3d::Identity(); pose2.rotate(Eigen::AngleAxisd(M_PI_2, Eigen::Vector3d::UnitX())); SE3StateSpace::ScopedState s2(&space); s2.setIsometry(pose2); Eigen::Isometry3d pose3 = Eigen::Isometry3d::Identity(); pose3.rotate(Eigen::AngleAxisd(M_PI_4, Eigen::Vector3d::UnitX())); SE3StateSpace::ScopedState s3(&space); s2.setIsometry(pose3); Eigen::Isometry3d expected = Eigen::Isometry3d::Identity(); expected.rotate(Eigen::AngleAxisd(3. * M_PI_4, Eigen::Vector3d::UnitX())); SE3StateSpace::ScopedState out(&space); space.compose(*s2, *s3, *out); std::cout << "expected\n" << expected.matrix() << "\n" << "actual\n" << out.getIsometry().matrix() << "\n" << std::endl; EXPECT_TRUE(expected.isApprox(out.getIsometry())); } TEST(CompoundStateSpace, Compose) { using Eigen::Vector2d; CompoundStateSpace space({ std::make_shared<SO2StateSpace>(), std::make_shared<RealVectorStateSpace>(2) }); // TODO: This syntax is _really_ bad. CompoundStateSpace::ScopedState s1 = space.createState(); s1.getSubState<SO2StateSpace>(0).setAngle(M_PI_2); s1.getSubStateHandle<RealVectorStateSpace>(1).getValue() = Vector2d(3., 4.); CompoundStateSpace::ScopedState s2 = space.createState(); space.getSubState<SO2StateSpace>(*s2, 0).setAngle(M_PI_2); space.getSubSpace<RealVectorStateSpace>(1).getValue( space.getSubState<RealVectorStateSpace>(*s2, 1)) = Vector2d(5., 10.); CompoundStateSpace::ScopedState out = space.createState(); space.compose(*s1, *s2, *out); const double out1 = out.getSubState<SO2StateSpace>(0).getAngle(); EXPECT_DOUBLE_EQ(M_PI, out1); const Vector2d out2 = out.getSubStateHandle<RealVectorStateSpace>(1).getValue(); EXPECT_TRUE(out2.isApprox(Vector2d(8., 14.))); } <commit_msg>Tweaks to test.<commit_after>#include <aikido/statespace/RealVectorStateSpace.hpp> #include <aikido/statespace/SO2StateSpace.hpp> #include <aikido/statespace/SO3StateSpace.hpp> #include <aikido/statespace/SE2StateSpace.hpp> #include <aikido/statespace/SE3StateSpace.hpp> #include <aikido/statespace/CompoundStateSpace.hpp> #include <aikido/statespace/StateSpace.hpp> #include <dart/math/Geometry.h> #include <gtest/gtest.h> #include <Eigen/Dense> #include <typeinfo> // std::bad_cast using namespace aikido::statespace; using namespace std; TEST(RealVectorStateSpace, Compose) { RealVectorStateSpace rvss(3); RealVectorStateSpace::ScopedState s1 = rvss.createState(); s1.getValue() = Eigen::Vector3d(1, 2, 3); RealVectorStateSpace::ScopedState s2 = rvss.createState(); s2.getValue() = Eigen::Vector3d(2, 3, 4); RealVectorStateSpace::ScopedState out = rvss.createState(); rvss.compose(*s1, *s2, *out); EXPECT_TRUE(out.getValue().isApprox(Eigen::Vector3d(3, 5, 7))); } TEST(SO2StateSpace, Compose) { SO2StateSpace::State s1(M_PI/4); SO2StateSpace::State s2(M_PI/2); SO2StateSpace::State out; SO2StateSpace::State expected(3.0/4.0*M_PI); SO2StateSpace so2; so2.compose(s1, s2, out); EXPECT_TRUE(out.getRotation().isApprox(expected.getRotation())); } TEST(SO3StateSpace, Compose) { SO3StateSpace::State identity; EXPECT_TRUE(identity.getQuaternion().isApprox( Eigen::Quaterniond::Identity())); SO3StateSpace::State s2(Eigen::Quaterniond( Eigen::AngleAxisd(M_PI_2, Eigen::Vector3d::UnitZ()))); SO3StateSpace::State s3(Eigen::Quaterniond( Eigen::AngleAxisd(M_PI_2, Eigen::Vector3d::UnitZ()))); SO3StateSpace::State expected(Eigen::Quaterniond( Eigen::AngleAxisd(M_PI, Eigen::Vector3d::UnitZ()))); SO3StateSpace::State out; SO3StateSpace so3; so3.compose(s2, s3, out); EXPECT_TRUE(expected.getQuaternion().isApprox(out.getQuaternion())); } TEST(SE2StateSpace, Compose) { SE2StateSpace space; SE2StateSpace::ScopedState identity(&space); EXPECT_TRUE(identity.getIsometry().isApprox(Eigen::Isometry2d::Identity())); Eigen::Isometry2d pose2 = Eigen::Isometry2d::Identity(); pose2.rotate(Eigen::Rotation2Dd(M_PI_2)); SE2StateSpace::ScopedState state2(&space); state2.setIsometry(pose2); Eigen::Isometry2d pose3 = Eigen::Isometry2d::Identity(); pose3.rotate(Eigen::Rotation2Dd(M_PI_4)); SE2StateSpace::ScopedState state3(&space); state3.setIsometry(pose3); Eigen::Isometry2d expected_pose = Eigen::Isometry2d::Identity(); expected_pose.rotate(Eigen::Rotation2Dd(3. * M_PI_4)); SE2StateSpace::ScopedState out(&space); space.compose(*state2, *state3, *out); EXPECT_TRUE(expected_pose.isApprox(out.getIsometry())); } TEST(SE3StateSpace, Compose) { SE3StateSpace space; SE3StateSpace::ScopedState identity(&space); EXPECT_TRUE(identity.getIsometry().isApprox(Eigen::Isometry3d::Identity())); Eigen::Isometry3d pose2 = Eigen::Isometry3d::Identity(); pose2.rotate(Eigen::AngleAxisd(M_PI_2, Eigen::Vector3d::UnitX())); SE3StateSpace::ScopedState s2(&space); s2.setIsometry(pose2); Eigen::Isometry3d pose3 = Eigen::Isometry3d::Identity(); pose3.rotate(Eigen::AngleAxisd(M_PI_4, Eigen::Vector3d::UnitX())); SE3StateSpace::ScopedState s3(&space); s2.setIsometry(pose3); Eigen::Isometry3d expected = pose2 * pose3; SE3StateSpace::ScopedState out(&space); space.compose(*s2, *s3, *out); std::cout << "expected\n" << expected.matrix() << "\n" << "actual\n" << out.getIsometry().matrix() << "\n" << std::endl; EXPECT_TRUE(expected.isApprox(out.getIsometry())); } TEST(CompoundStateSpace, Compose) { using Eigen::Vector2d; CompoundStateSpace space({ std::make_shared<SO2StateSpace>(), std::make_shared<RealVectorStateSpace>(2) }); // TODO: This syntax is _really_ bad. CompoundStateSpace::ScopedState s1 = space.createState(); s1.getSubState<SO2StateSpace>(0).setAngle(M_PI_2); s1.getSubStateHandle<RealVectorStateSpace>(1).getValue() = Vector2d(3., 4.); CompoundStateSpace::ScopedState s2 = space.createState(); space.getSubState<SO2StateSpace>(*s2, 0).setAngle(M_PI_2); space.getSubSpace<RealVectorStateSpace>(1).getValue( space.getSubState<RealVectorStateSpace>(*s2, 1)) = Vector2d(5., 10.); CompoundStateSpace::ScopedState out = space.createState(); space.compose(*s1, *s2, *out); const double out1 = out.getSubState<SO2StateSpace>(0).getAngle(); EXPECT_DOUBLE_EQ(M_PI, out1); const Vector2d out2 = out.getSubStateHandle<RealVectorStateSpace>(1).getValue(); EXPECT_TRUE(out2.isApprox(Vector2d(8., 14.))); } <|endoftext|>
<commit_before>#include "mem/cache/tags/utillru.hh" #include "base/intmath.hh" #include "debug/CacheRepl.hh" #include "mem/cache/tags/cacheset.hh" #include "mem/cache/tags/lru.hh" #include "mem/cache/base.hh" #include "sim/core.hh" #include "mem/cache/blk.hh" #include <typeinfo> UTILLRU::UTILLRU( unsigned _numSets, unsigned _blkSize, unsigned _assoc, unsigned _hit_latency, unsigned _L_assoc) : LRU(_numSets, _blkSize, _assoc, _hit_latency ) { L_assoc = _L_assoc; H_assoc = _assoc - L_assoc; assoc = _assoc; // umon counters umon_counters = new unsigned*[2]; for (unsigned i = 0; i < 2; i++) umon_counters[i] = new unsigned[assoc]; for (unsigned i = 0; i < 2; i++) for (unsigned j = 0; j < assoc; j++) umon_counters[i][j] = 0; init_sets(); } void UTILLRU::reset_umon() { for (unsigned i = 0; i < 2; i++) for (unsigned j = 0; j < assoc; j++) umon_counters[i][j] = umon_counters[i][j]/2; } unsigned UTILLRU::curr_L_assoc() { return L_assoc; } unsigned UTILLRU::lookup_umon(int index, uint64_t tid) { return umon_counters[tid][index]; } int UTILLRU::assoc_of_tc( int tcid ){ if (tcid == 0) return L_assoc; else return H_assoc; } CacheSet UTILLRU::get_set( int setnum, uint64_t tid, Addr addr ){ return sets[setnum]; } void UTILLRU::init_sets(){ sets = new CacheSet[numSets]; numBlocks = numSets * assoc; blks = new BlkType[numBlocks]; dataBlks = new uint8_t[numBlocks * blkSize]; unsigned blkIndex = 0; for( unsigned i = 0; i< numSets; i++ ){ sets[i].assoc = assoc; sets[i].blks = new BlkType*[assoc]; for( unsigned j = 0; j<assoc; j++ ){ BlkType *blk = &blks[blkIndex]; blk->data = &dataBlks[blkSize*blkIndex]; ++blkIndex; blk->status = 0; blk->tag = j; blk->whenReady = 0; blk->isTouched = false; blk->size = blkSize; blk->set = i; // initialize the threadID blk->threadID = 0; sets[i].blks[j]=blk; } } // shadow tags for monitoring umon_sets = new CacheSet*[2]; for( int i=0; i< 2; i++ ){ umon_sets[i] = new CacheSet[numSets]; } umon_blks = new BlkType*[2]; for( int i=0; i< 2; i++ ){ umon_blks[i] = new BlkType[numBlocks]; } for( unsigned tc=0; tc<2; tc++ ){ blkIndex = 0; for( unsigned i = 0; i < numSets; i++){ umon_sets[tc][i].assoc = assoc; umon_sets[tc][i].blks = new BlkType*[assoc]; for( unsigned j = 0; j<assoc; j++ ){ BlkType *blk = &umon_blks[tc][blkIndex]; blk->data = 0; ++blkIndex; blk->status = 0; blk->tag = j; blk->whenReady = 0; blk->isTouched = false; blk->size = blkSize; blk->set = i; // initialize the threadID blk->threadID = tc; umon_sets[tc][i].blks[j]=blk; } } } } // increase the size of Low partition unsigned UTILLRU::inc_size(){ if(H_assoc == 1) return 0; L_assoc += 1; H_assoc -= 1; fprintf(stderr, "L_assoc = %2d H_assoc = %2d\n", L_assoc, H_assoc); return numSets; } unsigned UTILLRU::dec_size(){ if(L_assoc == 1) return 0; L_assoc -= 1; H_assoc += 1; fprintf(stderr, "L_assoc = %2d H_assoc = %2d\n", L_assoc, H_assoc); return numSets; } UTILLRU::BlkType* UTILLRU::accessBlock(Addr addr, int &lat, int master_id, uint64_t tid) { Addr tag = extractTag(addr); unsigned set = extractSet(addr); // BlkType *blk = sets[set].findBlk(tag); BlkType *blk = get_set(set,tid,addr).findBlk(tag); lat = hitLatency; if (blk != 0 ) { // move this block to head of the MRU list get_set(set,tid,addr).moveToHead(blk); DPRINTF(CacheRepl, "set %x: moving blk %x to MRU\n", set, regenerateBlkAddr(tag, set)); if (blk->whenReady > curTick() && blk->whenReady - curTick() > hitLatency) { lat = blk->whenReady - curTick(); } blk->refCount += 1; // set the used bit blk->isTouched = 1; } BlkType *umon_blk = umon_sets[tid][set].findBlk(tag); unsigned index = umon_sets[tid][set].findBlkIndex(tag); // cache hit on umon tags if (umon_blk != 0) { umon_counters[index]++; umon_sets[tid][set].moveToHead(umon_blk); } // cache miss on umon tags else { umon_sets[tid][set].blks[assoc-1]->tag = tag; umon_sets[tid][set].blks[assoc-1]->status = BlkValid | BlkReadable; umon_sets[tid][set].moveToHead(umon_sets[tid][set].blks[assoc-1]); } return blk; } UTILLRU::BlkType* UTILLRU::findBlock(Addr addr, uint64_t tid) { Addr tag = extractTag(addr); unsigned set = extractSet(addr); BlkType *blk = get_set(set,tid,addr).findBlk(tag); return blk; } UTILLRU::BlkType* UTILLRU::findVictim(Addr addr, PacketList &writebacks, uint64_t tid) { unsigned set = extractSet(addr); // grab a replacement candidate BlkType *blk = get_set(set,tid,addr).findVictim(tid, L_assoc); if (blk->isValid()) { DPRINTF(CacheRepl, "set %x: selecting blk %x for replacement\n", set, regenerateBlkAddr(blk->tag, set)); } return blk; } void UTILLRU::invalidateBlk(BlkType *blk, uint64_t tid) { if (blk) { if (blk->isValid()) { tagsInUse--; assert(blk->srcMasterId < cache->system->maxMasters()); occupancies[blk->srcMasterId]--; blk->srcMasterId = Request::invldMasterId; unsigned set = blk->set; get_set(set,tid,blk->set).moveToTail(blk); } blk->status = 0; blk->isTouched = false; blk->clearLoadLocks(); // should be evicted before valid blocks //unsigned set = blk->set; //sets[set].moveToTail(blk); } BlkType *umon_blk = umon_sets[tid][blk->set].findBlk(blk->tag); if (umon_blk != 0) { if (umon_blk->isValid()) { umon_sets[tid][blk->set].moveToTail(umon_blk); } umon_blk->status = 0; umon_blk->isTouched = false; } }<commit_msg>fixed a segmentation fault<commit_after>#include "mem/cache/tags/utillru.hh" #include "base/intmath.hh" #include "debug/CacheRepl.hh" #include "mem/cache/tags/cacheset.hh" #include "mem/cache/tags/lru.hh" #include "mem/cache/base.hh" #include "sim/core.hh" #include "mem/cache/blk.hh" #include <typeinfo> UTILLRU::UTILLRU( unsigned _numSets, unsigned _blkSize, unsigned _assoc, unsigned _hit_latency, unsigned _L_assoc) : LRU(_numSets, _blkSize, _assoc, _hit_latency ) { L_assoc = _L_assoc; H_assoc = _assoc - L_assoc; assoc = _assoc; // umon counters umon_counters = new unsigned*[2]; for (unsigned i = 0; i < 2; i++) umon_counters[i] = new unsigned[assoc]; for (unsigned i = 0; i < 2; i++) for (unsigned j = 0; j < assoc; j++) umon_counters[i][j] = 0; init_sets(); } void UTILLRU::reset_umon() { for (unsigned i = 0; i < 2; i++) for (unsigned j = 0; j < assoc; j++) umon_counters[i][j] = umon_counters[i][j]/2; } unsigned UTILLRU::curr_L_assoc() { return L_assoc; } unsigned UTILLRU::lookup_umon(int index, uint64_t tid) { return umon_counters[tid][index]; } int UTILLRU::assoc_of_tc( int tcid ){ if (tcid == 0) return L_assoc; else return H_assoc; } CacheSet UTILLRU::get_set( int setnum, uint64_t tid, Addr addr ){ return sets[setnum]; } void UTILLRU::init_sets(){ sets = new CacheSet[numSets]; numBlocks = numSets * assoc; blks = new BlkType[numBlocks]; dataBlks = new uint8_t[numBlocks * blkSize]; unsigned blkIndex = 0; for( unsigned i = 0; i< numSets; i++ ){ sets[i].assoc = assoc; sets[i].blks = new BlkType*[assoc]; for( unsigned j = 0; j<assoc; j++ ){ BlkType *blk = &blks[blkIndex]; blk->data = &dataBlks[blkSize*blkIndex]; ++blkIndex; blk->status = 0; blk->tag = j; blk->whenReady = 0; blk->isTouched = false; blk->size = blkSize; blk->set = i; // initialize the threadID blk->threadID = 0; sets[i].blks[j]=blk; } } // shadow tags for monitoring umon_sets = new CacheSet*[2]; for( int i=0; i< 2; i++ ){ umon_sets[i] = new CacheSet[numSets]; } umon_blks = new BlkType*[2]; for( int i=0; i< 2; i++ ){ umon_blks[i] = new BlkType[numBlocks]; } for( unsigned tc=0; tc<2; tc++ ){ blkIndex = 0; for( unsigned i = 0; i < numSets; i++){ umon_sets[tc][i].assoc = assoc; umon_sets[tc][i].blks = new BlkType*[assoc]; for( unsigned j = 0; j<assoc; j++ ){ BlkType *blk = &umon_blks[tc][blkIndex]; blk->data = 0; ++blkIndex; blk->status = 0; blk->tag = j; blk->whenReady = 0; blk->isTouched = false; blk->size = blkSize; blk->set = i; // initialize the threadID blk->threadID = tc; umon_sets[tc][i].blks[j]=blk; } } } } // increase the size of Low partition unsigned UTILLRU::inc_size(){ if(H_assoc == 1) return 0; L_assoc += 1; H_assoc -= 1; fprintf(stderr, "L_assoc = %2d H_assoc = %2d\n", L_assoc, H_assoc); return numSets; } unsigned UTILLRU::dec_size(){ if(L_assoc == 1) return 0; L_assoc -= 1; H_assoc += 1; fprintf(stderr, "L_assoc = %2d H_assoc = %2d\n", L_assoc, H_assoc); return numSets; } UTILLRU::BlkType* UTILLRU::accessBlock(Addr addr, int &lat, int master_id, uint64_t tid) { Addr tag = extractTag(addr); unsigned set = extractSet(addr); // BlkType *blk = sets[set].findBlk(tag); BlkType *blk = get_set(set,tid,addr).findBlk(tag); lat = hitLatency; if (blk != 0 ) { // move this block to head of the MRU list get_set(set,tid,addr).moveToHead(blk); DPRINTF(CacheRepl, "set %x: moving blk %x to MRU\n", set, regenerateBlkAddr(tag, set)); if (blk->whenReady > curTick() && blk->whenReady - curTick() > hitLatency) { lat = blk->whenReady - curTick(); } blk->refCount += 1; // set the used bit blk->isTouched = 1; } BlkType *umon_blk = umon_sets[tid][set].findBlk(tag); unsigned index = umon_sets[tid][set].findBlkIndex(tag); // cache hit on umon tags if (umon_blk != 0) { umon_counters[tid][index]++; umon_sets[tid][set].moveToHead(umon_blk); } // cache miss on umon tags else { umon_sets[tid][set].blks[assoc-1]->tag = tag; umon_sets[tid][set].blks[assoc-1]->status = BlkValid | BlkReadable; umon_sets[tid][set].moveToHead(umon_sets[tid][set].blks[assoc-1]); } return blk; } UTILLRU::BlkType* UTILLRU::findBlock(Addr addr, uint64_t tid) { Addr tag = extractTag(addr); unsigned set = extractSet(addr); BlkType *blk = get_set(set,tid,addr).findBlk(tag); return blk; } UTILLRU::BlkType* UTILLRU::findVictim(Addr addr, PacketList &writebacks, uint64_t tid) { unsigned set = extractSet(addr); // grab a replacement candidate BlkType *blk = get_set(set,tid,addr).findVictim(tid, L_assoc); if (blk->isValid()) { DPRINTF(CacheRepl, "set %x: selecting blk %x for replacement\n", set, regenerateBlkAddr(blk->tag, set)); } return blk; } void UTILLRU::invalidateBlk(BlkType *blk, uint64_t tid) { if (blk) { if (blk->isValid()) { tagsInUse--; assert(blk->srcMasterId < cache->system->maxMasters()); occupancies[blk->srcMasterId]--; blk->srcMasterId = Request::invldMasterId; unsigned set = blk->set; get_set(set,tid,blk->set).moveToTail(blk); } blk->status = 0; blk->isTouched = false; blk->clearLoadLocks(); // should be evicted before valid blocks //unsigned set = blk->set; //sets[set].moveToTail(blk); } BlkType *umon_blk = umon_sets[tid][blk->set].findBlk(blk->tag); if (umon_blk != 0) { if (umon_blk->isValid()) { umon_sets[tid][blk->set].moveToTail(umon_blk); } umon_blk->status = 0; umon_blk->isTouched = false; } }<|endoftext|>
<commit_before>#ifndef VIENNAMETA_TYPELIST_HPP #define VIENNAMETA_TYPELIST_HPP #include "utils.hpp" #include "typelist_macros.hpp" namespace viennameta { template <class head_, class tail_> struct typelist_t { typedef head_ head; typedef tail_ tail; }; namespace typelist { namespace result_of { // size of a typelist template <typename typelist> struct size; template <> struct size<null_type> { enum { value = 0 }; }; template <typename head, typename tail> struct size< typelist_t<head, tail> > { enum { value = 1 + size<tail>::value }; }; // index access template <typename typelist, unsigned int index> struct at { typedef out_of_range type; }; template <typename head, typename tail> struct at<typelist_t<head, tail>, 0> { typedef head type; }; template <typename head, typename tail, unsigned int i> struct at<typelist_t<head, tail>, i> { typedef typename at<tail, i - 1>::type type; }; // find first type template <typename typelist, typename to_find> struct find; template <typename to_find> struct find<null_type, to_find> { enum { value = -1 }; }; template <typename to_find, typename tail> struct find<typelist_t<to_find, tail>, to_find> { enum { value = 0 }; }; template <typename head, typename tail, typename to_find> struct find<typelist_t<head, tail>, to_find> { private: enum { temp = find<tail, to_find>::value }; public: enum { value = (temp == -1 ? -1 : 1 + temp) }; }; // push back a single type template <typename typelist, typename to_add> struct push_back; template <> struct push_back<null_type, null_type> { typedef null_type type; }; template <typename to_add> struct push_back<null_type, to_add> { typedef typelist_t<to_add, null_type> type; }; template <typename head, typename tail, typename to_add> struct push_back<typelist_t<head, tail>, to_add> { typedef typelist_t<head, typename push_back<tail, to_add>::type> type; }; // push back list template <typename typelist, typename typelist_to_add> struct push_back_list; template <> struct push_back_list<null_type, null_type> { typedef null_type type; }; template <typename head, typename tail> struct push_back_list<null_type, typelist_t<head, tail> > { typedef typelist_t<head, tail> type; }; template <typename head, typename tail> struct push_back_list<typelist_t<head, tail>, null_type > { typedef typelist_t<head, tail> type; }; template <typename head1, typename tail1, typename head2, typename tail2> struct push_back_list<typelist_t<head1, tail1>, typelist_t<head2, tail2> > { typedef typename push_back_list< typename push_back< typelist_t<head1, tail1>, head2>::type, tail2 >::type type; }; // erase_at the type at index template <typename typelist, unsigned int index_to_erase> struct erase_at; template <unsigned int index_to_erase> struct erase_at<null_type, index_to_erase> { typedef null_type type; }; template <typename head, typename tail> struct erase_at< typelist_t<head, tail>, 0> { typedef tail type; }; template <typename head, typename tail, unsigned int index_to_erase> struct erase_at< typelist_t<head, tail>, index_to_erase> { typedef typelist_t<head, typename erase_at<tail, index_to_erase-1>::type> type; }; // erase the first type template <typename typelist, typename to_erase> struct erase; template <typename to_erase> struct erase<null_type, to_erase> { typedef null_type type; }; template <typename to_erase, typename tail> struct erase< typelist_t<to_erase, tail>, to_erase> { typedef tail type; }; template <typename head, typename tail, typename to_erase> struct erase< typelist_t<head, tail>, to_erase> { typedef typelist_t<head, typename erase<tail, to_erase>::type> type; }; // erase all types template <typename typelist, typename to_erase> struct erase_all; template <typename to_erase> struct erase_all<null_type, to_erase> { typedef null_type type; }; template <typename to_erase, typename tail> struct erase_all< typelist_t<to_erase, tail>, to_erase> { // Go all the way down the list removing the type typedef typename erase_all<tail, to_erase>::type type; }; template <typename head, typename tail, typename to_erase> struct erase_all< typelist_t<head, tail>, to_erase> { // Go all the way down the list removing the type typedef typelist_t<head, typename erase_all<tail, to_erase>::type> type; }; // no duplicate types template <typename typelist> struct no_duplicates; template <> struct no_duplicates<null_type> { typedef null_type type; }; template <typename head, typename tail> struct no_duplicates< typelist_t<head, tail> > { private: typedef typename no_duplicates<tail>::type L1; typedef typename erase<L1, head>::type L2; public: typedef typelist_t<head, L2> type; }; // replace the type at index by another type template <typename typelist, unsigned int index_to_replace, typename replaced> struct replace_at; template <unsigned int index_to_replace, typename replaced> struct replace_at<null_type, index_to_replace, replaced> { typedef null_type type; }; template <typename head, typename tail, typename replaced> struct replace_at<typelist_t<head, tail>, 0, replaced> { typedef typelist_t<replaced, tail> type; }; template <typename head, typename tail, unsigned int index_to_replace, typename replaced> struct replace_at<typelist_t<head, tail>, index_to_replace, replaced> { typedef typelist_t<head, typename replace_at<tail, index_to_replace-1, replaced>::type> type; }; // replace the first type by another type template <typename typelist, typename to_replace, typename replaced> struct replace; template <typename to_replace, typename replaced> struct replace<null_type, to_replace, replaced> { typedef null_type type; }; template <typename to_replace, typename tail, typename replaced> struct replace<typelist_t<to_replace, tail>, to_replace, replaced> { typedef typelist_t<replaced, tail> type; }; template <typename head, typename tail, typename to_replace, typename replaced> struct replace<typelist_t<head, tail>, to_replace, replaced> { typedef typelist_t<head, typename replace<tail, to_replace, replaced>::type> type; }; // replace all types by another type template <typename typelist, typename to_replace, typename replaced> struct replace_all; template <typename to_replace, typename replaced> struct replace_all<null_type, to_replace, replaced> { typedef null_type type; }; template <typename to_replace, typename tail, typename replaced> struct replace_all<typelist_t<to_replace, tail>, to_replace, replaced> { typedef typelist_t<replaced, typename replace_all<tail, to_replace, replaced>::type> type; }; template <typename head, typename tail, typename to_replace, typename replaced> struct replace_all<typelist_t<head, tail>, to_replace, replaced> { typedef typelist_t<head, typename replace_all<tail, to_replace, replaced>::type> type; }; } } } #endif // end file guardian <commit_msg>renamed find to index_of<commit_after>#ifndef VIENNAMETA_TYPELIST_HPP #define VIENNAMETA_TYPELIST_HPP #include "utils.hpp" #include "typelist_macros.hpp" namespace viennameta { template <class head_, class tail_> struct typelist_t { typedef head_ head; typedef tail_ tail; }; namespace typelist { namespace result_of { // size of a typelist template <typename typelist> struct size; template <> struct size<null_type> { enum { value = 0 }; }; template <typename head, typename tail> struct size< typelist_t<head, tail> > { enum { value = 1 + size<tail>::value }; }; // index access template <typename typelist, unsigned int index> struct at { typedef out_of_range type; }; template <typename head, typename tail> struct at<typelist_t<head, tail>, 0> { typedef head type; }; template <typename head, typename tail, unsigned int i> struct at<typelist_t<head, tail>, i> { typedef typename at<tail, i - 1>::type type; }; // returns the index of the first type in the typelist template <typename typelist, typename to_find> struct index_of; template <typename to_find> struct index_of<null_type, to_find> { enum { value = -1 }; }; template <typename to_find, typename tail> struct index_of<typelist_t<to_find, tail>, to_find> { enum { value = 0 }; }; template <typename head, typename tail, typename to_find> struct index_of<typelist_t<head, tail>, to_find> { private: enum { temp = index_of<tail, to_find>::value }; public: enum { value = (temp == -1 ? -1 : 1 + temp) }; }; // push back a single type template <typename typelist, typename to_add> struct push_back; template <> struct push_back<null_type, null_type> { typedef null_type type; }; template <typename to_add> struct push_back<null_type, to_add> { typedef typelist_t<to_add, null_type> type; }; template <typename head, typename tail, typename to_add> struct push_back<typelist_t<head, tail>, to_add> { typedef typelist_t<head, typename push_back<tail, to_add>::type> type; }; // push back list template <typename typelist, typename typelist_to_add> struct push_back_list; template <> struct push_back_list<null_type, null_type> { typedef null_type type; }; template <typename head, typename tail> struct push_back_list<null_type, typelist_t<head, tail> > { typedef typelist_t<head, tail> type; }; template <typename head, typename tail> struct push_back_list<typelist_t<head, tail>, null_type > { typedef typelist_t<head, tail> type; }; template <typename head1, typename tail1, typename head2, typename tail2> struct push_back_list<typelist_t<head1, tail1>, typelist_t<head2, tail2> > { typedef typename push_back_list< typename push_back< typelist_t<head1, tail1>, head2>::type, tail2 >::type type; }; // erase_at the type at index template <typename typelist, unsigned int index_to_erase> struct erase_at; template <unsigned int index_to_erase> struct erase_at<null_type, index_to_erase> { typedef null_type type; }; template <typename head, typename tail> struct erase_at< typelist_t<head, tail>, 0> { typedef tail type; }; template <typename head, typename tail, unsigned int index_to_erase> struct erase_at< typelist_t<head, tail>, index_to_erase> { typedef typelist_t<head, typename erase_at<tail, index_to_erase-1>::type> type; }; // erase the first type template <typename typelist, typename to_erase> struct erase; template <typename to_erase> struct erase<null_type, to_erase> { typedef null_type type; }; template <typename to_erase, typename tail> struct erase< typelist_t<to_erase, tail>, to_erase> { typedef tail type; }; template <typename head, typename tail, typename to_erase> struct erase< typelist_t<head, tail>, to_erase> { typedef typelist_t<head, typename erase<tail, to_erase>::type> type; }; // erase all types template <typename typelist, typename to_erase> struct erase_all; template <typename to_erase> struct erase_all<null_type, to_erase> { typedef null_type type; }; template <typename to_erase, typename tail> struct erase_all< typelist_t<to_erase, tail>, to_erase> { // Go all the way down the list removing the type typedef typename erase_all<tail, to_erase>::type type; }; template <typename head, typename tail, typename to_erase> struct erase_all< typelist_t<head, tail>, to_erase> { // Go all the way down the list removing the type typedef typelist_t<head, typename erase_all<tail, to_erase>::type> type; }; // no duplicate types template <typename typelist> struct no_duplicates; template <> struct no_duplicates<null_type> { typedef null_type type; }; template <typename head, typename tail> struct no_duplicates< typelist_t<head, tail> > { private: typedef typename no_duplicates<tail>::type L1; typedef typename erase<L1, head>::type L2; public: typedef typelist_t<head, L2> type; }; // replace the type at index by another type template <typename typelist, unsigned int index_to_replace, typename replaced> struct replace_at; template <unsigned int index_to_replace, typename replaced> struct replace_at<null_type, index_to_replace, replaced> { typedef null_type type; }; template <typename head, typename tail, typename replaced> struct replace_at<typelist_t<head, tail>, 0, replaced> { typedef typelist_t<replaced, tail> type; }; template <typename head, typename tail, unsigned int index_to_replace, typename replaced> struct replace_at<typelist_t<head, tail>, index_to_replace, replaced> { typedef typelist_t<head, typename replace_at<tail, index_to_replace-1, replaced>::type> type; }; // replace the first type by another type template <typename typelist, typename to_replace, typename replaced> struct replace; template <typename to_replace, typename replaced> struct replace<null_type, to_replace, replaced> { typedef null_type type; }; template <typename to_replace, typename tail, typename replaced> struct replace<typelist_t<to_replace, tail>, to_replace, replaced> { typedef typelist_t<replaced, tail> type; }; template <typename head, typename tail, typename to_replace, typename replaced> struct replace<typelist_t<head, tail>, to_replace, replaced> { typedef typelist_t<head, typename replace<tail, to_replace, replaced>::type> type; }; // replace all types by another type template <typename typelist, typename to_replace, typename replaced> struct replace_all; template <typename to_replace, typename replaced> struct replace_all<null_type, to_replace, replaced> { typedef null_type type; }; template <typename to_replace, typename tail, typename replaced> struct replace_all<typelist_t<to_replace, tail>, to_replace, replaced> { typedef typelist_t<replaced, typename replace_all<tail, to_replace, replaced>::type> type; }; template <typename head, typename tail, typename to_replace, typename replaced> struct replace_all<typelist_t<head, tail>, to_replace, replaced> { typedef typelist_t<head, typename replace_all<tail, to_replace, replaced>::type> type; }; } } } #endif // end file guardian <|endoftext|>
<commit_before>#ifndef VIENNAGRID_STORAGE_RANGE_HPP #define VIENNAGRID_STORAGE_RANGE_HPP namespace viennagrid { namespace storage { template<typename container_type> class container_range_wrapper { friend class container_range_wrapper<const container_type>; public: container_range_wrapper(container_type & _container) : container(_container) {} typedef typename container_type::size_type size_type; typedef typename container_type::value_type value_type; typedef typename container_type::reference reference; typedef typename container_type::const_reference const_reference; typedef typename container_type::pointer pointer; typedef typename container_type::const_pointer const_pointer; typedef typename container_type::iterator iterator; typedef typename container_type::const_iterator const_iterator; typedef typename container_type::reverse_iterator reverse_iterator; typedef typename container_type::const_reverse_iterator const_reverse_iterator; iterator begin() { return container.begin(); } const_iterator begin() const { return container.begin(); } iterator end() { return container.end(); } const_iterator end() const { return container.end(); } reverse_iterator rbegin() { return container.rbegin(); } const_reverse_iterator rbegin() const { return container.rbegin(); } reverse_iterator rend() { return container.rend(); } const_reverse_iterator rend() const { return container.rend(); } reference front() { return container.front(); } const_reference front() const { return container.front(); } reference back() { return container.back(); } const_reference back() const { return container.back(); } reference operator[] (size_type index) { return container[index]; } const_reference operator[] (size_type index) const { return container[index]; } bool empty() const { return container.empty(); } size_type size() const { return container.size(); } private: container_type & container; }; template<typename container_type> class container_range_wrapper<const container_type> { public: container_range_wrapper(const container_type & _container) : container(_container) {} container_range_wrapper(const container_range_wrapper<container_type> & rhs) : container(rhs.container) {} typedef typename container_type::size_type size_type; typedef typename container_type::value_type value_type; typedef typename container_type::const_reference reference; typedef typename container_type::const_reference const_reference; typedef typename container_type::const_pointer pointer; typedef typename container_type::const_pointer const_pointer; typedef typename container_type::const_iterator iterator; typedef typename container_type::const_iterator const_iterator; typedef typename container_type::const_reverse_iterator reverse_iterator; typedef typename container_type::const_reverse_iterator const_reverse_iterator; iterator begin() { return container.begin(); } const_iterator begin() const { return container.begin(); } iterator end() { return container.end(); } const_iterator end() const { return container.end(); } reverse_iterator rbegin() { return container.rbegin(); } const_reverse_iterator rbegin() const { return container.rbegin(); } reverse_iterator rend() { return container.rend(); } const_reverse_iterator rend() const { return container.rend(); } reference front() { return container.front(); } const_reference front() const { return container.front(); } reference back() { return container.back(); } const_reference back() const { return container.back(); } reference operator[] (size_type index) { return container[index]; } const_reference operator[] (size_type index) const { return container[index]; } bool empty() const { return container.empty(); } size_type size() const { return container.size(); } private: const container_type & container; }; template<typename iterator_type> class forward_iterator_range { public: forward_iterator_range(iterator_type _first, iterator_type _last) : first(_first), last(_last) {} typedef typename iterator_type::T value_type; typedef typename iterator_type::Reference reference; typedef const typename iterator_type::Reference const_reference; typedef typename iterator_type::Pointer pointer; typedef const typename iterator_type::Pointer const_pointer; typedef iterator_type iterator; typedef const iterator_type const_iterator; iterator begin() { return first; } const_iterator begin() const { return first; } iterator end() { return last; } const_iterator end() const { return last; } reference front() { return *first; } const_reference front() const { return *first; } reference back() { iterator_type tmp = last; return *(--tmp); } const_reference back() const { iterator_type tmp = last; return *(--tmp); } bool empty() const { return first == last; } private: iterator_type first; iterator_type last; }; } } #endif <commit_msg>added hook support for container_range_wrapper<commit_after>#ifndef VIENNAGRID_STORAGE_RANGE_HPP #define VIENNAGRID_STORAGE_RANGE_HPP namespace viennagrid { namespace storage { template<typename container_type> class container_range_wrapper { friend class container_range_wrapper<const container_type>; public: container_range_wrapper(container_type & _container) : container(_container) {} typedef typename container_type::size_type size_type; typedef typename container_type::value_type value_type; typedef typename container_type::reference reference; typedef typename container_type::const_reference const_reference; typedef typename container_type::pointer pointer; typedef typename container_type::const_pointer const_pointer; typedef typename container_type::iterator iterator; typedef typename container_type::const_iterator const_iterator; typedef typename container_type::reverse_iterator reverse_iterator; typedef typename container_type::const_reverse_iterator const_reverse_iterator; iterator begin() { return container.begin(); } const_iterator begin() const { return container.begin(); } iterator end() { return container.end(); } const_iterator end() const { return container.end(); } reverse_iterator rbegin() { return container.rbegin(); } const_reverse_iterator rbegin() const { return container.rbegin(); } reverse_iterator rend() { return container.rend(); } const_reverse_iterator rend() const { return container.rend(); } reference front() { return container.front(); } const_reference front() const { return container.front(); } reference back() { return container.back(); } const_reference back() const { return container.back(); } reference operator[] (size_type index) { return container[index]; } const_reference operator[] (size_type index) const { return container[index]; } bool empty() const { return container.empty(); } size_type size() const { return container.size(); } typedef typename container_type::hook_type hook_type; typedef typename container_type::hook_iterator hook_iterator; hook_iterator hook_begin() { return container.hook_begin(); } hook_iterator hook_end() { return container.hook_end(); } typedef typename container_type::const_hook_type const_hook_type; typedef typename container_type::const_hook_iterator const_hook_iterator; const_hook_iterator hook_begin() const { return container.hook_begin(); } const_hook_iterator hook_end() const { return container.hook_end(); } private: container_type & container; }; template<typename container_type> class container_range_wrapper<const container_type> { public: container_range_wrapper(const container_type & _container) : container(_container) {} container_range_wrapper(const container_range_wrapper<container_type> & rhs) : container(rhs.container) {} typedef typename container_type::size_type size_type; typedef typename container_type::value_type value_type; typedef typename container_type::const_reference reference; typedef typename container_type::const_reference const_reference; typedef typename container_type::const_pointer pointer; typedef typename container_type::const_pointer const_pointer; typedef typename container_type::const_iterator iterator; typedef typename container_type::const_iterator const_iterator; typedef typename container_type::const_reverse_iterator reverse_iterator; typedef typename container_type::const_reverse_iterator const_reverse_iterator; iterator begin() { return container.begin(); } const_iterator begin() const { return container.begin(); } iterator end() { return container.end(); } const_iterator end() const { return container.end(); } reverse_iterator rbegin() { return container.rbegin(); } const_reverse_iterator rbegin() const { return container.rbegin(); } reverse_iterator rend() { return container.rend(); } const_reverse_iterator rend() const { return container.rend(); } reference front() { return container.front(); } const_reference front() const { return container.front(); } reference back() { return container.back(); } const_reference back() const { return container.back(); } reference operator[] (size_type index) { return container[index]; } const_reference operator[] (size_type index) const { return container[index]; } bool empty() const { return container.empty(); } size_type size() const { return container.size(); } typedef typename container_type::const_hook_type hook_type; typedef typename container_type::const_hook_iterator hook_iterator; hook_iterator hook_begin() { return container.hook_begin(); } hook_iterator hook_end() { return container.hook_end(); } typedef typename container_type::const_hook_type const_hook_type; typedef typename container_type::const_hook_iterator const_hook_iterator; const_hook_iterator hook_begin() const { return container.hook_begin(); } const_hook_iterator hook_end() const { return container.hook_end(); } private: const container_type & container; }; template<typename iterator_type> class forward_iterator_range { public: forward_iterator_range(iterator_type _first, iterator_type _last) : first(_first), last(_last) {} typedef typename iterator_type::T value_type; typedef typename iterator_type::Reference reference; typedef const typename iterator_type::Reference const_reference; typedef typename iterator_type::Pointer pointer; typedef const typename iterator_type::Pointer const_pointer; typedef iterator_type iterator; typedef const iterator_type const_iterator; iterator begin() { return first; } const_iterator begin() const { return first; } iterator end() { return last; } const_iterator end() const { return last; } reference front() { return *first; } const_reference front() const { return *first; } reference back() { iterator_type tmp = last; return *(--tmp); } const_reference back() const { iterator_type tmp = last; return *(--tmp); } bool empty() const { return first == last; } private: iterator_type first; iterator_type last; }; } } #endif <|endoftext|>
<commit_before>/** * @file gmm_test.cpp * @author Ryan Curtin * * Test for the Gaussian Mixture Model class. */ #include <mlpack/core.h> #include <mlpack/methods/gmm/gmm.hpp> #include <mlpack/methods/gmm/phi.hpp> #include <boost/test/unit_test.hpp> using namespace mlpack; using namespace mlpack::gmm; BOOST_AUTO_TEST_SUITE(GMMTest); /** * Test the phi() function, in the univariate Gaussian case. */ BOOST_AUTO_TEST_CASE(UnivariatePhiTest) { // Simple case. BOOST_REQUIRE_CLOSE(phi(0.0, 0.0, 1.0), 0.398942280401433, 1e-5); // A few more cases... BOOST_REQUIRE_CLOSE(phi(0.0, 0.0, 2.0), 0.282094791773878, 1e-5); BOOST_REQUIRE_CLOSE(phi(1.0, 0.0, 1.0), 0.241970724519143, 1e-5); BOOST_REQUIRE_CLOSE(phi(-1.0, 0.0, 1.0), 0.241970724519143, 1e-5); BOOST_REQUIRE_CLOSE(phi(1.0, 0.0, 2.0), 0.219695644733861, 1e-5); BOOST_REQUIRE_CLOSE(phi(-1.0, 0.0, 2.0), 0.219695644733861, 1e-5); BOOST_REQUIRE_CLOSE(phi(1.0, 1.0, 1.0), 0.398942280401433, 1e-5); BOOST_REQUIRE_CLOSE(phi(-1.0, 1.0, 2.0), 0.103776874355149, 1e-5); } /** * Test the phi() function, in the multivariate Gaussian case. */ BOOST_AUTO_TEST_CASE(MultivariatePhiTest) { // Simple case. arma::vec mean = "0 0"; arma::mat cov = "1 0; 0 1"; arma::vec x = "0 0"; BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.159154943091895, 1e-5); cov = "2 0; 0 2"; BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.0795774715459477, 1e-5); x = "1 1"; BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.0482661763150270, 1e-5); BOOST_REQUIRE_CLOSE(phi(-x, mean, cov), 0.0482661763150270, 1e-5); mean = "1 1"; BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.0795774715459477, 1e-5); BOOST_REQUIRE_CLOSE(phi(-x, -mean, cov), 0.0795774715459477, 1e-5); cov = "2 1.5; 1 4"; BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.0624257046546403, 1e-5); BOOST_REQUIRE_CLOSE(phi(-x, -mean, cov), 0.0624257046546403, 1e-5); x = "-1 4"; BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.00144014867515135, 1e-5); BOOST_REQUIRE_CLOSE(phi(-x, mean, cov), 0.00133352162064845, 1e-5); // Higher-dimensional case. x = "0 1 2 3 4"; mean = "5 6 3 3 2"; cov = "6 1 1 0 2;" "0 7 1 0 1;" "1 1 4 1 1;" "1 0 1 7 0;" "2 0 1 1 6"; BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 1.02531207499358e-6, 1e-5); BOOST_REQUIRE_CLOSE(phi(-x, -mean, cov), 1.02531207499358e-6, 1e-5); BOOST_REQUIRE_CLOSE(phi(x, -mean, cov), 1.06784794079363e-8, 1e-5); BOOST_REQUIRE_CLOSE(phi(-x, mean, cov), 1.06784794079363e-8, 1e-5); } /** * Test the phi() function, for multiple points in the multivariate Gaussian * case. */ BOOST_AUTO_TEST_CASE(MultipointMultivariatePhiTest) { // Same case as before. arma::vec mean = "5 6 3 3 2"; arma::mat cov = "6 1 1 0 2; 0 7 1 0 1; 1 1 4 1 1; 1 0 1 7 0; 2 0 1 1 6"; arma::mat points = "0 3 2 2 3 4;" "1 2 2 1 0 0;" "2 3 0 5 5 6;" "3 7 8 0 1 1;" "4 8 1 1 0 0;"; arma::vec phis; phi(points, mean, cov, phis); BOOST_REQUIRE_EQUAL(phis.n_elem, 6); BOOST_REQUIRE_CLOSE(phis(0), 1.02531207499358e-6, 1e-5); BOOST_REQUIRE_CLOSE(phis(1), 1.82353695848039e-7, 1e-5); BOOST_REQUIRE_CLOSE(phis(2), 1.29759261892949e-6, 1e-5); BOOST_REQUIRE_CLOSE(phis(3), 1.33218060268258e-6, 1e-5); BOOST_REQUIRE_CLOSE(phis(4), 1.12120427975708e-6, 1e-5); BOOST_REQUIRE_CLOSE(phis(5), 4.57951032485297e-7, 1e-5); } /** * Test training a model on only one Gaussian (randomly generated) in two * dimensions. We will vary the dataset size from small to large. The EM * algorithm is used for training the GMM. */ BOOST_AUTO_TEST_CASE(GMMTrainEMOneGaussian) { // Initialize random seed. srand(time(NULL)); for (size_t iterations = 0; iterations < 4; iterations++) { // Determine random covariance and mean. arma::vec mean; mean.randu(2); arma::vec covar; covar.randu(2); arma::mat data; data.randn(2 /* dimension */, 100 * pow(10, (iterations / 3.0))); // Now apply mean and covariance. data.row(0) *= covar(0); data.row(1) *= covar(1); data.row(0) += mean(0); data.row(1) += mean(1); // Now, train the model. GMM gmm(1, 2); gmm.ExpectationMaximization(data); arma::vec actual_mean = arma::mean(data, 1); arma::mat actual_covar = ccov(data, 1 /* biased estimator */); // Check the model to see that it is correct. BOOST_REQUIRE_CLOSE((gmm.Means()[0])[0], actual_mean(0), 1e-5); BOOST_REQUIRE_CLOSE((gmm.Means()[0])[1], actual_mean(1), 1e-5); BOOST_REQUIRE_CLOSE((gmm.Covariances()[0])(0, 0), actual_covar(0, 0), 1e-5); BOOST_REQUIRE_CLOSE((gmm.Covariances()[0])(0, 1), actual_covar(0, 1), 1e-5); BOOST_REQUIRE_CLOSE((gmm.Covariances()[0])(1, 0), actual_covar(1, 0), 1e-5); BOOST_REQUIRE_CLOSE((gmm.Covariances()[0])(1, 1), actual_covar(1, 1), 1e-5); BOOST_REQUIRE_CLOSE(gmm.Weights()[0], 1.0, 1e-5); } } /** * Test a training model on multiple Gaussians in higher dimensionality than * two. We will hold the dataset size constant at 10k points. The EM algorithm * is used for training the GMM. */ BOOST_AUTO_TEST_CASE(GMMTrainEMMultipleGaussians) { // Higher dimensionality gives us a greater chance of having separated // Gaussians. size_t dims = 8; size_t gaussians = 3; // Generate dataset. arma::mat data; data.zeros(dims, 500); std::vector<arma::vec> means(gaussians); std::vector<arma::mat> covars(gaussians); arma::vec weights(gaussians); arma::Col<size_t> counts(gaussians); // Choose weights randomly. weights.zeros(); while (weights.min() < 0.02) { weights.randu(gaussians); weights /= accu(weights); } for (size_t i = 0; i < gaussians; i++) counts[i] = round(weights[i] * (data.n_cols - gaussians)); // Ensure one point minimum in each. counts += 1; // Account for rounding errors (possibly necessary). counts[gaussians - 1] += (data.n_cols - arma::accu(counts)); // Build each Gaussian individually. size_t point = 0; for (int i = 0; i < gaussians; i++) { arma::mat gaussian; gaussian.randn(dims, counts[i]); // Randomly generate mean and covariance. means[i].randu(dims); means[i] -= 0.5; means[i] *= 50; covars[i].randu(dims, dims); covars[i] *= 2; data.cols(point, point + counts[i] - 1) = (covars[i] * gaussian + means[i] * arma::ones<arma::rowvec>(counts[i])); // Calculate the actual means and covariances because they will probably // be different (this is easier to do before we shuffle the points). means[i] = arma::mean(data.cols(point, point + counts[i] - 1), 1); covars[i] = ccov(data.cols(point, point + counts[i] - 1), 1 /* biased */); point += counts[i]; } // Calculate actual weights. for (size_t i = 0; i < gaussians; i++) weights[i] = (double) counts[i] / data.n_cols; // Now train the model. GMM gmm(gaussians, dims); gmm.ExpectationMaximization(data); arma::uvec sort_ref = sort_index(weights); arma::uvec sort_try = sort_index(gmm.Weights()); // Check the model to see that it is correct. for (int i = 0; i < gaussians; i++) { // Check the mean. for (int j = 0; j < dims; j++) BOOST_REQUIRE_CLOSE((gmm.Means()[sort_try[i]])[j], (means[sort_ref[i]])[j], 1e-5); // Check the covariance. for (int row = 0; row < dims; row++) for (int col = 0; col < dims; col++) BOOST_REQUIRE_CLOSE((gmm.Covariances()[sort_try[i]])(row, col), (covars[sort_ref[i]])(row, col), 1e-5); // Check the weight. BOOST_REQUIRE_CLOSE(gmm.Weights()[sort_try[i]], weights[sort_ref[i]], 1e-5); } } BOOST_AUTO_TEST_SUITE_END(); <commit_msg>Fix some warnings I inadvertently introduced.<commit_after>/** * @file gmm_test.cpp * @author Ryan Curtin * * Test for the Gaussian Mixture Model class. */ #include <mlpack/core.h> #include <mlpack/methods/gmm/gmm.hpp> #include <mlpack/methods/gmm/phi.hpp> #include <boost/test/unit_test.hpp> using namespace mlpack; using namespace mlpack::gmm; BOOST_AUTO_TEST_SUITE(GMMTest); /** * Test the phi() function, in the univariate Gaussian case. */ BOOST_AUTO_TEST_CASE(UnivariatePhiTest) { // Simple case. BOOST_REQUIRE_CLOSE(phi(0.0, 0.0, 1.0), 0.398942280401433, 1e-5); // A few more cases... BOOST_REQUIRE_CLOSE(phi(0.0, 0.0, 2.0), 0.282094791773878, 1e-5); BOOST_REQUIRE_CLOSE(phi(1.0, 0.0, 1.0), 0.241970724519143, 1e-5); BOOST_REQUIRE_CLOSE(phi(-1.0, 0.0, 1.0), 0.241970724519143, 1e-5); BOOST_REQUIRE_CLOSE(phi(1.0, 0.0, 2.0), 0.219695644733861, 1e-5); BOOST_REQUIRE_CLOSE(phi(-1.0, 0.0, 2.0), 0.219695644733861, 1e-5); BOOST_REQUIRE_CLOSE(phi(1.0, 1.0, 1.0), 0.398942280401433, 1e-5); BOOST_REQUIRE_CLOSE(phi(-1.0, 1.0, 2.0), 0.103776874355149, 1e-5); } /** * Test the phi() function, in the multivariate Gaussian case. */ BOOST_AUTO_TEST_CASE(MultivariatePhiTest) { // Simple case. arma::vec mean = "0 0"; arma::mat cov = "1 0; 0 1"; arma::vec x = "0 0"; BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.159154943091895, 1e-5); cov = "2 0; 0 2"; BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.0795774715459477, 1e-5); x = "1 1"; BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.0482661763150270, 1e-5); BOOST_REQUIRE_CLOSE(phi(-x, mean, cov), 0.0482661763150270, 1e-5); mean = "1 1"; BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.0795774715459477, 1e-5); BOOST_REQUIRE_CLOSE(phi(-x, -mean, cov), 0.0795774715459477, 1e-5); cov = "2 1.5; 1 4"; BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.0624257046546403, 1e-5); BOOST_REQUIRE_CLOSE(phi(-x, -mean, cov), 0.0624257046546403, 1e-5); x = "-1 4"; BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 0.00144014867515135, 1e-5); BOOST_REQUIRE_CLOSE(phi(-x, mean, cov), 0.00133352162064845, 1e-5); // Higher-dimensional case. x = "0 1 2 3 4"; mean = "5 6 3 3 2"; cov = "6 1 1 0 2;" "0 7 1 0 1;" "1 1 4 1 1;" "1 0 1 7 0;" "2 0 1 1 6"; BOOST_REQUIRE_CLOSE(phi(x, mean, cov), 1.02531207499358e-6, 1e-5); BOOST_REQUIRE_CLOSE(phi(-x, -mean, cov), 1.02531207499358e-6, 1e-5); BOOST_REQUIRE_CLOSE(phi(x, -mean, cov), 1.06784794079363e-8, 1e-5); BOOST_REQUIRE_CLOSE(phi(-x, mean, cov), 1.06784794079363e-8, 1e-5); } /** * Test the phi() function, for multiple points in the multivariate Gaussian * case. */ BOOST_AUTO_TEST_CASE(MultipointMultivariatePhiTest) { // Same case as before. arma::vec mean = "5 6 3 3 2"; arma::mat cov = "6 1 1 0 2; 0 7 1 0 1; 1 1 4 1 1; 1 0 1 7 0; 2 0 1 1 6"; arma::mat points = "0 3 2 2 3 4;" "1 2 2 1 0 0;" "2 3 0 5 5 6;" "3 7 8 0 1 1;" "4 8 1 1 0 0;"; arma::vec phis; phi(points, mean, cov, phis); BOOST_REQUIRE_EQUAL(phis.n_elem, 6); BOOST_REQUIRE_CLOSE(phis(0), 1.02531207499358e-6, 1e-5); BOOST_REQUIRE_CLOSE(phis(1), 1.82353695848039e-7, 1e-5); BOOST_REQUIRE_CLOSE(phis(2), 1.29759261892949e-6, 1e-5); BOOST_REQUIRE_CLOSE(phis(3), 1.33218060268258e-6, 1e-5); BOOST_REQUIRE_CLOSE(phis(4), 1.12120427975708e-6, 1e-5); BOOST_REQUIRE_CLOSE(phis(5), 4.57951032485297e-7, 1e-5); } /** * Test training a model on only one Gaussian (randomly generated) in two * dimensions. We will vary the dataset size from small to large. The EM * algorithm is used for training the GMM. */ BOOST_AUTO_TEST_CASE(GMMTrainEMOneGaussian) { // Initialize random seed. srand(time(NULL)); for (size_t iterations = 0; iterations < 4; iterations++) { // Determine random covariance and mean. arma::vec mean; mean.randu(2); arma::vec covar; covar.randu(2); arma::mat data; data.randn(2 /* dimension */, 100 * pow(10, (iterations / 3.0))); // Now apply mean and covariance. data.row(0) *= covar(0); data.row(1) *= covar(1); data.row(0) += mean(0); data.row(1) += mean(1); // Now, train the model. GMM gmm(1, 2); gmm.ExpectationMaximization(data); arma::vec actual_mean = arma::mean(data, 1); arma::mat actual_covar = ccov(data, 1 /* biased estimator */); // Check the model to see that it is correct. BOOST_REQUIRE_CLOSE((gmm.Means()[0])[0], actual_mean(0), 1e-5); BOOST_REQUIRE_CLOSE((gmm.Means()[0])[1], actual_mean(1), 1e-5); BOOST_REQUIRE_CLOSE((gmm.Covariances()[0])(0, 0), actual_covar(0, 0), 1e-5); BOOST_REQUIRE_CLOSE((gmm.Covariances()[0])(0, 1), actual_covar(0, 1), 1e-5); BOOST_REQUIRE_CLOSE((gmm.Covariances()[0])(1, 0), actual_covar(1, 0), 1e-5); BOOST_REQUIRE_CLOSE((gmm.Covariances()[0])(1, 1), actual_covar(1, 1), 1e-5); BOOST_REQUIRE_CLOSE(gmm.Weights()[0], 1.0, 1e-5); } } /** * Test a training model on multiple Gaussians in higher dimensionality than * two. We will hold the dataset size constant at 10k points. The EM algorithm * is used for training the GMM. */ BOOST_AUTO_TEST_CASE(GMMTrainEMMultipleGaussians) { // Higher dimensionality gives us a greater chance of having separated // Gaussians. size_t dims = 8; size_t gaussians = 3; // Generate dataset. arma::mat data; data.zeros(dims, 500); std::vector<arma::vec> means(gaussians); std::vector<arma::mat> covars(gaussians); arma::vec weights(gaussians); arma::Col<size_t> counts(gaussians); // Choose weights randomly. weights.zeros(); while (weights.min() < 0.02) { weights.randu(gaussians); weights /= accu(weights); } for (size_t i = 0; i < gaussians; i++) counts[i] = round(weights[i] * (data.n_cols - gaussians)); // Ensure one point minimum in each. counts += 1; // Account for rounding errors (possibly necessary). counts[gaussians - 1] += (data.n_cols - arma::accu(counts)); // Build each Gaussian individually. size_t point = 0; for (size_t i = 0; i < gaussians; i++) { arma::mat gaussian; gaussian.randn(dims, counts[i]); // Randomly generate mean and covariance. means[i].randu(dims); means[i] -= 0.5; means[i] *= 50; covars[i].randu(dims, dims); covars[i] *= 2; data.cols(point, point + counts[i] - 1) = (covars[i] * gaussian + means[i] * arma::ones<arma::rowvec>(counts[i])); // Calculate the actual means and covariances because they will probably // be different (this is easier to do before we shuffle the points). means[i] = arma::mean(data.cols(point, point + counts[i] - 1), 1); covars[i] = ccov(data.cols(point, point + counts[i] - 1), 1 /* biased */); point += counts[i]; } // Calculate actual weights. for (size_t i = 0; i < gaussians; i++) weights[i] = (double) counts[i] / data.n_cols; // Now train the model. GMM gmm(gaussians, dims); gmm.ExpectationMaximization(data); arma::uvec sort_ref = sort_index(weights); arma::uvec sort_try = sort_index(gmm.Weights()); // Check the model to see that it is correct. for (size_t i = 0; i < gaussians; i++) { // Check the mean. for (size_t j = 0; j < dims; j++) BOOST_REQUIRE_CLOSE((gmm.Means()[sort_try[i]])[j], (means[sort_ref[i]])[j], 1e-5); // Check the covariance. for (size_t row = 0; row < dims; row++) for (size_t col = 0; col < dims; col++) BOOST_REQUIRE_CLOSE((gmm.Covariances()[sort_try[i]])(row, col), (covars[sort_ref[i]])(row, col), 1e-5); // Check the weight. BOOST_REQUIRE_CLOSE(gmm.Weights()[sort_try[i]], weights[sort_ref[i]], 1e-5); } } BOOST_AUTO_TEST_SUITE_END(); <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2013-2014 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file navigator_rtl.cpp * Helper class to access RTL * @author Julian Oes <julian@oes.ch> * @author Anton Babushkin <anton.babushkin@me.com> */ #include <string.h> #include <stdlib.h> #include <math.h> #include <fcntl.h> #include <mavlink/mavlink_log.h> #include <systemlib/err.h> #include <uORB/uORB.h> #include <uORB/topics/mission.h> #include <uORB/topics/home_position.h> #include "navigator.h" #include "rtl.h" RTL::RTL(Navigator *navigator, const char *name) : NavigatorMode(navigator, name), MissionBlock(navigator), _rtl_state(RTL_STATE_NONE), _param_return_alt(this, "RETURN_ALT"), _param_descend_alt(this, "DESCEND_ALT"), _param_land_delay(this, "LAND_DELAY"), _param_acceptance_radius(this, "ACCEPT_RAD") { /* load initial params */ updateParams(); /* initial reset */ on_inactive(); } RTL::~RTL() { } void RTL::on_inactive() { _first_run = true; _rtl_state = RTL_STATE_NONE; } bool RTL::on_active(struct position_setpoint_triplet_s *pos_sp_triplet) { bool updated = false; if (_first_run) { set_rtl_item(pos_sp_triplet); updated = true; _first_run = false; } if ((_rtl_state == RTL_STATE_CLIMB || _rtl_state == RTL_STATE_RETURN) && is_mission_item_reached()) { advance_rtl(); set_rtl_item(pos_sp_triplet); updated = true; } return updated; } void RTL::set_rtl_item(position_setpoint_triplet_s *pos_sp_triplet) { /* make sure we have the latest params */ updateParams(); /* decide where to enter the RTL procedure when we switch into it */ if (_rtl_state == RTL_STATE_NONE) { /* for safety reasons don't go into RTL if landed */ if (_navigator->get_vstatus()->condition_landed) { _rtl_state = RTL_STATE_FINISHED; mavlink_log_info(_navigator->get_mavlink_fd(), "#audio: no RTL when landed"); /* if lower than return altitude, climb up first */ } else if (_navigator->get_global_position()->alt < _navigator->get_home_position()->alt + _param_return_alt.get()) { _rtl_state = RTL_STATE_CLIMB; /* otherwise go straight to return */ } else { _rtl_state = RTL_STATE_RETURN; } } /* if switching directly to return state, set altitude setpoint to current altitude */ if (_rtl_state == RTL_STATE_RETURN) { _mission_item.altitude_is_relative = false; _mission_item.altitude = _navigator->get_global_position()->alt; } switch (_rtl_state) { case RTL_STATE_CLIMB: { float climb_alt = _navigator->get_home_position()->alt + _param_return_alt.get(); _mission_item.lat = _navigator->get_global_position()->lat; _mission_item.lon = _navigator->get_global_position()->lon; _mission_item.altitude_is_relative = false; _mission_item.altitude = climb_alt; _mission_item.yaw = NAN; _mission_item.loiter_radius = _navigator->get_loiter_radius(); _mission_item.loiter_direction = 1; _mission_item.nav_cmd = NAV_CMD_WAYPOINT; _mission_item.acceptance_radius = _param_acceptance_radius.get(); _mission_item.time_inside = 0.0f; _mission_item.pitch_min = 0.0f; _mission_item.autocontinue = true; _mission_item.origin = ORIGIN_ONBOARD; _navigator->set_is_in_loiter(false); mavlink_log_info(_navigator->get_mavlink_fd(), "#audio: RTL: climb to %d meters above home", (int)(climb_alt - _navigator->get_home_position()->alt)); break; } case RTL_STATE_RETURN: { _mission_item.lat = _navigator->get_home_position()->lat; _mission_item.lon = _navigator->get_home_position()->lon; /* TODO: add this again */ // don't change altitude // if (_pos_sp_triplet.previous.valid) { // /* if previous setpoint is valid then use it to calculate heading to home */ // _mission_item.yaw = get_bearing_to_next_waypoint(_pos_sp_triplet.previous.lat, _pos_sp_triplet.previous.lon, _mission_item.lat, _mission_item.lon); // } else { // /* else use current position */ // _mission_item.yaw = get_bearing_to_next_waypoint(_global_pos.lat, _global_pos.lon, _mission_item.lat, _mission_item.lon); // } _mission_item.loiter_radius = _navigator->get_loiter_radius(); _mission_item.loiter_direction = 1; _mission_item.nav_cmd = NAV_CMD_WAYPOINT; _mission_item.acceptance_radius = _param_acceptance_radius.get(); _mission_item.time_inside = 0.0f; _mission_item.pitch_min = 0.0f; _mission_item.autocontinue = true; _mission_item.origin = ORIGIN_ONBOARD; _navigator->set_is_in_loiter(false); mavlink_log_info(_navigator->get_mavlink_fd(), "#audio: RTL: return at %d meters above home", (int)(_mission_item.altitude - _navigator->get_home_position()->alt)); break; } case RTL_STATE_DESCEND: { _mission_item.lat = _navigator->get_home_position()->lat; _mission_item.lon = _navigator->get_home_position()->lon; _mission_item.altitude_is_relative = false; _mission_item.altitude = _navigator->get_home_position()->alt + _param_descend_alt.get(); _mission_item.yaw = NAN; _mission_item.loiter_radius = _navigator->get_loiter_radius(); _mission_item.loiter_direction = 1; _mission_item.nav_cmd = NAV_CMD_LOITER_TIME_LIMIT; _mission_item.acceptance_radius = _param_acceptance_radius.get(); _mission_item.time_inside = _param_land_delay.get() < 0.0f ? 0.0f : _param_land_delay.get(); _mission_item.pitch_min = 0.0f; _mission_item.autocontinue = _param_land_delay.get() > -0.001f; _mission_item.origin = ORIGIN_ONBOARD; _navigator->set_is_in_loiter(true); mavlink_log_info(_navigator->get_mavlink_fd(), "#audio: RTL: descend to %d meters above home", (int)(_mission_item.altitude - _navigator->get_home_position()->alt)); break; } case RTL_STATE_LAND: { _mission_item.lat = _navigator->get_home_position()->lat; _mission_item.lon = _navigator->get_home_position()->lon; _mission_item.altitude_is_relative = false; _mission_item.altitude = _navigator->get_home_position()->alt; _mission_item.yaw = NAN; _mission_item.loiter_radius = _navigator->get_loiter_radius(); _mission_item.loiter_direction = 1; _mission_item.nav_cmd = NAV_CMD_LAND; _mission_item.acceptance_radius = _param_acceptance_radius.get(); _mission_item.time_inside = 0.0f; _mission_item.pitch_min = 0.0f; _mission_item.autocontinue = true; _mission_item.origin = ORIGIN_ONBOARD; _navigator->set_is_in_loiter(false); mavlink_log_info(_navigator->get_mavlink_fd(), "#audio: RTL: land at home"); break; } case RTL_STATE_FINISHED: { /* nothing to do, report fail */ } default: break; } if (_rtl_state == RTL_STATE_FINISHED) { pos_sp_triplet->current.valid = false; pos_sp_triplet->next.valid = false; } else { /* if not finished, convert mission item to current position setpoint and make it valid */ mission_item_to_position_setpoint(&_mission_item, &pos_sp_triplet->current); reset_mission_item_reached(); pos_sp_triplet->current.valid = true; pos_sp_triplet->next.valid = false; } } void RTL::advance_rtl() { switch (_rtl_state) { case RTL_STATE_CLIMB: _rtl_state = RTL_STATE_RETURN; break; case RTL_STATE_RETURN: _rtl_state = RTL_STATE_DESCEND; break; case RTL_STATE_DESCEND: /* only go to land if autoland is enabled */ if (_param_land_delay.get() < 0) { _rtl_state = RTL_STATE_FINISHED; } else { _rtl_state = RTL_STATE_LAND; } break; case RTL_STATE_LAND: _rtl_state = RTL_STATE_FINISHED; break; case RTL_STATE_FINISHED: break; default: break; } } <commit_msg>navigator: RTL return altitude fixed<commit_after>/**************************************************************************** * * Copyright (c) 2013-2014 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file navigator_rtl.cpp * Helper class to access RTL * @author Julian Oes <julian@oes.ch> * @author Anton Babushkin <anton.babushkin@me.com> */ #include <string.h> #include <stdlib.h> #include <math.h> #include <fcntl.h> #include <mavlink/mavlink_log.h> #include <systemlib/err.h> #include <geo/geo.h> #include <uORB/uORB.h> #include <uORB/topics/mission.h> #include <uORB/topics/home_position.h> #include "navigator.h" #include "rtl.h" RTL::RTL(Navigator *navigator, const char *name) : NavigatorMode(navigator, name), MissionBlock(navigator), _rtl_state(RTL_STATE_NONE), _param_return_alt(this, "RETURN_ALT"), _param_descend_alt(this, "DESCEND_ALT"), _param_land_delay(this, "LAND_DELAY"), _param_acceptance_radius(this, "ACCEPT_RAD") { /* load initial params */ updateParams(); /* initial reset */ on_inactive(); } RTL::~RTL() { } void RTL::on_inactive() { _first_run = true; _rtl_state = RTL_STATE_NONE; } bool RTL::on_active(struct position_setpoint_triplet_s *pos_sp_triplet) { bool updated = false; if (_first_run) { set_rtl_item(pos_sp_triplet); updated = true; _first_run = false; } if ((_rtl_state == RTL_STATE_CLIMB || _rtl_state == RTL_STATE_RETURN) && is_mission_item_reached()) { advance_rtl(); set_rtl_item(pos_sp_triplet); updated = true; } return updated; } void RTL::set_rtl_item(position_setpoint_triplet_s *pos_sp_triplet) { /* make sure we have the latest params */ updateParams(); /* decide where to enter the RTL procedure when we switch into it */ if (_rtl_state == RTL_STATE_NONE) { /* for safety reasons don't go into RTL if landed */ if (_navigator->get_vstatus()->condition_landed) { _rtl_state = RTL_STATE_FINISHED; mavlink_log_info(_navigator->get_mavlink_fd(), "#audio: no RTL when landed"); /* if lower than return altitude, climb up first */ } else if (_navigator->get_global_position()->alt < _navigator->get_home_position()->alt + _param_return_alt.get()) { _rtl_state = RTL_STATE_CLIMB; /* otherwise go straight to return */ } else { /* set altitude setpoint to current altitude */ _rtl_state = RTL_STATE_RETURN; _mission_item.altitude_is_relative = false; _mission_item.altitude = _navigator->get_global_position()->alt; } } if (_rtl_state == RTL_STATE_FINISHED) { /* RTL finished, nothing to do */ pos_sp_triplet->current.valid = false; pos_sp_triplet->next.valid = false; return; } set_previous_pos_setpoint(pos_sp_triplet); switch (_rtl_state) { case RTL_STATE_CLIMB: { float climb_alt = _navigator->get_home_position()->alt + _param_return_alt.get(); _mission_item.lat = _navigator->get_global_position()->lat; _mission_item.lon = _navigator->get_global_position()->lon; _mission_item.altitude_is_relative = false; _mission_item.altitude = climb_alt; _mission_item.yaw = NAN; _mission_item.loiter_radius = _navigator->get_loiter_radius(); _mission_item.loiter_direction = 1; _mission_item.nav_cmd = NAV_CMD_WAYPOINT; _mission_item.acceptance_radius = _param_acceptance_radius.get(); _mission_item.time_inside = 0.0f; _mission_item.pitch_min = 0.0f; _mission_item.autocontinue = true; _mission_item.origin = ORIGIN_ONBOARD; _navigator->set_is_in_loiter(false); mavlink_log_info(_navigator->get_mavlink_fd(), "#audio: RTL: climb to %d meters above home", (int)(climb_alt - _navigator->get_home_position()->alt)); break; } case RTL_STATE_RETURN: { _mission_item.lat = _navigator->get_home_position()->lat; _mission_item.lon = _navigator->get_home_position()->lon; // don't change altitude if (pos_sp_triplet->previous.valid) { /* if previous setpoint is valid then use it to calculate heading to home */ _mission_item.yaw = get_bearing_to_next_waypoint( pos_sp_triplet->previous.lat, pos_sp_triplet->previous.lon, _mission_item.lat, _mission_item.lon); } else { /* else use current position */ _mission_item.yaw = get_bearing_to_next_waypoint( _navigator->get_global_position()->lat, _navigator->get_global_position()->lon, _mission_item.lat, _mission_item.lon); } _mission_item.loiter_radius = _navigator->get_loiter_radius(); _mission_item.loiter_direction = 1; _mission_item.nav_cmd = NAV_CMD_WAYPOINT; _mission_item.acceptance_radius = _param_acceptance_radius.get(); _mission_item.time_inside = 0.0f; _mission_item.pitch_min = 0.0f; _mission_item.autocontinue = true; _mission_item.origin = ORIGIN_ONBOARD; _navigator->set_is_in_loiter(false); mavlink_log_info(_navigator->get_mavlink_fd(), "#audio: RTL: return at %d meters above home", (int)(_mission_item.altitude - _navigator->get_home_position()->alt)); break; } case RTL_STATE_DESCEND: { _mission_item.lat = _navigator->get_home_position()->lat; _mission_item.lon = _navigator->get_home_position()->lon; _mission_item.altitude_is_relative = false; _mission_item.altitude = _navigator->get_home_position()->alt + _param_descend_alt.get(); _mission_item.yaw = NAN; _mission_item.loiter_radius = _navigator->get_loiter_radius(); _mission_item.loiter_direction = 1; _mission_item.nav_cmd = NAV_CMD_LOITER_TIME_LIMIT; _mission_item.acceptance_radius = _param_acceptance_radius.get(); _mission_item.time_inside = _param_land_delay.get() < 0.0f ? 0.0f : _param_land_delay.get(); _mission_item.pitch_min = 0.0f; _mission_item.autocontinue = _param_land_delay.get() > -0.001f; _mission_item.origin = ORIGIN_ONBOARD; _navigator->set_is_in_loiter(true); mavlink_log_info(_navigator->get_mavlink_fd(), "#audio: RTL: descend to %d meters above home", (int)(_mission_item.altitude - _navigator->get_home_position()->alt)); break; } case RTL_STATE_LAND: { _mission_item.lat = _navigator->get_home_position()->lat; _mission_item.lon = _navigator->get_home_position()->lon; _mission_item.altitude_is_relative = false; _mission_item.altitude = _navigator->get_home_position()->alt; _mission_item.yaw = NAN; _mission_item.loiter_radius = _navigator->get_loiter_radius(); _mission_item.loiter_direction = 1; _mission_item.nav_cmd = NAV_CMD_LAND; _mission_item.acceptance_radius = _param_acceptance_radius.get(); _mission_item.time_inside = 0.0f; _mission_item.pitch_min = 0.0f; _mission_item.autocontinue = true; _mission_item.origin = ORIGIN_ONBOARD; _navigator->set_is_in_loiter(false); mavlink_log_info(_navigator->get_mavlink_fd(), "#audio: RTL: land at home"); break; } default: break; } /* convert mission item to current position setpoint and make it valid */ mission_item_to_position_setpoint(&_mission_item, &pos_sp_triplet->current); reset_mission_item_reached(); pos_sp_triplet->current.valid = true; pos_sp_triplet->next.valid = false; } void RTL::advance_rtl() { switch (_rtl_state) { case RTL_STATE_CLIMB: _rtl_state = RTL_STATE_RETURN; break; case RTL_STATE_RETURN: _rtl_state = RTL_STATE_DESCEND; break; case RTL_STATE_DESCEND: /* only go to land if autoland is enabled */ if (_param_land_delay.get() < 0) { _rtl_state = RTL_STATE_FINISHED; } else { _rtl_state = RTL_STATE_LAND; } break; case RTL_STATE_LAND: _rtl_state = RTL_STATE_FINISHED; break; case RTL_STATE_FINISHED: break; default: break; } } <|endoftext|>
<commit_before>/// // // LibSourcey // Copyright (c) 2005, Sourcey <http://sourcey.com> // // SPDX-License-Identifier: LGPL-2.1+ // /// @addtogroup net /// @{ #include "scy/net/socketadapter.h" #include "scy/net/socket.h" #include <iterator> using std::endl; namespace scy { namespace net { SocketAdapter::SocketAdapter(SocketAdapter* sender) : priority(0) , _sender(sender) , _dirty(false) { // TraceS(this) << "Create" << endl; assert(sender != this); } SocketAdapter::~SocketAdapter() { // TraceS(this) << "Destroy" << endl; // assert(_receivers.empty()); } ssize_t SocketAdapter::send(const char* data, size_t len, int flags) { assert(_sender); // should have output adapter if default impl is used if (!_sender) return -1; return _sender->send(data, len, flags); } ssize_t SocketAdapter::send(const char* data, size_t len, const Address& peerAddress, int flags) { assert(_sender); // should have output adapter if default impl is used if (!_sender) return -1; return _sender->send(data, len, peerAddress, flags); } ssize_t SocketAdapter::sendPacket(const IPacket& packet, int flags) { // Try to cast as RawPacket so we can send without copying any data. auto raw = dynamic_cast<const RawPacket*>(&packet); if (raw) return send((const char*)raw->data(), raw->size(), flags); // Dynamically generated packets need to be written to a // temp buffer for sending. else { Buffer buf; packet.write(buf); return send(buf.data(), buf.size(), flags); } } ssize_t SocketAdapter::sendPacket(const IPacket& packet, const Address& peerAddress, int flags) { // Try to cast as RawPacket so we can send without copying any data. auto raw = dynamic_cast<const RawPacket*>(&packet); if (raw) return send((const char*)raw->data(), raw->size(), peerAddress, flags); // Dynamically generated packets need to be written to a // temp buffer for sending. else { Buffer buf; buf.reserve(2048); packet.write(buf); return send(buf.data(), buf.size(), peerAddress, flags); } } void SocketAdapter::sendPacket(IPacket& packet) { size_t res = sendPacket(packet, 0); if (res < 0) throw std::runtime_error("Invalid socket operation"); } void SocketAdapter::onSocketConnect(Socket& socket) { try { cleanupReceivers(); size_t current = _receivers.size() - 1; while (current >= 0) { auto ref = _receivers[current--]; if (ref->alive) ref->ptr->onSocketConnect(socket); } } catch (StopPropagation&) { } } void SocketAdapter::onSocketRecv(Socket& socket, const MutableBuffer& buffer, const Address& peerAddress) { try { cleanupReceivers(); size_t current = _receivers.size() - 1; while (current >= 0) { auto ref = _receivers[current--]; if (ref->alive) ref->ptr->onSocketRecv(socket, buffer, peerAddress); } } catch (StopPropagation&) { } } void SocketAdapter::onSocketError(Socket& socket, const scy::Error& error) { try { cleanupReceivers(); size_t current = _receivers.size() - 1; while (current >= 0) { auto ref = _receivers[current--]; if (ref->alive) ref->ptr->onSocketError(socket, error); } } catch (StopPropagation&) { } } void SocketAdapter::onSocketClose(Socket& socket) { try { cleanupReceivers(); size_t current = _receivers.size() - 1; while (current >= 0) { auto ref = _receivers[current--]; if (ref->alive) { ref->ptr->onSocketClose(socket); } } } catch (StopPropagation&) { } } void SocketAdapter::setSender(SocketAdapter* adapter) { assert(adapter != this); if (_sender == adapter) return; _sender = adapter; } bool SocketAdapter::hasReceiver(SocketAdapter* adapter) { for (auto& receiver : _receivers) { if (receiver->ptr == adapter) return true; } return false; } void SocketAdapter::addReceiver(SocketAdapter* adapter) { assert(adapter->priority <= 100); assert(adapter != this); if (hasReceiver(adapter)) return; // Note that we insert new adapters in the back of the queue, // and iterate in reverse to ensure calling order is preserved. _dirty = true; _receivers.push_back(new Ref{ adapter, true }); // _receivers.insert(_receivers.begin(), new Ref{ adapter, false }); // insert front // std::sort(_receivers.begin(), _receivers.end(), // [](SocketAdapter const& l, SocketAdapter const& r) { // return l.priority > r.priority; }); } void SocketAdapter::removeReceiver(SocketAdapter* adapter) { assert(adapter != this); auto it = std::find_if(_receivers.begin(), _receivers.end(), [&](const Ref* ref) { return ref->ptr == adapter; }); if (it != _receivers.end()) { (*it)->alive = false; } } void SocketAdapter::cleanupReceivers() { if (!_dirty) return; for (auto it = _receivers.begin(); it != _receivers.end();) { auto ref = *it; if (!ref->alive) { delete ref; it = _receivers.erase(it); } else ++it; } _dirty = false; } SocketAdapter* SocketAdapter::sender() { return _sender; } std::vector<SocketAdapter*> SocketAdapter::receivers() { std::vector<SocketAdapter*> items; std::transform(_receivers.begin(), _receivers.end(), std::back_inserter(items), [](const Ref* ref) { return ref->ptr; }); return items; } } // namespace net } // namespace scy /// @\} <commit_msg>Update the use of signed/unsigned integers<commit_after>/// // // LibSourcey // Copyright (c) 2005, Sourcey <http://sourcey.com> // // SPDX-License-Identifier: LGPL-2.1+ // /// @addtogroup net /// @{ #include "scy/net/socketadapter.h" #include "scy/net/socket.h" #include <iterator> using std::endl; namespace scy { namespace net { SocketAdapter::SocketAdapter(SocketAdapter* sender) : priority(0) , _sender(sender) , _dirty(false) { // TraceS(this) << "Create" << endl; assert(sender != this); } SocketAdapter::~SocketAdapter() { // TraceS(this) << "Destroy" << endl; // assert(_receivers.empty()); } ssize_t SocketAdapter::send(const char* data, size_t len, int flags) { assert(_sender); // should have output adapter if default impl is used if (!_sender) return -1; return _sender->send(data, len, flags); } ssize_t SocketAdapter::send(const char* data, size_t len, const Address& peerAddress, int flags) { assert(_sender); // should have output adapter if default impl is used if (!_sender) return -1; return _sender->send(data, len, peerAddress, flags); } ssize_t SocketAdapter::sendPacket(const IPacket& packet, int flags) { // Try to cast as RawPacket so we can send without copying any data. auto raw = dynamic_cast<const RawPacket*>(&packet); if (raw) return send((const char*)raw->data(), raw->size(), flags); // Dynamically generated packets need to be written to a // temp buffer for sending. else { Buffer buf; packet.write(buf); return send(buf.data(), buf.size(), flags); } } ssize_t SocketAdapter::sendPacket(const IPacket& packet, const Address& peerAddress, int flags) { // Try to cast as RawPacket so we can send without copying any data. auto raw = dynamic_cast<const RawPacket*>(&packet); if (raw) return send((const char*)raw->data(), raw->size(), peerAddress, flags); // Dynamically generated packets need to be written to a // temp buffer for sending. else { Buffer buf; buf.reserve(2048); packet.write(buf); return send(buf.data(), buf.size(), peerAddress, flags); } } void SocketAdapter::sendPacket(IPacket& packet) { size_t res = sendPacket(packet, 0); if (res < 0) throw std::runtime_error("Invalid socket operation"); } void SocketAdapter::onSocketConnect(Socket& socket) { try { cleanupReceivers(); int current = int(_receivers.size() - 1); while (current >= 0) { auto ref = _receivers[current--]; if (ref->alive) ref->ptr->onSocketConnect(socket); } } catch (StopPropagation&) { } } void SocketAdapter::onSocketRecv(Socket& socket, const MutableBuffer& buffer, const Address& peerAddress) { try { cleanupReceivers(); int current = int(_receivers.size() - 1); while (current >= 0) { auto ref = _receivers[current--]; if (ref->alive) ref->ptr->onSocketRecv(socket, buffer, peerAddress); } } catch (StopPropagation&) { } } void SocketAdapter::onSocketError(Socket& socket, const scy::Error& error) { try { cleanupReceivers(); int current = int(_receivers.size() - 1); while (current >= 0) { auto ref = _receivers[current--]; if (ref->alive) ref->ptr->onSocketError(socket, error); } } catch (StopPropagation&) { } } void SocketAdapter::onSocketClose(Socket& socket) { try { cleanupReceivers(); int current = int(_receivers.size() - 1); while (current >= 0) { auto ref = _receivers[current--]; if (ref->alive) { ref->ptr->onSocketClose(socket); } } } catch (StopPropagation&) { } } void SocketAdapter::setSender(SocketAdapter* adapter) { assert(adapter != this); if (_sender == adapter) return; _sender = adapter; } bool SocketAdapter::hasReceiver(SocketAdapter* adapter) { for (auto& receiver : _receivers) { if (receiver->ptr == adapter) return true; } return false; } void SocketAdapter::addReceiver(SocketAdapter* adapter) { assert(adapter->priority <= 100); assert(adapter != this); if (hasReceiver(adapter)) return; // Note that we insert new adapters in the back of the queue, // and iterate in reverse to ensure calling order is preserved. _dirty = true; _receivers.push_back(new Ref{ adapter, true }); // _receivers.insert(_receivers.begin(), new Ref{ adapter, false }); // insert front // std::sort(_receivers.begin(), _receivers.end(), // [](SocketAdapter const& l, SocketAdapter const& r) { // return l.priority > r.priority; }); } void SocketAdapter::removeReceiver(SocketAdapter* adapter) { assert(adapter != this); auto it = std::find_if(_receivers.begin(), _receivers.end(), [&](const Ref* ref) { return ref->ptr == adapter; }); if (it != _receivers.end()) { (*it)->alive = false; } } void SocketAdapter::cleanupReceivers() { if (!_dirty) return; for (auto it = _receivers.begin(); it != _receivers.end();) { auto ref = *it; if (!ref->alive) { delete ref; it = _receivers.erase(it); } else ++it; } _dirty = false; } SocketAdapter* SocketAdapter::sender() { return _sender; } std::vector<SocketAdapter*> SocketAdapter::receivers() { std::vector<SocketAdapter*> items; std::transform(_receivers.begin(), _receivers.end(), std::back_inserter(items), [](const Ref* ref) { return ref->ptr; }); return items; } } // namespace net } // namespace scy /// @\} <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, Rice 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 Rice University 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. *********************************************************************/ /* Author: Ioan Sucan */ #include "ompl/base/Planner.h" #include "ompl/util/Exception.h" #include "ompl/base/GoalSampleableRegion.h" #include <boost/thread.hpp> ompl::base::Planner::Planner(const SpaceInformationPtr &si, const std::string &name) : si_(si), pis_(this), name_(name), setup_(false), msg_(name) { if (!si_) throw Exception(name_, "Invalid space information instance for planner"); } const ompl::base::PlannerSpecs& ompl::base::Planner::getSpecs(void) const { return specs_; } const std::string& ompl::base::Planner::getName(void) const { return name_; } void ompl::base::Planner::setName(const std::string &name) { name_ = name; msg_.setPrefix(name_); } const ompl::base::SpaceInformationPtr& ompl::base::Planner::getSpaceInformation(void) const { return si_; } const ompl::base::ProblemDefinitionPtr& ompl::base::Planner::getProblemDefinition(void) const { return pdef_; } void ompl::base::Planner::setProblemDefinition(const ProblemDefinitionPtr &pdef) { pdef_ = pdef; pis_.update(); } const ompl::base::PlannerInputStates& ompl::base::Planner::getPlannerInputStates(void) const { return pis_; } void ompl::base::Planner::setup(void) { if (!si_->isSetup()) { msg_.inform("Space information setup was not yet called. Calling now."); si_->setup(); } if (setup_) msg_.warn("Planner setup called multiple times"); else setup_ = true; } void ompl::base::Planner::checkValidity(void) { if (!isSetup()) setup(); pis_.checkValidity(); } bool ompl::base::Planner::isSetup(void) const { return setup_; } void ompl::base::Planner::clear(void) { pis_.clear(); pis_.update(); } void ompl::base::Planner::getPlannerData(PlannerData &data) const { } ompl::base::PlannerStatus ompl::base::Planner::solve(const PlannerTerminationConditionFn &ptc, double checkInterval) { return solve(PlannerThreadedTerminationCondition(ptc, checkInterval)); } ompl::base::PlannerStatus ompl::base::Planner::solve(double solveTime) { if (solveTime < 1.0) return solve(timedPlannerTerminationCondition(solveTime)); else return solve(timedPlannerTerminationCondition(solveTime, std::min(solveTime / 100.0, 0.1))); } void ompl::base::Planner::printProperties(std::ostream &out) const { out << "Planner " + getName() + " specs:" << std::endl; out << "Multithreaded: " << (getSpecs().multithreaded ? "Yes" : "No") << std::endl; out << "Reports approximate solutions: " << (getSpecs().approximateSolutions ? "Yes" : "No") << std::endl; out << "Can optimize solutions: " << (getSpecs().optimizingPaths ? "Yes" : "No") << std::endl; out << "Aware of the following parameters:"; std::vector<std::string> params; params_.getParamNames(params); for (unsigned int i = 0 ; i < params.size() ; ++i) out << " " << params[i]; out << std::endl; } void ompl::base::Planner::printSettings(std::ostream &out) const { out << "Declared parameters for planner " << getName() << ":" << std::endl; params_.print(out); } void ompl::base::PlannerInputStates::clear(void) { if (tempState_) { si_->freeState(tempState_); tempState_ = NULL; } addedStartStates_ = 0; sampledGoalsCount_ = 0; pdef_ = NULL; si_ = NULL; } void ompl::base::PlannerInputStates::restart(void) { addedStartStates_ = 0; sampledGoalsCount_ = 0; } bool ompl::base::PlannerInputStates::update(void) { if (!planner_) throw Exception("No planner set for PlannerInputStates"); return use(planner_->getSpaceInformation(), planner_->getProblemDefinition()); } void ompl::base::PlannerInputStates::checkValidity(void) const { std::string error; if (!pdef_) error = "Problem definition not specified"; else { if (pdef_->getStartStateCount() <= 0) error = "No start states specified"; else if (!pdef_->getGoal()) error = "No goal specified"; } if (!error.empty()) { if (planner_) throw Exception(planner_->getName(), error); else throw Exception(error); } } bool ompl::base::PlannerInputStates::use(const SpaceInformationPtr &si, const ProblemDefinitionPtr &pdef) { if (si && pdef) return use(si.get(), pdef.get()); else { clear(); return true; } } bool ompl::base::PlannerInputStates::use(const SpaceInformation *si, const ProblemDefinition *pdef) { if (pdef_ != pdef || si_ != si) { clear(); pdef_ = pdef; si_ = si; return true; } return false; } const ompl::base::State* ompl::base::PlannerInputStates::nextStart(void) { if (pdef_ == NULL || si_ == NULL) { std::string error = "Missing space information or problem definition"; if (planner_) throw Exception(planner_->getName(), error); else throw Exception(error); } while (addedStartStates_ < pdef_->getStartStateCount()) { const base::State *st = pdef_->getStartState(addedStartStates_); addedStartStates_++; bool bounds = si_->satisfiesBounds(st); bool valid = bounds ? si_->isValid(st) : false; if (bounds && valid) return st; else { msg::Interface msg(planner_ ? planner_->getName() : ""); msg.warn("Skipping invalid start state (invalid %s)", bounds ? "state": "bounds"); } } return NULL; } const ompl::base::State* ompl::base::PlannerInputStates::nextGoal(void) { static PlannerAlwaysTerminatingCondition ptc; return nextGoal(ptc); } const ompl::base::State* ompl::base::PlannerInputStates::nextGoal(const PlannerTerminationCondition &ptc) { if (pdef_ == NULL || si_ == NULL) { std::string error = "Missing space information or problem definition"; if (planner_) throw Exception(planner_->getName(), error); else throw Exception(error); } const GoalSampleableRegion *goal = pdef_->getGoal()->hasType(GOAL_SAMPLEABLE_REGION) ? pdef_->getGoal()->as<GoalSampleableRegion>() : NULL; if (goal) { time::point start_wait; bool first = true; bool attempt = true; while (attempt) { attempt = false; if (sampledGoalsCount_ < goal->maxSampleCount() && goal->canSample()) { if (tempState_ == NULL) tempState_ = si_->allocState(); do { goal->sampleGoal(tempState_); sampledGoalsCount_++; bool bounds = si_->satisfiesBounds(tempState_); bool valid = bounds ? si_->isValid(tempState_) : false; if (bounds && valid) { if (!first) // if we waited, show how long { msg::Interface msg(planner_ ? planner_->getName() : ""); msg.debug("Waited %lf seconds for the first goal sample.", time::seconds(time::now() - start_wait)); } return tempState_; } else { msg::Interface msg(planner_ ? planner_->getName() : ""); msg.warn("Skipping invalid goal state (invalid %s)", bounds ? "state": "bounds"); } } while (!ptc() && sampledGoalsCount_ < goal->maxSampleCount() && goal->canSample()); } if (goal->couldSample() && !ptc()) { if (first) { first = false; start_wait = time::now(); msg::Interface msg(planner_ ? planner_->getName() : ""); msg.debug("Waiting for goal region samples ..."); } boost::this_thread::sleep(time::seconds(0.01)); attempt = !ptc(); } } } return NULL; } bool ompl::base::PlannerInputStates::haveMoreStartStates(void) const { if (pdef_) return addedStartStates_ < pdef_->getStartStateCount(); return false; } bool ompl::base::PlannerInputStates::haveMoreGoalStates(void) const { if (pdef_ && pdef_->getGoal()) if (pdef_->getGoal()->hasType(GOAL_SAMPLEABLE_REGION)) return sampledGoalsCount_ < pdef_->getGoal()->as<GoalSampleableRegion>()->maxSampleCount(); return false; } <commit_msg>more debug info<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, Rice 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 Rice University 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. *********************************************************************/ /* Author: Ioan Sucan */ #include "ompl/base/Planner.h" #include "ompl/util/Exception.h" #include "ompl/base/GoalSampleableRegion.h" #include <sstream> #include <boost/thread.hpp> ompl::base::Planner::Planner(const SpaceInformationPtr &si, const std::string &name) : si_(si), pis_(this), name_(name), setup_(false), msg_(name) { if (!si_) throw Exception(name_, "Invalid space information instance for planner"); } const ompl::base::PlannerSpecs& ompl::base::Planner::getSpecs(void) const { return specs_; } const std::string& ompl::base::Planner::getName(void) const { return name_; } void ompl::base::Planner::setName(const std::string &name) { name_ = name; msg_.setPrefix(name_); } const ompl::base::SpaceInformationPtr& ompl::base::Planner::getSpaceInformation(void) const { return si_; } const ompl::base::ProblemDefinitionPtr& ompl::base::Planner::getProblemDefinition(void) const { return pdef_; } void ompl::base::Planner::setProblemDefinition(const ProblemDefinitionPtr &pdef) { pdef_ = pdef; pis_.update(); } const ompl::base::PlannerInputStates& ompl::base::Planner::getPlannerInputStates(void) const { return pis_; } void ompl::base::Planner::setup(void) { if (!si_->isSetup()) { msg_.inform("Space information setup was not yet called. Calling now."); si_->setup(); } if (setup_) msg_.warn("Planner setup called multiple times"); else setup_ = true; } void ompl::base::Planner::checkValidity(void) { if (!isSetup()) setup(); pis_.checkValidity(); } bool ompl::base::Planner::isSetup(void) const { return setup_; } void ompl::base::Planner::clear(void) { pis_.clear(); pis_.update(); } void ompl::base::Planner::getPlannerData(PlannerData &data) const { } ompl::base::PlannerStatus ompl::base::Planner::solve(const PlannerTerminationConditionFn &ptc, double checkInterval) { return solve(PlannerThreadedTerminationCondition(ptc, checkInterval)); } ompl::base::PlannerStatus ompl::base::Planner::solve(double solveTime) { if (solveTime < 1.0) return solve(timedPlannerTerminationCondition(solveTime)); else return solve(timedPlannerTerminationCondition(solveTime, std::min(solveTime / 100.0, 0.1))); } void ompl::base::Planner::printProperties(std::ostream &out) const { out << "Planner " + getName() + " specs:" << std::endl; out << "Multithreaded: " << (getSpecs().multithreaded ? "Yes" : "No") << std::endl; out << "Reports approximate solutions: " << (getSpecs().approximateSolutions ? "Yes" : "No") << std::endl; out << "Can optimize solutions: " << (getSpecs().optimizingPaths ? "Yes" : "No") << std::endl; out << "Aware of the following parameters:"; std::vector<std::string> params; params_.getParamNames(params); for (unsigned int i = 0 ; i < params.size() ; ++i) out << " " << params[i]; out << std::endl; } void ompl::base::Planner::printSettings(std::ostream &out) const { out << "Declared parameters for planner " << getName() << ":" << std::endl; params_.print(out); } void ompl::base::PlannerInputStates::clear(void) { if (tempState_) { si_->freeState(tempState_); tempState_ = NULL; } addedStartStates_ = 0; sampledGoalsCount_ = 0; pdef_ = NULL; si_ = NULL; } void ompl::base::PlannerInputStates::restart(void) { addedStartStates_ = 0; sampledGoalsCount_ = 0; } bool ompl::base::PlannerInputStates::update(void) { if (!planner_) throw Exception("No planner set for PlannerInputStates"); return use(planner_->getSpaceInformation(), planner_->getProblemDefinition()); } void ompl::base::PlannerInputStates::checkValidity(void) const { std::string error; if (!pdef_) error = "Problem definition not specified"; else { if (pdef_->getStartStateCount() <= 0) error = "No start states specified"; else if (!pdef_->getGoal()) error = "No goal specified"; } if (!error.empty()) { if (planner_) throw Exception(planner_->getName(), error); else throw Exception(error); } } bool ompl::base::PlannerInputStates::use(const SpaceInformationPtr &si, const ProblemDefinitionPtr &pdef) { if (si && pdef) return use(si.get(), pdef.get()); else { clear(); return true; } } bool ompl::base::PlannerInputStates::use(const SpaceInformation *si, const ProblemDefinition *pdef) { if (pdef_ != pdef || si_ != si) { clear(); pdef_ = pdef; si_ = si; return true; } return false; } const ompl::base::State* ompl::base::PlannerInputStates::nextStart(void) { if (pdef_ == NULL || si_ == NULL) { std::string error = "Missing space information or problem definition"; if (planner_) throw Exception(planner_->getName(), error); else throw Exception(error); } while (addedStartStates_ < pdef_->getStartStateCount()) { const base::State *st = pdef_->getStartState(addedStartStates_); addedStartStates_++; bool bounds = si_->satisfiesBounds(st); bool valid = bounds ? si_->isValid(st) : false; if (bounds && valid) return st; else { msg::Interface msg(planner_ ? planner_->getName() : ""); msg.warn("Skipping invalid start state (invalid %s)", bounds ? "state": "bounds"); std::stringstream ss; si_->printState(st, ss); msg.debug("Discarded start state %s", ss.str().c_str()); } } return NULL; } const ompl::base::State* ompl::base::PlannerInputStates::nextGoal(void) { static PlannerAlwaysTerminatingCondition ptc; return nextGoal(ptc); } const ompl::base::State* ompl::base::PlannerInputStates::nextGoal(const PlannerTerminationCondition &ptc) { if (pdef_ == NULL || si_ == NULL) { std::string error = "Missing space information or problem definition"; if (planner_) throw Exception(planner_->getName(), error); else throw Exception(error); } const GoalSampleableRegion *goal = pdef_->getGoal()->hasType(GOAL_SAMPLEABLE_REGION) ? pdef_->getGoal()->as<GoalSampleableRegion>() : NULL; if (goal) { time::point start_wait; bool first = true; bool attempt = true; while (attempt) { attempt = false; if (sampledGoalsCount_ < goal->maxSampleCount() && goal->canSample()) { if (tempState_ == NULL) tempState_ = si_->allocState(); do { goal->sampleGoal(tempState_); sampledGoalsCount_++; bool bounds = si_->satisfiesBounds(tempState_); bool valid = bounds ? si_->isValid(tempState_) : false; if (bounds && valid) { if (!first) // if we waited, show how long { msg::Interface msg(planner_ ? planner_->getName() : ""); msg.debug("Waited %lf seconds for the first goal sample.", time::seconds(time::now() - start_wait)); } return tempState_; } else { msg::Interface msg(planner_ ? planner_->getName() : ""); msg.warn("Skipping invalid goal state (invalid %s)", bounds ? "state": "bounds"); std::stringstream ss; si_->printState(tempState_, ss); msg.debug("Discarded goal state %s", ss.str().c_str()); } } while (!ptc() && sampledGoalsCount_ < goal->maxSampleCount() && goal->canSample()); } if (goal->couldSample() && !ptc()) { if (first) { first = false; start_wait = time::now(); msg::Interface msg(planner_ ? planner_->getName() : ""); msg.debug("Waiting for goal region samples ..."); } boost::this_thread::sleep(time::seconds(0.01)); attempt = !ptc(); } } } return NULL; } bool ompl::base::PlannerInputStates::haveMoreStartStates(void) const { if (pdef_) return addedStartStates_ < pdef_->getStartStateCount(); return false; } bool ompl::base::PlannerInputStates::haveMoreGoalStates(void) const { if (pdef_ && pdef_->getGoal()) if (pdef_->getGoal()->hasType(GOAL_SAMPLEABLE_REGION)) return sampledGoalsCount_ < pdef_->getGoal()->as<GoalSampleableRegion>()->maxSampleCount(); return false; } <|endoftext|>
<commit_before>#include <float.h> #include <math.h> #include <stdio.h> #include "simple_label.h" #include "cache.h" #include "rand48.h" #include "vw.h" using namespace std; char* bufread_simple_label(shared_data* sd, label_data* ld, char* c) { ld->label = *(float *)c; c += sizeof(ld->label); if (sd->binary_label && fabs(ld->label) != 1.f && ld->label != FLT_MAX) cout << "You are using a label not -1 or 1 with a loss function expecting that!" << endl; ld->weight = *(float *)c; c += sizeof(ld->weight); ld->initial = *(float *)c; c += sizeof(ld->initial); return c; } size_t read_cached_simple_label(shared_data* sd, void* v, io_buf& cache) { label_data* ld = (label_data*) v; char *c; size_t total = sizeof(ld->label)+sizeof(ld->weight)+sizeof(ld->initial); if (buf_read(cache, c, total) < total) return 0; c = bufread_simple_label(sd, ld,c); return total; } float get_weight(void* v) { label_data* ld = (label_data*) v; return ld->weight; } float get_initial(void* v) { label_data* ld = (label_data*) v; return ld->initial; } char* bufcache_simple_label(label_data* ld, char* c) { *(float *)c = ld->label; c += sizeof(ld->label); *(float *)c = ld->weight; c += sizeof(ld->weight); *(float *)c = ld->initial; c += sizeof(ld->initial); return c; } void cache_simple_label(void* v, io_buf& cache) { char *c; label_data* ld = (label_data*) v; buf_write(cache, c, sizeof(ld->label)+sizeof(ld->weight)+sizeof(ld->initial)); c = bufcache_simple_label(ld,c); } void default_simple_label(void* v) { label_data* ld = (label_data*) v; ld->label = FLT_MAX; ld->weight = 1.; ld->initial = 0.; } void delete_simple_label(void* v) { } void parse_simple_label(parser* p, shared_data* sd, void* v, v_array<substring>& words) { label_data* ld = (label_data*)v; switch(words.size()) { case 0: break; case 1: ld->label = float_of_substring(words[0]); break; case 2: ld->label = float_of_substring(words[0]); ld->weight = float_of_substring(words[1]); break; case 3: ld->label = float_of_substring(words[0]); ld->weight = float_of_substring(words[1]); ld->initial = float_of_substring(words[2]); break; default: cerr << "malformed example!\n"; cerr << "words.size() = " << words.size() << endl; } if (words.size() > 0 && sd->binary_label && fabs(ld->label) != 1.f) cout << "You are using a label not -1 or 1 with a loss function expecting that!" << endl; } float get_active_coin_bias(float k, float l, float g, float c0) { float b,sb,rs,sl; b=(float)(c0*(log(k+1.)+0.0001)/(k+0.0001)); sb=sqrt(b); if (l > 1.0) { l = 1.0; } else if (l < 0.0) { l = 0.0; } //loss should be in [0,1] sl=sqrt(l)+sqrt(l+g); if (g<=sb*sl+b) return 1; rs = (sl+sqrt(sl*sl+4*g))/(2*g); return b*rs*rs; } float query_decision(vw& all, example* ec, float k) { float bias, avg_loss, weighted_queries; if (k<=1.) bias=1.; else{ weighted_queries = (float)(all.initial_t + all.sd->weighted_examples - all.sd->weighted_unlabeled_examples); avg_loss = (float)(all.sd->sum_loss/k + sqrt((1.+0.5*log(k))/(weighted_queries+0.0001))); bias = get_active_coin_bias(k, avg_loss, ec->revert_weight/k, all.active_c0); } if(frand48()<bias) return 1.f/bias; else return -1.; } void print_update(vw& all, example *ec) { if (all.sd->weighted_examples > all.sd->dump_interval && !all.quiet && !all.bfgs) { label_data* ld = (label_data*) ec->ld; char label_buf[32]; if (ld->label == FLT_MAX) strcpy(label_buf," unknown"); else sprintf(label_buf,"%8.4f",ld->label); if(!all.holdout_set_off && all.current_pass >= 1){ fprintf(stderr, "%-6.5fh %-6.5fh %10ld %11.1f %s %8.4f %8lu\n", all.sd->holdout_sum_loss/all.sd->weighted_holdout_examples, all.sd->holdout_sum_loss_since_last_dump / all.sd->weighted_holdout_examples_since_last_dump, (long int)all.sd->example_number, all.sd->weighted_examples, label_buf, ec->final_prediction, (long unsigned int)ec->num_features); all.sd->weighted_holdout_examples_since_last_dump = 0; all.sd->holdout_sum_loss_since_last_dump = 0.0; } else fprintf(stderr, "%-10.6f %-10.6f %10ld %11.1f %s %8.4f %8lu\n", all.sd->sum_loss/all.sd->weighted_examples, all.sd->sum_loss_since_last_dump / (all.sd->weighted_examples - all.sd->old_weighted_examples), (long int)all.sd->example_number, all.sd->weighted_examples, label_buf, ec->final_prediction, (long unsigned int)ec->num_features); all.sd->sum_loss_since_last_dump = 0.0; all.sd->old_weighted_examples = all.sd->weighted_examples; all.sd->dump_interval *= 2; } } void output_and_account_example(vw& all, example* ec) { label_data* ld = (label_data*)ec->ld; if(ec->test_only) { all.sd->weighted_holdout_examples += ec->global_weight;//test weight seen all.sd->weighted_holdout_examples_since_last_dump += ec->global_weight; } else { all.sd->weighted_examples += ld->weight; all.sd->weighted_labels += ld->label == FLT_MAX ? 0 : ld->label * ld->weight; all.sd->total_features += ec->num_features; all.sd->sum_loss += ec->loss; all.sd->sum_loss_since_last_dump += ec->loss; all.sd->example_number++; } all.print(all.raw_prediction, ec->partial_prediction, -1, ec->tag); float ai=-1; if(all.active && ld->label == FLT_MAX) ai=query_decision(all, ec, (float)all.sd->weighted_unlabeled_examples); all.sd->weighted_unlabeled_examples += ld->label == FLT_MAX ? ld->weight : 0; for (size_t i = 0; i<all.final_prediction_sink.size(); i++) { int f = (int)all.final_prediction_sink[i]; if(all.active) active_print_result(f, ec->final_prediction, ai, ec->tag); else if (all.lda > 0) print_lda_result(all, f,ec->topic_predictions.begin,0.,ec->tag); else all.print(f, ec->final_prediction, 0, ec->tag); } print_update(all, ec); } void return_simple_example(vw& all, example* ec) { if (!command_example(&all, ec)) output_and_account_example(all, ec); VW::finish_example(all,ec); } <commit_msg>add h to the end of each line<commit_after>#include <float.h> #include <math.h> #include <stdio.h> #include "simple_label.h" #include "cache.h" #include "rand48.h" #include "vw.h" using namespace std; char* bufread_simple_label(shared_data* sd, label_data* ld, char* c) { ld->label = *(float *)c; c += sizeof(ld->label); if (sd->binary_label && fabs(ld->label) != 1.f && ld->label != FLT_MAX) cout << "You are using a label not -1 or 1 with a loss function expecting that!" << endl; ld->weight = *(float *)c; c += sizeof(ld->weight); ld->initial = *(float *)c; c += sizeof(ld->initial); return c; } size_t read_cached_simple_label(shared_data* sd, void* v, io_buf& cache) { label_data* ld = (label_data*) v; char *c; size_t total = sizeof(ld->label)+sizeof(ld->weight)+sizeof(ld->initial); if (buf_read(cache, c, total) < total) return 0; c = bufread_simple_label(sd, ld,c); return total; } float get_weight(void* v) { label_data* ld = (label_data*) v; return ld->weight; } float get_initial(void* v) { label_data* ld = (label_data*) v; return ld->initial; } char* bufcache_simple_label(label_data* ld, char* c) { *(float *)c = ld->label; c += sizeof(ld->label); *(float *)c = ld->weight; c += sizeof(ld->weight); *(float *)c = ld->initial; c += sizeof(ld->initial); return c; } void cache_simple_label(void* v, io_buf& cache) { char *c; label_data* ld = (label_data*) v; buf_write(cache, c, sizeof(ld->label)+sizeof(ld->weight)+sizeof(ld->initial)); c = bufcache_simple_label(ld,c); } void default_simple_label(void* v) { label_data* ld = (label_data*) v; ld->label = FLT_MAX; ld->weight = 1.; ld->initial = 0.; } void delete_simple_label(void* v) { } void parse_simple_label(parser* p, shared_data* sd, void* v, v_array<substring>& words) { label_data* ld = (label_data*)v; switch(words.size()) { case 0: break; case 1: ld->label = float_of_substring(words[0]); break; case 2: ld->label = float_of_substring(words[0]); ld->weight = float_of_substring(words[1]); break; case 3: ld->label = float_of_substring(words[0]); ld->weight = float_of_substring(words[1]); ld->initial = float_of_substring(words[2]); break; default: cerr << "malformed example!\n"; cerr << "words.size() = " << words.size() << endl; } if (words.size() > 0 && sd->binary_label && fabs(ld->label) != 1.f) cout << "You are using a label not -1 or 1 with a loss function expecting that!" << endl; } float get_active_coin_bias(float k, float l, float g, float c0) { float b,sb,rs,sl; b=(float)(c0*(log(k+1.)+0.0001)/(k+0.0001)); sb=sqrt(b); if (l > 1.0) { l = 1.0; } else if (l < 0.0) { l = 0.0; } //loss should be in [0,1] sl=sqrt(l)+sqrt(l+g); if (g<=sb*sl+b) return 1; rs = (sl+sqrt(sl*sl+4*g))/(2*g); return b*rs*rs; } float query_decision(vw& all, example* ec, float k) { float bias, avg_loss, weighted_queries; if (k<=1.) bias=1.; else{ weighted_queries = (float)(all.initial_t + all.sd->weighted_examples - all.sd->weighted_unlabeled_examples); avg_loss = (float)(all.sd->sum_loss/k + sqrt((1.+0.5*log(k))/(weighted_queries+0.0001))); bias = get_active_coin_bias(k, avg_loss, ec->revert_weight/k, all.active_c0); } if(frand48()<bias) return 1.f/bias; else return -1.; } void print_update(vw& all, example *ec) { if (all.sd->weighted_examples > all.sd->dump_interval && !all.quiet && !all.bfgs) { label_data* ld = (label_data*) ec->ld; char label_buf[32]; if (ld->label == FLT_MAX) strcpy(label_buf," unknown"); else sprintf(label_buf,"%8.4f",ld->label); if(!all.holdout_set_off && all.current_pass >= 1){ fprintf(stderr, "%-10.6f %-10.6f %10ld %11.1f %s %8.4f %8luh\n", all.sd->holdout_sum_loss/all.sd->weighted_holdout_examples, all.sd->holdout_sum_loss_since_last_dump / all.sd->weighted_holdout_examples_since_last_dump, (long int)all.sd->example_number, all.sd->weighted_examples, label_buf, ec->final_prediction, (long unsigned int)ec->num_features); all.sd->weighted_holdout_examples_since_last_dump = 0; all.sd->holdout_sum_loss_since_last_dump = 0.0; } else fprintf(stderr, "%-10.6f %-10.6f %10ld %11.1f %s %8.4f %8lu\n", all.sd->sum_loss/all.sd->weighted_examples, all.sd->sum_loss_since_last_dump / (all.sd->weighted_examples - all.sd->old_weighted_examples), (long int)all.sd->example_number, all.sd->weighted_examples, label_buf, ec->final_prediction, (long unsigned int)ec->num_features); all.sd->sum_loss_since_last_dump = 0.0; all.sd->old_weighted_examples = all.sd->weighted_examples; all.sd->dump_interval *= 2; } } void output_and_account_example(vw& all, example* ec) { label_data* ld = (label_data*)ec->ld; if(ec->test_only) { all.sd->weighted_holdout_examples += ec->global_weight;//test weight seen all.sd->weighted_holdout_examples_since_last_dump += ec->global_weight; } else { all.sd->weighted_examples += ld->weight; all.sd->weighted_labels += ld->label == FLT_MAX ? 0 : ld->label * ld->weight; all.sd->total_features += ec->num_features; all.sd->sum_loss += ec->loss; all.sd->sum_loss_since_last_dump += ec->loss; all.sd->example_number++; } all.print(all.raw_prediction, ec->partial_prediction, -1, ec->tag); float ai=-1; if(all.active && ld->label == FLT_MAX) ai=query_decision(all, ec, (float)all.sd->weighted_unlabeled_examples); all.sd->weighted_unlabeled_examples += ld->label == FLT_MAX ? ld->weight : 0; for (size_t i = 0; i<all.final_prediction_sink.size(); i++) { int f = (int)all.final_prediction_sink[i]; if(all.active) active_print_result(f, ec->final_prediction, ai, ec->tag); else if (all.lda > 0) print_lda_result(all, f,ec->topic_predictions.begin,0.,ec->tag); else all.print(f, ec->final_prediction, 0, ec->tag); } print_update(all, ec); } void return_simple_example(vw& all, example* ec) { if (!command_example(&all, ec)) output_and_account_example(all, ec); VW::finish_example(all,ec); } <|endoftext|>
<commit_before>/* * This file is part of m-keyboard * * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation (directui@nokia.com) * * If you have questions regarding the use of this file, please contact * Nokia at directui@nokia.com. * * 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 * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "mkeyboardsettings.h" #include "mkeyboardsettingswidget.h" #include "keyboarddata.h" #include <QObject> #include <QGraphicsWidget> #include <QDir> #include <QFileInfo> #include <QDebug> namespace { const QString SettingsIMCorrectionSetting("/meegotouch/inputmethods/correctionenabled"); const QString InputMethodLanguages("/meegotouch/inputmethods/languages"); const QString VKBConfigurationPath("/usr/share/meegotouch/virtual-keyboard/layouts/"); const QString VKBLayoutsFilterRule("*.xml"); const QString VKBLayoutsIgnoreRules("number|test"); // use as regexp to ignore number and test layouts }; MKeyboardSettings::MKeyboardSettings() : keyboardErrorCorrectionConf(SettingsIMCorrectionSetting, this), selectedKeyboardsConf(InputMethodLanguages, this) { readAvailableKeyboards(); connect(&keyboardErrorCorrectionConf, SIGNAL(valueChanged()), this, SIGNAL(errorCorrectionChanged())); connect(&selectedKeyboardsConf, SIGNAL(valueChanged()), this, SIGNAL(selectedKeyboardsChanged())); } MKeyboardSettings::~MKeyboardSettings() { } QGraphicsWidget *MKeyboardSettings::createContentWidget(QGraphicsWidget *parent) { // the pointer of returned QGraphicsWidget is owned by the caller, // so we just always create a new containerWidget. return new MKeyboardSettingsWidget(this, parent); } QString MKeyboardSettings::title() { //% "Virtual keyboards"; return qtTrId("qtn_txts_virtual_keyboards");; } QString MKeyboardSettings::icon() { return ""; } void MKeyboardSettings::readAvailableKeyboards() { availableKeyboardInfos.clear(); // available keyboard languages are determined by xml layouts that can be found const QDir layoutsDir(VKBConfigurationPath, VKBLayoutsFilterRule); QRegExp ignoreExp(VKBLayoutsIgnoreRules, Qt::CaseInsensitive); foreach (QFileInfo keyboardFileInfo, layoutsDir.entryInfoList()) { if (keyboardFileInfo.fileName().contains(ignoreExp)) continue; KeyboardData keyboard; if (keyboard.loadNokiaKeyboard(keyboardFileInfo.fileName())) { bool duplicated = false; foreach (const KeyboardInfo &info, availableKeyboardInfos) { if (info.language == keyboard.language()) { duplicated = true; break; } } if (!duplicated) { KeyboardInfo keyboardInfo; keyboardInfo.fileName = keyboardFileInfo.fileName(); keyboardInfo.language = keyboard.language(); keyboardInfo.title = keyboard.title(); availableKeyboardInfos.append(keyboardInfo); } } } } QMap<QString, QString> MKeyboardSettings::availableKeyboards() const { QMap<QString, QString> keyboards; foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) { keyboards.insert(keyboardInfo.language, keyboardInfo.title); } return keyboards; } QMap<QString, QString> MKeyboardSettings::selectedKeyboards() const { QMap<QString, QString> keyboards; foreach (const QString language, selectedKeyboardsConf.value().toStringList()) { keyboards.insert(language, keyboardTitle(language)); } return keyboards; } void MKeyboardSettings::setSelectedKeyboards(const QStringList &keyboardTitles) { QStringList languages; foreach (const QString &title, keyboardTitles) { QString language = keyboardLanguage(title); if (!language.isEmpty() && !languages.contains(language)) { languages.append(language); } } selectedKeyboardsConf.set(languages); } QString MKeyboardSettings::keyboardTitle(const QString &language) const { QString title; foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) { if (keyboardInfo.language == language) { title = keyboardInfo.title; break; } } return title; } QString MKeyboardSettings::keyboardLanguage(const QString &title) const { QString language; foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) { if (keyboardInfo.title == title) { language = keyboardInfo.language; break; } } return language; } bool MKeyboardSettings::errorCorrection() const { return keyboardErrorCorrectionConf.value().toBool(); } void MKeyboardSettings::setErrorCorrection(bool enabled) { if (keyboardErrorCorrectionConf.value().toBool() != enabled) keyboardErrorCorrectionConf.set(enabled); } <commit_msg>Fixes: keyboard settings should filter invalid layouts<commit_after>/* * This file is part of m-keyboard * * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation (directui@nokia.com) * * If you have questions regarding the use of this file, please contact * Nokia at directui@nokia.com. * * 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 * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "mkeyboardsettings.h" #include "mkeyboardsettingswidget.h" #include "keyboarddata.h" #include <QObject> #include <QGraphicsWidget> #include <QDir> #include <QFileInfo> #include <QDebug> namespace { const QString SettingsIMCorrectionSetting("/meegotouch/inputmethods/correctionenabled"); const QString InputMethodLanguages("/meegotouch/inputmethods/languages"); const QString VKBConfigurationPath("/usr/share/meegotouch/virtual-keyboard/layouts/"); const QString VKBLayoutsFilterRule("*.xml"); const QString VKBLayoutsIgnoreRules("number|test"); // use as regexp to ignore number and test layouts }; MKeyboardSettings::MKeyboardSettings() : keyboardErrorCorrectionConf(SettingsIMCorrectionSetting, this), selectedKeyboardsConf(InputMethodLanguages, this) { readAvailableKeyboards(); connect(&keyboardErrorCorrectionConf, SIGNAL(valueChanged()), this, SIGNAL(errorCorrectionChanged())); connect(&selectedKeyboardsConf, SIGNAL(valueChanged()), this, SIGNAL(selectedKeyboardsChanged())); } MKeyboardSettings::~MKeyboardSettings() { } QGraphicsWidget *MKeyboardSettings::createContentWidget(QGraphicsWidget *parent) { // the pointer of returned QGraphicsWidget is owned by the caller, // so we just always create a new containerWidget. return new MKeyboardSettingsWidget(this, parent); } QString MKeyboardSettings::title() { //% "Virtual keyboards"; return qtTrId("qtn_txts_virtual_keyboards");; } QString MKeyboardSettings::icon() { return ""; } void MKeyboardSettings::readAvailableKeyboards() { availableKeyboardInfos.clear(); // available keyboard languages are determined by xml layouts that can be found const QDir layoutsDir(VKBConfigurationPath, VKBLayoutsFilterRule); QRegExp ignoreExp(VKBLayoutsIgnoreRules, Qt::CaseInsensitive); foreach (QFileInfo keyboardFileInfo, layoutsDir.entryInfoList()) { if (keyboardFileInfo.fileName().contains(ignoreExp)) continue; KeyboardData keyboard; if (keyboard.loadNokiaKeyboard(keyboardFileInfo.fileName())) { if (keyboard.language().isEmpty() || keyboard.title().isEmpty()) continue; bool duplicated = false; foreach (const KeyboardInfo &info, availableKeyboardInfos) { if (info.language == keyboard.language()) { duplicated = true; break; } } if (!duplicated) { KeyboardInfo keyboardInfo; keyboardInfo.fileName = keyboardFileInfo.fileName(); keyboardInfo.language = keyboard.language(); keyboardInfo.title = keyboard.title(); availableKeyboardInfos.append(keyboardInfo); } } } } QMap<QString, QString> MKeyboardSettings::availableKeyboards() const { QMap<QString, QString> keyboards; foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) { keyboards.insert(keyboardInfo.language, keyboardInfo.title); } return keyboards; } QMap<QString, QString> MKeyboardSettings::selectedKeyboards() const { QMap<QString, QString> keyboards; foreach (const QString language, selectedKeyboardsConf.value().toStringList()) { keyboards.insert(language, keyboardTitle(language)); } return keyboards; } void MKeyboardSettings::setSelectedKeyboards(const QStringList &keyboardTitles) { QStringList languages; foreach (const QString &title, keyboardTitles) { QString language = keyboardLanguage(title); if (!language.isEmpty() && !languages.contains(language)) { languages.append(language); } } selectedKeyboardsConf.set(languages); } QString MKeyboardSettings::keyboardTitle(const QString &language) const { QString title; foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) { if (keyboardInfo.language == language) { title = keyboardInfo.title; break; } } return title; } QString MKeyboardSettings::keyboardLanguage(const QString &title) const { QString language; foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) { if (keyboardInfo.title == title) { language = keyboardInfo.language; break; } } return language; } bool MKeyboardSettings::errorCorrection() const { return keyboardErrorCorrectionConf.value().toBool(); } void MKeyboardSettings::setErrorCorrection(bool enabled) { if (keyboardErrorCorrectionConf.value().toBool() != enabled) keyboardErrorCorrectionConf.set(enabled); } <|endoftext|>
<commit_before>// @(#)root/tree:$Id$ // Author: Marek Biskup 07/06/2005 /************************************************************************* * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // A Chain Index // ////////////////////////////////////////////////////////////////////////// #include "TChainIndex.h" #include "TChain.h" #include "TTreeFormula.h" #include "TTreeIndex.h" #include "TFile.h" #include "TError.h" ClassImp(TChainIndex) //______________________________________________________________________________ TChainIndex::TChainIndex(): TVirtualIndex() { // Default constructor for TChainIndex fTree = 0; fMajorFormulaParent = fMinorFormulaParent = 0; } //______________________________________________________________________________ TChainIndex::TChainIndex(const TTree *T, const char *majorname, const char *minorname) : TVirtualIndex() { // Normal constructor for TChainIndex. See TTreeIndex::TTreeIndex for the description of the // parameters. // The tree must be a TChain. // All the index values in the first tree of the chain must be // less then any index value in the second one, and so on. // If any of those requirements isn't met the object becomes a zombie. // If some subtrees don't have indices the indices are created and stored inside this // TChainIndex. fTree = 0; fMajorFormulaParent = fMinorFormulaParent = 0; TChain *chain = dynamic_cast<TChain*>(const_cast<TTree*>(T)); if (!chain) { MakeZombie(); Error("TChainIndex", "Cannot create a TChainIndex." " The Tree passed as an argument is not a TChain"); return; } fTree = (TTree*)T; fMajorName = majorname; fMinorName = minorname; Int_t i = 0; // Go through all the trees and check if they have indeces. If not then build them. for (i = 0; i < chain->GetNtrees(); i++) { chain->LoadTree((chain->GetTreeOffset())[i]); TVirtualIndex *index = chain->GetTree()->GetTreeIndex(); TChainIndexEntry entry; entry.fTreeIndex = 0; //if an index already exists, we must check if major/minorname correspond //to the major/minor names in this function call if (index) { if (strcmp(majorname,index->GetMajorName()) || strcmp(minorname,index->GetMinorName())) { MakeZombie(); Error("TChainIndex","Tree in file %s has an index built with majorname=%s and minorname=%s",chain->GetTree()->GetCurrentFile()->GetName(),index->GetMajorName(),index->GetMinorName()); return; } } if (!index) { chain->GetTree()->BuildIndex(majorname, minorname); index = chain->GetTree()->GetTreeIndex(); chain->GetTree()->SetTreeIndex(0); entry.fTreeIndex = index; } if (!index || index->IsZombie() || index->GetN() == 0) { DeleteIndices(); MakeZombie(); Error("TChainIndex", "Error creating a tree index on a tree in the chain"); return; } TTreeIndex *ti_index = dynamic_cast<TTreeIndex*>(index); if (ti_index == 0) { Error("TChainIndex", "The underlying TTree must have a TTreeIndex but has a %s.", index->IsA()->GetName()); return; } entry.fMinIndexValue = ti_index->GetIndexValues()[0]; entry.fMaxIndexValue = ti_index->GetIndexValues()[index->GetN() - 1]; fEntries.push_back(entry); } // Check if the indices of different trees are in order. If not then return an error. for (i = 0; i < Int_t(fEntries.size() - 1); i++) { if (fEntries[i].fMaxIndexValue > fEntries[i+1].fMinIndexValue) { DeleteIndices(); MakeZombie(); Error("TChainIndex", "The indices in files of this chain aren't sorted."); } } } //______________________________________________________________________________ void TChainIndex::Append(const TVirtualIndex *index, Bool_t delaySort ) { // add an index to this chain // if delaySort is kFALSE (default) check if the indices of different trees are in order. if (index) { const TTreeIndex *ti_index = dynamic_cast<const TTreeIndex*>(index); if (ti_index == 0) { Error("Append", "The given index is not a TTreeIndex but a %s", index->IsA()->GetName()); } TChainIndexEntry entry; entry.fTreeIndex = 0; entry.fMinIndexValue = ti_index->GetIndexValues()[0]; entry.fMaxIndexValue = ti_index->GetIndexValues()[index->GetN() - 1]; fEntries.push_back(entry); } if (!delaySort) { // Check if the indices of different trees are in order. If not then return an error. for (Int_t i = 0; i < Int_t(fEntries.size() - 1); i++) { if (fEntries[i].fMaxIndexValue > fEntries[i+1].fMinIndexValue) { DeleteIndices(); MakeZombie(); Error("Append", "The indices in files of this chain aren't sorted."); } } } } //______________________________________________________________________________ void TChainIndex::DeleteIndices() { // Delete all the indices which were built by this object for (unsigned int i = 0; i < fEntries.size(); i++) { if (fEntries[i].fTreeIndex) { if (fTree->GetTree() && fTree->GetTree()->GetTreeIndex() == fEntries[i].fTreeIndex) { fTree->GetTree()->SetTreeIndex(0); SafeDelete(fEntries[i].fTreeIndex); } SafeDelete(fEntries[i].fTreeIndex); } } } //______________________________________________________________________________ TChainIndex::~TChainIndex() { // The destructor. DeleteIndices(); if (fTree && fTree->GetTreeIndex() == this) fTree->SetTreeIndex(0); } //______________________________________________________________________________ std::pair<TVirtualIndex*, Int_t> TChainIndex::GetSubTreeIndex(Int_t major, Int_t minor) const { // Returns a TVirtualIndex for a tree which holds the entry with the specified // major and minor values and the number of that tree. // If the index for that tree was created by this object it's set to the tree. // The tree index should be later released using ReleaseSubTreeIndex(); using namespace std; if (fEntries.size() == 0) { Warning("GetSubTreeIndex", "No subindices in the chain. The chain is probably empty"); return make_pair(static_cast<TVirtualIndex*>(0), 0); } Long64_t indexValue = (Long64_t(major) << 31) + minor; if (indexValue < fEntries[0].fMinIndexValue) { Warning("GetSubTreeIndex", "The index value is less than the smallest index values in subtrees"); return make_pair(static_cast<TVirtualIndex*>(0), 0); } Int_t treeNo = fEntries.size() - 1; for (unsigned int i = 0; i < fEntries.size() - 1; i++) { if (indexValue < fEntries[i+1].fMinIndexValue) { treeNo = i; break; } } // Double check we found the right range. if (0 && indexValue > fEntries[treeNo].fMaxIndexValue) { return make_pair(static_cast<TVirtualIndex*>(0), 0); } TChain* chain = dynamic_cast<TChain*> (fTree); R__ASSERT(chain); chain->LoadTree(chain->GetTreeOffset()[treeNo]); TVirtualIndex* index = fTree->GetTree()->GetTreeIndex(); if (index) return make_pair(static_cast<TVirtualIndex*>(index), treeNo); else { index = fEntries[treeNo].fTreeIndex; if (!index) { Warning("GetSubTreeIndex", "The tree has no index and the chain index" " doesn't store an index for that tree"); return make_pair(static_cast<TVirtualIndex*>(0), 0); } else { fTree->GetTree()->SetTreeIndex(index); return make_pair(static_cast<TVirtualIndex*>(index), treeNo); } } } //______________________________________________________________________________ void TChainIndex::ReleaseSubTreeIndex(TVirtualIndex* index, int treeNo) const { // Releases the tree index got using GetSubTreeIndex. If the index was // created by this object it is removed from the current tree, so that it isn't // deleted in its destructor. if (fEntries[treeNo].fTreeIndex == index) { R__ASSERT(fTree->GetTree()->GetTreeIndex() == index); fTree->GetTree()->SetTreeIndex(0); } } //______________________________________________________________________________ Long64_t TChainIndex::GetEntryNumberFriend(const TTree *parent) { // see TTreeIndex::GetEntryNumberFriend for description if (!parent) return -3; GetMajorFormulaParent(parent); GetMinorFormulaParent(parent); if (!fMajorFormulaParent || !fMinorFormulaParent) return -1; if (!fMajorFormulaParent->GetNdim() || !fMinorFormulaParent->GetNdim()) { // The Tree Index in the friend has a pair majorname,minorname // not available in the parent Tree T. // if the friend Tree has less entries than the parent, this is an error Long64_t pentry = parent->GetReadEntry(); if (pentry >= fTree->GetEntries()) return -2; // otherwise we ignore the Tree Index and return the entry number // in the parent Tree. return pentry; } // majorname, minorname exist in the parent Tree // we find the current values pair majorv,minorv in the parent Tree Double_t majord = fMajorFormulaParent->EvalInstance(); Double_t minord = fMinorFormulaParent->EvalInstance(); Long64_t majorv = (Long64_t)majord; Long64_t minorv = (Long64_t)minord; // we check if this pair exist in the index. // if yes, we return the corresponding entry number // if not the function returns -1 return fTree->GetEntryNumberWithIndex(majorv,minorv); } //______________________________________________________________________________ Long64_t TChainIndex::GetEntryNumberWithBestIndex(Int_t major, Int_t minor) const { // See TTreeIndex::GetEntryNumberWithBestIndex for details. std::pair<TVirtualIndex*, Int_t> indexAndNumber = GetSubTreeIndex(major, minor); if (!indexAndNumber.first) { Error("GetEntryNumberWithBestIndex","no index found"); return -1; } else { Long64_t rv = indexAndNumber.first->GetEntryNumberWithBestIndex(major, minor); ReleaseSubTreeIndex(indexAndNumber.first, indexAndNumber.second); TChain* chain = dynamic_cast<TChain*> (fTree); R__ASSERT(chain); return rv + chain->GetTreeOffset()[indexAndNumber.second]; } } //______________________________________________________________________________ Long64_t TChainIndex::GetEntryNumberWithIndex(Int_t major, Int_t minor) const { // Returns the entry number with given index values. // See TTreeIndex::GetEntryNumberWithIndex for details. std::pair<TVirtualIndex*, Int_t> indexAndNumber = GetSubTreeIndex(major, minor); if (!indexAndNumber.first) { Error("GetEntryNumberWithIndex","no index found"); return -1; } else { Long64_t rv = indexAndNumber.first->GetEntryNumberWithIndex(major, minor); ReleaseSubTreeIndex(indexAndNumber.first, indexAndNumber.second); TChain* chain = dynamic_cast<TChain*> (fTree); R__ASSERT(chain); if (rv > 0) { return rv + chain->GetTreeOffset()[indexAndNumber.second]; } else { return rv; } } } //______________________________________________________________________________ TTreeFormula *TChainIndex::GetMajorFormulaParent(const TTree *parent) { // return a pointer to the TreeFormula corresponding to the majorname in parent tree T if (!fMajorFormulaParent) { TTree::TFriendLock friendlock(fTree, TTree::kFindLeaf | TTree::kFindBranch | TTree::kGetBranch | TTree::kGetLeaf); fMajorFormulaParent = new TTreeFormula("MajorP",fMajorName.Data(),const_cast<TTree*>(parent)); fMajorFormulaParent->SetQuickLoad(kTRUE); } if (fMajorFormulaParent->GetTree() != parent) { fMajorFormulaParent->SetTree(const_cast<TTree*>(parent)); fMajorFormulaParent->UpdateFormulaLeaves(); } return fMajorFormulaParent; } //______________________________________________________________________________ TTreeFormula *TChainIndex::GetMinorFormulaParent(const TTree *parent) { // return a pointer to the TreeFormula corresponding to the minorname in parent tree T if (!fMinorFormulaParent) { // Prevent TTreeFormula from finding any of the branches in our TTree even if it // is a friend of the parent TTree. TTree::TFriendLock friendlock(fTree, TTree::kFindLeaf | TTree::kFindBranch | TTree::kGetBranch | TTree::kGetLeaf); fMinorFormulaParent = new TTreeFormula("MinorP",fMinorName.Data(),const_cast<TTree*>(parent)); fMinorFormulaParent->SetQuickLoad(kTRUE); } if (fMinorFormulaParent->GetTree() != parent) { fMinorFormulaParent->SetTree(const_cast<TTree*>(parent)); fMinorFormulaParent->UpdateFormulaLeaves(); } return fMinorFormulaParent; } //______________________________________________________________________________ void TChainIndex::UpdateFormulaLeaves(const TTree *parent) { // Updates the parent formulae. // Called by TChain::LoadTree when the parent chain changes it's tree. if (fMajorFormulaParent) { // Prevent TTreeFormula from finding any of the branches in our TTree even if it // is a friend of the parent TTree. TTree::TFriendLock friendlock(fTree, TTree::kFindLeaf | TTree::kFindBranch | TTree::kGetBranch | TTree::kGetLeaf); if (parent) fMajorFormulaParent->SetTree((TTree*)parent); fMajorFormulaParent->UpdateFormulaLeaves(); } if (fMinorFormulaParent) { if (parent) fMinorFormulaParent->SetTree((TTree*)parent); fMinorFormulaParent->UpdateFormulaLeaves(); } } //______________________________________________________________________________ void TChainIndex::SetTree(const TTree *T) { // See TTreeIndex::SetTree. R__ASSERT(fTree == 0 || fTree == T || T==0); } <commit_msg>GetEntryNumberWith[Best]Index is not suppose to complain on stderr/stdout when the index is out of range, just return -1. (also remove debug '0' in if statement)<commit_after>// @(#)root/tree:$Id$ // Author: Marek Biskup 07/06/2005 /************************************************************************* * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // A Chain Index // ////////////////////////////////////////////////////////////////////////// #include "TChainIndex.h" #include "TChain.h" #include "TTreeFormula.h" #include "TTreeIndex.h" #include "TFile.h" #include "TError.h" ClassImp(TChainIndex) //______________________________________________________________________________ TChainIndex::TChainIndex(): TVirtualIndex() { // Default constructor for TChainIndex fTree = 0; fMajorFormulaParent = fMinorFormulaParent = 0; } //______________________________________________________________________________ TChainIndex::TChainIndex(const TTree *T, const char *majorname, const char *minorname) : TVirtualIndex() { // Normal constructor for TChainIndex. See TTreeIndex::TTreeIndex for the description of the // parameters. // The tree must be a TChain. // All the index values in the first tree of the chain must be // less then any index value in the second one, and so on. // If any of those requirements isn't met the object becomes a zombie. // If some subtrees don't have indices the indices are created and stored inside this // TChainIndex. fTree = 0; fMajorFormulaParent = fMinorFormulaParent = 0; TChain *chain = dynamic_cast<TChain*>(const_cast<TTree*>(T)); if (!chain) { MakeZombie(); Error("TChainIndex", "Cannot create a TChainIndex." " The Tree passed as an argument is not a TChain"); return; } fTree = (TTree*)T; fMajorName = majorname; fMinorName = minorname; Int_t i = 0; // Go through all the trees and check if they have indeces. If not then build them. for (i = 0; i < chain->GetNtrees(); i++) { chain->LoadTree((chain->GetTreeOffset())[i]); TVirtualIndex *index = chain->GetTree()->GetTreeIndex(); TChainIndexEntry entry; entry.fTreeIndex = 0; //if an index already exists, we must check if major/minorname correspond //to the major/minor names in this function call if (index) { if (strcmp(majorname,index->GetMajorName()) || strcmp(minorname,index->GetMinorName())) { MakeZombie(); Error("TChainIndex","Tree in file %s has an index built with majorname=%s and minorname=%s",chain->GetTree()->GetCurrentFile()->GetName(),index->GetMajorName(),index->GetMinorName()); return; } } if (!index) { chain->GetTree()->BuildIndex(majorname, minorname); index = chain->GetTree()->GetTreeIndex(); chain->GetTree()->SetTreeIndex(0); entry.fTreeIndex = index; } if (!index || index->IsZombie() || index->GetN() == 0) { DeleteIndices(); MakeZombie(); Error("TChainIndex", "Error creating a tree index on a tree in the chain"); return; } TTreeIndex *ti_index = dynamic_cast<TTreeIndex*>(index); if (ti_index == 0) { Error("TChainIndex", "The underlying TTree must have a TTreeIndex but has a %s.", index->IsA()->GetName()); return; } entry.fMinIndexValue = ti_index->GetIndexValues()[0]; entry.fMaxIndexValue = ti_index->GetIndexValues()[index->GetN() - 1]; fEntries.push_back(entry); } // Check if the indices of different trees are in order. If not then return an error. for (i = 0; i < Int_t(fEntries.size() - 1); i++) { if (fEntries[i].fMaxIndexValue > fEntries[i+1].fMinIndexValue) { DeleteIndices(); MakeZombie(); Error("TChainIndex", "The indices in files of this chain aren't sorted."); } } } //______________________________________________________________________________ void TChainIndex::Append(const TVirtualIndex *index, Bool_t delaySort ) { // add an index to this chain // if delaySort is kFALSE (default) check if the indices of different trees are in order. if (index) { const TTreeIndex *ti_index = dynamic_cast<const TTreeIndex*>(index); if (ti_index == 0) { Error("Append", "The given index is not a TTreeIndex but a %s", index->IsA()->GetName()); } TChainIndexEntry entry; entry.fTreeIndex = 0; entry.fMinIndexValue = ti_index->GetIndexValues()[0]; entry.fMaxIndexValue = ti_index->GetIndexValues()[index->GetN() - 1]; fEntries.push_back(entry); } if (!delaySort) { // Check if the indices of different trees are in order. If not then return an error. for (Int_t i = 0; i < Int_t(fEntries.size() - 1); i++) { if (fEntries[i].fMaxIndexValue > fEntries[i+1].fMinIndexValue) { DeleteIndices(); MakeZombie(); Error("Append", "The indices in files of this chain aren't sorted."); } } } } //______________________________________________________________________________ void TChainIndex::DeleteIndices() { // Delete all the indices which were built by this object for (unsigned int i = 0; i < fEntries.size(); i++) { if (fEntries[i].fTreeIndex) { if (fTree->GetTree() && fTree->GetTree()->GetTreeIndex() == fEntries[i].fTreeIndex) { fTree->GetTree()->SetTreeIndex(0); SafeDelete(fEntries[i].fTreeIndex); } SafeDelete(fEntries[i].fTreeIndex); } } } //______________________________________________________________________________ TChainIndex::~TChainIndex() { // The destructor. DeleteIndices(); if (fTree && fTree->GetTreeIndex() == this) fTree->SetTreeIndex(0); } //______________________________________________________________________________ std::pair<TVirtualIndex*, Int_t> TChainIndex::GetSubTreeIndex(Int_t major, Int_t minor) const { // Returns a TVirtualIndex for a tree which holds the entry with the specified // major and minor values and the number of that tree. // If the index for that tree was created by this object it's set to the tree. // The tree index should be later released using ReleaseSubTreeIndex(); using namespace std; if (fEntries.size() == 0) { Warning("GetSubTreeIndex", "No subindices in the chain. The chain is probably empty"); return make_pair(static_cast<TVirtualIndex*>(0), 0); } Long64_t indexValue = (Long64_t(major) << 31) + minor; if (indexValue < fEntries[0].fMinIndexValue) { Warning("GetSubTreeIndex", "The index value is less than the smallest index values in subtrees"); return make_pair(static_cast<TVirtualIndex*>(0), 0); } Int_t treeNo = fEntries.size() - 1; for (unsigned int i = 0; i < fEntries.size() - 1; i++) { if (indexValue < fEntries[i+1].fMinIndexValue) { treeNo = i; break; } } // Double check we found the right range. if (indexValue > fEntries[treeNo].fMaxIndexValue) { return make_pair(static_cast<TVirtualIndex*>(0), 0); } TChain* chain = dynamic_cast<TChain*> (fTree); R__ASSERT(chain); chain->LoadTree(chain->GetTreeOffset()[treeNo]); TVirtualIndex* index = fTree->GetTree()->GetTreeIndex(); if (index) return make_pair(static_cast<TVirtualIndex*>(index), treeNo); else { index = fEntries[treeNo].fTreeIndex; if (!index) { Warning("GetSubTreeIndex", "The tree has no index and the chain index" " doesn't store an index for that tree"); return make_pair(static_cast<TVirtualIndex*>(0), 0); } else { fTree->GetTree()->SetTreeIndex(index); return make_pair(static_cast<TVirtualIndex*>(index), treeNo); } } } //______________________________________________________________________________ void TChainIndex::ReleaseSubTreeIndex(TVirtualIndex* index, int treeNo) const { // Releases the tree index got using GetSubTreeIndex. If the index was // created by this object it is removed from the current tree, so that it isn't // deleted in its destructor. if (fEntries[treeNo].fTreeIndex == index) { R__ASSERT(fTree->GetTree()->GetTreeIndex() == index); fTree->GetTree()->SetTreeIndex(0); } } //______________________________________________________________________________ Long64_t TChainIndex::GetEntryNumberFriend(const TTree *parent) { // see TTreeIndex::GetEntryNumberFriend for description if (!parent) return -3; GetMajorFormulaParent(parent); GetMinorFormulaParent(parent); if (!fMajorFormulaParent || !fMinorFormulaParent) return -1; if (!fMajorFormulaParent->GetNdim() || !fMinorFormulaParent->GetNdim()) { // The Tree Index in the friend has a pair majorname,minorname // not available in the parent Tree T. // if the friend Tree has less entries than the parent, this is an error Long64_t pentry = parent->GetReadEntry(); if (pentry >= fTree->GetEntries()) return -2; // otherwise we ignore the Tree Index and return the entry number // in the parent Tree. return pentry; } // majorname, minorname exist in the parent Tree // we find the current values pair majorv,minorv in the parent Tree Double_t majord = fMajorFormulaParent->EvalInstance(); Double_t minord = fMinorFormulaParent->EvalInstance(); Long64_t majorv = (Long64_t)majord; Long64_t minorv = (Long64_t)minord; // we check if this pair exist in the index. // if yes, we return the corresponding entry number // if not the function returns -1 return fTree->GetEntryNumberWithIndex(majorv,minorv); } //______________________________________________________________________________ Long64_t TChainIndex::GetEntryNumberWithBestIndex(Int_t major, Int_t minor) const { // See TTreeIndex::GetEntryNumberWithBestIndex for details. std::pair<TVirtualIndex*, Int_t> indexAndNumber = GetSubTreeIndex(major, minor); if (!indexAndNumber.first) { // Error("GetEntryNumberWithBestIndex","no index found"); return -1; } else { Long64_t rv = indexAndNumber.first->GetEntryNumberWithBestIndex(major, minor); ReleaseSubTreeIndex(indexAndNumber.first, indexAndNumber.second); TChain* chain = dynamic_cast<TChain*> (fTree); R__ASSERT(chain); return rv + chain->GetTreeOffset()[indexAndNumber.second]; } } //______________________________________________________________________________ Long64_t TChainIndex::GetEntryNumberWithIndex(Int_t major, Int_t minor) const { // Returns the entry number with given index values. // See TTreeIndex::GetEntryNumberWithIndex for details. std::pair<TVirtualIndex*, Int_t> indexAndNumber = GetSubTreeIndex(major, minor); if (!indexAndNumber.first) { // Error("GetEntryNumberWithIndex","no index found"); return -1; } else { Long64_t rv = indexAndNumber.first->GetEntryNumberWithIndex(major, minor); ReleaseSubTreeIndex(indexAndNumber.first, indexAndNumber.second); TChain* chain = dynamic_cast<TChain*> (fTree); R__ASSERT(chain); if (rv > 0) { return rv + chain->GetTreeOffset()[indexAndNumber.second]; } else { return rv; } } } //______________________________________________________________________________ TTreeFormula *TChainIndex::GetMajorFormulaParent(const TTree *parent) { // return a pointer to the TreeFormula corresponding to the majorname in parent tree T if (!fMajorFormulaParent) { TTree::TFriendLock friendlock(fTree, TTree::kFindLeaf | TTree::kFindBranch | TTree::kGetBranch | TTree::kGetLeaf); fMajorFormulaParent = new TTreeFormula("MajorP",fMajorName.Data(),const_cast<TTree*>(parent)); fMajorFormulaParent->SetQuickLoad(kTRUE); } if (fMajorFormulaParent->GetTree() != parent) { fMajorFormulaParent->SetTree(const_cast<TTree*>(parent)); fMajorFormulaParent->UpdateFormulaLeaves(); } return fMajorFormulaParent; } //______________________________________________________________________________ TTreeFormula *TChainIndex::GetMinorFormulaParent(const TTree *parent) { // return a pointer to the TreeFormula corresponding to the minorname in parent tree T if (!fMinorFormulaParent) { // Prevent TTreeFormula from finding any of the branches in our TTree even if it // is a friend of the parent TTree. TTree::TFriendLock friendlock(fTree, TTree::kFindLeaf | TTree::kFindBranch | TTree::kGetBranch | TTree::kGetLeaf); fMinorFormulaParent = new TTreeFormula("MinorP",fMinorName.Data(),const_cast<TTree*>(parent)); fMinorFormulaParent->SetQuickLoad(kTRUE); } if (fMinorFormulaParent->GetTree() != parent) { fMinorFormulaParent->SetTree(const_cast<TTree*>(parent)); fMinorFormulaParent->UpdateFormulaLeaves(); } return fMinorFormulaParent; } //______________________________________________________________________________ void TChainIndex::UpdateFormulaLeaves(const TTree *parent) { // Updates the parent formulae. // Called by TChain::LoadTree when the parent chain changes it's tree. if (fMajorFormulaParent) { // Prevent TTreeFormula from finding any of the branches in our TTree even if it // is a friend of the parent TTree. TTree::TFriendLock friendlock(fTree, TTree::kFindLeaf | TTree::kFindBranch | TTree::kGetBranch | TTree::kGetLeaf); if (parent) fMajorFormulaParent->SetTree((TTree*)parent); fMajorFormulaParent->UpdateFormulaLeaves(); } if (fMinorFormulaParent) { if (parent) fMinorFormulaParent->SetTree((TTree*)parent); fMinorFormulaParent->UpdateFormulaLeaves(); } } //______________________________________________________________________________ void TChainIndex::SetTree(const TTree *T) { // See TTreeIndex::SetTree. R__ASSERT(fTree == 0 || fTree == T || T==0); } <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2014 Intel Corporation // // // // 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 "tutorial/tutorial.h" #include "tutorial/obj_loader.h" #include "sys/taskscheduler.h" #include "image/image.h" namespace embree { /* name of the tutorial */ const char* tutorialName = "tutorial03"; /* configuration */ static std::string g_rtcore = ""; static size_t g_numThreads = 0; /* output settings */ static size_t g_width = 512; static size_t g_height = 512; static bool g_fullscreen = false; static FileName outFilename = ""; static int g_skipBenchmarkFrames = 0; static int g_numBenchmarkFrames = 0; static bool g_interactive = true; /* scene */ OBJScene g_obj_scene; static FileName filename = ""; static void parseCommandLine(Ref<ParseStream> cin, const FileName& path) { while (true) { std::string tag = cin->getString(); if (tag == "") return; /* parse command line parameters from a file */ else if (tag == "-c") { FileName file = path + cin->getFileName(); parseCommandLine(new ParseStream(new LineCommentFilter(file, "#")), file.path()); } /* load OBJ model*/ else if (tag == "-i") { filename = path + cin->getFileName(); } /* parse camera parameters */ else if (tag == "-vp") g_camera.from = cin->getVec3fa(); else if (tag == "-vi") g_camera.to = cin->getVec3fa(); else if (tag == "-vd") g_camera.to = g_camera.from + cin->getVec3fa(); else if (tag == "-vu") g_camera.up = cin->getVec3fa(); else if (tag == "-fov") g_camera.fov = cin->getFloat(); /* frame buffer size */ else if (tag == "-size") { g_width = cin->getInt(); g_height = cin->getInt(); } /* full screen mode */ else if (tag == "-fullscreen") g_fullscreen = true; /* output filename */ else if (tag == "-o") { outFilename = cin->getFileName(); g_interactive = false; } /* number of frames to render in benchmark mode */ else if (tag == "-benchmark") { g_skipBenchmarkFrames = cin->getInt(); g_numBenchmarkFrames = cin->getInt(); g_interactive = false; } /* rtcore configuration */ else if (tag == "-rtcore") g_rtcore = cin->getString(); /* number of threads to use */ else if (tag == "-threads") g_numThreads = cin->getInt(); /* skip unknown command line parameter */ else { std::cerr << "unknown command line parameter: " << tag << " "; while (cin->peek() != "" && cin->peek()[0] != '-') std::cerr << cin->getString() << " "; std::cerr << std::endl; } } } void renderBenchmark(const FileName& fileName) { resize(g_width,g_height); AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height); double dt = 0.0f; size_t numTotalFrames = g_skipBenchmarkFrames + g_numBenchmarkFrames; for (size_t i=0; i<numTotalFrames; i++) { double t0 = getSeconds(); render(0.0f,pixel2world.l.vx,pixel2world.l.vy,pixel2world.l.vz,pixel2world.p); double t1 = getSeconds(); std::cout << "frame [" << i << " / " << numTotalFrames << "] "; std::cout << 1.0/(t1-t0) << "fps "; if (i < g_skipBenchmarkFrames) std::cout << "(skipped)"; std::cout << std::endl; if (i >= g_skipBenchmarkFrames) dt += t1-t0; } std::cout << "frame [" << g_skipBenchmarkFrames << " - " << numTotalFrames << "] " << std::flush; std::cout << double(g_numBenchmarkFrames)/dt << "fps " << std::endl; std::cout << "BENCHMARK_RENDER " << double(g_numBenchmarkFrames)/dt << std::endl; } void renderToFile(const FileName& fileName) { resize(g_width,g_height); AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height); render(0.0f,pixel2world.l.vx,pixel2world.l.vy,pixel2world.l.vz,pixel2world.p); void* ptr = map(); Ref<Image> image = new Image4c(g_width, g_height, (Col4c*)ptr); storeImage(image, fileName); unmap(); } /* main function in embree namespace */ int main(int argc, char** argv) { /* create stream for parsing */ Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv)); /* parse command line */ parseCommandLine(stream, FileName()); if (g_numThreads) g_rtcore += ",threads=" + std::stringOf(g_numThreads); if (g_numBenchmarkFrames) g_rtcore += ",benchmark=1"; /* initialize task scheduler */ #if !defined(__EXPORT_ALL_SYMBOLS__) TaskScheduler::create(g_numThreads); #endif /* load scene */ if (filename.str() != "") loadOBJ(filename,g_obj_scene); /* initialize ray tracing core */ init(g_rtcore.c_str()); /* send model */ set_scene(&g_obj_scene); /* benchmark mode */ if (g_numBenchmarkFrames) renderBenchmark(outFilename); /* render to disk */ if (outFilename.str() != "") renderToFile(outFilename); /* interactive mode */ if (g_interactive) { initWindowState(tutorialName, g_width, g_height, g_fullscreen); enterWindowRunLoop(); } return 0; } } int main(int argc, char** argv) { try { return embree::main(argc, argv); } catch (const std::exception& e) { std::cout << "Error: " << e.what() << std::endl; return 1; } catch (...) { std::cout << "Error: unknown exception caught." << std::endl; return 1; } } <commit_msg>added light parsing to tutorial03<commit_after>// ======================================================================== // // Copyright 2009-2014 Intel Corporation // // // // 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 "tutorial/tutorial.h" #include "tutorial/obj_loader.h" #include "sys/taskscheduler.h" #include "image/image.h" namespace embree { /* name of the tutorial */ const char* tutorialName = "tutorial03"; /* configuration */ static std::string g_rtcore = ""; static size_t g_numThreads = 0; /* output settings */ static size_t g_width = 512; static size_t g_height = 512; static bool g_fullscreen = false; static FileName outFilename = ""; static int g_skipBenchmarkFrames = 0; static int g_numBenchmarkFrames = 0; static bool g_interactive = true; /* scene */ OBJScene g_obj_scene; static FileName filename = ""; static void parseCommandLine(Ref<ParseStream> cin, const FileName& path) { while (true) { std::string tag = cin->getString(); if (tag == "") return; /* parse command line parameters from a file */ else if (tag == "-c") { FileName file = path + cin->getFileName(); parseCommandLine(new ParseStream(new LineCommentFilter(file, "#")), file.path()); } /* load OBJ model*/ else if (tag == "-i") { filename = path + cin->getFileName(); } /* parse camera parameters */ else if (tag == "-vp") g_camera.from = cin->getVec3fa(); else if (tag == "-vi") g_camera.to = cin->getVec3fa(); else if (tag == "-vd") g_camera.to = g_camera.from + cin->getVec3fa(); else if (tag == "-vu") g_camera.up = cin->getVec3fa(); else if (tag == "-fov") g_camera.fov = cin->getFloat(); /* frame buffer size */ else if (tag == "-size") { g_width = cin->getInt(); g_height = cin->getInt(); } /* full screen mode */ else if (tag == "-fullscreen") g_fullscreen = true; /* output filename */ else if (tag == "-o") { outFilename = cin->getFileName(); g_interactive = false; } /* number of frames to render in benchmark mode */ else if (tag == "-benchmark") { g_skipBenchmarkFrames = cin->getInt(); g_numBenchmarkFrames = cin->getInt(); g_interactive = false; } /* rtcore configuration */ else if (tag == "-rtcore") g_rtcore = cin->getString(); /* number of threads to use */ else if (tag == "-threads") g_numThreads = cin->getInt(); /* ambient light source */ else if (tag == "-ambientlight") { const Vec3fa L = cin->getVec3fa(); g_obj_scene.ambientLights.push_back(OBJScene::AmbientLight(L)); } /* point light source */ else if (tag == "-pointlight") { const Vec3fa P = cin->getVec3fa(); const Vec3fa I = cin->getVec3fa(); g_obj_scene.pointLights.push_back(OBJScene::PointLight(P,I)); } /* directional light source */ else if (tag == "-directionallight" || tag == "-dirlight") { const Vec3fa D = cin->getVec3fa(); const Vec3fa E = cin->getVec3fa(); g_obj_scene.directionalLights.push_back(OBJScene::DirectionalLight(D,E)); } /* distant light source */ else if (tag == "-distantlight") { const Vec3fa D = cin->getVec3fa(); const Vec3fa L = cin->getVec3fa(); const float halfAngle = cin->getFloat(); g_obj_scene.distantLights.push_back(OBJScene::DistantLight(D,L,halfAngle)); } /* skip unknown command line parameter */ else { std::cerr << "unknown command line parameter: " << tag << " "; while (cin->peek() != "" && cin->peek()[0] != '-') std::cerr << cin->getString() << " "; std::cerr << std::endl; } } } void renderBenchmark(const FileName& fileName) { resize(g_width,g_height); AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height); double dt = 0.0f; size_t numTotalFrames = g_skipBenchmarkFrames + g_numBenchmarkFrames; for (size_t i=0; i<numTotalFrames; i++) { double t0 = getSeconds(); render(0.0f,pixel2world.l.vx,pixel2world.l.vy,pixel2world.l.vz,pixel2world.p); double t1 = getSeconds(); std::cout << "frame [" << i << " / " << numTotalFrames << "] "; std::cout << 1.0/(t1-t0) << "fps "; if (i < g_skipBenchmarkFrames) std::cout << "(skipped)"; std::cout << std::endl; if (i >= g_skipBenchmarkFrames) dt += t1-t0; } std::cout << "frame [" << g_skipBenchmarkFrames << " - " << numTotalFrames << "] " << std::flush; std::cout << double(g_numBenchmarkFrames)/dt << "fps " << std::endl; std::cout << "BENCHMARK_RENDER " << double(g_numBenchmarkFrames)/dt << std::endl; } void renderToFile(const FileName& fileName) { resize(g_width,g_height); AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height); render(0.0f,pixel2world.l.vx,pixel2world.l.vy,pixel2world.l.vz,pixel2world.p); void* ptr = map(); Ref<Image> image = new Image4c(g_width, g_height, (Col4c*)ptr); storeImage(image, fileName); unmap(); } /* main function in embree namespace */ int main(int argc, char** argv) { /* create stream for parsing */ Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv)); /* parse command line */ parseCommandLine(stream, FileName()); if (g_numThreads) g_rtcore += ",threads=" + std::stringOf(g_numThreads); if (g_numBenchmarkFrames) g_rtcore += ",benchmark=1"; /* initialize task scheduler */ #if !defined(__EXPORT_ALL_SYMBOLS__) TaskScheduler::create(g_numThreads); #endif /* load scene */ if (filename.str() != "") loadOBJ(filename,g_obj_scene); /* initialize ray tracing core */ init(g_rtcore.c_str()); /* send model */ set_scene(&g_obj_scene); /* benchmark mode */ if (g_numBenchmarkFrames) renderBenchmark(outFilename); /* render to disk */ if (outFilename.str() != "") renderToFile(outFilename); /* interactive mode */ if (g_interactive) { initWindowState(tutorialName, g_width, g_height, g_fullscreen); enterWindowRunLoop(); } return 0; } } int main(int argc, char** argv) { try { return embree::main(argc, argv); } catch (const std::exception& e) { std::cout << "Error: " << e.what() << std::endl; return 1; } catch (...) { std::cout << "Error: unknown exception caught." << std::endl; return 1; } } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkLookupTablePropertySerializer.h" #include <mitkLookupTableProperty.h> TiXmlElement* mitk::LookupTablePropertySerializer::Serialize() { if (const LookupTableProperty* prop = dynamic_cast<const LookupTableProperty*>(m_Property.GetPointer())) { LookupTable::Pointer mitkLut = const_cast<LookupTableProperty*>(prop)->GetLookupTable(); if (mitkLut.IsNull()) return nullptr; // really? vtkLookupTable* lut = mitkLut->GetVtkLookupTable(); if (!lut) return nullptr; auto element = new TiXmlElement("LookupTable"); double* range; double* rgba; element->SetAttribute("NumberOfColors", lut->GetNumberOfTableValues()); element->SetAttribute("Scale", lut->GetScale()); element->SetAttribute("Ramp", lut->GetRamp()); range = lut->GetHueRange(); auto child = new TiXmlElement("HueRange"); element->LinkEndChild( child ); child->SetDoubleAttribute("min", range[0]); child->SetDoubleAttribute("max", range[1]); range = lut->GetValueRange(); child = new TiXmlElement("ValueRange"); element->LinkEndChild( child ); child->SetDoubleAttribute("min", range[0]); child->SetDoubleAttribute("max", range[1]); range = lut->GetSaturationRange(); child = new TiXmlElement("SaturationRange"); element->LinkEndChild( child ); child->SetDoubleAttribute("min", range[0]); child->SetDoubleAttribute("max", range[1]); range = lut->GetAlphaRange(); child = new TiXmlElement("AlphaRange"); element->LinkEndChild( child ); child->SetDoubleAttribute("min", range[0]); child->SetDoubleAttribute("max", range[1]); range = lut->GetTableRange(); child = new TiXmlElement("TableRange"); element->LinkEndChild( child ); child->SetDoubleAttribute("min", range[0]); child->SetDoubleAttribute("max", range[1]); child = new TiXmlElement("Table"); element->LinkEndChild( child ); for ( int index = 0; index < lut->GetNumberOfTableValues(); ++index) { auto grandChildNinife = new TiXmlElement("RgbaColor"); rgba = lut->GetTableValue(index); grandChildNinife->SetDoubleAttribute("R", rgba[0]); grandChildNinife->SetDoubleAttribute("G", rgba[1]); grandChildNinife->SetDoubleAttribute("B", rgba[2]); grandChildNinife->SetDoubleAttribute("A", rgba[3]); child->LinkEndChild( grandChildNinife ); } return element; } else return nullptr; } mitk::BaseProperty::Pointer mitk::LookupTablePropertySerializer::Deserialize(TiXmlElement* element) { if (!element) return nullptr; typedef double OUR_VTK_FLOAT_TYPE; double range[2]; double rgba[4]; double d; // bec. of tinyXML's interface that takes a pointer to float or double... vtkSmartPointer<vtkLookupTable> lut = vtkSmartPointer<vtkLookupTable>::New(); int numberOfColors; int scale; int ramp; // hope the int values don't change betw. vtk versions... if ( element->QueryIntAttribute( "NumberOfColors", &numberOfColors ) == TIXML_SUCCESS ) { lut->SetNumberOfTableValues( numberOfColors ); } else return nullptr; if ( element->QueryIntAttribute( "Scale", &scale ) == TIXML_SUCCESS ) { lut->SetScale( scale ); } else return nullptr; if ( element->QueryIntAttribute( "Ramp", &ramp ) == TIXML_SUCCESS ) { lut->SetRamp( ramp ); } else return nullptr; TiXmlElement* child = element->FirstChildElement("HueRange"); if (child) { if ( child->QueryDoubleAttribute( "min", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d); if ( child->QueryDoubleAttribute( "max", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d); lut->SetHueRange( range ); } child = element->FirstChildElement("ValueRange"); if (child) { if ( child->QueryDoubleAttribute( "min", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d); if ( child->QueryDoubleAttribute( "max", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d); lut->SetValueRange( range ); } child = element->FirstChildElement("SaturationRange"); if (child) { if ( child->QueryDoubleAttribute( "min", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d); if ( child->QueryDoubleAttribute( "max", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d); lut->SetSaturationRange( range ); } child = element->FirstChildElement("AlphaRange"); if (child) { if ( child->QueryDoubleAttribute( "min", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d); if ( child->QueryDoubleAttribute( "max", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d); lut->SetAlphaRange( range ); } child = element->FirstChildElement("TableRange"); if (child) { if ( child->QueryDoubleAttribute( "min", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d); if ( child->QueryDoubleAttribute( "max", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d); lut->SetTableRange( range ); } child = element->FirstChildElement("Table"); if (child) { unsigned int index(0); for( TiXmlElement* grandChild = child->FirstChildElement("RgbaColor"); grandChild; grandChild = grandChild->NextSiblingElement("RgbaColor")) { if ( grandChild->QueryDoubleAttribute("R", &d) != TIXML_SUCCESS ) return nullptr; rgba[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d); if ( grandChild->QueryDoubleAttribute("G", &d) != TIXML_SUCCESS ) return nullptr; rgba[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d); if ( grandChild->QueryDoubleAttribute("B", &d) != TIXML_SUCCESS ) return nullptr; rgba[2] = static_cast<OUR_VTK_FLOAT_TYPE>(d); if ( grandChild->QueryDoubleAttribute("A", &d) != TIXML_SUCCESS ) return nullptr; rgba[3] = static_cast<OUR_VTK_FLOAT_TYPE>(d); lut->SetTableValue( index, rgba ); ++index; } } LookupTable::Pointer mitkLut = LookupTable::New(); mitkLut->SetVtkLookupTable( lut ); return LookupTableProperty::New(mitkLut).GetPointer(); }<commit_msg>Revert "Separating mitkLookupTablePropertySerliazer into header and source"<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkLookupTablePropertySerializer_h_included #define mitkLookupTablePropertySerializer_h_included #include "mitkBasePropertySerializer.h" #include "mitkLookupTableProperty.h" namespace mitk { class LookupTablePropertySerializer : public BasePropertySerializer { public: mitkClassMacro( LookupTablePropertySerializer, BasePropertySerializer ); itkFactorylessNewMacro(Self) itkCloneMacro(Self) virtual TiXmlElement* Serialize() override { if (const LookupTableProperty* prop = dynamic_cast<const LookupTableProperty*>(m_Property.GetPointer())) { LookupTable::Pointer mitkLut = const_cast<LookupTableProperty*>(prop)->GetLookupTable(); if (mitkLut.IsNull()) return nullptr; // really? vtkLookupTable* lut = mitkLut->GetVtkLookupTable(); if (!lut) return nullptr; auto element = new TiXmlElement("LookupTable"); double* range; double* rgba; element->SetAttribute("NumberOfColors", lut->GetNumberOfTableValues()); element->SetAttribute("Scale", lut->GetScale()); element->SetAttribute("Ramp", lut->GetRamp()); range = lut->GetHueRange(); auto child = new TiXmlElement("HueRange"); element->LinkEndChild( child ); child->SetDoubleAttribute("min", range[0]); child->SetDoubleAttribute("max", range[1]); range = lut->GetValueRange(); child = new TiXmlElement("ValueRange"); element->LinkEndChild( child ); child->SetDoubleAttribute("min", range[0]); child->SetDoubleAttribute("max", range[1]); range = lut->GetSaturationRange(); child = new TiXmlElement("SaturationRange"); element->LinkEndChild( child ); child->SetDoubleAttribute("min", range[0]); child->SetDoubleAttribute("max", range[1]); range = lut->GetAlphaRange(); child = new TiXmlElement("AlphaRange"); element->LinkEndChild( child ); child->SetDoubleAttribute("min", range[0]); child->SetDoubleAttribute("max", range[1]); range = lut->GetTableRange(); child = new TiXmlElement("TableRange"); element->LinkEndChild( child ); child->SetDoubleAttribute("min", range[0]); child->SetDoubleAttribute("max", range[1]); child = new TiXmlElement("Table"); element->LinkEndChild( child ); for ( int index = 0; index < lut->GetNumberOfTableValues(); ++index) { auto grandChildNinife = new TiXmlElement("RgbaColor"); rgba = lut->GetTableValue(index); grandChildNinife->SetDoubleAttribute("R", rgba[0]); grandChildNinife->SetDoubleAttribute("G", rgba[1]); grandChildNinife->SetDoubleAttribute("B", rgba[2]); grandChildNinife->SetDoubleAttribute("A", rgba[3]); child->LinkEndChild( grandChildNinife ); } return element; } else return nullptr; } virtual BaseProperty::Pointer Deserialize(TiXmlElement* element) override { if (!element) return nullptr; typedef double OUR_VTK_FLOAT_TYPE; double range[2]; double rgba[4]; double d; // bec. of tinyXML's interface that takes a pointer to float or double... vtkSmartPointer<vtkLookupTable> lut = vtkSmartPointer<vtkLookupTable>::New(); int numberOfColors; int scale; int ramp; // hope the int values don't change betw. vtk versions... if ( element->QueryIntAttribute( "NumberOfColors", &numberOfColors ) == TIXML_SUCCESS ) { lut->SetNumberOfTableValues( numberOfColors ); } else return nullptr; if ( element->QueryIntAttribute( "Scale", &scale ) == TIXML_SUCCESS ) { lut->SetScale( scale ); } else return nullptr; if ( element->QueryIntAttribute( "Ramp", &ramp ) == TIXML_SUCCESS ) { lut->SetRamp( ramp ); } else return nullptr; TiXmlElement* child = element->FirstChildElement("HueRange"); if (child) { if ( child->QueryDoubleAttribute( "min", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d); if ( child->QueryDoubleAttribute( "max", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d); lut->SetHueRange( range ); } child = element->FirstChildElement("ValueRange"); if (child) { if ( child->QueryDoubleAttribute( "min", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d); if ( child->QueryDoubleAttribute( "max", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d); lut->SetValueRange( range ); } child = element->FirstChildElement("SaturationRange"); if (child) { if ( child->QueryDoubleAttribute( "min", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d); if ( child->QueryDoubleAttribute( "max", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d); lut->SetSaturationRange( range ); } child = element->FirstChildElement("AlphaRange"); if (child) { if ( child->QueryDoubleAttribute( "min", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d); if ( child->QueryDoubleAttribute( "max", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d); lut->SetAlphaRange( range ); } child = element->FirstChildElement("TableRange"); if (child) { if ( child->QueryDoubleAttribute( "min", &d ) != TIXML_SUCCESS ) return nullptr; range[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d); if ( child->QueryDoubleAttribute( "max", &d ) != TIXML_SUCCESS ) return nullptr; range[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d); lut->SetTableRange( range ); } child = element->FirstChildElement("Table"); if (child) { unsigned int index(0); for( TiXmlElement* grandChild = child->FirstChildElement("RgbaColor"); grandChild; grandChild = grandChild->NextSiblingElement("RgbaColor")) { if ( grandChild->QueryDoubleAttribute("R", &d) != TIXML_SUCCESS ) return nullptr; rgba[0] = static_cast<OUR_VTK_FLOAT_TYPE>(d); if ( grandChild->QueryDoubleAttribute("G", &d) != TIXML_SUCCESS ) return nullptr; rgba[1] = static_cast<OUR_VTK_FLOAT_TYPE>(d); if ( grandChild->QueryDoubleAttribute("B", &d) != TIXML_SUCCESS ) return nullptr; rgba[2] = static_cast<OUR_VTK_FLOAT_TYPE>(d); if ( grandChild->QueryDoubleAttribute("A", &d) != TIXML_SUCCESS ) return nullptr; rgba[3] = static_cast<OUR_VTK_FLOAT_TYPE>(d); lut->SetTableValue( index, rgba ); ++index; } } LookupTable::Pointer mitkLut = LookupTable::New(); mitkLut->SetVtkLookupTable( lut ); return LookupTableProperty::New(mitkLut).GetPointer(); } protected: LookupTablePropertySerializer() {} virtual ~LookupTablePropertySerializer() {} }; } // namespace // important to put this into the GLOBAL namespace (because it starts with 'namespace mitk') MITK_REGISTER_SERIALIZER(LookupTablePropertySerializer); #endif <|endoftext|>
<commit_before>// $Id$ // The libMesh Finite Element Library. // Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // library configuration #include "libmesh_config.h" // C++ includes #include <algorithm> // for std::min #include <map> // for std::multimap #include <sstream> // for std::ostringstream // Local includes #include "boundary_info.h" #include "elem.h" #include "mesh_base.h" #include "parallel.h" #include "partitioner.h" #include "point_locator_base.h" namespace libMesh { // ------------------------------------------------------------ // MeshBase class member functions MeshBase::MeshBase (unsigned int d) : boundary_info (new BoundaryInfo(*this)), _n_parts (1), _dim (d), _is_prepared (false), _point_locator (NULL), _partitioner (NULL) { libmesh_assert (LIBMESH_DIM <= 3); libmesh_assert (LIBMESH_DIM >= _dim); libmesh_assert (libMesh::initialized()); } MeshBase::MeshBase (const MeshBase& other_mesh) : boundary_info (new BoundaryInfo(*this)), // no copy constructor defined for BoundaryInfo? _n_parts (other_mesh._n_parts), _dim (other_mesh._dim), _is_prepared (other_mesh._is_prepared), _point_locator (NULL), _partitioner (other_mesh._partitioner->clone()) { } MeshBase::~MeshBase() { this->clear(); libmesh_assert (!libMesh::closed()); } void MeshBase::prepare_for_use (const bool skip_renumber_nodes_and_elements) { // Renumber the nodes and elements so that they in contiguous // blocks. By default, skip_renumber_nodes_and_elements is false, // however we may skip this step by passing // skip_renumber_nodes_and_elements==true to this function. // // Instances where you if prepare_for_use() should not renumber the nodes // and elements include reading in e.g. an xda/r or gmv file. In // this case, the ordering of the nodes may depend on an accompanying // solution, and the node ordering cannot be changed. if(!skip_renumber_nodes_and_elements) this->renumber_nodes_and_elements(); // Let all the elements find their neighbors this->find_neighbors(); // Partition the mesh. this->partition(); // If we're using ParallelMesh, we'll want it parallelized. this->delete_remote_elements(); if(!skip_renumber_nodes_and_elements) this->renumber_nodes_and_elements(); // Reset our PointLocator. This needs to happen any time the elements // in the underlying elements in the mesh have changed, so we do it here. this->clear_point_locator(); // The mesh is now prepared for use. _is_prepared = true; } void MeshBase::clear () { // Reset the number of partitions _n_parts = 1; // Reset the _is_prepared flag _is_prepared = false; // Clear boundary information this->boundary_info->clear(); // Clear our point locator. this->clear_point_locator(); } unsigned int MeshBase::n_subdomains() const { // This requires an inspection on every processor parallel_only(); const_element_iterator el = this->active_elements_begin(); const const_element_iterator end = this->active_elements_end(); std::set<unsigned int> subdomain_ids; for (; el!=end; ++el) subdomain_ids.insert((*el)->subdomain_id()); // Some subdomains may only live on other processors Parallel::set_union(subdomain_ids, 0); unsigned int n_sbd_ids = subdomain_ids.size(); Parallel::broadcast(n_sbd_ids); return n_sbd_ids; } unsigned int MeshBase::n_nodes_on_proc (const unsigned int proc_id) const { // We're either counting a processor's nodes or unpartitioned // nodes libmesh_assert (proc_id < libMesh::n_processors() || proc_id == DofObject::invalid_processor_id); return static_cast<unsigned int>(std::distance (this->pid_nodes_begin(proc_id), this->pid_nodes_end (proc_id))); } unsigned int MeshBase::n_elem_on_proc (const unsigned int proc_id) const { // We're either counting a processor's elements or unpartitioned // elements libmesh_assert (proc_id < libMesh::n_processors() || proc_id == DofObject::invalid_processor_id); return static_cast<unsigned int>(std::distance (this->pid_elements_begin(proc_id), this->pid_elements_end (proc_id))); } unsigned int MeshBase::n_active_elem_on_proc (const unsigned int proc_id) const { libmesh_assert (proc_id < libMesh::n_processors()); return static_cast<unsigned int>(std::distance (this->active_pid_elements_begin(proc_id), this->active_pid_elements_end (proc_id))); } unsigned int MeshBase::n_sub_elem () const { unsigned int ne=0; const_element_iterator el = this->elements_begin(); const const_element_iterator end = this->elements_end(); for (; el!=end; ++el) ne += (*el)->n_sub_elem(); return ne; } unsigned int MeshBase::n_active_sub_elem () const { unsigned int ne=0; const_element_iterator el = this->active_elements_begin(); const const_element_iterator end = this->active_elements_end(); for (; el!=end; ++el) ne += (*el)->n_sub_elem(); return ne; } std::string MeshBase::get_info() const { std::ostringstream out; out << " Mesh Information:" << '\n' << " mesh_dimension()=" << this->mesh_dimension() << '\n' << " spatial_dimension()=" << this->spatial_dimension() << '\n' << " n_nodes()=" << this->n_nodes() << '\n' << " n_local_nodes()=" << this->n_local_nodes() << '\n' << " n_elem()=" << this->n_elem() << '\n' << " n_local_elem()=" << this->n_local_elem() << '\n' #ifdef LIBMESH_ENABLE_AMR << " n_active_elem()=" << this->n_active_elem() << '\n' #endif << " n_subdomains()=" << this->n_subdomains() << '\n' << " n_processors()=" << this->n_processors() << '\n' << " processor_id()=" << this->processor_id() << '\n'; return out.str(); } void MeshBase::print_info(std::ostream& os) const { os << this->get_info() << std::endl; } std::ostream& operator << (std::ostream& os, const MeshBase& m) { m.print_info(os); return os; } void MeshBase::partition (const unsigned int n_parts) { if (partitioner().get()) // "NULL" means don't partition partitioner()->partition (*this, n_parts); } unsigned int MeshBase::recalculate_n_partitions() { const_element_iterator el = this->active_elements_begin(); const const_element_iterator end = this->active_elements_end(); unsigned int max_proc_id=0; for (; el!=end; ++el) max_proc_id = std::max(max_proc_id, static_cast<unsigned int>((*el)->processor_id())); // The number of partitions is one more than the max processor ID. _n_parts = max_proc_id+1; return _n_parts; } const PointLocatorBase & MeshBase::point_locator () const { // Double checked lock pattern for efficiency if (_point_locator.get() == NULL) { Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx); if (_point_locator.get() == NULL) _point_locator.reset (PointLocatorBase::build(TREE, *this).release()); } return *_point_locator; } void MeshBase::clear_point_locator () { _point_locator.reset(NULL); } } // namespace libMesh <commit_msg>Remove unnecessary/buggy mutex acquisition from point_locator()<commit_after>// $Id$ // The libMesh Finite Element Library. // Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // library configuration #include "libmesh_config.h" // C++ includes #include <algorithm> // for std::min #include <map> // for std::multimap #include <sstream> // for std::ostringstream // Local includes #include "boundary_info.h" #include "elem.h" #include "mesh_base.h" #include "parallel.h" #include "partitioner.h" #include "point_locator_base.h" #include "threads.h" namespace libMesh { // ------------------------------------------------------------ // MeshBase class member functions MeshBase::MeshBase (unsigned int d) : boundary_info (new BoundaryInfo(*this)), _n_parts (1), _dim (d), _is_prepared (false), _point_locator (NULL), _partitioner (NULL) { libmesh_assert (LIBMESH_DIM <= 3); libmesh_assert (LIBMESH_DIM >= _dim); libmesh_assert (libMesh::initialized()); } MeshBase::MeshBase (const MeshBase& other_mesh) : boundary_info (new BoundaryInfo(*this)), // no copy constructor defined for BoundaryInfo? _n_parts (other_mesh._n_parts), _dim (other_mesh._dim), _is_prepared (other_mesh._is_prepared), _point_locator (NULL), _partitioner (other_mesh._partitioner->clone()) { } MeshBase::~MeshBase() { this->clear(); libmesh_assert (!libMesh::closed()); } void MeshBase::prepare_for_use (const bool skip_renumber_nodes_and_elements) { // Renumber the nodes and elements so that they in contiguous // blocks. By default, skip_renumber_nodes_and_elements is false, // however we may skip this step by passing // skip_renumber_nodes_and_elements==true to this function. // // Instances where you if prepare_for_use() should not renumber the nodes // and elements include reading in e.g. an xda/r or gmv file. In // this case, the ordering of the nodes may depend on an accompanying // solution, and the node ordering cannot be changed. if(!skip_renumber_nodes_and_elements) this->renumber_nodes_and_elements(); // Let all the elements find their neighbors this->find_neighbors(); // Partition the mesh. this->partition(); // If we're using ParallelMesh, we'll want it parallelized. this->delete_remote_elements(); if(!skip_renumber_nodes_and_elements) this->renumber_nodes_and_elements(); // Reset our PointLocator. This needs to happen any time the elements // in the underlying elements in the mesh have changed, so we do it here. this->clear_point_locator(); // The mesh is now prepared for use. _is_prepared = true; } void MeshBase::clear () { // Reset the number of partitions _n_parts = 1; // Reset the _is_prepared flag _is_prepared = false; // Clear boundary information this->boundary_info->clear(); // Clear our point locator. this->clear_point_locator(); } unsigned int MeshBase::n_subdomains() const { // This requires an inspection on every processor parallel_only(); const_element_iterator el = this->active_elements_begin(); const const_element_iterator end = this->active_elements_end(); std::set<unsigned int> subdomain_ids; for (; el!=end; ++el) subdomain_ids.insert((*el)->subdomain_id()); // Some subdomains may only live on other processors Parallel::set_union(subdomain_ids, 0); unsigned int n_sbd_ids = subdomain_ids.size(); Parallel::broadcast(n_sbd_ids); return n_sbd_ids; } unsigned int MeshBase::n_nodes_on_proc (const unsigned int proc_id) const { // We're either counting a processor's nodes or unpartitioned // nodes libmesh_assert (proc_id < libMesh::n_processors() || proc_id == DofObject::invalid_processor_id); return static_cast<unsigned int>(std::distance (this->pid_nodes_begin(proc_id), this->pid_nodes_end (proc_id))); } unsigned int MeshBase::n_elem_on_proc (const unsigned int proc_id) const { // We're either counting a processor's elements or unpartitioned // elements libmesh_assert (proc_id < libMesh::n_processors() || proc_id == DofObject::invalid_processor_id); return static_cast<unsigned int>(std::distance (this->pid_elements_begin(proc_id), this->pid_elements_end (proc_id))); } unsigned int MeshBase::n_active_elem_on_proc (const unsigned int proc_id) const { libmesh_assert (proc_id < libMesh::n_processors()); return static_cast<unsigned int>(std::distance (this->active_pid_elements_begin(proc_id), this->active_pid_elements_end (proc_id))); } unsigned int MeshBase::n_sub_elem () const { unsigned int ne=0; const_element_iterator el = this->elements_begin(); const const_element_iterator end = this->elements_end(); for (; el!=end; ++el) ne += (*el)->n_sub_elem(); return ne; } unsigned int MeshBase::n_active_sub_elem () const { unsigned int ne=0; const_element_iterator el = this->active_elements_begin(); const const_element_iterator end = this->active_elements_end(); for (; el!=end; ++el) ne += (*el)->n_sub_elem(); return ne; } std::string MeshBase::get_info() const { std::ostringstream out; out << " Mesh Information:" << '\n' << " mesh_dimension()=" << this->mesh_dimension() << '\n' << " spatial_dimension()=" << this->spatial_dimension() << '\n' << " n_nodes()=" << this->n_nodes() << '\n' << " n_local_nodes()=" << this->n_local_nodes() << '\n' << " n_elem()=" << this->n_elem() << '\n' << " n_local_elem()=" << this->n_local_elem() << '\n' #ifdef LIBMESH_ENABLE_AMR << " n_active_elem()=" << this->n_active_elem() << '\n' #endif << " n_subdomains()=" << this->n_subdomains() << '\n' << " n_processors()=" << this->n_processors() << '\n' << " processor_id()=" << this->processor_id() << '\n'; return out.str(); } void MeshBase::print_info(std::ostream& os) const { os << this->get_info() << std::endl; } std::ostream& operator << (std::ostream& os, const MeshBase& m) { m.print_info(os); return os; } void MeshBase::partition (const unsigned int n_parts) { if (partitioner().get()) // "NULL" means don't partition partitioner()->partition (*this, n_parts); } unsigned int MeshBase::recalculate_n_partitions() { const_element_iterator el = this->active_elements_begin(); const const_element_iterator end = this->active_elements_end(); unsigned int max_proc_id=0; for (; el!=end; ++el) max_proc_id = std::max(max_proc_id, static_cast<unsigned int>((*el)->processor_id())); // The number of partitions is one more than the max processor ID. _n_parts = max_proc_id+1; return _n_parts; } const PointLocatorBase & MeshBase::point_locator () const { if (_point_locator.get() == NULL) { // PointLocator construction may not be safe within threads libmesh_assert(!Threads::in_threads); _point_locator.reset (PointLocatorBase::build(TREE, *this).release()); } } void MeshBase::clear_point_locator () { _point_locator.reset(NULL); } } // namespace libMesh <|endoftext|>
<commit_before><commit_msg>Rename ImplGetGradientColorValue<commit_after><|endoftext|>
<commit_before><commit_msg>help coverity out wrt coverity#1267682 String not null terminated<commit_after><|endoftext|>
<commit_before>#include <QApplication> #include <QMainWindow> #include <QToolBar> #include <QDebug> #include "../core/folder.h" #include "../foldermodel.h" #include "../folderview.h" #include "../cachedfoldermodel.h" #include "../proxyfoldermodel.h" #include "../pathedit.h" #include "libfmqt.h" int main(int argc, char** argv) { QApplication app(argc, argv); Fm::LibFmQt contex; QMainWindow win; Fm::FolderView folder_view; win.setCentralWidget(&folder_view); auto home = Fm::FilePath::homeDir(); Fm::CachedFolderModel* model = Fm::CachedFolderModel::modelFromPath(home); auto proxy_model = new Fm::ProxyFolderModel(); proxy_model->sort(Fm::FolderModel::ColumnFileName, Qt::AscendingOrder); proxy_model->setSourceModel(model); proxy_model->setThumbnailSize(64); proxy_model->setShowThumbnails(true); folder_view.setModel(proxy_model); QToolBar toolbar; win.addToolBar(Qt::TopToolBarArea, &toolbar); Fm::PathEdit edit; edit.setText(home.toString().get()); toolbar.addWidget(&edit); auto action = new QAction(QStringLiteral("Go"), nullptr); toolbar.addAction(action); QObject::connect(action, &QAction::triggered, [&]() { auto path = Fm::FilePath::fromPathStr(edit.text().toLocal8Bit().constData()); auto new_model = Fm::CachedFolderModel::modelFromPath(path); proxy_model->setSourceModel(new_model); }); win.show(); return app.exec(); } <commit_msg>Update test-folderview.cpp<commit_after>/* * Copyright (C) 2017 Hong Jen Yee (PCMan) <pcman.tw@gmail.com> * * 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 * */ #include <QApplication> #include <QMainWindow> #include <QToolBar> #include <QDebug> #include "../core/folder.h" #include "../foldermodel.h" #include "../folderview.h" #include "../cachedfoldermodel.h" #include "../proxyfoldermodel.h" #include "../pathedit.h" #include "libfmqt.h" int main(int argc, char** argv) { QApplication app(argc, argv); Fm::LibFmQt contex; QMainWindow win; Fm::FolderView folder_view; win.setCentralWidget(&folder_view); auto home = Fm::FilePath::homeDir(); Fm::CachedFolderModel* model = Fm::CachedFolderModel::modelFromPath(home); auto proxy_model = new Fm::ProxyFolderModel(); proxy_model->sort(Fm::FolderModel::ColumnFileName, Qt::AscendingOrder); proxy_model->setSourceModel(model); proxy_model->setThumbnailSize(64); proxy_model->setShowThumbnails(true); folder_view.setModel(proxy_model); QToolBar toolbar; win.addToolBar(Qt::TopToolBarArea, &toolbar); Fm::PathEdit edit; edit.setText(home.toString().get()); toolbar.addWidget(&edit); auto action = new QAction(QStringLiteral("Go"), nullptr); toolbar.addAction(action); QObject::connect(action, &QAction::triggered, [&]() { auto path = Fm::FilePath::fromPathStr(edit.text().toLocal8Bit().constData()); auto new_model = Fm::CachedFolderModel::modelFromPath(path); proxy_model->setSourceModel(new_model); }); win.show(); return app.exec(); } <|endoftext|>
<commit_before>#include <taichi/visual/gui.h> #include "../tlang.h" TLANG_NAMESPACE_BEGIN auto volume_renderer = [] { CoreState::set_trigger_gdb_when_crash(true); int n = 512; int grid_resolution = 256; auto f = fopen("snow_density_256.bin", "rb"); TC_ASSERT_INFO(f, "./snow_density_256.bin not found"); std::vector<float32> density_field(pow<3>(grid_resolution)); std::fread(density_field.data(), sizeof(float32), density_field.size(), f); std::fclose(f); Program prog(Arch::gpu); prog.config.print_ir = true; Vector buffer(DataType::f32, 3); Global(density, f32); layout([&]() { root.dense(Index(0), n * n * 2).place(buffer(0), buffer(1), buffer(2)); root.dense(Indices(0, 1, 2), grid_resolution).place(density); }); // If p is in the density field return the density, other 0 auto query_density = [&](Vector p) { auto inside_box = Var(0.0f <= p(0) && p(0) < 1.0f && 0.0f <= p(1) && p(1) < 1.0f && 0.0f <= p(2) && p(2) < 1.0f); auto ret = Var(0.0f); If(inside_box).Then([&] { auto i = floor(p(0) * float32(grid_resolution)); auto j = floor(p(1) * float32(grid_resolution)); auto k = floor(p(2) * float32(grid_resolution)); ret = density[i, j, k]; }); return ret; }; auto background = [](Vector dir) { return 1.0f * max(dir(1) + dir(0), 0.0f); }; float32 fov = 0.7; Kernel(main).def([&]() { For(0, n * n * 2, [&](Expr i) { auto orig = Var(Vector({0.5f, 0.3f, 1.5f})); auto c = Var(Vector({fov * (cast<float32>(i / n) / float32(n / 2) - 2.0f), fov * (cast<float32>(i % n) / float32(n / 2) - 1.0f), -1.0f})); c = normalized(c); auto color = Var(Vector({1.0f, 1.0f, 1.0f})); For(0, 200, [&](Expr k) { auto p = Var(orig + c * ((cast<float32>(k) + Rand<float32>()) * 0.01f)); color *= (1.0_f - query_density(p) * 0.1f); }); buffer[i] += color; }); }); for (int i = 0; i < grid_resolution; i++) { for (int j = 0; j < grid_resolution; j++) { for (int k = 0; k < grid_resolution; k++) { density.val<float32>(i, j, k) = density_field[i * grid_resolution * grid_resolution + j * grid_resolution + k]; } } } GUI gui("Volume Renderer", Vector2i(n * 2, n)); auto tone_map = [](real x) { return x; }; constexpr int N = 10; for (int frame = 0;; frame++) { for (int i = 0; i < N; i++) main(); real scale = 1.0f / ((frame + 1) * N); for (int i = 0; i < n * n * 2; i++) { gui.buffer[i / n][i % n] = Vector4(tone_map(scale * buffer(0).val<float32>(i)), tone_map(scale * buffer(1).val<float32>(i)), tone_map(scale * buffer(2).val<float32>(i)), 1); } gui.update(); } }; TC_REGISTER_TASK(volume_renderer); TLANG_NAMESPACE_END <commit_msg>Volume renderer<commit_after>#include <taichi/visual/gui.h> #include "../tlang.h" TLANG_NAMESPACE_BEGIN auto volume_renderer = [] { //CoreState::set_trigger_gdb_when_crash(true); int depth_limit = 40; int n = 512; int grid_resolution = 256; Vector3 albedo(0.95, 0.95, 0.95); float32 scale = 724.0; float32 one_over_four_pi = 0.07957747154; float32 pi = 3.14159265359; auto f = fopen("snow_density_256.bin", "rb"); TC_ASSERT_INFO(f, "./snow_density_256.bin not found"); std::vector<float32> density_field(pow<3>(grid_resolution)); std::fread(density_field.data(), sizeof(float32), density_field.size(), f); std::fclose(f); Program prog(Arch::gpu); prog.config.print_ir = true; Vector buffer(DataType::f32, 3); Global(density, f32); layout([&]() { root.dense(Index(0), n * n * 2).place(buffer(0), buffer(1), buffer(2)); root.dense(Indices(0, 1, 2), grid_resolution).place(density); }); auto point_inside_box = [&](Vector p) { return Var(0.0f <= p(0) && p(0) < 1.0f && 0.0f <= p(1) && p(1) < 1.0f && 0.0f <= p(2) && p(2) < 1.0f); }; // If p is in the density field, return the density, otherwise return 0 auto query_density = [&](Vector p) { auto inside_box = point_inside_box(p); auto ret = Var(0.0f); If(inside_box).Then([&] { auto i = floor(p(0) * float32(grid_resolution)); auto j = floor(p(1) * float32(grid_resolution)); auto k = floor(p(2) * float32(grid_resolution)); ret = density[i, j, k] * scale; }); return ret; }; // Adapted from Mitsuba: include/mitsuba/core/aabb.h#L308 auto box_intersect = [&](Vector o, Vector d, Expr& near_t, Expr& far_t) { auto result = Var(1); /* For each pair of AABB planes */ for (int i = 0; i < 3; i++) { auto origin = o(i); auto min_val = Var(0.f); auto max_val = Var(1.f); auto d_rcp = Var(1.f / d(i)); If(d(i) == 0.f) .Then([&] { /* The ray is parallel to the planes */ If(origin < min_val || origin > max_val, [&] { result = 0; }); }).Else([&] { /* Calculate intersection distances */ auto t1 = Var((min_val - origin) * d_rcp); auto t2 = Var((max_val - origin) * d_rcp); If(t1 > t2, [&] { auto tmp = Var(t1); t1 = t2; t2 = tmp; }); near_t = max(t1, near_t); far_t = min(t2, far_t); If(near_t > far_t, [&] { result = 0; }); }); } return result; }; // Adapted from Mitsuba: src/libcore/warp.cpp#L25 auto sample_phase_isotropic = [&]() { auto z = Var(1.0f - 2.0f * Rand<float32>()); auto r = Var(sqrt(1.0f - z * z)); auto phi = Var(2.0f * pi * Rand<float32>()); auto sin_phi = Var(sin(phi)); auto cos_phi = Var(cos(phi)); return Var(Vector({r * cos_phi, r * sin_phi, z})); }; auto pdf_phase_isotropic = [&]() { return Var(one_over_four_pi); }; auto eval_phase_isotropic = [&]() { return pdf_phase_isotropic(); }; // Direct sample light auto sample_light = [&](Vector p, float32 inv_max_density) { auto Le = Var(Vector({5.0f, 5.0f, 5.0f})); auto light_p = Var(Vector({0.5f, 1.5f, 0.5f})); auto dir_to_p = Var(p - light_p); auto dist_to_p = Var(dir_to_p.norm()); auto inv_dist_to_p = Var(1.f / dist_to_p); dir_to_p = normalized(dir_to_p); auto near_t = Var(-std::numeric_limits<float>::max()); auto far_t = Var(std::numeric_limits<float>::max()); auto hit = box_intersect(light_p, dir_to_p, near_t, far_t); auto interaction = Var(0); auto transmittance = Var(1.f); If(hit, [&] { auto cond = Var(hit); auto t = Var(near_t); While(cond, [&] { t -= log(1.f - Rand<float32>()) * inv_max_density; p = Var(light_p + t * dir_to_p); If(t >= dist_to_p || !point_inside_box(p)) .Then([&] { cond = 0; }) .Else([&] { auto density_at_p = query_density(p); If(density_at_p * inv_max_density > Rand<float32>()).Then([&] { cond = 0; transmittance = Var(0.f); }); }); }); }); return Var(transmittance * Le * inv_dist_to_p * inv_dist_to_p); }; // Woodcock tracking auto sample_distance = [&](Vector o, Vector d, float32 inv_max_density, Expr& dist, Vector& sigma_s, Expr& transmittance, Vector& p) { auto near_t = Var(-std::numeric_limits<float>::max()); auto far_t = Var(std::numeric_limits<float>::max()); auto hit = box_intersect(o, d, near_t, far_t); auto cond = Var(hit); auto interaction = Var(0); auto t = Var(near_t); While(cond, [&] { t -= log(1.f - Rand<float32>()) * inv_max_density; p = Var(o + t * d); If(t >= far_t || !point_inside_box(p)) .Then([&] { cond = 0; }) .Else([&] { auto density_at_p = query_density(p); If(density_at_p * inv_max_density > Rand<float32>()).Then([&] { sigma_s(0) = Var(density_at_p * albedo[0]); sigma_s(1) = Var(density_at_p * albedo[1]); sigma_s(2) = Var(density_at_p * albedo[2]); If(density_at_p != 0.f).Then([&] { transmittance = 1.f / density_at_p; }); cond = 0; interaction = 1; }); }); }); dist = t - near_t; return hit && interaction; }; auto background = [](Vector dir) { return Vector({0.4f, 0.4f, 0.4f}); }; float32 fov = 0.7; auto max_density = *std::max_element(density_field.begin(), density_field.end()) * scale; auto inv_max_density = 0.f; if (max_density > 0.f) { inv_max_density = 1.f / max_density; } Kernel(main).def([&]() { For(0, n * n * 2, [&](Expr i) { auto orig = Var(Vector({0.5f, 0.3f, 1.5f})); auto c = Var(Vector({fov * ((Rand<float32>() + cast<float32>(i / n)) / float32(n / 2) - 2.0f), fov * ((Rand<float32>() + cast<float32>(i % n)) / float32(n / 2) - 1.0f), -1.0f})); c = normalized(c); auto color = Var(Vector({1.0f, 1.0f, 1.0f})); auto Li = Var(Vector({0.0f, 0.0f, 0.0f})); auto throughput = Var(Vector({1.0f, 1.0f, 1.0f})); auto depth = Var(0); While(depth < depth_limit, [&] { auto dist = Var(0.f); auto transmittance = Var(0.f); auto sigma_s = Var(Vector({0.f, 0.f, 0.f})); auto interaction_p = Var(Vector({0.f, 0.f, 0.f})); auto interaction = sample_distance(orig, c, inv_max_density, dist, sigma_s, transmittance, interaction_p); depth += 1; If(interaction) .Then([&] { throughput = throughput.element_wise_prod(sigma_s * transmittance); auto phase_value = eval_phase_isotropic(); auto light_value = sample_light(interaction_p, inv_max_density); Li += phase_value * throughput.element_wise_prod(light_value); orig = interaction_p; c = sample_phase_isotropic(); }).Else([&] { Li += throughput.element_wise_prod(background(c)); depth = depth_limit; }); }); buffer[i] += Li; }); }); for (int i = 0; i < grid_resolution; i++) { for (int j = 0; j < grid_resolution; j++) { for (int k = 0; k < grid_resolution; k++) { density.val<float32>(i, j, k) = density_field[i * grid_resolution * grid_resolution + j * grid_resolution + k]; } } } //GUI gui("Volume Renderer", Vector2i(n * 2, n)); Vector2i render_size(n * 2, n); Array2D<Vector4> render_buffer; std::unique_ptr<Canvas> canvas; auto tone_map = [](real x) { return x; }; constexpr int N = 1024; for (int frame = 0; frame < 1; frame++) { for (int i = 0; i < N; i++) { main(); } real scale = 1.0f / ((frame + 1) * N); render_buffer.initialize(render_size); canvas = std::make_unique<Canvas>(render_buffer); for (int i = 0; i < n * n * 2; i++) { render_buffer[i / n][i % n] = Vector4(tone_map(scale * buffer(0).val<float32>(i)), tone_map(scale * buffer(1).val<float32>(i)), tone_map(scale * buffer(2).val<float32>(i)), 1); } //gui.update(); canvas->img.write_as_image(fmt::format("{:05d}-{:05d}-{:05d}.png", frame, N, depth_limit)); } }; TC_REGISTER_TASK(volume_renderer); TLANG_NAMESPACE_END <|endoftext|>
<commit_before> #include "vtrc-transport-tcp.h" #include "vtrc-protocol-layer.h" #include "vtrc-transport-stream-impl.h" namespace vtrc { namespace common { namespace basio = boost::asio; namespace bip = boost::asio::ip; namespace bsys = boost::system; namespace { typedef transport_tcp::socket_type socket_type; typedef transport_impl<socket_type, transport_tcp> impl_type; } struct transport_tcp::impl: public impl_type { impl( vtrc::shared_ptr<socket_type> s, const std::string &n ) :impl_type(s, n) { } std::string prepare_for_write(const char *data, size_t len) { return get_parent( )->prepare_for_write( data, len ); } }; std::string make_name( socket_type &sock ) { std::ostringstream oss; oss << "tcp://" << sock.remote_endpoint( ); } transport_tcp::transport_tcp( vtrc::shared_ptr<socket_type> sock ) :impl_(new impl(sock, "tcp")) { impl_->set_parent( this ); } transport_tcp::~transport_tcp( ) { delete impl_; } std::string transport_tcp::name( ) const { return impl_->name( ); } void transport_tcp::close( ) { impl_->close( ); } void transport_tcp::write( const char *data, size_t length ) { return impl_->write( data, length ); } void transport_tcp::write(const char *data, size_t length, const system_closure_type &success, bool on_send_success) { impl_->write( data, length, success, on_send_success ); } std::string transport_tcp::prepare_for_write(const char *data, size_t len) { return impl_->prepare_for_write( data, len ); } socket_type &transport_tcp::get_socket( ) { return impl_->get_socket( ); } const socket_type &transport_tcp::get_socket( ) const { return impl_->get_socket( ); } }} <commit_msg>listener<commit_after> #include "vtrc-transport-tcp.h" #include "vtrc-protocol-layer.h" #include "vtrc-transport-stream-impl.h" namespace vtrc { namespace common { namespace basio = boost::asio; namespace bip = boost::asio::ip; namespace bsys = boost::system; namespace { typedef transport_tcp::socket_type socket_type; typedef transport_impl<socket_type, transport_tcp> impl_type; } struct transport_tcp::impl: public impl_type { impl( vtrc::shared_ptr<socket_type> s, const std::string &n ) :impl_type(s, n) { } std::string prepare_for_write(const char *data, size_t len) { return get_parent( )->prepare_for_write( data, len ); } }; transport_tcp::transport_tcp( vtrc::shared_ptr<socket_type> sock ) :impl_(new impl(sock, "tcp")) { impl_->set_parent( this ); } transport_tcp::~transport_tcp( ) { delete impl_; } std::string transport_tcp::name( ) const { return impl_->name( ); } void transport_tcp::close( ) { impl_->close( ); } void transport_tcp::write( const char *data, size_t length ) { return impl_->write( data, length ); } void transport_tcp::write(const char *data, size_t length, const system_closure_type &success, bool on_send_success) { impl_->write( data, length, success, on_send_success ); } std::string transport_tcp::prepare_for_write(const char *data, size_t len) { return impl_->prepare_for_write( data, len ); } socket_type &transport_tcp::get_socket( ) { return impl_->get_socket( ); } const socket_type &transport_tcp::get_socket( ) const { return impl_->get_socket( ); } }} <|endoftext|>
<commit_before>#ifndef MJOLNIR_UTIL_ALIGNED_STORAGE_HPP #define MJOLNIR_UTIL_ALIGNED_STORAGE_HPP #include <type_traits> #include <array> #include <cstdint> namespace mjolnir { template<typename T, std::size_t Align = 64> struct alignas(Align) aligned_storage { public: using type = T; static_assert(Align != 0, ""); static constexpr std::size_t alignment_size = Align; static constexpr std::size_t value_size = sizeof(T); static constexpr std::size_t padded_size = alignment_size * (value_size / alignment_size + 1); static constexpr std::size_t padding_size = alignment_size - (value_size % alignment_size); static_assert((padding_size + value_size) % padded_size == 0, ""); static_assert((padding_size + value_size) % alignment_size == 0, ""); public: aligned_storage() = default; ~aligned_storage() = default; aligned_storage(aligned_storage const&) = default; aligned_storage(aligned_storage &&) = default; aligned_storage& operator=(aligned_storage const&) = default; aligned_storage& operator=(aligned_storage &&) = default; aligned_storage(const T& v) noexcept(std::is_nothrow_copy_constructible<T>::value) : value(v) {} aligned_storage(T&& v) noexcept(std::is_nothrow_move_constructible<T>::value) : value(v) {} T value; private: std::array<std::uint8_t, padding_size> padding_; }; static_assert(alignof(aligned_storage<std::int32_t, 64>) == 64, ""); static_assert(sizeof (aligned_storage<std::int32_t, 64>) == 64, ""); } // mjolnir #endif// MJOLNIR_UTIL_ALIGNED_STORAGE_HPP <commit_msg>test: add a static_assert for aligned storage<commit_after>#ifndef MJOLNIR_UTIL_ALIGNED_STORAGE_HPP #define MJOLNIR_UTIL_ALIGNED_STORAGE_HPP #include <type_traits> #include <utility> #include <array> #include <cstdint> namespace mjolnir { template<typename T, std::size_t Align = 64> struct alignas(Align) aligned_storage { public: using type = T; static_assert(Align != 0, ""); static constexpr std::size_t alignment_size = Align; static constexpr std::size_t value_size = sizeof(T); static constexpr std::size_t padded_size = alignment_size * (value_size / alignment_size + 1); static constexpr std::size_t padding_size = alignment_size - (value_size % alignment_size); static_assert((padding_size + value_size) % padded_size == 0, ""); static_assert((padding_size + value_size) % alignment_size == 0, ""); public: aligned_storage() = default; ~aligned_storage() = default; aligned_storage(aligned_storage const&) = default; aligned_storage(aligned_storage &&) = default; aligned_storage& operator=(aligned_storage const&) = default; aligned_storage& operator=(aligned_storage &&) = default; aligned_storage(const T& v) noexcept(std::is_nothrow_copy_constructible<T>::value) : value(v) {} aligned_storage(T&& v) noexcept(std::is_nothrow_move_constructible<T>::value) : value(v) {} T value; private: std::array<std::uint8_t, padding_size> padding_; }; static_assert(alignof(aligned_storage<std::int32_t, 64>) == 64, ""); static_assert(sizeof (aligned_storage<std::int32_t, 64>) == 64, ""); static_assert(alignof(aligned_storage<std::pair<std::int32_t, std::int64_t>, 64>) == 64, ""); static_assert(sizeof (aligned_storage<std::pair<std::int32_t, std::int64_t>, 64>) == 64, ""); } // mjolnir #endif// MJOLNIR_UTIL_ALIGNED_STORAGE_HPP <|endoftext|>
<commit_before>/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.com */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without modification, */ /* are permitted provided that the following conditions are met: */ /* */ /* - Redistributions of source code must retain the above copyright notice, this */ /* list of conditions and the following disclaimer. */ /* */ /* - Redistributions in binary form must reproduce the above copyright notice, this */ /* list of conditions and the following disclaimer in the documentation and/or */ /* other materials provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */ /* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ /* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */ /* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ /* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */ /* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */ /* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* */ /**************************************************************************************/ #ifndef DrawArrays_INCLUDE_DEFINE #define DrawArrays_INCLUDE_DEFINE #include <vlGraphics/DrawCall.hpp> #include <vlGraphics/TriangleIterator.hpp> namespace vl { //------------------------------------------------------------------------------ // DrawArrays //------------------------------------------------------------------------------ /** * Wraps the OpenGL function glDrawArrays(). See also http://www.opengl.org/sdk/docs/man/xhtml/glDrawArrays.xml for more information. * * DrawElements, MultiDrawElements, DrawRangeElements, DrawArrays are used by Geometry to define a set of primitives to be rendered, see Geometry::drawCalls(). * * \sa DrawCall, DrawElements, MultiDrawElements, DrawRangeElements, Geometry, Actor */ class DrawArrays: public DrawCall { public: DrawArrays(): mStart(0), mCount(0) { VL_DEBUG_SET_OBJECT_NAME() mType = PT_TRIANGLES; mInstances = 1; } DrawArrays(EPrimitiveType primitive, int start, int count, int instances=1) : mStart(start), mCount(count) { VL_DEBUG_SET_OBJECT_NAME() mInstances = instances; mType = primitive; } virtual const char* className() const { return "vl::DrawArrays"; } DrawArrays& operator=(const DrawArrays& other) { DrawCall::operator=(other); mStart = other.mStart; mCount = other.mCount; mInstances = other.mInstances; return *this; } virtual ref<DrawCall> clone() const { return new DrawArrays( primitiveType(), (int)start(), (int)count(), (int)instances() ); } virtual void deleteVBOs() {} virtual void updateVBOs(bool,bool) {} virtual unsigned int handle() const { return 0; } virtual void render(bool) const { // apply patch parameters if any and if using PT_PATCHES applyPatchParameters(); if ( instances() > 1 && (Has_GL_ARB_draw_instanced||Has_GL_EXT_draw_instanced) ) VL_glDrawArraysInstanced( primitiveType(), (int)start(), (int)count(), (int)instances() ); else glDrawArrays( primitiveType(), (int)start(), (int)count() ); #ifndef NDEBUG unsigned int glerr = glGetError(); if (glerr != GL_NO_ERROR) { String msg( (char*)gluErrorString(glerr) ); Log::error( Say("glGetError() [%s:%n]: %s\n") << __FILE__ << __LINE__ << msg ); Log::print( "OpenGL Geometry Instancing (GL_ARB_draw_instanced) does not support display lists." "If you are using geometry instancing in conjunction with display lists you will have to disable one of them.\n" ); VL_TRAP() } #endif } //! sets the starting vertex for the rendering. void setStart(int start) { mStart = start; } //! returns the starting vertex for the rendering. int start() const { return mStart; } //! sets the number of vertices to be rendered. void setCount(int count) { mCount = count; } //! returns the number of vertices to be rendered. int count() const { return mCount; } //! Sets the number of instances for this set of primitives. void setInstances(int instances) { mInstances = instances; } //! Returns the number of instances for this set of primitives. int instances() const { return mInstances; } TriangleIterator triangleIterator() const { ref<TriangleIteratorDirect> tid = new TriangleIteratorDirect( primitiveType() ); tid->initialize(mStart, mStart+mCount); return TriangleIterator(tid.get()); } IndexIterator indexIterator() const { ref<IndexIteratorDrawArrays> iida = new IndexIteratorDrawArrays; iida->initialize( mStart, mCount ); IndexIterator iit; iit.initialize( iida.get() ); return iit; } protected: int mStart; int mCount; int mInstances; }; } #endif <commit_msg>Removed glu dependency.<commit_after>/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.com */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without modification, */ /* are permitted provided that the following conditions are met: */ /* */ /* - Redistributions of source code must retain the above copyright notice, this */ /* list of conditions and the following disclaimer. */ /* */ /* - Redistributions in binary form must reproduce the above copyright notice, this */ /* list of conditions and the following disclaimer in the documentation and/or */ /* other materials provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */ /* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ /* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */ /* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ /* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */ /* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */ /* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* */ /**************************************************************************************/ #ifndef DrawArrays_INCLUDE_DEFINE #define DrawArrays_INCLUDE_DEFINE #include <vlGraphics/DrawCall.hpp> #include <vlGraphics/TriangleIterator.hpp> namespace vl { //------------------------------------------------------------------------------ // DrawArrays //------------------------------------------------------------------------------ /** * Wraps the OpenGL function glDrawArrays(). See also http://www.opengl.org/sdk/docs/man/xhtml/glDrawArrays.xml for more information. * * DrawElements, MultiDrawElements, DrawRangeElements, DrawArrays are used by Geometry to define a set of primitives to be rendered, see Geometry::drawCalls(). * * \sa DrawCall, DrawElements, MultiDrawElements, DrawRangeElements, Geometry, Actor */ class DrawArrays: public DrawCall { public: DrawArrays(): mStart(0), mCount(0) { VL_DEBUG_SET_OBJECT_NAME() mType = PT_TRIANGLES; mInstances = 1; } DrawArrays(EPrimitiveType primitive, int start, int count, int instances=1) : mStart(start), mCount(count) { VL_DEBUG_SET_OBJECT_NAME() mInstances = instances; mType = primitive; } virtual const char* className() const { return "vl::DrawArrays"; } DrawArrays& operator=(const DrawArrays& other) { DrawCall::operator=(other); mStart = other.mStart; mCount = other.mCount; mInstances = other.mInstances; return *this; } virtual ref<DrawCall> clone() const { return new DrawArrays( primitiveType(), (int)start(), (int)count(), (int)instances() ); } virtual void deleteVBOs() {} virtual void updateVBOs(bool,bool) {} virtual unsigned int handle() const { return 0; } virtual void render(bool) const { // apply patch parameters if any and if using PT_PATCHES applyPatchParameters(); if ( instances() > 1 && (Has_GL_ARB_draw_instanced||Has_GL_EXT_draw_instanced) ) VL_glDrawArraysInstanced( primitiveType(), (int)start(), (int)count(), (int)instances() ); else glDrawArrays( primitiveType(), (int)start(), (int)count() ); #ifndef NDEBUG unsigned int glerr = glGetError(); if (glerr != GL_NO_ERROR) { String msg( getGLErrorString(glerr) ); Log::error( Say("glGetError() [%s:%n]: %s\n") << __FILE__ << __LINE__ << msg ); Log::print( "OpenGL Geometry Instancing (GL_ARB_draw_instanced) does not support display lists." "If you are using geometry instancing in conjunction with display lists you will have to disable one of them.\n" ); VL_TRAP() } #endif } //! sets the starting vertex for the rendering. void setStart(int start) { mStart = start; } //! returns the starting vertex for the rendering. int start() const { return mStart; } //! sets the number of vertices to be rendered. void setCount(int count) { mCount = count; } //! returns the number of vertices to be rendered. int count() const { return mCount; } //! Sets the number of instances for this set of primitives. void setInstances(int instances) { mInstances = instances; } //! Returns the number of instances for this set of primitives. int instances() const { return mInstances; } TriangleIterator triangleIterator() const { ref<TriangleIteratorDirect> tid = new TriangleIteratorDirect( primitiveType() ); tid->initialize(mStart, mStart+mCount); return TriangleIterator(tid.get()); } IndexIterator indexIterator() const { ref<IndexIteratorDrawArrays> iida = new IndexIteratorDrawArrays; iida->initialize( mStart, mCount ); IndexIterator iit; iit.initialize( iida.get() ); return iit; } protected: int mStart; int mCount; int mInstances; }; } #endif <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_FUN_SOFTMAX_HPP #define STAN_MATH_REV_FUN_SOFTMAX_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/fun/value_of.hpp> #include <stan/math/rev/functor/reverse_pass_callback.hpp> #include <stan/math/rev/functor/arena_matrix.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/fun/typedefs.hpp> #include <stan/math/prim/fun/softmax.hpp> #include <stan/math/prim/fun/to_ref.hpp> #include <stan/math/prim/fun/value_of.hpp> #include <tuple> #include <vector> namespace stan { namespace math { /** * Return the softmax of the specified Eigen vector. Softmax is * guaranteed to return a simplex. * * @param alpha Unconstrained input vector. * @return Softmax of the input. * @throw std::domain_error If the input vector is size 0. */ inline Eigen::Matrix<var, Eigen::Dynamic, 1> softmax( const Eigen::Matrix<var, Eigen::Dynamic, 1>& alpha) { if (alpha.size() == 0) { return alpha; } arena_matrix<Eigen::VectorXd> res_val = softmax(value_of(alpha)); arena_matrix<Eigen::Matrix<var, Eigen::Dynamic, 1>> res = res_val; arena_matrix<Eigen::Matrix<var, Eigen::Dynamic, 1>> alpha_arena = alpha; reverse_pass_callback([res_val, res, alpha_arena]() mutable { const auto& res_adj = to_ref(res.adj()); alpha_arena.adj() += -res_val * res_adj.dot(res_val) + res_val.cwiseProduct(res_adj); }); return res; } template <typename Mat, require_var_vt<is_eigen, Mat>* = nullptr> inline auto softmax(const Mat& alpha) { if (alpha.size() == 0) { return alpha; } Mat res(softmax(value_of(alpha))); reverse_pass_callback([alpha, res]() mutable { alpha.adj() += alpha.adj() -res.val() * res.adj().dot(res.val()) + res.val().cwiseProduct(res.adj()); }); return res; } } // namespace math } // namespace stan #endif <commit_msg>remove double += alpha.adj()<commit_after>#ifndef STAN_MATH_REV_FUN_SOFTMAX_HPP #define STAN_MATH_REV_FUN_SOFTMAX_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/fun/value_of.hpp> #include <stan/math/rev/functor/reverse_pass_callback.hpp> #include <stan/math/rev/functor/arena_matrix.hpp> #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/fun/typedefs.hpp> #include <stan/math/prim/fun/softmax.hpp> #include <stan/math/prim/fun/to_ref.hpp> #include <stan/math/prim/fun/value_of.hpp> #include <tuple> #include <vector> namespace stan { namespace math { /** * Return the softmax of the specified Eigen vector. Softmax is * guaranteed to return a simplex. * * @param alpha Unconstrained input vector. * @return Softmax of the input. * @throw std::domain_error If the input vector is size 0. */ inline Eigen::Matrix<var, Eigen::Dynamic, 1> softmax( const Eigen::Matrix<var, Eigen::Dynamic, 1>& alpha) { if (alpha.size() == 0) { return alpha; } arena_matrix<Eigen::VectorXd> res_val = softmax(value_of(alpha)); arena_matrix<Eigen::Matrix<var, Eigen::Dynamic, 1>> res = res_val; arena_matrix<Eigen::Matrix<var, Eigen::Dynamic, 1>> alpha_arena = alpha; reverse_pass_callback([res_val, res, alpha_arena]() mutable { const auto& res_adj = to_ref(res.adj()); alpha_arena.adj() += -res_val * res_adj.dot(res_val) + res_val.cwiseProduct(res_adj); }); return res; } template <typename Mat, require_var_vt<is_eigen, Mat>* = nullptr> inline auto softmax(const Mat& alpha) { if (alpha.size() == 0) { return alpha; } Mat res(softmax(value_of(alpha))); reverse_pass_callback([alpha, res]() mutable { alpha.adj() += -res.val() * res.adj().dot(res.val()) + res.val().cwiseProduct(res.adj()); }); return res; } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/* 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 "Camera.h" #include "Device.h" #include "Types.h" #include "Renderer.h" namespace crown { Camera::Camera(const Vec3& position, bool visible, float fov, float aspect, bool active) : mPosition(position), mLookAt(0, 0, -1), mUp(0, 1, 0), mFOV(fov), mAspect(aspect), mNear(0.1f), mFar(1000.0f), mActive(active), mAutoAspect(true) { UpdateProjectionMatrix(); UpdateViewMatrix(); UpdateFrustum(); } Camera::~Camera() { } void Camera::SetPosition(const Vec3& position) { mPosition = position; UpdateViewMatrix(); } const Vec3& Camera::GetLookAt() const { return mLookAt; } void Camera::SetLookAt(const Vec3& lookat) { mLookAt = lookat; UpdateViewMatrix(); } const Vec3& Camera::GetUpVector() const { return mUp; } bool Camera::IsActive() const { return mActive; } void Camera::SetActive(bool active) { mActive = active; } float Camera::GetFOV() const { return mFOV; } void Camera::SetFOV(float fov) { mFOV = fov; UpdateProjectionMatrix(); } bool Camera::GetAutoAspect() const { return mAutoAspect; } void Camera::SetAutoAspect(bool autoAspect) { mAutoAspect = autoAspect; } float Camera::GetAspect() const { return mAspect; } void Camera::SetAspect(float aspect) { mAspect = aspect; UpdateProjectionMatrix(); } float Camera::GetNearClipDistance() const { return mNear; } void Camera::SetNearClipDistance(float near) { mNear = near; UpdateProjectionMatrix(); } float Camera::GetFarClipDistance() const { return mFar; } void Camera::SetFarClipDistance(float far) { mFar = far; UpdateProjectionMatrix(); } const Mat4& Camera::GetProjectionMatrix() const { return mProjection; } const Mat4& Camera::GetViewMatrix() const { return mView; } const Frustum& Camera::GetFrustum() const { return mFrustum; } void Camera::Render() { GetDevice()->GetRenderer()->SetMatrix(MT_PROJECTION, mProjection); GetDevice()->GetRenderer()->SetMatrix(MT_VIEW, mView); } void Camera::UpdateProjectionMatrix() { mProjection.build_projection_perspective_rh(mFOV, mAspect, mNear, mFar); } void Camera::UpdateViewMatrix() { mView.build_look_at_rh(mPosition, mPosition + mLookAt, mUp); } void Camera::UpdateFrustum() { mFrustum.from_matrix(mProjection * mView); } } // namespace crown <commit_msg>Update Camera.cpp<commit_after>/* 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 "Camera.h" #include "Device.h" #include "Types.h" #include "Renderer.h" namespace crown { Camera::Camera(const Vec3& position, bool visible, float fov, float aspect, bool active) : mPosition(position), mLookAt(0, 0, -1), mUp(0, 1, 0), mFOV(fov), mAspect(aspect), mNear(0.1f), mFar(1000.0f), mActive(active), mAutoAspect(true) { UpdateProjectionMatrix(); UpdateViewMatrix(); UpdateFrustum(); } Camera::~Camera() { } void Camera::SetPosition(const Vec3& position) { mPosition = position; UpdateViewMatrix(); } const Vec3& Camera::GetLookAt() const { return mLookAt; } void Camera::SetLookAt(const Vec3& lookat) { mLookAt = lookat; UpdateViewMatrix(); } const Vec3& Camera::GetUpVector() const { return mUp; } bool Camera::IsActive() const { return mActive; } void Camera::SetActive(bool active) { mActive = active; } float Camera::GetFOV() const { return mFOV; } void Camera::SetFOV(float fov) { mFOV = fov; UpdateProjectionMatrix(); } bool Camera::GetAutoAspect() const { return mAutoAspect; } void Camera::SetAutoAspect(bool autoAspect) { mAutoAspect = autoAspect; } float Camera::GetAspect() const { return mAspect; } void Camera::SetAspect(float aspect) { mAspect = aspect; UpdateProjectionMatrix(); } float Camera::GetNearClipDistance() const { return mNear; } void Camera::SetNearClipDistance(float near) { mNear = near; UpdateProjectionMatrix(); } float Camera::GetFarClipDistance() const { return mFar; } void Camera::SetFarClipDistance(float far) { mFar = far; UpdateProjectionMatrix(); } const Mat4& Camera::GetProjectionMatrix() const { return mProjection; } const Mat4& Camera::GetViewMatrix() const { return mView; } const Frustum& Camera::GetFrustum() const { return mFrustum; } void Camera::Render() { GetDevice()->GetRenderer()->set_matrix(MT_PROJECTION, mProjection); GetDevice()->GetRenderer()->set_matrix(MT_VIEW, mView); } void Camera::UpdateProjectionMatrix() { mProjection.build_projection_perspective_rh(mFOV, mAspect, mNear, mFar); } void Camera::UpdateViewMatrix() { mView.build_look_at_rh(mPosition, mPosition + mLookAt, mUp); } void Camera::UpdateFrustum() { mFrustum.from_matrix(mProjection * mView); } } // namespace crown <|endoftext|>
<commit_before>#include <Refal2.h> namespace Refal2 { //----------------------------------------------------------------------------- // CError void CError::Reset() { ResetSeverity(); ResetFileName(); ResetToken(); ResetMessage(); } bool CError::IsSet() const { return ( Severity() != ES_None && !Message().empty() ); } void CError::ResetSeverity() { severity = ES_None; resetCache(); } void CError::SetSeverity( TErrorSeverity _severity ) { assert( _severity != ES_None ); severity = _severity; resetCache(); } void CError::ResetFileName() { fileName.clear(); resetCache(); } void CError::SetFileName( const std::string& _fileName ) { assert( !_fileName.empty() ); fileName = _fileName; resetCache(); } void CError::ResetToken() { token.type = TT_None; resetCache(); } void CError::SetTokenData( int line, int position, const std::string& wrongText ) { token.type = TT_Word; token.line = line; token.position = position; token.word = wrongText; } void CError::SetToken( const CToken& _token ) { assert( !_token.IsNone() ); token = _token; resetCache(); } void CError::ResetMessage() { message.clear(); resetCache(); } void CError::SetMessage( const std::string& _message ) { assert( !_message.empty() ); message = _message; resetCache(); } const std::string& CError::UserMessage() const { if( userMessage.empty() ) { std::ostringstream userMessageStream; if( !fileName.empty() ) { userMessageStream << fileName << ":"; if( !token.IsNone() ) { userMessageStream << token.line << ":" << token.position << ":"; } userMessageStream << " "; } else { assert( token.IsNone() ); } switch( Severity() ) { case ES_Warning: userMessageStream << "warning"; break; case ES_Error: userMessageStream << "error"; break; case ES_LinkError: userMessageStream << "link error"; break; case ES_FatalError: userMessageStream << "fatal error"; break; case ES_None: default: assert( false ); break; } assert( !message.empty() ); userMessageStream << ": " << message << "."; userMessage = userMessageStream.str(); } return userMessage; } //----------------------------------------------------------------------------- CErrorsHelper::CErrorsHelper( IErrorHandler* errorHandler ) { CError::Reset(); Reset(); SetErrorHandler( errorHandler ); } void CErrorsHelper::Reset() { errorHandler = nullptr; errorSeverity = ES_None; } void CErrorsHelper::SetErrorHandler( IErrorHandler* _errorHandler ) { errorHandler = _errorHandler; } bool CErrorsHelper::HasErrors() const { switch( ErrorSeverity() ) { case ES_None: case ES_Warning: return false; case ES_Error: case ES_LinkError: case ES_FatalError: return true; } assert( false ); return false; } void CErrorsHelper::RaiseError( TErrorSeverity severity, const std::string& message ) { CError::SetSeverity( severity ); CError::SetMessage( message ); raiseError(); CError::ResetSeverity(); CError::ResetMessage(); } void CErrorsHelper::RaiseError( TErrorSeverity severity, const std::string& message, const CToken& token ) { CError::SetToken( token ); RaiseError( severity, message ); CError::ResetToken(); } void CErrorsHelper::raiseError() { assert( errorHandler != nullptr ); assert( CError::IsSet() ); const TErrorSeverity severities[] = { ES_FatalError, ES_LinkError, ES_Error, ES_Warning, ES_None }; for( int i = 0; i < sizeof( severities ) / sizeof( TErrorSeverity ); i++ ) { if( severities[i] == CError::Severity() || severities[i] == errorSeverity ) { errorSeverity = severities[i]; } } errorHandler->Error( *this ); } //----------------------------------------------------------------------------- } // end of namespace Refal2 <commit_msg>allow print error with position without filename (for stdin)<commit_after>#include <Refal2.h> namespace Refal2 { //----------------------------------------------------------------------------- // CError void CError::Reset() { ResetSeverity(); ResetFileName(); ResetToken(); ResetMessage(); } bool CError::IsSet() const { return ( Severity() != ES_None && !Message().empty() ); } void CError::ResetSeverity() { severity = ES_None; resetCache(); } void CError::SetSeverity( TErrorSeverity _severity ) { assert( _severity != ES_None ); severity = _severity; resetCache(); } void CError::ResetFileName() { fileName.clear(); resetCache(); } void CError::SetFileName( const std::string& _fileName ) { assert( !_fileName.empty() ); fileName = _fileName; resetCache(); } void CError::ResetToken() { token.type = TT_None; resetCache(); } void CError::SetTokenData( int line, int position, const std::string& wrongText ) { token.type = TT_Word; token.line = line; token.position = position; token.word = wrongText; } void CError::SetToken( const CToken& _token ) { assert( !_token.IsNone() ); token = _token; resetCache(); } void CError::ResetMessage() { message.clear(); resetCache(); } void CError::SetMessage( const std::string& _message ) { assert( !_message.empty() ); message = _message; resetCache(); } const std::string& CError::UserMessage() const { if( userMessage.empty() ) { std::ostringstream userMessageStream; if( !fileName.empty() ) { userMessageStream << fileName << ":"; } if( !token.IsNone() ) { userMessageStream << token.line << ":" << token.position << ":"; } if( !fileName.empty() || !token.IsNone() ) { userMessageStream << " "; } switch( Severity() ) { case ES_Warning: userMessageStream << "warning"; break; case ES_Error: userMessageStream << "error"; break; case ES_LinkError: userMessageStream << "link error"; break; case ES_FatalError: userMessageStream << "fatal error"; break; case ES_None: default: assert( false ); break; } assert( !message.empty() ); userMessageStream << ": " << message << "."; userMessage = userMessageStream.str(); } return userMessage; } //----------------------------------------------------------------------------- CErrorsHelper::CErrorsHelper( IErrorHandler* errorHandler ) { CError::Reset(); Reset(); SetErrorHandler( errorHandler ); } void CErrorsHelper::Reset() { errorHandler = nullptr; errorSeverity = ES_None; } void CErrorsHelper::SetErrorHandler( IErrorHandler* _errorHandler ) { errorHandler = _errorHandler; } bool CErrorsHelper::HasErrors() const { switch( ErrorSeverity() ) { case ES_None: case ES_Warning: return false; case ES_Error: case ES_LinkError: case ES_FatalError: return true; } assert( false ); return false; } void CErrorsHelper::RaiseError( TErrorSeverity severity, const std::string& message ) { CError::SetSeverity( severity ); CError::SetMessage( message ); raiseError(); CError::ResetSeverity(); CError::ResetMessage(); } void CErrorsHelper::RaiseError( TErrorSeverity severity, const std::string& message, const CToken& token ) { CError::SetToken( token ); RaiseError( severity, message ); CError::ResetToken(); } void CErrorsHelper::raiseError() { assert( errorHandler != nullptr ); assert( CError::IsSet() ); const TErrorSeverity severities[] = { ES_FatalError, ES_LinkError, ES_Error, ES_Warning, ES_None }; for( int i = 0; i < sizeof( severities ) / sizeof( TErrorSeverity ); i++ ) { if( severities[i] == CError::Severity() || severities[i] == errorSeverity ) { errorSeverity = severities[i]; } } errorHandler->Error( *this ); } //----------------------------------------------------------------------------- } // end of namespace Refal2 <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2013 rajendrauppal 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 <iostream> #include "Exceptions.h" #include "GcdLcm.h" using std::cout; using std::cin; using std::endl; int GcdLcm::GCD_Euclidean_Iterative(int m, int n) { if ( (m < 0) || (n < 0) ) throw InvalidInputException(); if ( !m && !n ) throw InvalidInputException(); if ( m && !n ) return m; if ( !m && n ) return n; while ( n ) { int temp = n; n = m % n; m = temp; } return m; } int GcdLcm::GCD_Euclidean_Recursive(int m, int n) { if ( (m < 0) || (n < 0) ) throw InvalidInputException(); if ( !m && !n ) throw InvalidInputException(); if ( m && !n ) return m; if ( !m && n ) return n; return GCD_Euclidean_Recursive(n, m % n); } int GcdLcm::GCD_AlternateEuclidean_Iterative(int m, int n) { if ( (m < 0) || (n < 0) ) throw InvalidInputException(); if ( !m && !n ) throw InvalidInputException(); if ( m && !n ) return m; if ( !m && n ) return n; while ( m != n ) { if ( m > n ) m = m - n; else n = n - m; } return m; } int GcdLcm::GCD_AlternateEuclidean_Recursive(int m, int n) { if ( (m < 0) || (n < 0) ) throw InvalidInputException(); if ( !m && !n ) throw InvalidInputException(); if ( m && !n ) return m; if ( !m && n ) return n; if ( m == n ) return m; if ( m > n ) return GCD_AlternateEuclidean_Recursive(m - n, n); else return GCD_AlternateEuclidean_Recursive(m, n - m); } int GcdLcm::GCD_Binary_Iterative(int m, int n) { return 0; } int GcdLcm::GCD_Binary_Recursive(int m, int n) { return 0; } int GcdLcm::LCM_Iterative(int m, int n) { return 0; } int GcdLcm::LCM_Recursive(int m, int n) { return 0; } int GcdLcm::GCD_UsingLCM(int m, int n) { return 0; } int main() { GcdLcm gcdlcm; int nums[13][2] = {{0,1}, {1,0}, {0,0}, {1,1}, {-1,1}, {1,-1}, {-1,-1}, {1,1}, {2,3}, {10,10}, {121,11}, {24,60}, {36253652,183728732}}; for ( size_t i = 0; i < 13; ++i ) { try { cout << gcdlcm.GCD_Euclidean_Iterative(nums[i][0], nums[i][1]) << endl; cout << gcdlcm.GCD_Euclidean_Recursive(nums[i][0], nums[i][1]) << endl; cout << gcdlcm.GCD_AlternateEuclidean_Iterative(nums[i][0], nums[i][1]) << endl; cout << gcdlcm.GCD_AlternateEuclidean_Recursive(nums[i][0], nums[i][1]) << endl<<endl; } catch (CPPExceptions& e) { cout << e.message() << endl; } } cout << "Press Enter to continue..." << endl; cin.get(); return 0; }<commit_msg>Implemented Binary GCD algorithm<commit_after>/* The MIT License (MIT) Copyright (c) 2013 rajendrauppal 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 <iostream> #include "Exceptions.h" #include "GcdLcm.h" using std::cout; using std::cin; using std::endl; int GcdLcm::GCD_Euclidean_Iterative(int m, int n) { if ( (m < 0) || (n < 0) ) throw InvalidInputException(); if ( !m && !n ) throw InvalidInputException(); if ( m && !n ) return m; if ( !m && n ) return n; while ( n ) { int temp = n; n = m % n; m = temp; } return m; } int GcdLcm::GCD_Euclidean_Recursive(int m, int n) { if ( (m < 0) || (n < 0) ) throw InvalidInputException(); if ( !m && !n ) throw InvalidInputException(); if ( m && !n ) return m; if ( !m && n ) return n; return GCD_Euclidean_Recursive(n, m % n); } int GcdLcm::GCD_AlternateEuclidean_Iterative(int m, int n) { if ( (m < 0) || (n < 0) ) throw InvalidInputException(); if ( !m && !n ) throw InvalidInputException(); if ( m && !n ) return m; if ( !m && n ) return n; while ( m != n ) { if ( m > n ) m = m - n; else n = n - m; } return m; } int GcdLcm::GCD_AlternateEuclidean_Recursive(int m, int n) { if ( (m < 0) || (n < 0) ) throw InvalidInputException(); if ( !m && !n ) throw InvalidInputException(); if ( m && !n ) return m; if ( !m && n ) return n; if ( m == n ) return m; if ( m > n ) return GCD_AlternateEuclidean_Recursive(m - n, n); else return GCD_AlternateEuclidean_Recursive(m, n - m); } int GcdLcm::GCD_Binary_Iterative(int m, int n) { return 0; } /* Binary GCD algorithm (Credit: en.wikipedia.org/wiki/Binary_GCD_algorithm) ----------------------------------------------- m n gcd ----------------------------------------------- even even 2 * gcd( m/2, n/2 ) even odd gcd( m/2, n ) odd even gcd( m, n/2 ) odd odd m >= n then gcd( (m - n)/2, n ) m < n then gcd( (n - m)/2, m ) ----------------------------------------------- */ int GcdLcm::GCD_Binary_Recursive(int m, int n) { if ( (m < 0) || (n < 0) ) throw InvalidInputException(); if ( !m && !n ) throw InvalidInputException(); if ( m && !n ) return m; if ( !m && n ) return n; if ( m == n ) return m; bool m_even = ~m & 1; bool n_even = ~n & 1; if ( m_even && n_even ) return GCD_Binary_Recursive( m >> 1, n >> 1 ) << 1; if ( m_even && !n_even ) return GCD_Binary_Recursive( m >> 1, n ); if ( !m_even && n_even ) return GCD_Binary_Recursive( m, n >> 1 ); if ( m >= n ) return GCD_Binary_Recursive( (m - n) >> 1, n ); else return GCD_Binary_Recursive( (n - m) >> 1, m ); } int GcdLcm::LCM_Iterative(int m, int n) { return 0; } int GcdLcm::LCM_Recursive(int m, int n) { return 0; } int GcdLcm::GCD_UsingLCM(int m, int n) { return 0; } int main() { GcdLcm gcdlcm; int nums[13][2] = {{0,1}, {1,0}, {0,0}, {1,1}, {-1,1}, {1,-1}, {-1,-1}, {1,1}, {2,3}, {10,10}, {121,11}, {24,60}, {36253652,183728732}}; for ( size_t i = 0; i < 13; ++i ) { try { cout << gcdlcm.GCD_Euclidean_Iterative(nums[i][0], nums[i][1]) << endl; cout << gcdlcm.GCD_Euclidean_Recursive(nums[i][0], nums[i][1]) << endl; cout << gcdlcm.GCD_AlternateEuclidean_Iterative(nums[i][0], nums[i][1]) << endl; cout << gcdlcm.GCD_AlternateEuclidean_Recursive(nums[i][0], nums[i][1]) << endl; cout << gcdlcm.GCD_Binary_Recursive(nums[i][0], nums[i][1]) << endl; } catch (CPPExceptions& e) { cout << e.message() << endl; } } cout << "Press Enter to continue..." << endl; cin.get(); return 0; }<|endoftext|>
<commit_before>#include "GrsApi.h" #include "amount.h" #include "chainparams.h" #include "main.h" #include "util.h" #include <iostream> #include <sstream> #include <curlpp/cURLpp.hpp> #include <curlpp/Easy.hpp> #include <curlpp/Options.hpp> #include <curlpp/Infos.hpp> #include "json/json_spirit_value.h" #include "json/json_spirit_reader_template.h" #include <boost/thread.hpp> CGrsApi::CGrsApi(const std::string& baseUrl) : baseApiUrl(baseUrl) { curlpp::initialize(); } CGrsApi::~CGrsApi() { curlpp::terminate(); } CAmount CGrsApi::GetPrice(unsigned int time) { LogPrintf("CGrsApi::GetPrice: time = %d\n", time); // projected prices for before-the-trading era if (time >= block_0_t && time < block_128002_t) { // genesis reward zone return 656 * USD1 + 35 * USCENT1; } else if (time >= block_128002_t && time < block_193536_t) { // decreasing reward zone return 10 * USCENT1; } else if (time >= block_193536_t && time < Params().LiveFeedSwitchTime()) { return 10 * USCENT1; } // TODO(dmc): check cached price // get price from the live feed while (true) { //TODO(dmc): !!! try { boost::this_thread::interruption_point(); unsigned int timestamp = 0; //TODO(dmc): must be 'time' CAmount price = GetGrsApiPrice(timestamp); LogPrintf("GRS price for timestamp: time = %d, price = %d\n", time, price); return price; } catch (const std::runtime_error& e) { error("Can't get GRS price for timestamp: %s\n", e.what()); } catch (const boost::thread_interrupted& e) { LogPrintf("CGrsApi::GetPrice thread terminated\n"); throw; } } } CAmount CGrsApi::GetLatestPrice() { return 10 * USCENT1; // STUB: 0.1USD, TODO(dmc): get actual coin price } CAmount CGrsApi::GetGrsApiPrice(unsigned int timestamp) { LogPrintf("Getting GRS price for timestamp: time = %d\n", timestamp); std::ostringstream reqArgs; if (timestamp != 0) { reqArgs << timestamp; } return DoApiPriceRequest("price", reqArgs.str()); } CAmount CGrsApi::DoApiPriceRequest(const std::string& reqName, const std::string& args) { CAmount price = 0; int apiResponseCode = 200; std::ostringstream apiUrl; apiUrl << baseApiUrl << reqName << "/" << args; std::ostringstream rawResponse; try { apiResponseCode = DoApiRequest(apiUrl.str(), rawResponse); std::clog << "GRS API response: " << rawResponse.str() << std::endl; } catch (const curlpp::RuntimeError& e) { throw std::runtime_error(std::string(e.what()) + "; url = '" + apiUrl.str() + "'" + "; response = '" + rawResponse.str() + "'"); } catch (const curlpp::LogicError& e) { throw std::runtime_error(std::string(e.what()) + "; url = '" + apiUrl.str() + "'" + "; response = '" + rawResponse.str() + "'"); } catch (const std::invalid_argument& e) { throw std::runtime_error(std::string(e.what()) + "; url = '" + apiUrl.str() + "'" + "; response = '" + rawResponse.str() + "'"); } catch (const std::domain_error& e) { throw std::runtime_error(std::string(e.what()) + "; url = '" + apiUrl.str() + "'" + "; response = '" + rawResponse.str() + "'"); } if (apiResponseCode != 200) { std::ostringstream oss; oss << "apiResponseCode != 200; code = " << apiResponseCode << "; url = '" + apiUrl.str() + "'" + "; response = '" + rawResponse.str() + "'"; throw std::runtime_error(oss.str()); } try { json_spirit::Value value; json_spirit::read_string(rawResponse.str(), value); json_spirit::Object obj(value.get_obj()); bool price_read = false; for(json_spirit::Object::size_type i = 0; i != obj.size(); ++i) { const json_spirit::Pair& pair = obj[i]; if (pair.name_ == "price") { price = pair.value_.get_int(); price_read = true; } } if (!price_read) { throw std::domain_error("No price field found"); } } catch (const std::invalid_argument& e) { throw std::runtime_error(std::string(e.what()) + "; url = '" + apiUrl.str() + "'" + "; response = '" + rawResponse.str() + "'"); } catch (const std::domain_error& e) { throw std::runtime_error(std::string(e.what()) + "; url = '" + apiUrl.str() + "'" + "; response = '" + rawResponse.str() + "'"); } return price; } int CGrsApi::DoApiRequest(const std::string& url, std::ostringstream& oss) { LogPrintf("CGrsApi::DoApiRequest: url=%s, oss.str()=%s\n", url, oss.str()); // std::clog << "GRS API url: " << url << std::endl; curlpp::options::Url reqUrl(url); curlpp::Easy request; request.setOpt(curlpp::options::NoSignal(false)); request.setOpt(reqUrl); curlpp::options::WriteStream ws(&oss); request.setOpt(ws); request.perform(); return curlpp::infos::ResponseCode::get(request); } CDmcSystem::CDmcSystem(const std::string& apiUrl) : grsApi(apiUrl) { genesisReward = 65535 * COIN; minReward = 1 * COIN; maxReward = 100000 * COIN; minTargetPrice = 1 * USD1 + 1 * USCENT1; // 1.01USD } bool CDmcSystem::CheckBlockReward(const CBlock& block, CAmount nFees, CValidationState& state, CBlockIndex* pindex) { LogPrintf("CDmcSystem::CheckBlockReward: block.nTime=%d, fees=%d, hash=%s, height=%d, time=%d\n", block.nTime, nFees, pindex->phashBlock ? pindex->GetBlockHash().ToString() : "null", pindex->nHeight, pindex->nTime); CAmount blockOutput = block.vtx[0].GetValueOut(); if (!blockOutput || blockOutput <= nFees) { return state.DoS(100, error("CDmcSystem::CheckBlockReward() : coinbase pays zero or <= fees (coinbase=%d, fees=%d)", blockOutput, nFees), REJECT_INVALID, "bad-cb-amount"); } CAmount blockReward = blockOutput - nFees; //TODO(dmc): temporary simplification – one GetBlockReward result comparison check // should be enough in the future (the second case of "if" construction) if (pindex->nTime > Params().LiveFeedSwitchTime()) { // simplified reward checks CAmount prevReward = pindex->pprev ? pindex->pprev->nReward : genesisReward; CAmount rewDiff = std::abs(blockReward - prevReward); if ((rewDiff == 0 || rewDiff == 1 * COIN) && (blockReward >= minReward && blockReward <= maxReward)) { return true; } return state.DoS(100, error("CDmcSystem::CheckBlockReward() : coinbase pays wrong (actual=%d vs mustbe=%d)", blockOutput, GetBlockReward(pindex) + nFees), REJECT_INVALID, "bad-cb-amount"); } if (blockReward != GetBlockReward(pindex)) { return state.DoS(100, error("CDmcSystem::CheckBlockReward() : coinbase pays wrong reward (actual=%d vs mustbe=%d, fees=%d)", blockReward, GetBlockReward(pindex), nFees), REJECT_INVALID, "bad-cb-amount"); } return true; } CAmount CDmcSystem::GetBlockReward(const CBlockIndex* pindex) { LogPrintf("CDmcSystem::GetBlockReward: hash=%s, height=%d, time=%d\n", pindex->phashBlock ? pindex->GetBlockHash().ToString() : "null", pindex->nHeight, pindex->nTime); CAmount nSubsidy = 1 * COIN; int nHeight = pindex->nHeight; if (pindex->nTime > Params().LiveFeedSwitchTime()) { CAmount prevReward = pindex->pprev ? pindex->pprev->nReward : genesisReward; CAmount reward = prevReward; unsigned int price = GetPrice(pindex->nTime); CAmount target = GetTargetPrice(prevReward); if (price < target) { reward -= 1 * COIN; } else if (price > target) { reward += 1 * COIN; } nSubsidy = std::max(minReward, std::min(reward, maxReward)); } else { if (Params().NetworkID() == CBaseChainParams::MAIN) { const int kGenesisRewardZone = 128000; const int kGenesisReward = 65535; const int kDecreasingRewardZone = kGenesisRewardZone + 1 + kGenesisReward; if (nHeight >= 0 && nHeight <= kGenesisRewardZone) { nSubsidy = kGenesisReward * COIN; } else if (nHeight > kGenesisRewardZone && nHeight < kDecreasingRewardZone) { nSubsidy = (kDecreasingRewardZone - nHeight) * COIN; } } else { nSubsidy = 1024 * COIN; } } return nSubsidy; } CAmount CDmcSystem::GetBlockRewardForNewTip(unsigned int time) { LogPrintf("CDmcSystem::GetBlockRewardForNewTip: time=%d\n", time); const CBlockIndex* tip = chainActive.Tip(); if (!tip) { return genesisReward; } CAmount nSubsidy = 1 * COIN; int nHeight = tip->nHeight + 1; if (tip->nTime > Params().LiveFeedSwitchTime()) { CAmount prevReward = tip->nReward; CAmount reward = prevReward; unsigned int price = GetPrice(time); CAmount target = GetTargetPrice(prevReward); if (price < target) { reward -= 1 * COIN; } else if (price > target) { reward += 1 * COIN; } nSubsidy = std::max(minReward, std::min(reward, maxReward)); } else { if (Params().NetworkID() == CBaseChainParams::MAIN) { const int kGenesisRewardZone = 128000; const int kGenesisReward = 65535; const int kDecreasingRewardZone = kGenesisRewardZone + 1 + kGenesisReward; if (nHeight >= 0 && nHeight <= kGenesisRewardZone) { nSubsidy = kGenesisReward * COIN; } else if (nHeight > kGenesisRewardZone && nHeight < kDecreasingRewardZone) { nSubsidy = (kDecreasingRewardZone - nHeight) * COIN; } } else { nSubsidy = 1024 * COIN; } } LogPrintf("CDmcSystem::GetBlockRewardForNewTip: time=%d, nSubsidy=%d\n", time, nSubsidy); return nSubsidy; } CAmount CDmcSystem::GetBlockReward() const { LOCK(cs_main); return chainActive.Tip()->nReward; } CAmount CDmcSystem::GetPrice() { LOCK(cs_main); return grsApi.GetPrice(chainActive.Tip()->nTime); } CAmount CDmcSystem::GetTargetPrice() const { LOCK(cs_main); return GetTargetPrice(chainActive.Tip()->nReward); } CAmount CDmcSystem::GetTotalCoins() const { LOCK(cs_main); return chainActive.Tip()->nChainReward; } CAmount CDmcSystem::GetMarketCap() { return (GetTotalCoins() / COIN) * GetPrice(); } CAmount CDmcSystem::GetPrice(unsigned int time) { return grsApi.GetPrice(time); } CAmount CDmcSystem::GetTargetPrice(unsigned int time) const { //TODO(dmc): temporary simplification // const CBlockIndex* pindex; // TODO(dmc): get block for time // return GetTargetPrice(pindex->nReward); return 10 * USCENT1; } CAmount CDmcSystem::GetTargetPrice(CAmount reward) const { CAmount targetPrice = 1 * USD1 + (reward * USD1) / (100 * COIN); return std::max(minTargetPrice, targetPrice); } <commit_msg>Raise max block reward<commit_after>#include "GrsApi.h" #include "amount.h" #include "chainparams.h" #include "main.h" #include "util.h" #include <iostream> #include <sstream> #include <curlpp/cURLpp.hpp> #include <curlpp/Easy.hpp> #include <curlpp/Options.hpp> #include <curlpp/Infos.hpp> #include "json/json_spirit_value.h" #include "json/json_spirit_reader_template.h" #include <boost/thread.hpp> CGrsApi::CGrsApi(const std::string& baseUrl) : baseApiUrl(baseUrl) { curlpp::initialize(); } CGrsApi::~CGrsApi() { curlpp::terminate(); } CAmount CGrsApi::GetPrice(unsigned int time) { LogPrintf("CGrsApi::GetPrice: time = %d\n", time); // projected prices for before-the-trading era if (time >= block_0_t && time < block_128002_t) { // genesis reward zone return 656 * USD1 + 35 * USCENT1; } else if (time >= block_128002_t && time < block_193536_t) { // decreasing reward zone return 10 * USCENT1; } else if (time >= block_193536_t && time < Params().LiveFeedSwitchTime()) { return 10 * USCENT1; } // TODO(dmc): check cached price // get price from the live feed while (true) { //TODO(dmc): !!! try { boost::this_thread::interruption_point(); unsigned int timestamp = 0; //TODO(dmc): must be 'time' CAmount price = GetGrsApiPrice(timestamp); LogPrintf("GRS price for timestamp: time = %d, price = %d\n", time, price); return price; } catch (const std::runtime_error& e) { error("Can't get GRS price for timestamp: %s\n", e.what()); } catch (const boost::thread_interrupted& e) { LogPrintf("CGrsApi::GetPrice thread terminated\n"); throw; } } } CAmount CGrsApi::GetLatestPrice() { return 10 * USCENT1; // STUB: 0.1USD, TODO(dmc): get actual coin price } CAmount CGrsApi::GetGrsApiPrice(unsigned int timestamp) { LogPrintf("Getting GRS price for timestamp: time = %d\n", timestamp); std::ostringstream reqArgs; if (timestamp != 0) { reqArgs << timestamp; } return DoApiPriceRequest("price", reqArgs.str()); } CAmount CGrsApi::DoApiPriceRequest(const std::string& reqName, const std::string& args) { CAmount price = 0; int apiResponseCode = 200; std::ostringstream apiUrl; apiUrl << baseApiUrl << reqName << "/" << args; std::ostringstream rawResponse; try { apiResponseCode = DoApiRequest(apiUrl.str(), rawResponse); std::clog << "GRS API response: " << rawResponse.str() << std::endl; } catch (const curlpp::RuntimeError& e) { throw std::runtime_error(std::string(e.what()) + "; url = '" + apiUrl.str() + "'" + "; response = '" + rawResponse.str() + "'"); } catch (const curlpp::LogicError& e) { throw std::runtime_error(std::string(e.what()) + "; url = '" + apiUrl.str() + "'" + "; response = '" + rawResponse.str() + "'"); } catch (const std::invalid_argument& e) { throw std::runtime_error(std::string(e.what()) + "; url = '" + apiUrl.str() + "'" + "; response = '" + rawResponse.str() + "'"); } catch (const std::domain_error& e) { throw std::runtime_error(std::string(e.what()) + "; url = '" + apiUrl.str() + "'" + "; response = '" + rawResponse.str() + "'"); } if (apiResponseCode != 200) { std::ostringstream oss; oss << "apiResponseCode != 200; code = " << apiResponseCode << "; url = '" + apiUrl.str() + "'" + "; response = '" + rawResponse.str() + "'"; throw std::runtime_error(oss.str()); } try { json_spirit::Value value; json_spirit::read_string(rawResponse.str(), value); json_spirit::Object obj(value.get_obj()); bool price_read = false; for(json_spirit::Object::size_type i = 0; i != obj.size(); ++i) { const json_spirit::Pair& pair = obj[i]; if (pair.name_ == "price") { price = pair.value_.get_int(); price_read = true; } } if (!price_read) { throw std::domain_error("No price field found"); } } catch (const std::invalid_argument& e) { throw std::runtime_error(std::string(e.what()) + "; url = '" + apiUrl.str() + "'" + "; response = '" + rawResponse.str() + "'"); } catch (const std::domain_error& e) { throw std::runtime_error(std::string(e.what()) + "; url = '" + apiUrl.str() + "'" + "; response = '" + rawResponse.str() + "'"); } return price; } int CGrsApi::DoApiRequest(const std::string& url, std::ostringstream& oss) { LogPrintf("CGrsApi::DoApiRequest: url=%s, oss.str()=%s\n", url, oss.str()); // std::clog << "GRS API url: " << url << std::endl; curlpp::options::Url reqUrl(url); curlpp::Easy request; request.setOpt(curlpp::options::NoSignal(false)); request.setOpt(reqUrl); curlpp::options::WriteStream ws(&oss); request.setOpt(ws); request.perform(); return curlpp::infos::ResponseCode::get(request); } CDmcSystem::CDmcSystem(const std::string& apiUrl) : grsApi(apiUrl) { genesisReward = 65535 * COIN; minReward = 1 * COIN; maxReward = 1000000 * COIN; minTargetPrice = 1 * USD1 + 1 * USCENT1; // 1.01USD } bool CDmcSystem::CheckBlockReward(const CBlock& block, CAmount nFees, CValidationState& state, CBlockIndex* pindex) { LogPrintf("CDmcSystem::CheckBlockReward: block.nTime=%d, fees=%d, hash=%s, height=%d, time=%d\n", block.nTime, nFees, pindex->phashBlock ? pindex->GetBlockHash().ToString() : "null", pindex->nHeight, pindex->nTime); CAmount blockOutput = block.vtx[0].GetValueOut(); if (!blockOutput || blockOutput <= nFees) { return state.DoS(100, error("CDmcSystem::CheckBlockReward() : coinbase pays zero or <= fees (coinbase=%d, fees=%d)", blockOutput, nFees), REJECT_INVALID, "bad-cb-amount"); } CAmount blockReward = blockOutput - nFees; //TODO(dmc): temporary simplification – one GetBlockReward result comparison check // should be enough in the future (the second case of "if" construction) if (pindex->nTime > Params().LiveFeedSwitchTime()) { // simplified reward checks CAmount prevReward = pindex->pprev ? pindex->pprev->nReward : genesisReward; CAmount rewDiff = std::abs(blockReward - prevReward); if ((rewDiff == 0 || rewDiff == 1 * COIN) && (blockReward >= minReward && blockReward <= maxReward)) { return true; } return state.DoS(100, error("CDmcSystem::CheckBlockReward() : coinbase pays wrong (actual=%d vs mustbe=%d)", blockOutput, GetBlockReward(pindex) + nFees), REJECT_INVALID, "bad-cb-amount"); } if (blockReward != GetBlockReward(pindex)) { return state.DoS(100, error("CDmcSystem::CheckBlockReward() : coinbase pays wrong reward (actual=%d vs mustbe=%d, fees=%d)", blockReward, GetBlockReward(pindex), nFees), REJECT_INVALID, "bad-cb-amount"); } return true; } CAmount CDmcSystem::GetBlockReward(const CBlockIndex* pindex) { LogPrintf("CDmcSystem::GetBlockReward: hash=%s, height=%d, time=%d\n", pindex->phashBlock ? pindex->GetBlockHash().ToString() : "null", pindex->nHeight, pindex->nTime); CAmount nSubsidy = 1 * COIN; int nHeight = pindex->nHeight; if (pindex->nTime > Params().LiveFeedSwitchTime()) { CAmount prevReward = pindex->pprev ? pindex->pprev->nReward : genesisReward; CAmount reward = prevReward; unsigned int price = GetPrice(pindex->nTime); CAmount target = GetTargetPrice(prevReward); if (price < target) { reward -= 1 * COIN; } else if (price > target) { reward += 1 * COIN; } nSubsidy = std::max(minReward, std::min(reward, maxReward)); } else { if (Params().NetworkID() == CBaseChainParams::MAIN) { const int kGenesisRewardZone = 128000; const int kGenesisReward = 65535; const int kDecreasingRewardZone = kGenesisRewardZone + 1 + kGenesisReward; if (nHeight >= 0 && nHeight <= kGenesisRewardZone) { nSubsidy = kGenesisReward * COIN; } else if (nHeight > kGenesisRewardZone && nHeight < kDecreasingRewardZone) { nSubsidy = (kDecreasingRewardZone - nHeight) * COIN; } } else { nSubsidy = 1024 * COIN; } } return nSubsidy; } CAmount CDmcSystem::GetBlockRewardForNewTip(unsigned int time) { LogPrintf("CDmcSystem::GetBlockRewardForNewTip: time=%d\n", time); const CBlockIndex* tip = chainActive.Tip(); if (!tip) { return genesisReward; } CAmount nSubsidy = 1 * COIN; int nHeight = tip->nHeight + 1; if (tip->nTime > Params().LiveFeedSwitchTime()) { CAmount prevReward = tip->nReward; CAmount reward = prevReward; unsigned int price = GetPrice(time); CAmount target = GetTargetPrice(prevReward); if (price < target) { reward -= 1 * COIN; } else if (price > target) { reward += 1 * COIN; } nSubsidy = std::max(minReward, std::min(reward, maxReward)); } else { if (Params().NetworkID() == CBaseChainParams::MAIN) { const int kGenesisRewardZone = 128000; const int kGenesisReward = 65535; const int kDecreasingRewardZone = kGenesisRewardZone + 1 + kGenesisReward; if (nHeight >= 0 && nHeight <= kGenesisRewardZone) { nSubsidy = kGenesisReward * COIN; } else if (nHeight > kGenesisRewardZone && nHeight < kDecreasingRewardZone) { nSubsidy = (kDecreasingRewardZone - nHeight) * COIN; } } else { nSubsidy = 1024 * COIN; } } LogPrintf("CDmcSystem::GetBlockRewardForNewTip: time=%d, nSubsidy=%d\n", time, nSubsidy); return nSubsidy; } CAmount CDmcSystem::GetBlockReward() const { LOCK(cs_main); return chainActive.Tip()->nReward; } CAmount CDmcSystem::GetPrice() { LOCK(cs_main); return grsApi.GetPrice(chainActive.Tip()->nTime); } CAmount CDmcSystem::GetTargetPrice() const { LOCK(cs_main); return GetTargetPrice(chainActive.Tip()->nReward); } CAmount CDmcSystem::GetTotalCoins() const { LOCK(cs_main); return chainActive.Tip()->nChainReward; } CAmount CDmcSystem::GetMarketCap() { return (GetTotalCoins() / COIN) * GetPrice(); } CAmount CDmcSystem::GetPrice(unsigned int time) { return grsApi.GetPrice(time); } CAmount CDmcSystem::GetTargetPrice(unsigned int time) const { //TODO(dmc): temporary simplification // const CBlockIndex* pindex; // TODO(dmc): get block for time // return GetTargetPrice(pindex->nReward); return 10 * USCENT1; } CAmount CDmcSystem::GetTargetPrice(CAmount reward) const { CAmount targetPrice = 1 * USD1 + (reward * USD1) / (100 * COIN); return std::max(minTargetPrice, targetPrice); } <|endoftext|>
<commit_before>#include "InGame.h" #include <sstream> InGame::InGame(Configuration& newConfig, std::unique_ptr<StartInfo> startInfo) : config(newConfig) { loadGame(startInfo); } InGame::~InGame() { delete interfacePtr; delete networkPtr; delete systemPtr; } void InGame::run() { sf::RenderWindow& window = config.window; window.setFramerateLimit(60); while (window.isOpen()) { //input & update phase systemPtr->updateQuadTree(); networkPtr->update(); sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); if (event.type == sf::Event::KeyPressed) { if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) systemPtr->interact(); } interfacePtr->updateGUI(event); } //handle keyboard input, move character, interact...etc handleKeyboardInput(); //if this is server, send status update to client if (networkPtr->isServer()) { server_sendUpdate(); } else //if this is client, send status update to server { client_sendUpdate(); } config.cursor.update(); //rendering phase window.clear(); interfacePtr->draw(); //window.draw(config.cursor); window.display(); } } void InGame::loadGame(std::unique_ptr<StartInfo>& startInfo) { //graphics in loading screen sf::RenderWindow& window = config.window; tgui::Gui gui; gui.setWindow(window); gui.setFont(tgui::Font(config.fontMan.get("Carlito-Bold.ttf"))); tgui::Picture::Ptr background = std::make_shared<tgui::Picture>(); background->setTexture(config.texMan.get("Book.png")); background->setSize(gui.getSize()); gui.add(background); tgui::ProgressBar::Ptr progressBar = std::make_shared<tgui::ProgressBar>(); gui.add(progressBar); progressBar->setPosition(50, 700); progressBar->setSize(930, 20); progressBar->setMinimum(0); progressBar->setMaximum(100); progressBar->setText("loading...0%"); unsigned int percent = 0; tgui::Panel::Ptr panel = std::make_shared<tgui::Panel>(); gui.add(panel); panel->setSize(820, 200); panel->setPosition(100, 450); panel->setBackgroundColor(tgui::Color(192, 192, 192, 150)); tgui::Label::Ptr tips = std::make_shared<tgui::Label>(); panel->add(tips); tips->setPosition(20, 20); tips->setTextSize(24); tips->setText("This is testing. Click cross button to leave."); //************************************************************************* //the render loop bool loading_complete = false; //leave the loop when loading completed Connection* temp_networkPtr = new Connection; if (!temp_networkPtr) { throw "Failed to create network module!"; } while (window.isOpen() && !loading_complete) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); gui.handleEvent(event); } config.cursor.update(); //if still loading, update percent if (percent < 0) { if (clock.getElapsedTime() > sf::seconds(0.05)) { percent++; std::stringstream ss; ss << percent; progressBar->setText(sf::String("loading...") + sf::String(ss.str()) + sf::String("%")); progressBar->setValue(percent); clock.restart(); } } else //else, client: send "ready" signal to server for every 5s; server: start anyway { progressBar->setText(sf::String("waiting for server...")); loading_complete = waitForStart(startInfo, temp_networkPtr); } window.clear(); gui.draw(); window.draw(config.cursor); window.display(); } delete temp_networkPtr; //************************************************************************* //if it is server, start server system... if (startInfo->type == StartInfo::TYPE::Server) { systemPtr = new Gameplay::ServerSystem(config, startInfo); } else //else it is client, start client system { systemPtr = new Gameplay::ClientSystem(config, startInfo); } //create network and interface which is pointing to the game system networkPtr = new Gameplay::GameNetwork(systemPtr, startInfo); systemPtr->setNetworkPtr(networkPtr); interfacePtr = new Gameplay::GameInterface(systemPtr); systemPtr->setInterfacePtr(interfacePtr); if (startInfo->type == StartInfo::TYPE::Server) { //send ready signal to every player //... } else //if it is a client { //wait for server's signal } } bool InGame::waitForStart(std::unique_ptr<StartInfo>& startInfoPtr, Connection * connectionPtr) { if (startInfoPtr->type == StartInfo::TYPE::Server) { return true; } else { //if recevied somthing, if that's from server and the signal if "start", return true if (!connectionPtr->empty()) { Package& package = connectionPtr->front(); std::string signal; package.packet >> signal; if (package.ip == startInfoPtr->serverIP && signal == "start") { connectionPtr->pop(); return true; } } else //else, send "ready" signal to server for every 2s { if (clock.getElapsedTime() > sf::seconds(2)) { sf::Packet packet; packet << "ready"; connectionPtr->send(startInfoPtr->serverIP, packet); } } } return false; } void InGame::handleKeyboardInput() { if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Left)) { systemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::left); sf::Packet packet; packet << config.player_name; packet << "move"; packet << "left"; if (networkPtr->isServer()) networkPtr->boardCast(packet); else networkPtr->send(networkPtr->getServerIP(), packet); } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Right)) { systemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::right); sf::Packet packet; packet << config.player_name; packet << "move"; packet << "right"; if (networkPtr->isServer()) networkPtr->boardCast(packet); else networkPtr->send(networkPtr->getServerIP(), packet); } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Down)) { systemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::down); sf::Packet packet; packet << config.player_name; packet << "move"; packet << "down"; if (networkPtr->isServer()) networkPtr->boardCast(packet); else networkPtr->send(networkPtr->getServerIP(), packet); } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Up)) { systemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::up); sf::Packet packet; packet << config.player_name; packet << "move"; packet << "up"; if (networkPtr->isServer()) networkPtr->boardCast(packet); else networkPtr->send(networkPtr->getServerIP(), packet); } } void InGame::client_sendUpdate() { if (updateClock.getElapsedTime() > sf::seconds(2)) { //update the position sf::Packet packet; packet << "setPosition"; float x = systemPtr->getPlayerPosition().x; float y = systemPtr->getPlayerPosition().y; packet << x << y; networkPtr->send(networkPtr->getServerIP(), packet); updateClock.restart(); } } void InGame::server_sendUpdate() { } <commit_msg>moving function 2<commit_after>#include "InGame.h" #include <sstream> InGame::InGame(Configuration& newConfig, std::unique_ptr<StartInfo> startInfo) : config(newConfig) { loadGame(startInfo); } InGame::~InGame() { delete interfacePtr; delete networkPtr; delete systemPtr; } void InGame::run() { sf::RenderWindow& window = config.window; window.setFramerateLimit(60); while (window.isOpen()) { //input & update phase systemPtr->updateQuadTree(); networkPtr->update(); sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); if (event.type == sf::Event::KeyPressed) { if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) systemPtr->interact(); } interfacePtr->updateGUI(event); } //handle keyboard input, move character, interact...etc handleKeyboardInput(); //if this is server, send status update to client if (networkPtr->isServer()) { server_sendUpdate(); } else //if this is client, send status update to server { client_sendUpdate(); } config.cursor.update(); //rendering phase window.clear(); interfacePtr->draw(); //window.draw(config.cursor); window.display(); } } void InGame::loadGame(std::unique_ptr<StartInfo>& startInfo) { //graphics in loading screen sf::RenderWindow& window = config.window; tgui::Gui gui; gui.setWindow(window); gui.setFont(tgui::Font(config.fontMan.get("Carlito-Bold.ttf"))); tgui::Picture::Ptr background = std::make_shared<tgui::Picture>(); background->setTexture(config.texMan.get("Book.png")); background->setSize(gui.getSize()); gui.add(background); tgui::ProgressBar::Ptr progressBar = std::make_shared<tgui::ProgressBar>(); gui.add(progressBar); progressBar->setPosition(50, 700); progressBar->setSize(930, 20); progressBar->setMinimum(0); progressBar->setMaximum(100); progressBar->setText("loading...0%"); unsigned int percent = 0; tgui::Panel::Ptr panel = std::make_shared<tgui::Panel>(); gui.add(panel); panel->setSize(820, 200); panel->setPosition(100, 450); panel->setBackgroundColor(tgui::Color(192, 192, 192, 150)); tgui::Label::Ptr tips = std::make_shared<tgui::Label>(); panel->add(tips); tips->setPosition(20, 20); tips->setTextSize(24); tips->setText("This is testing. Click cross button to leave."); //************************************************************************* //the render loop bool loading_complete = false; //leave the loop when loading completed Connection* temp_networkPtr = new Connection; if (!temp_networkPtr) { throw "Failed to create network module!"; } while (window.isOpen() && !loading_complete) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); gui.handleEvent(event); } config.cursor.update(); //if still loading, update percent if (percent < 0) { if (clock.getElapsedTime() > sf::seconds(0.05)) { percent++; std::stringstream ss; ss << percent; progressBar->setText(sf::String("loading...") + sf::String(ss.str()) + sf::String("%")); progressBar->setValue(percent); clock.restart(); } } else //else, client: send "ready" signal to server for every 5s; server: start anyway { progressBar->setText(sf::String("waiting for server...")); loading_complete = waitForStart(startInfo, temp_networkPtr); } window.clear(); gui.draw(); window.draw(config.cursor); window.display(); } delete temp_networkPtr; //************************************************************************* //if it is server, start server system... if (startInfo->type == StartInfo::TYPE::Server) { systemPtr = new Gameplay::ServerSystem(config, startInfo); } else //else it is client, start client system { systemPtr = new Gameplay::ClientSystem(config, startInfo); } //create network and interface which is pointing to the game system networkPtr = new Gameplay::GameNetwork(systemPtr, startInfo); systemPtr->setNetworkPtr(networkPtr); interfacePtr = new Gameplay::GameInterface(systemPtr); systemPtr->setInterfacePtr(interfacePtr); if (startInfo->type == StartInfo::TYPE::Server) { //send ready signal to every player //... } else //if it is a client { //wait for server's signal } } bool InGame::waitForStart(std::unique_ptr<StartInfo>& startInfoPtr, Connection * connectionPtr) { if (startInfoPtr->type == StartInfo::TYPE::Server) { return true; } else { //if recevied somthing, if that's from server and the signal if "start", return true if (!connectionPtr->empty()) { Package& package = connectionPtr->front(); std::string signal; package.packet >> signal; if (package.ip == startInfoPtr->serverIP && signal == "start") { connectionPtr->pop(); return true; } } else //else, send "ready" signal to server for every 2s { if (clock.getElapsedTime() > sf::seconds(2)) { sf::Packet packet; packet << "ready"; connectionPtr->send(startInfoPtr->serverIP, packet); } } } return false; } void InGame::handleKeyboardInput() { if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Left)) { systemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::left); sf::Packet packet; packet << "move"; packet << config.player_name; packet << "left"; if (networkPtr->isServer()) networkPtr->boardCast(packet); else networkPtr->send(networkPtr->getServerIP(), packet); } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Right)) { systemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::right); sf::Packet packet; packet << "move"; packet << config.player_name; packet << "right"; if (networkPtr->isServer()) networkPtr->boardCast(packet); else networkPtr->send(networkPtr->getServerIP(), packet); } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Down)) { systemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::down); sf::Packet packet; packet << "move"; packet << config.player_name; packet << "down"; if (networkPtr->isServer()) networkPtr->boardCast(packet); else networkPtr->send(networkPtr->getServerIP(), packet); } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Up)) { systemPtr->movePlayer(config.player_name, Gameplay::Character::Direction::up); sf::Packet packet; packet << "move"; packet << config.player_name; packet << "up"; if (networkPtr->isServer()) networkPtr->boardCast(packet); else networkPtr->send(networkPtr->getServerIP(), packet); } } void InGame::client_sendUpdate() { if (updateClock.getElapsedTime() > sf::seconds(2)) { //update the position sf::Packet packet; packet << "setPosition"; float x = systemPtr->getPlayerPosition().x; float y = systemPtr->getPlayerPosition().y; packet << x << y; networkPtr->send(networkPtr->getServerIP(), packet); updateClock.restart(); } } void InGame::server_sendUpdate() { } <|endoftext|>
<commit_before>// Copyright (C) 2014 Matteo Agostini <matteo.agostini@ph.tum.de> // This 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 software 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. // c++ libs #include <iostream> #include <limits> #include <cmath> #include <vector> // ROOT libs #include <TMath.h> // m-stats libs #include "MSMath.h" namespace mst { double MSMath::LogGaus(double x, double mean, double sigma) { // sigma must be positive if (sigma <= 0.0) { std::cerr << "MSMath::LogGaus >> error: sigma must be positive\n"; return 0; } const double dx = (x - mean) / sigma; return -0.5*dx*dx - 0.5*log(2*M_PI) - log(sigma); } double MSMath::LogPoisson(double x, double lambda) { // If the parameters are negative the Poission probability is not defined if (lambda < 0.0 || x < 0.0) { std::cerr << "MSMath::LogPoisson >> error: " << "function not defined for negative parameters\n"; return std::numeric_limits<double>::quiet_NaN(); } // The expectation must be positive. Empty bins in the PSD should be avoided else if (lambda == 0.0) { if (x == 0) return 0; else return std::numeric_limits<double>::quiet_NaN(); } // Copute Poission probability for positive lambda values else { if (x == 0) return -lambda; else if (lambda < 899) return x*log(lambda)-lambda-TMath::LnGamma(x+1.); else return LogGaus(x, lambda, sqrt(lambda)); } } double MSMath::LogExp (double x, double limit, double quantile, double offset) { // the expoential function should be normalized in the range [offset, inf] and // have the quantile corresponding to the desidered probablity at the limit // value. // // Starting from the standard exp function normalized betweeen 0 and inf: // // f(x) = a*exp(-a*x) // // the parameter a is hence fixed by: // // int _0 ^limit f(x) dx = quantile // => a = -ln(1-quantile)/limit // // and final the frame must be changed such that 0->offset // // => a = -ln(1-quantile)/(limit-offset) // f(x) = a * exp(-a* (x-offset)) // Check that the quantile is in the range ]0,1[ if (quantile <= 0.0 && quantile >= 1.0) { std::cerr << "MSMath::Logexp >> error: " << "quantile must be >0 && <1\n"; return std::numeric_limits<double>::quiet_NaN(); // Check that the limit is above the offset } else if (limit <= offset) { std::cerr << "MSModelPullExp >> error: " << "the limit must be larger than the offset\n"; return std::numeric_limits<double>::quiet_NaN(); // Check that the parameter is in the physical range } else if (x < offset) { std::cerr << "MSMath::Logexp >> error: " << "parameter must be larger than the offset\n"; return std::numeric_limits<double>::quiet_NaN(); // compute LogExp } else { const double a = -log(1.0-quantile)/(limit-offset); return log(a)-a*(x-offset); } } } <commit_msg>changed returned values when the likelhood is not defined to push minuit away<commit_after>// Copyright (C) 2014 Matteo Agostini <matteo.agostini@ph.tum.de> // This 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 software 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. // c++ libs #include <iostream> #include <limits> #include <cmath> #include <vector> // ROOT libs #include <TMath.h> // m-stats libs #include "MSMath.h" namespace mst { double MSMath::LogGaus(double x, double mean, double sigma) { // sigma must be positive if (sigma <= 0.0) { std::cerr << "MSMath::LogGaus >> error: sigma must be positive\n"; return 0; } const double dx = (x - mean) / sigma; return -0.5*dx*dx - 0.5*log(2*M_PI) - log(sigma); } double MSMath::LogPoisson(double x, double lambda) { // If the parameters are negative the Poission probability is not defined if (lambda < 0.0 || x < 0.0) { std::cerr << "MSMath::LogPoisson >> error: " << "function not defined for negative parameters\n"; return -std::numeric_limits<double>::infinity(); } // The expectation must be positive. Empty bins in the PSD should be avoided else if (lambda == 0.0) { if (x == 0) return 0; else return -std::numeric_limits<double>::infinity(); } // Copute Poission probability for positive lambda values else { if (x == 0) return -lambda; else if (lambda < 899) return x*log(lambda)-lambda-TMath::LnGamma(x+1.); else return LogGaus(x, lambda, sqrt(lambda)); } } double MSMath::LogExp (double x, double limit, double quantile, double offset) { // the expoential function should be normalized in the range [offset, inf] and // have the quantile corresponding to the desidered probablity at the limit // value. // // Starting from the standard exp function normalized betweeen 0 and inf: // // f(x) = a*exp(-a*x) // // the parameter a is hence fixed by: // // int _0 ^limit f(x) dx = quantile // => a = -ln(1-quantile)/limit // // and final the frame must be changed such that 0->offset // // => a = -ln(1-quantile)/(limit-offset) // f(x) = a * exp(-a* (x-offset)) // Check that the quantile is in the range ]0,1[ if (quantile <= 0.0 && quantile >= 1.0) { std::cerr << "MSMath::Logexp >> error: " << "quantile must be >0 && <1\n"; return std::numeric_limits<double>::quiet_NaN(); // Check that the limit is above the offset } else if (limit <= offset) { std::cerr << "MSModelPullExp >> error: " << "the limit must be larger than the offset\n"; return std::numeric_limits<double>::quiet_NaN(); // Check that the parameter is in the physical range } else if (x < offset) { std::cerr << "MSMath::Logexp >> error: " << "parameter must be larger than the offset\n"; return std::numeric_limits<double>::quiet_NaN(); // compute LogExp } else { const double a = -log(1.0-quantile)/(limit-offset); return log(a)-a*(x-offset); } } } <|endoftext|>