Esempio n. 1
0
void
GroupControl::adjustArchiveWorldViewBackward(QmcTime::Packet *packet, bool setup)
{
    console->post("GroupControl::adjustArchiveWorldViewBackward");
    my.timeState = BackwardState;

    int setmode = PM_MODE_INTERP;
    int delta = packet->delta.tv_sec;
    if (packet->delta.tv_usec == 0) {
	setmode |= PM_XTB_SET(PM_TIME_SEC);
    } else {
	delta = delta * 1000 + packet->delta.tv_usec / 1000;
	setmode |= PM_XTB_SET(PM_TIME_MSEC);
    }

    //
    // X-Axis _min_ becomes packet->position.
    // Rest of (following) time window filled in using packet->delta.
    //
    int last = my.samples - 1;
    double tolerance = my.realDelta / 20.0;	// 5% of the sample interval
    double position = my.realPosition;

    double left = position - (my.realDelta * last);
    double right = position;
    double interval = pmchart->timeAxis()->scaleValue((double)delta, my.visible);

    for (int i = 0; i <= last; i++, position -= my.realDelta) {
	if (setup == false &&
	    fuzzyTimeMatch(my.timeData[i], position, tolerance) == true) {
	    continue;
	}

	my.timeData[i] = position;

	struct timeval timeval;
	__pmtimevalFromReal(position, &timeval);
	setArchiveMode(setmode, &timeval, -delta);
	console->post("Fetching data[%d] at %s", i, timeString(position));
	fetch();
	if (i == last)		// refreshGadgets() finishes up last one
	    break;
	console->post("GroupControl::adjustArchiveWorldViewBackward: "
		      "setting time position[%d]=%.2f[%s] state=%s count=%d",
			i, position, timeString(position),
			timeState(), gadgetCount());
	for (int j = 0; j < gadgetCount(); j++)
	    my.gadgetsList.at(j)->updateValues(false, false, my.samples, my.visible,
						left, right, interval);
    }

    bool active = isActive(packet);
    if (setup)
	packet->state = QmcTime::StoppedState;
    if (active)
	newButtonState(packet->state, packet->mode, pmchart->isTabRecording());
    pmtime->setArchivePosition(&packet->position);
    pmtime->setArchiveInterval(&packet->delta);
    refreshGadgets(active);
}
Esempio n. 2
0
void ChessClockWidget::repaintClock()
{
    // Set picture
    if( getStatus() == Running || getStatus() == Paused)
        pictureLabel_->setPixmap( picActive_);
    else
        pictureLabel_->setPixmap(picPassive_);

    timeUsedLabel_->setText( timeString( getTimePlayed() ));

    // Time average per turn
    int timeAverage;
    if( getTurn() == 0)
        timeAverage = 0;
    else
        timeAverage = getTimePlayed() / getTurn();
    timeAverageLabel_->setText( tr("Avg %1").arg( timeString( timeAverage ) ) );

    turnLabel_->setText( tr("Turn %1").arg(getTurn()));

    // Current turn played
    // Extra time of this turn is shown in green.
    if( currentTurnPlayed() < greenTime_ )
        turnTimeLabel_->setText( QString("<font color=green> %1 </font>") .arg(timeString( currentTurnPlayed()) ) );
    else
        turnTimeLabel_->setText( timeString( currentTurnPlayed() ) );

    // Loser flag
    loserLabel_->setVisible( isLoser());

    leftLabel_->setText( timeString(getTimeAvailable()));

}
Esempio n. 3
0
void
GroupControl::updateTimeAxis(void)
{
    QString tz, otz, unused;

    if (numContexts() > 0 || isArchiveSource() == false) {
	if (numContexts() > 0)
	    defaultTZ(unused, otz);
	else
	    otz = QmcSource::localHost;
	tz = otz;
	pmchart->timeAxis()->setAxisScale(QwtPlot::xBottom,
		my.timeData[my.visible - 1], my.timeData[0],
		pmchart->timeAxis()->scaleValue(my.realDelta, my.visible));
	pmchart->setDateLabel(my.position.tv_sec, tz);
	pmchart->timeAxis()->replot();
    } else {
	pmchart->timeAxis()->noArchiveSources();
	pmchart->setDateLabel(tr("[No open archives]"));
    }

    if (console->logLevel(PmChart::DebugProtocol)) {
	int i = my.visible - 1;
	console->post(PmChart::DebugProtocol,
		"GroupControl::updateTimeAxis: tz=%s; visible points=%d",
		(const char *)tz.toLatin1(), i);
	console->post(PmChart::DebugProtocol,
		"GroupControl::updateTimeAxis: first time is %.3f (%s)",
		my.timeData[i], timeString(my.timeData[i]));
	console->post(PmChart::DebugProtocol,
		"GroupControl::updateTimeAxis: final time is %.3f (%s)",
		my.timeData[0], timeString(my.timeData[0]));
    }
}
Esempio n. 4
0
QString KFileItem::timeString( unsigned int which ) const
{
    switch (which) {
    case KIO::UDSEntry::UDS_ACCESS_TIME:
        return timeString(AccessTime);
    case KIO::UDSEntry::UDS_CREATION_TIME:
        return timeString(CreationTime);
    case KIO::UDSEntry::UDS_MODIFICATION_TIME:
    default:
        return timeString(ModificationTime);
    }
}
Esempio n. 5
0
GrayScott::GrayScott(int N, double L, double dt, double Du, double Dv, double F, double k, int nSteps, std::string pngname)
    : N_(N)
    , Ntot_(N*N)
//    , L_(L)
    , dx_((double) L / (double) N)
    , dt_(dt)
    , nSteps_(nSteps)
    , currStep_(0)
    , Du_(Du)
    , Dv_(Dv)
    , F_(F)
    , k_(k)
    , matU1_(N, -Du*dt/(2.*dx_*dx_), 1.+Du*dt/(dx_*dx_), -Du*dt/(2.*dx_*dx_))
    , matU2_(N, -Du*dt/(2.*dx_*dx_), 1.+Du*dt/(dx_*dx_), -Du*dt/(2.*dx_*dx_)) // equal to matU1_, since we have a square grid (dx==dy)
    , matV1_(N, -Dv*dt/(2.*dx_*dx_), 1.+Dv*dt/(dx_*dx_), -Dv*dt/(2.*dx_*dx_))
    , matV2_(N, -Dv*dt/(2.*dx_*dx_), 1.+Dv*dt/(dx_*dx_), -Dv*dt/(2.*dx_*dx_))
    , pngName_(pngname)
{
    // create directory to save output to
    time_t rawtime;
	struct tm * timeinfo;
	char buffer[80];
	time (&rawtime);
	timeinfo = localtime(&rawtime);
	strftime(buffer,80,"%d-%m-%Y_%H-%M-%S",timeinfo);
	std::string timeString(buffer);
	
	dirPath_ = "data/" + timeString + "/";
	
	boost::filesystem::path dir(dirPath_);
	boost::filesystem::create_directory(dir);
    
    initialize_fields();
}
Esempio n. 6
0
void GLPresenter::testAAinternal()
{
	const char* ts = timeString();
	GLRenderTexture target(getW(), getH(), GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE);

	AAManager::aaMode prevMode = aaManager->getAAMode();

	aaManager->setAAMode(AAManager::NONE);
	aaManager->applyAA(buffer, &target);
	target.saveToImage(format("%s__noaa.png", ts));
	aaManager->setAAMode(AAManager::FXAA);
	aaManager->applyAA(buffer, &target);
	target.saveToImage(format("%s__fxaa.png", ts));
	aaManager->setAAMode(AAManager::PXAA);
	aaManager->applyAA(buffer, &target);
	target.saveToImage(format("%s__pxaa.png", ts));
	aaManager->setAAMode(AAManager::TPXAA);
	aaManager->applyAA(buffer, &target);
	target.saveToImage(format("%s__tpxaa.png", ts));
	aaManager->setAAMode(AAManager::SMAA);
	aaManager->applyAA(buffer, &target);
	target.saveToImage(format("%s__smaa.png", ts));


	aaManager->setAAMode(prevMode);
}
Esempio n. 7
0
void
QmcSource::dump(QTextStream &stream)
{
    stream << "  sts = " << my.status << ", type = " << my.type
	   << ", source = " << my.source << endl
	   << "  host = " << my.host << ", timezone = " << my.timezone
	   << ", tz hndl = " << my.tz << endl;
    if (my.status >= 0)
	stream << "  start = " << timeString(&my.start) << ", end = "
	       << timeString(&my.end) << ", dupFlag = "
	       << (my.dupFlag == true ? "true" : "false") << endl << "  " 
	       << my.handles.size() << " contexts: ";
    for (int i = 0; i < my.handles.size(); i++)
	stream << my.handles[i] << ' ';
    stream << endl;
}
Esempio n. 8
0
local int DumpScore(const char *key, void *val, void *clos)
{
	char time[TIMEBUFFERSIZE];
	int *seconds = (int *)val;
	chat->SendArenaMessage((Arena *)clos, "%s : %s", key, timeString(*seconds, time));
	return FALSE;
}
Esempio n. 9
0
//
// Received a Set or a VCRMode requiring us to adjust our state
// and possibly rethink everything.  This can result from a time
// control position change, delta change, direction change, etc.
//
void
GroupControl::adjustWorldView(QmcTime::Packet *packet, bool vcrMode)
{
    my.delta = packet->delta;
    my.position = packet->position;
    my.realDelta = __pmtimevalToReal(&packet->delta);
    my.realPosition = __pmtimevalToReal(&packet->position);

    console->post("GroupControl::adjustWorldView: "
		  "sh=%d vh=%d delta=%.2f position=%.2f (%s) state=%s",
		my.samples, my.visible, my.realDelta, my.realPosition,
		timeString(my.realPosition), timeState());

    QmcTime::State state = packet->state;
    if (isArchiveSource()) {
	if (packet->state == QmcTime::ForwardState)
	    adjustArchiveWorldViewForward(packet, vcrMode);
	else if (packet->state == QmcTime::BackwardState)
	    adjustArchiveWorldViewBackward(packet, vcrMode);
	else
	    adjustArchiveWorldViewStopped(packet, vcrMode);
    }
    else if (state != QmcTime::StoppedState)
	adjustLiveWorldViewForward(packet);
    else
	adjustLiveWorldViewStopped(packet);
}
Esempio n. 10
0
local void DumpScores(FlagTeam *team)
{
	char time[TIMEBUFFERSIZE];
	chat->SendArenaMessage(team->Arena, "Freq %d : %s", team->Freq, timeString(team->FlagSeconds, time));
	MYGLOCK;
	HashEnum(team->Breakdown, DumpScore, team->Arena);
	MYGUNLOCK;
	chat->SendArenaMessage(team->Arena, "------------------------------");
}
Esempio n. 11
0
String DateField::timeToString(int64_t time) {
    if (time < 0) {
        boost::throw_exception(RuntimeException(L"time '" + StringUtils::toString(time) + L"' is too early, must be >= 0"));
    }

    String timeString(DATE_LEN(), L'0');
    timeString += StringUtils::toString(time, StringUtils::CHARACTER_MAX_RADIX);

    return timeString.substr(timeString.length() - DATE_LEN(), DATE_LEN());
}
Esempio n. 12
0
/*
 * Print one line listing the information about the specified archive member.
 */
static void
listMember(const Archive * arch)
{
	printf("%s %6ld/%-6ld %8lu %s %s\n",
	       modeString(arch->mode) + 1,
	       (long) arch->uid,
	       (long) arch->gid,
	       (unsigned long) arch->size,
	       timeString(arch->date),
	       arch->name);
}
Esempio n. 13
0
void ChannelChatTab::topic(std::string const & channelName, std::string const & author, time_t epochSeconds, std::string const & topic)
{
    if (channelName == channelName_)
    {
        append("Topic: " + topic);

        std::string timeString(ctime(&epochSeconds));
        boost::algorithm::erase_all(timeString, "\n");

        append("Topic set " + timeString + " by " + author);
    }
}
Esempio n. 14
0
void Logger::setFile(const std::string& filename, const FileType& pFileType)
{
	time_t rawTime;
	time(&rawTime);
	std::string timeString(ctime(&rawTime));
	
	filename_ = timeString + "_" + filename; 
	fileType_ = pFileType;
	
	std::ofstream logFile;
	logFile.open(filename_.c_str());
	logFile << getHeader() << std::flush;
	logFile.close();
}
Esempio n. 15
0
void Logger::logToFile(const std::string& pText, const Type& pType)
{
	time_t rawTime;
	time(&rawTime);
	std::string timeString(ctime(&rawTime));
	std::string finalText;
	
	switch (fileType_) {
		case LOG_FILE_TEXT:
			switch (pType) {
				case LOG_TYPE_DEBUG:
					finalText = ("[DEBUG]" + timeString + "[DEBUG]" + pText);
					break;
				case LOG_TYPE_INFO:
					finalText = ("[INFO]" + timeString + "[INFO]" + pText);
					break;
				case LOG_TYPE_ERROR:
					finalText = ("[ERROR]" + timeString + "[ERROR]" + pText);
					break;
				default:
					break; // Should not get here.. so just ignore...
			}
			break;
		case LOG_FILE_HTML:
			switch (pType) {
				case LOG_TYPE_DEBUG:
					finalText = ("\t<div id=\"DEBUG\">[" + timeString + "] " + pText + "</div>");
					break;
				case LOG_TYPE_INFO:
					finalText = ("\t<div id=\"INFO\">[" + timeString + "] " + pText + "</div>");
					break;
				case LOG_TYPE_ERROR:
					finalText = ("\t<div id=\"ERROR\">[" + timeString + "] " + pText + "</div>");
					break;
				default:
					break; // Should not get here.. so just ignore...
			}
			break;
		case LOG_FILE_UNOPENED:
			log("Logger: There is no file open to output to!", LOG_TYPE_ERROR, LOG_OUTPUT_TERMINAL);
			return;
		default:
			break; // Should not get here.. so just ignore
	}
	
	std::ofstream logFile;
	logFile.open(filename_.c_str(), std::ios::app);
	logFile << finalText << std::flush;
	logFile.close();
}
Esempio n. 16
0
std::string Logger::getTimeString() const {
	stringstream ss;
	ss.str("");
	ss.clear();
	GetLocalTime(&systemTime);
	ss << std::setw(4) << systemTime.wYear << "/" <<
		setw(2) << setfill('0') << systemTime.wMonth << "/" <<
		setw(2) << setfill('0') << systemTime.wDay << " " <<
		setw(2) << setfill('0') << systemTime.wHour << ":" <<
		setw(2) << setfill('0') << systemTime.wMinute  << ":" <<
		setw(2) << setfill('0') << systemTime.wSecond  << "." <<
		setw(3) << setfill('0') << systemTime.wMilliseconds;
	std::string timeString(ss.str());
	return timeString;
}
UnicodeString& RelativeDateFormat::format(  Calendar& cal,
        UnicodeString& appendTo,
        FieldPosition& pos) const {

    UErrorCode status = U_ZERO_ERROR;
    UChar emptyStr = 0;
    UnicodeString dateString(&emptyStr);

    // calculate the difference, in days, between 'cal' and now.
    int dayDiff = dayDifference(cal, status);

    // look up string
    int32_t len = 0;
    const UChar *theString = getStringForDay(dayDiff, len, status);
    if(U_SUCCESS(status) && (theString!=NULL)) {
        // found a relative string
        dateString.setTo(theString, len);
    }

    if(fTimeFormat == NULL || fCombinedFormat == 0) {
        if (dateString.length() > 0) {
            appendTo.append(dateString);
        } else if(fDateFormat != NULL) {
            fDateFormat->format(cal,appendTo,pos);
        }
    } else {
        if (dateString.length() == 0 && fDateFormat != NULL) {
            fDateFormat->format(cal,dateString,pos);
        }
        UnicodeString timeString(&emptyStr);
        FieldPosition timepos = pos;
        fTimeFormat->format(cal,timeString,timepos);
        Formattable timeDateStrings[] = { timeString, dateString };
        fCombinedFormat->format(timeDateStrings, 2, appendTo, pos, status); // pos is ignored by this
        int32_t offset;
        if (pos.getEndIndex() > 0 && (offset = appendTo.indexOf(dateString)) >= 0) {
            // pos.field was found in dateString, offset start & end based on final position of dateString
            pos.setBeginIndex( pos.getBeginIndex() + offset );
            pos.setEndIndex( pos.getEndIndex() + offset );
        } else if (timepos.getEndIndex() > 0 && (offset = appendTo.indexOf(timeString)) >= 0) {
            // pos.field was found in timeString, offset start & end based on final position of timeString
            pos.setBeginIndex( timepos.getBeginIndex() + offset );
            pos.setEndIndex( timepos.getEndIndex() + offset );
        }
    }

    return appendTo;
}
Esempio n. 18
0
void GLPresenter::testScaling()
{
	const char* ts = timeString();
	GLRenderTexture target(1920, 1080, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE);

	scalingManager->setScalingMode(ScalingManager::BILINEAR);
	scalingManager->drawScaled(buffer, &target);
	target.saveToImage(format("%s__bilinear.png", ts));
	scalingManager->setScalingMode(ScalingManager::FIXED);
	scalingManager->drawScaled(buffer, &target);
	target.saveToImage(format("%s__fixed_lanc.png", ts));
	scalingManager->setScalingMode(ScalingManager::ADAPTIVE);
	scalingManager->drawScaled(buffer, &target);
	target.saveToImage(format("%s__adaptive_lanc.png", ts));
	glFinish();
}
Esempio n. 19
0
string Packet::toString() const{
	// Serialize this object for the network

	string delimiter = "\n";

	stringstream serialization;
	
	serialization << getType();

	serialization << delimiter;

	struct tm *nowtm;
	char tmbuf[64] ;
	
	nowtm = localtime(&timeSent);
	strftime(tmbuf, sizeof tmbuf, "%Y-%m-%d %H:%M:%S", nowtm);
	
	string timeString (tmbuf);

	serialization << timeString;

	serialization << delimiter;

	serialization << getLifeTime(); 

	serialization << delimiter;

	serialization << getPacketNumber();

	serialization << delimiter;

	serialization << getHopCount();

	serialization << delimiter;
	
	serialization << getSourceAddress();

	serialization << delimiter;

	serialization << getDestinationAddress();

	serialization << delimiter;

	serialization << getPayload();

	return serialization.str();
}
Esempio n. 20
0
void ZLTextView::PositionIndicator::draw() {
	ZLTextBaseStyle &baseStyle = ZLTextStyleCollection::instance().baseStyle();

	ZLPaintContext &context = this->context();

	ZLTextWordCursor endCursor = myTextView.endCursor();
	bool isEndOfText = false;
	if (endCursor.isEndOfParagraph()) {
		isEndOfText = !endCursor.nextParagraph();
	}

	myExtraWidth = 0;
	if (myInfo.isTimeShown()) {
		drawExtraText(timeString());
	}
	if (myInfo.isBatteryShown()) {
		drawExtraText(batteryString());
	}
	if (myInfo.isTextPositionShown()) {
		drawExtraText(textPositionString());
	}

	const long bottom = this->bottom();
	const long top = this->top();
	const long left = this->left();
	const long right = this->right();

	if (left >= right) {
		return;
	}

	size_t fillWidth = right - left - 1;

	if (!isEndOfText) {
		fillWidth =
			muldiv(fillWidth, sizeOfTextBeforeCursor(myTextView.endCursor()), sizeOfTextBeforeParagraph(endTextIndex()));
	}

	context.setColor(baseStyle.RegularTextColorOption.value());
	context.setFillColor(myInfo.color());
	context.fillRectangle(myTextView.visualX(left + 1), top + 1, myTextView.visualX(left + fillWidth + 1), bottom - 1);
	context.drawLine(myTextView.visualX(left), top, myTextView.visualX(right), top);
	context.drawLine(myTextView.visualX(left), bottom, myTextView.visualX(right), bottom);
	context.drawLine(myTextView.visualX(left), bottom, myTextView.visualX(left), top);
	context.drawLine(myTextView.visualX(right), bottom, myTextView.visualX(right), top);
}
Esempio n. 21
0
File: tool.cpp Progetto: xfun68/test
/*
 * 日志输出函数
 */
void logger(const uint32_t zone,
    const uint32_t gateway,
    const char*    type,     //desciption of operation
    const int      ret,
    const uint32_t user_id,
    const uint32_t role_id,
    const char*    format,
    ...)
{
    int retcode = E_ERROR;
    uint32_t buf_len = 0;
    static char buf[1024] = {0};
    va_list arg;

    va_start(arg, format);
    buf_len = vsprintf(buf, format, arg);
    va_end(arg);

    buf[buf_len] = '\0';

    retcode = SysLogManager::output(
        (SysLog::LOG_TYPE)(SysLog::LOG_INFO),
        "%u|%u|%s|%d|%u|%u|%s\n",
        zone,
        gateway,
        type,
        ret,
        user_id,
        role_id,
        buf);
#ifdef DEBUG
    printf("%s|%u|%u|%s|%d|%u|%u|%s\n",
        timeString(),
        zone,
        gateway,
        type,
        ret,
        user_id,
        role_id,
        buf);
#endif // DEBUG

    return;
}
Esempio n. 22
0
File: tool.cpp Progetto: xfun68/test
void logger(const char* format, ...)
{
    int retcode = E_ERROR;
    uint32_t buf_len = 0;
    static char buf[MAX_BUFFER_SIZE] = {0};
    va_list arg;

    va_start(arg, format);
    buf_len = vsprintf(buf, format, arg);
    va_end(arg);

    buf[buf_len] = '\0';

    retcode = SysLogManager::output((SysLog::LOG_TYPE)(SysLog::LOG_INFO), "%s\n", buf);
#ifdef DEBUG
    printf("%s %s\n", timeString(), buf);
#endif // DEBUG
    return;
}
Esempio n. 23
0
void Logger::logToTerm(const std::string& pText, const Type& pType)
{
	time_t rawTime;
	time(&rawTime);
	std::string timeString(ctime(&rawTime));
	
	switch (pType) {
		case LOG_TYPE_DEBUG:
			std::cout << "[DEBUG]" << timeString << "[DEBUG]" << pText;
			break;
		case LOG_TYPE_INFO:
			std::cout << "[INFO]" << timeString << "[INFO]" << pText;
			break;
		case LOG_TYPE_ERROR:
			std::cerr << "[ERROR]" << timeString << "[ERROR]" << pText;
			break;
		default:
			break; // Should not get here.. so just ignore...
	}
}
void ZLTextView::PositionIndicator::draw() {
	ZLPaintContext &context = this->context();

	ZLTextWordCursor endCursor = myTextView.textArea().endCursor();
	bool isEndOfText = false;
	if (endCursor.isEndOfParagraph()) {
		isEndOfText = !endCursor.nextParagraph();
	}

	myExtraWidth = 0;
	if (myInfo.isTimeShown()) {
		drawExtraText(timeString());
	}
	if (myInfo.isTextPositionShown()) {
		drawExtraText(textPositionString());
	}

	const long bottom = this->bottom();
	const long top = this->top();
	const long left = this->left();
	const long right = this->right();

	if (left >= right) {
		return;
	}

	size_t fillWidth = right - left - 1;

	if (!isEndOfText) {
		fillWidth =
			muldiv(fillWidth, sizeOfTextBeforeCursor(myTextView.textArea().endCursor()), sizeOfTextBeforeParagraph(endTextIndex()));
	}

	context.setColor(myTextView.color());
	context.setFillColor(myInfo.color());
	context.fillRectangle(left + 1, top + 1, left + fillWidth + 1, bottom - 1);
	context.drawLine(left, top, right, top);
	context.drawLine(left, bottom, right, bottom);
	context.drawLine(left, bottom, left, top);
	context.drawLine(right, bottom, right, top);
}
Esempio n. 25
0
const std::string Logger::getFooter()
{
	time_t rawTime;
	time(&rawTime);
	std::string timeString(ctime(&rawTime));
	
	std::string footer;
	
	switch (fileType_) {
		case LOG_FILE_HTML:
			footer = ("\t\t<h1>Ended - " + timeString + "</h1>\n\t</body>\n</html>");
			break;
		case LOG_FILE_TEXT:
			footer = "Ended - " + timeString + "\n";
			break;
		default:
			break;
	}
	
	return footer;
}
Esempio n. 26
0
const std::string Logger::getHeader()
{
	time_t rawTime;
	time(&rawTime);
	std::string timeString(ctime(&rawTime));
	
	std::string header;
	
	switch (fileType_) {
		case LOG_FILE_HTML:
			header = ("<html>\n\t<head>\n\t\t<title>SGEngine Log</title>\n\t</head>\n\t<body>\n\t\t<h1>Started - " + timeString + "</h1>");
			break;
		case LOG_FILE_TEXT:
			header = "SGEngine Log\nStarted - " + timeString + "\n";
			break;
		default:
			break;
	}
	
	return header;
}
Esempio n. 27
0
void Log::vprint(int logLevel, const TCHAR *fmt, va_list argList)
{
  Log *instance = getInstance();
  if (instance == 0) {
    return;
  }

  StringStorage timeString(_T("[Temporary unavaliable]"));
  SYSTEMTIME st;
  GetLocalTime(&st);
  timeString.format(_T("%.4d-%.2d-%.2d %.2d:%.2d:%.2d"),
                    st.wYear, st.wMonth, st.wDay,
                    st.wHour, st.wMinute, st.wSecond);

  const TCHAR logLevelSignature[] = _T("@!*+-:    xxxxxx");
  TCHAR sig = logLevelSignature[logLevel & 0x0F];

  int count = _vsctprintf(fmt, argList);
  TCHAR *formattedString = new TCHAR[count + 1];
  _vstprintf(formattedString, fmt, argList);

  StringStorage message;
  message.format(_T("[%4d] %s %c %s"),
                 GetCurrentThreadId(),
                 timeString.getString(),
                 sig,
                 formattedString);
  const TCHAR badCharacters[] = {13, 10, 0};
  message.removeChars(badCharacters, sizeof(badCharacters) / sizeof(TCHAR));
  delete[] formattedString;

  const TCHAR endLine[3] = {13, 10, 0};
  message.appendString(endLine);

  instance->flushLine(logLevel, message.getString());
}
Esempio n. 28
0
//
// Drive all updates into each gadget (refresh the display)
//
void
GroupControl::refreshGadgets(bool active)
{
#if DESPERATE
    for (int s = 0; s < my.samples; s++)
	console->post(PmChart::DebugProtocol,
		"GroupControl::refreshGadgets: timeData[%2d] is %.2f (%s)",
		s, my.timeData[s], timeString(my.timeData[s]));
    console->post(PmChart::DebugProtocol,
		"GroupControl::refreshGadgets: state=%s", timeState());
#endif

    for (int i = 0; i < gadgetCount(); i++) {
	my.gadgetsList.at(i)->updateValues(my.timeState != BackwardState,
					active, my.samples, my.visible,
					my.timeData[my.visible - 1],
					my.timeData[0],
					my.realDelta);
    }
    if (active) {
	updateTimeButton();
	updateTimeAxis();
    }
}
Esempio n. 29
0
/*
 * Examine the header block that was just read.
 * This can specify the information for another file, or it can mark
 * the end of the tar file.
 */
static void
readHeader(const TarHeader * hp, int fileCount, const char ** fileTable)
{
	int		mode;
	int		uid;
	int		gid;
	//int		checkSum;
	long		size;
	time_t		mtime;
	const char *	name;
	int		cc;
	BOOL		hardLink;
	BOOL		softLink;

	/*
	 * If the block is completely empty, then this is the end of the
	 * archive file.  If the name is null, then just skip this header.
	 */
	name = hp->name;

	if (*name == '\0')
	{
		for (cc = TAR_BLOCK_SIZE; cc > 0; cc--)
		{
			if (*name++)
				return;
		}

		eofFlag = TRUE;

		return;
	}

	/*
	 * There is another file in the archive to examine.
	 * Extract the encoded information and check it.
	 */
	mode = getOctal(hp->mode, sizeof(hp->mode));
	uid = getOctal(hp->uid, sizeof(hp->uid));
	gid = getOctal(hp->gid, sizeof(hp->gid));
	size = getOctal(hp->size, sizeof(hp->size));
	mtime = getOctal(hp->mtime, sizeof(hp->mtime));
	//checkSum = getOctal(hp->checkSum, sizeof(hp->checkSum));

	if ((mode < 0) || (uid < 0) || (gid < 0) || (size < 0))
	{
		if (!badHeader)
			fprintf(stderr, "Bad tar header, skipping\n");

		badHeader = TRUE;

		return;
	}

	badHeader = FALSE;
	skipFileFlag = FALSE;

	/*
	 * Check for the file modes.
	 */
	hardLink = ((hp->typeFlag == TAR_TYPE_HARD_LINK) ||
		(hp->typeFlag == TAR_TYPE_HARD_LINK - '0'));

	softLink = ((hp->typeFlag == TAR_TYPE_SOFT_LINK) ||
		(hp->typeFlag == TAR_TYPE_SOFT_LINK - '0'));

	/*
	 * Check for a directory or a regular file.
	 */
	if (name[strlen(name) - 1] == '/')
		mode |= S_IFDIR;
	else if ((mode & S_IFMT) == 0)
		mode |= S_IFREG;

	/*
	 * Check for absolute paths in the file.
	 * If we find any, then warn the user and make them relative.
	 */
	if (*name == '/')
	{
		while (*name == '/')
			name++;

		if (!warnedRoot)
		{
			fprintf(stderr,
			"Absolute path detected, removing leading slashes\n");
		}

		warnedRoot = TRUE;
	}

	/*
	 * See if we want this file to be restored.
	 * If not, then set up to skip it.
	 */
	if (!wantFileName(name, fileCount, fileTable))
	{
		if (!hardLink && !softLink && S_ISREG(mode))
		{
			inHeader = (size == 0);
			dataCc = size;
		}

		skipFileFlag = TRUE;

		return;
	}

	/*
	 * This file is to be handled.
	 * If we aren't extracting then just list information about the file.
	 */
	if (!extractFlag)
	{
		if (verboseFlag)
		{
			printf("%s %3d/%-d %9ld %s %s", modeString(mode),
				uid, gid, size, timeString(mtime), name);
		}
		else
			printf("%s", name);

		if (hardLink)
			printf(" (link to \"%s\")", hp->linkName);
		else if (softLink)
			printf(" (symlink to \"%s\")", hp->linkName);
		else if (S_ISREG(mode))
		{
			inHeader = (size == 0);
			dataCc = size;
		}

		printf("\n");

		return;
	}

	/*
	 * We really want to extract the file.
	 */
	if (verboseFlag)
		printf("x %s\n", name);

	if (hardLink)
	{
		if (link(hp->linkName, name) < 0)
			perror(name);

		return;
	}

	if (softLink)
	{
#ifdef	S_ISLNK
		if (symlink(hp->linkName, name) < 0)
			perror(name);
#else
		fprintf(stderr, "Cannot create symbolic links\n");
#endif
		return;
	}

	/*
	 * If the file is a directory, then just create the path.
	 */
	if (S_ISDIR(mode))
	{
		createPath(name, mode);

		return;
	}

	/*
	 * There is a file to write.
	 * First create the path to it if necessary with a default permission.
	 */
	createPath(name, 0777);

	inHeader = (size == 0);
	dataCc = size;

	/*
	 * Start the output file.
	 */
	outFd = open(name, O_WRONLY | O_CREAT | O_TRUNC, mode);

	if (outFd < 0)
	{
		perror(name);
		skipFileFlag = TRUE;

		return;
	}

	/*
	 * If the file is empty, then that's all we need to do.
	 */
	if (size == 0)
	{
		(void) close(outFd);
		outFd = -1;
	}
}
Esempio n. 30
0
void load_ply(const std::string &filename, MatrixXu &F, MatrixXf &V, bool load_faces,
              const ProgressCallback &progress) {
    auto message_cb = [](p_ply ply, const char *msg) {
        cerr << "rply: " << msg << endl;
    };

    Timer<> timer;
    cout << "Loading \"" << filename << "\" .. ";
    cout.flush();

    p_ply ply = ply_open(filename.c_str(), message_cb, 0, nullptr);
    if (!ply)
        throw std::runtime_error("Unable to open PLY file \"" + filename + "\"!");

    if (!ply_read_header(ply)) {
        ply_close(ply);
        throw std::runtime_error("Unable to open PLY header of \"" + filename + "\"!");
    }

    p_ply_element element = nullptr;
    uint32_t vertexCount = 0, faceCount = 0;

    /* Inspect the structure of the PLY file */
    while ((element = ply_get_next_element(ply, element)) != nullptr) {
        const char *name;
        long nInstances;

        ply_get_element_info(element, &name, &nInstances);
        if (!strcmp(name, "vertex"))
            vertexCount = (uint32_t) nInstances;
        else if (!strcmp(name, "face"))
            faceCount = (uint32_t) nInstances;
    }

    if (vertexCount == 0 && faceCount == 0)
        throw std::runtime_error("PLY file \"" + filename + "\" is invalid! No face/vertex/elements found!");

    if (load_faces)
        F.resize(3, faceCount);
    V.resize(3, vertexCount);

    struct VertexCallbackData {
        MatrixXf &V;
        const ProgressCallback &progress;
        VertexCallbackData(MatrixXf &V, const ProgressCallback &progress)
            : V(V), progress(progress) {}
    };

    struct FaceCallbackData {
        MatrixXu &F;
        const ProgressCallback &progress;
        FaceCallbackData(MatrixXu &F, const ProgressCallback &progress)
            : F(F), progress(progress) {}
    };

    auto rply_vertex_cb = [](p_ply_argument argument) -> int {
        VertexCallbackData *data;
        long index, coord;
        ply_get_argument_user_data(argument, (void **) &data, &coord);
        ply_get_argument_element(argument, nullptr, &index);
        data->V(coord, index) = (Float) ply_get_argument_value(argument);
        if (data->progress && coord == 0 && index % 500000 == 0)
            data->progress("Loading vertex data", index / (Float) data->V.cols());
        return 1;
    };

    auto rply_index_cb = [](p_ply_argument argument) -> int {
        FaceCallbackData *data;
        long length, value_index, index;
        ply_get_argument_property(argument, nullptr, &length, &value_index);

        if (length != 3)
            throw std::runtime_error("Only triangle faces are supported!");

        ply_get_argument_user_data(argument, (void **) &data, nullptr);
        ply_get_argument_element(argument, nullptr, &index);

        if (value_index >= 0)
            data->F(value_index, index) = (uint32_t) ply_get_argument_value(argument);

        if (data->progress && value_index == 0 && index % 500000 == 0)
            data->progress("Loading face data", index / (Float) data->F.cols());

        return 1;
    };

    VertexCallbackData vcbData(V, progress);
    FaceCallbackData fcbData(F, progress);

    if (!ply_set_read_cb(ply, "vertex", "x", rply_vertex_cb, &vcbData, 0) ||
            !ply_set_read_cb(ply, "vertex", "y", rply_vertex_cb, &vcbData, 1) ||
            !ply_set_read_cb(ply, "vertex", "z", rply_vertex_cb, &vcbData, 2)) {
        ply_close(ply);
        throw std::runtime_error("PLY file \"" + filename + "\" does not contain vertex position data!");
    }

    if (load_faces) {
        if (!ply_set_read_cb(ply, "face", "vertex_indices", rply_index_cb, &fcbData, 0)) {
            ply_close(ply);
            throw std::runtime_error("PLY file \"" + filename + "\" does not contain vertex indices!");
        }
    }

    if (!ply_read(ply)) {
        ply_close(ply);
        throw std::runtime_error("Error while loading PLY data from \"" + filename + "\"!");
    }

    ply_close(ply);
    cout << "done. (V=" << vertexCount;
    if (load_faces)
        cout << ", F=" << faceCount;
    cout << ", took " << timeString(timer.value()) << ")" << endl;
}