Exemple #1
0
    nint NDateTime::compareTo(const INObject * other) const
    {
        if (this == other)
            return 0;
        try
        {
            const NDateTime * obj = dynamic_cast<const NDateTime *>(other);

            if (obj != NULL)
            {
                int result = 0;
                if ((result = getYear() - obj->getYear()) == 0)
                {
                    if ((result = getMonth() - obj->getMonth()) == 0)
                    {
                        if ((result = getDay() - obj->getDay()) == 0)
                        {
                            if ((result = getHour() - obj->getHour()) == 0)
                            {
                                if ((result = getMinute() - obj->getMinute()) == 0)
                                {
                                    if ((result = getSecond() - obj->getSecond()) == 0)
                                    {
                                        result = getMillisecond() - obj->getMillisecond();
                                    }
                                }
                            }
                        }
                    }
                }
                return result;
            }
            else
            {
                return 1;
            }
        }
        catch (bad_cast &)
        {
            return 1;
        }
    }
void Store::markTasksDueToday() {
	log.log("Store: changing due status");

	string todayDay = currentDay();
	string todayMonth = currentMonth();
	string todayYear = currentYear();


	for(int i = 0; i <  taskList.size(); i++) {

		if(getDay(i) == todayDay  && getMonth(i) == todayMonth && getYear(i) == todayYear) {
			taskList[i].isBold = true;
		}
		else {
			taskList[i].isBold = false;
		}
	}

	markTasksOverdue();
}
Exemple #3
0
void loadCurrentReminder(char **rStr)
{
	char str[256];
	sprintf(str,"%s%02d%02d%04d.REM",d_reminder,getMonth(),getDay(),getYear());	
	
	if(DRAGON_FileExists(str) == FE_FILE)
	{		
		DRAGON_FILE *fFile = DRAGON_fopen(str, "r");
		u32 tLen = DRAGON_flength(fFile);
		
		*rStr = (char *)trackMalloc(tLen+5, "tmp reminder");
		memset(*rStr, 0, tLen+5);
		
		DRAGON_fread(*rStr, 1, tLen, fFile);
		DRAGON_fclose(fFile);
	}
	else
	{
		*rStr = (char *)trackMalloc(1, "tmp reminder");
		*rStr[0] = 0;
	}
}
Exemple #4
0
uint32_t RTCDue::unixtime ()
{
  uint32_t _ticks;
  uint16_t _days;
  
  _hour   = getHours ();
  _minute = getMinutes ();
  _second = getSeconds ();
  
  _day    = getDay ();
  _month  = getMonth ();
  _year   = getYear (); //4 digits
  
  // Based on https://github.com/punkiller/workspace/blob/master/string2UnixTimeStamp.cpp
  // days of the years between start of unixtime and now
  _days = 365 * (_year - 1970);
  
  // add days from switch years in between except year from date
  for( int i = 1970; i < _year; i++ ){
    if( switch_years (i) ) {
      _days++;
    }
  }
  
  // Based on https://github.com/adafruit/RTClib/blob/master/RTClib.cpp
  // add switch day from actuall year if necessary
  for ( int i = 1; i < _month; ++i )
    _days += daysInMonth[i - 1];
  
  if ( _month > 2 && switch_years (_year) )
    ++_days;
  
  _days += _day - 1;
  
  _ticks = ((_days * 24 + _hour) * 60 + _minute) * 60 + _second;
  
  return _ticks;
}
//implemented for non-leap years
void Store::markTasksDueTomorrow() { 

	vector<string> returnedVector = getDateTomorrow();
	
	string tomorrowDay = returnedVector[0];
	string tomorrowMonth = returnedVector[1];
	string tomorrowYear = returnedVector[2];


	for(int i =0; i < taskList.size(); i++) {

		if(getDay(i) ==  tomorrowDay && getMonth(i) == tomorrowMonth && getYear(i) == tomorrowYear) {

			taskList[i].isTomorrow = true;
		}
		else
			taskList[i].isTomorrow = false;
	}
		
		//taskList[1].isTomorrow = true;

	
} //this returns the tasks marked with tomorrow! now check if tomorrow really works!
Exemple #6
0
void Date::setDayName()
{
	string dayName;
	int yyyy = getYear();
	int mm = getMonth();
	int dd = getDay();
	dd += ((yyyy-1)*365 + (yyyy-1)/4 - (yyyy-1)/100 + (yyyy-1)/400) % 7;//Daycode for prev year 31st Dec
	switch(mm)
	{
		case 12:dd += 334;break;
		case 11:dd += 304;break;
		case 10:dd += 273;break;
		case 9:dd += 243;break;
		case 8:dd += 212;break;
		case 7:dd += 181;break;
		case 6:dd += 151;break;
		case 5:dd += 120;break;
		case 4:dd += 90;break;
		case 3:dd += 59;break;
		case 2:dd += 31;break;
	}
	if ((!(yyyy % 4) && ((yyyy % 100) || !(yyyy % 400)))&& mm > 2)
		dd++;
	dd = dd%7;
	switch(dd)
	{
		case 0:dayName = "SUNDAY";break;
		case 1:dayName = "MONDAY";break;
		case 2:dayName = "TUESDAY";break;
		case 3:dayName = "WEDNESDAY";break;
		case 4:dayName = "THURSDAY";break;
		case 5:dayName = "FRIDAY";break;
		case 6:dayName = "SATURDAY";break;
	}
	setDayw(getHalfDayName(dayName));
}
Exemple #7
0
int main(int argc, char *argv[])
{
	int server_sock, client_sock;
	char header[2] = {'$', '#'};
	struct sockaddr_in server_addr, client_addr;

	pid_t pid;
	struct sigaction act;
	socklen_t addr_size;

	if(argc!=2) {
		printf("Usage : %s <port>\n", argv[0]);
		exit(1);
	}

	// signal setting
	act.sa_handler = ctrl_childproc;
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	if(sigaction(SIGCHLD, &act, 0) != 0)
		error_handling("LOG ( Sigaction() error. )\n");

	// socket create
	if((server_sock = socket(PF_INET, SOCK_STREAM, 0)) < 0)
		error_handling("LOG ( Can't open stream socket. )\n");

	// socket addr setting
	bzero((char *)&server_addr, sizeof(server_addr));
	server_addr.sin_family=AF_INET;
	server_addr.sin_addr.s_addr=htonl(INADDR_ANY);
	server_addr.sin_port=htons(atoi(argv[1]));

	// socket bind
	if(bind(server_sock, (struct sockaddr*) &server_addr, sizeof(server_addr)) == -1)
		error_handling("LOG ( Bind() error )\n");

	// stay for client
	if(listen(server_sock, MAX_CLIENT) == -1)
		error_handling("LOG ( Listen() error )\n");

	while(1)
	{
		// client connetion
		addr_size = sizeof(client_addr);

		// try to client accept
		if((client_sock = accept(server_sock, (struct sockaddr*)&client_addr, &addr_size)) == -1)
			continue;
		else
			puts("LOG ( New client connected... )");

		if((pid = fork()) > 0)
			childcnt++;

		if(pid == -1)
		{
			close(client_sock);
			continue;
		}

		// child process
		if(pid == 0)
		{
			close(server_sock);

			int tempSec = getSec();
			int OESec = tempSec % 2;
			char buf[BUF_SIZE];
			memset(buf, 0, sizeof(buf));

			sprintf(buf, "%c%d_0123456789\n", header[childcnt], childcnt);

			while(1)
			{
				char strTemp[256] = { 0, };

				int y = getYear();
				int mon = getMonth();
				int d = getDay();
				int h = getHour();
				int min = getMin();
				int s = getSec();

				if (s % 2 == OESec && tempSec != s) {

					//////////////////////////////
					//add checksum byte...
					char setData[1024] = {0,};

					int index = 1;
					unsigned char checksum = 0;

					while (index < strlen(buf) - 1) {
						if (c_state == IDLE) {
							c_state =
									(buf[0] == '$' || buf[0] == '#') ?
											PAYLOAD : IDLE;
						} else if (c_state == PAYLOAD) {
							printf(
									"add buf[%d] = %c, checksum = (%%c)%c, (%%x)%x\n",
									index, buf[index], checksum, checksum);
							checksum ^= (buf[index++] & 0xFF);
						}
					}

					printf("checksum = %x\n", checksum);
					////////////////////////////////////////////////////////////////

					sprintf(setData, "%s%c", buf, checksum);

					sprintf(strTemp,
							"%04d-%02d-%02d %02dhour %02dmin %02dsec\n", y, mon,
							d, h, min, s);
					strcat(strTemp, setData);
					tempSec = s;

					if(write(client_sock, setData, strlen(setData)) < 0)
						break;
					printf("send to client : %s\n", strTemp);

					memset(strTemp, 0, sizeof(strTemp));
				}
			}

			close(client_sock);
			puts("LOG ( Client disconnected... )");
			return 0;
		}
		else
			close(client_sock);
	}
	close(server_sock);
	return 0;
}
Exemple #8
0
void setDate()
{
	curDay = getDay();
	curMonth = getMonth();
	curYear = getYear();
}
Exemple #9
0
 void RTCTimeProvider::setSeconds(byte secs) {
   rtc.adjust(DateTime(getYear(),getMonth(),getDay(), getHours(),getMinutes(),secs));
 }
Exemple #10
0
void drawCalendar()
{	
	uint16 x = 0;
	uint16 y = 0;
	uint16 z = 0;
	
	setFont(font_arial_11);
	setColor(genericTextColor);
	
	{
		char str[128];
		sprintf(str, "%s - %d",l_months[curMonth-1],curYear);
		bg_dispString(23,20-2,str);
	}
	
	setFont(font_gautami_10);
	setColor(genericTextColor);
	
	for(x=0;x<7;x++)
	{		
		bg_dispString(23+(x*31), 20+20, l_days[x+7]);
		bg_drawRect(23+(x*31), 28+20, 20+(x*31)+27, 28+20, calendarDayUnderlineColor);
	}
	
	z = 1;	
	x = dayOfWeek(1,curMonth,curYear);
	y = 0;
	
	if(curDay > daysInMonth(curMonth-1,curYear))
		curDay = daysInMonth(curMonth-1,curYear);
	
	while(z <= daysInMonth(curMonth-1,curYear))
	{	
		if(dayOfWeek(z,curMonth,curYear) == 0 || dayOfWeek(z,curMonth,curYear) == 6)
	    	setColor(calendarWeekendColor);
		else
			setColor(calendarNormalColor);		
		
		if(z == curDay)
		{
			// we gotta draw a rect behind today
			bg_drawRect(23+(x*31), 57+(15*y), 44+(x*31), 70+(15*y), genericHighlightColor);			
		}
		
		if(dayViews[z] == 1)
			bg_drawRect(26+(x*31), 68+(15*y), 41+(x*31), 68+(15*y), calendarHasDayPlannerColor);			
		
		if(reminders[z] == 1)
			setColor(calencarHasReminderColor);		
		
		if(curMonth == getMonth() && curYear == getYear() and z == getDay())
			setColor(calendarCurrentDateColor);
		
		char str[512];	
		
		sprintf(str,"%02d", z);
		bg_dispString(29+(x*31), 40 + 20 + (15*y), str);		
		
		x++;
		if(x > 6)
		{
			x = 0;
			y++;
		}
		
		z++;
	}
}
Exemple #11
0
void drawTimeline(void){
	uint8_t iter_higher_than_end = 0;
	uint8_t menuPage = 0;
	uint8_t totalPages = 0;
	char tempString[3];
	char timeBuf[18];
	char buf[18];

	printTime();
	printStringOnLine(1,"    Timeline      ", 1,NONE);

	uint8_t index = 0;
	
	start = getMemMapStartIndex();
	end = getMemMapEndIndex();
	iter = start;
	
	if(iter > end)
		iter_higher_than_end = 1;
		
	uint8_t currentMenuLength = getUnencrpytedRecordCount();
	
	for (uint8_t i = 0; i < cellsPerFrame; i++){
		char hourString[3] = {"0"};
		char minuteString[3] = {"0"};
		char yearString[3] = {"0"};
		char monthString[3] = {"0"};
		char dateString[3] = {"0"};
		
		if (currentMenuLength == 0){
			printTimeLineIsEmpty();
			break;
		}
		
		totalPages = ((currentMenuLength-1)/cellsPerFrame);
		menuPage = (selectionInMenu/cellsPerFrame);	
		index = ((menuPage)*cellsPerFrame)+i;
		
		iter = (index + start) % maxRecNum;

		selectedDate = getDate(getMemMapElement(iter));
		itoa(selectedDate, tempString, 10);
		if (selectedDate < 10)
			strcat(dateString, tempString);
		else{
			strcpy(dateString, tempString);
		}
		
		selectedMonth = getMonth(getMemMapElement(iter));
		itoa(selectedMonth, tempString, 10);
		if (selectedMonth < 10)
			strcat(monthString, tempString);
		else{
			strcpy(monthString, tempString);
		}

		selectedYear = getYear(getMemMapElement(iter));
		itoa(selectedYear, tempString, 10);
		if (selectedYear < 10)
			strcat(yearString, tempString);
		else{
			strcpy(yearString, tempString);
		}

		selectedHour = getHour(getMemMapElement(iter));
		itoa(selectedHour, tempString, 10);
		if (selectedHour < 10)
			strcat(hourString, tempString);
		else{
			strcpy(hourString, tempString);
		}
	
		selectedMinute = getMinute(getMemMapElement(iter));
		itoa(selectedMinute, tempString, 10);
		if (selectedMinute < 10)
			strcat(minuteString, tempString);
		else{
			strcpy(minuteString, tempString);
		}
		
		//USART_Sendbyte(totalPages);
		//USART_Sendbyte(menuPage);
		//USART_Sendbyte(index);
		//USART_Sendbyte(iter);
		//USART_Sendbyte(start);
		//USART_Sendbyte(end);
		
		//USART_Sendbyte(iter_higher_than_end);
		if(iter <= end || (i == 0 && currentMenuLength >= maxRecNum) || (iter_higher_than_end == 1)){
			if (iter <= end)
				iter_higher_than_end = 0;
			snprintf(timeBuf, sizeof(timeBuf), "%s%s%s%s%s%s%s%s%s%s", dateString, "/", monthString, "/", yearString, " - ", hourString, ":", minuteString, "  "); 
			snprintf(buf, sizeof(buf), "%s%s%s%s", activityArray[getActivity(getMemMapElement(iter))], "-", moodArray[getMood(getMemMapElement(iter))], "                  "); 	
			timeBuf[17] = ' ';
			buf[17] = ' ';
	
			drawMenuBands(menuPage,totalPages,TOPBAND);			
				
			//Draw Menu Contents
			if (i == selectionInFrame){
				printStringOnLine(i*2+yOffset,timeBuf, 1,NOBOXMENU);
				printTimelineStringOnLine(i*2+yOffset+1,buf, 1,faceArray[getMood(getMemMapElement(iter))]);
			}			
			else if (index < currentMenuLength){
				printStringOnLine(i*2+yOffset,timeBuf, 0,NOBOXMENU);
				printTimelineStringOnLine(i*2+yOffset+1,buf, 0,faceArray[getMood(getMemMapElement(iter))]);
			}
		}	
		else{
			printStringOnLine(i*2+yOffset,"                  ", 0,NOBOXMENU);
			printStringOnLine(i*2+yOffset+1,"                  ", 0,NOBOXMENU);
		}				
		drawMenuBands(menuPage,totalPages,BOTTOMBAND);			
	}		
	
}
Exemple #12
0
void drawChooseStartTime(void){
	uint8_t modMinute = 0;
	uint8_t divMinute = 0;
	uint8_t numberOfRecords = getUnencrpytedRecordCount();
	iter = 0;
	printTime();
	printStringOnLine(1,"     Timeline     ", 1,NOBOXMENU);	
	printStringOnLine(2,"                  ", 0,NOBOXMENU);		
	
	iter = getMemMapStartIndex();
	iter = (iter + selectedRecord) % maxRecNum;
	
	if (firstPass == 0){
		timeSelection = 0;
		
		if(numberOfRecords != 0){
			//find closest time to selected time in time slot
			selectedYear = getYear(getMemMapElement(iter));
			selectedMonth = getMonth(getMemMapElement(iter));
			selectedDay = getTimeDate(getMemMapElement(iter));
			selectedDOW = getTimeDay(getMemMapElement(iter));
			selectedHour = getHour(getMemMapElement(iter));
			selectedMinute = getMinute(getMemMapElement(iter));
		}			
		
		modMinute = selectedMinute % 15;
		if(modMinute != 0){
			divMinute = selectedMinute/15;
			if(modMinute <=8)
				selectedMinute = divMinute*15;
			else
				selectedMinute = divMinute*15 + 15; 
			if(selectedMinute >= 60)
				selectedMinute = 0;
		}
		firstPass = 1;
	}
	if (timeSelection == HOUR){
		if (manipulateTime == INCREMENT){
			if ((selectedHour + 1) >= 24)
				selectedHour = 0;
			else
				selectedHour += 1;
			manipulateTime = NEUTRAL;
		}
		if (manipulateTime == DECREMENT){
			if ((selectedHour - 1) < 0)
				selectedHour = 23;
			else
				selectedHour -= 1;
			manipulateTime = NEUTRAL;		
		}
	}		
	else if (timeSelection == MINUTE){
		if (manipulateTime == INCREMENT){
			if ((selectedMinute + 15) >= 60)
				selectedMinute = 0;
			else
				selectedMinute += 15;
			manipulateTime = NEUTRAL;
		}
		else if (manipulateTime == DECREMENT){
			if ((selectedMinute - 15) < 0)
				selectedMinute = 45;
			else
				selectedMinute -= 15;
			manipulateTime = NEUTRAL;		
		}
	}	
	
	printTimeSelectionOnLine(3,selectedHour,selectedMinute,0,timeSelection);	
	
	printStringOnLine(4,"                  ", 0,NOBOXMENU);	
	printStringOnLine(5,"                  ", 1,NOBOXMENU);	
	printStringOnLine(6,"Choose Start Time ", 1,NOBOXMENU);	
	printStringOnLine(7,"                  ", 1,NOBOXMENU);	
	
}
Exemple #13
0
void printDate() {
	printf("%d/%d/%d\n", getDay(), getMonth(), getYear());
}
Exemple #14
0
	void								setAge(int age)							{ _birthYear = getYear() - age; }
Exemple #15
0
bool Date::operator==(const Date &right)
{
	return (getYear() == right.getYear() && 
		getMonth() == right.getMonth() && 
		getDay() == right.getDay());
}
Exemple #16
0
void Track::writeData( QByteArray& data) const {
    QBuffer buffer( data);
    buffer.open(IO_WriteOnly);
    QDataStream stream( &buffer);
    stream.setByteOrder( QDataStream::LittleEndian);

    /** Write the track header **/
    stream << (Q_UINT32) 0x7469686D;        // 0x00 mhit
    stream << (Q_UINT32) 0xf4;              // 0x04 headerlen
    stream << (Q_UINT32) 0x0;               // 0x08 length - set later
    stream << (Q_UINT32) 0x0;               // 0x0C number of mhods
    stream << (Q_UINT32) getID();           // 0x10
    stream << (Q_UINT32) 1;                 // 0x14
    //stream << (Q_UINT32) 0;                 // 0x18
    stream << (Q_UINT32) 0x4d503320;        // ipod shiffle wants a "MP3 " here
    stream << vbr;                          // 0x1C
    stream << type;                         // 0x1D
    stream << compilation;                  // 0x1E
    stream << rating;                       // 0x1F
    stream << (Q_UINT32) getLastModified()+ MAC_EPOCH_DELTA; // 0x20
    stream << (Q_UINT32) getFileSize();     // 0x24
    stream << (Q_UINT32) getTrackLength();  // 0x28
    stream << (Q_UINT32) getTrackNumber();  // 0x2C
    stream << (Q_UINT32) getTrackCount();   // 0x30
    stream << (Q_UINT32) getYear();         // 0x34
    stream << (Q_UINT32) getBitrate();      // 0x38
    stream << (Q_UINT32) getSamplerate();   // 0x3C
    stream << (Q_UINT32) getVolumeAdjust(); // 0x40
    stream << (Q_UINT32) 0;                 // 0x44 empty space
    //stream << (Q_UINT32) getTrackLength();  // 0x48 empty space
    stream << (Q_UINT32) 0;  // 0x48 empty space
    stream << (Q_UINT32) 0;                 // 0x4C empty space
    stream << (Q_UINT32) getPlayCount();    // 0x50
    stream << (Q_UINT32) getPlayCount();    // 0x54
    stream << (Q_UINT32) getLastPlayed();   // 0x58
    stream << (Q_UINT32) getCdNumber();     // 0x5C
    stream << (Q_UINT32) getCdCount();      // 0x60
    stream << (Q_UINT32) 0;                 // 0x64 empty space //userid from apple store
    stream << (Q_UINT32) date_added;        // 0x68
    stream << (Q_UINT32) 0;                 // boockmarktime
    stream << (Q_UINT64) dbid;              // unique bit (64 bit)
    stream << (Q_UINT8) 0;                 // checked in iTZnes
    stream << (Q_UINT8) 0;                 // application rating
    stream << (Q_UINT16) 0;                 // BPM
    stream << (Q_UINT16) 0;                 // artworkcount
    stream << (Q_UINT16) 0xffff;            // unkown
    stream << (Q_UINT32) 0;                 // artwork size
    stream << (Q_UINT32) 0;                 // unkown
    stream << (float) -getSamplerate();      // samplerate as floating point "-"?!?
    stream << (Q_UINT32) 0;                 // date/time added
    stream << (Q_UINT32) file_format_code;  // unkown, but 0x0000000c for MP3 ?
    stream << (Q_UINT32) 0;                 // unkown
    stream << (Q_UINT32) 0;                 // unkown
    stream << (Q_UINT32) 0;                 // unkown
    stream << (Q_UINT32) 0;                 // unkown
    stream << (Q_UINT32) 0x02;              // unknown
    stream << (Q_UINT64) dbid; // same unique id as above
    for( int i= 0; i< 17; i++)
        stream << (Q_UINT32) 0;
    
    /** Write Track contents **/
    Q_UINT32 num_mhods = 0;
    for( PropertyMap::const_iterator element= properties.begin(); element!= properties.end(); ++element) {
        if( (*element).isEmpty())
            continue;

        const char *data= (const char *)(*element).ucs2();
        if( data == NULL)
            continue;

        int datalen= 2* (*element).length();

        stream << (Q_UINT32) 0x646F686D;    // mhod
        stream << (Q_UINT32) 0x18;    // headerlen
        stream << (Q_UINT32) 40+ datalen;
        stream << (Q_UINT32) element.key();
        stream << (Q_UINT32) 0;
        stream << (Q_UINT32) 0;
        stream << (Q_UINT32) 1;    // dummy - would refer to the trackID if used in playlist
        stream << (Q_UINT32) datalen;
        stream << (Q_UINT32) 0;
        stream << (Q_UINT32) 0;
        stream.writeRawBytes( data, datalen);
        num_mhods++;
    }
    buffer.at( 8);
    stream << (Q_UINT32)data.size();	// set content length
    stream << (Q_UINT32)num_mhods;	// set real mhod count
    buffer.close();
}
Exemple #17
0
int ossimLocalTm::getShortYear()const
{
   return (getYear()%100);
}
Exemple #18
0
Date Date::addYearsGet(long years)
{
	long g = getDays(getYear()+years,getMonth(),getDay());
	return getDateFromDays(g);
}
Exemple #19
0
void Date::displayDate() {
	std::cout << getMonth() << "/" << getDay() << "/" << getYear() << std::endl;
}
Exemple #20
0
void BrowseThread::populateModel() {
    m_path_mutex.lock();
    MDir thisPath = m_path;
    BrowseTableModel* thisModelObserver = m_model_observer;
    m_path_mutex.unlock();

    // Refresh the name filters in case we loaded new SoundSource plugins.
    QStringList nameFilters(SoundSourceProxy::getSupportedFileNamePatterns());

    QDirIterator fileIt(thisPath.dir().absolutePath(), nameFilters,
                        QDir::Files | QDir::NoDotAndDotDot);

    // remove all rows
    // This is a blocking operation
    // see signal/slot connection in BrowseTableModel
    emit(clearModel(thisModelObserver));

    QList< QList<QStandardItem*> > rows;

    int row = 0;
    // Iterate over the files
    while (fileIt.hasNext()) {
        // If a user quickly jumps through the folders
        // the current task becomes "dirty"
        m_path_mutex.lock();
        MDir newPath = m_path;
        m_path_mutex.unlock();

        if (thisPath.dir() != newPath.dir()) {
            qDebug() << "Abort populateModel()";
            return populateModel();
        }

        QString filepath = fileIt.next();
        auto pTrack = Track::newTemporary(filepath, thisPath.token());
        SoundSourceProxy(pTrack).updateTrackFromSource();

        QList<QStandardItem*> row_data;

        QStandardItem* item = new QStandardItem("0");
        item->setData("0", Qt::UserRole);
        row_data.insert(COLUMN_PREVIEW, item);

        item = new QStandardItem(pTrack->getFileName());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_FILENAME, item);

        item = new QStandardItem(pTrack->getArtist());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_ARTIST, item);

        item = new QStandardItem(pTrack->getTitle());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_TITLE, item);

        item = new QStandardItem(pTrack->getAlbum());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_ALBUM, item);

        item = new QStandardItem(pTrack->getAlbumArtist());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_ALBUMARTIST, item);

        item = new QStandardItem(pTrack->getTrackNumber());
        item->setToolTip(item->text());
        item->setData(item->text().toInt(), Qt::UserRole);
        row_data.insert(COLUMN_TRACK_NUMBER, item);

        const QString year(pTrack->getYear());
        item = new YearItem(year);
        item->setToolTip(year);
        // The year column is sorted according to the numeric calendar year
        item->setData(mixxx::TrackMetadata::parseCalendarYear(year), Qt::UserRole);
        row_data.insert(COLUMN_YEAR, item);

        item = new QStandardItem(pTrack->getGenre());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_GENRE, item);

        item = new QStandardItem(pTrack->getComposer());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_COMPOSER, item);

        item = new QStandardItem(pTrack->getGrouping());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_GROUPING, item);

        item = new QStandardItem(pTrack->getComment());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_COMMENT, item);

        QString duration = pTrack->getDurationText(mixxx::Duration::Precision::SECONDS);
        item = new QStandardItem(duration);
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_DURATION, item);

        item = new QStandardItem(pTrack->getBpmText());
        item->setToolTip(item->text());
        item->setData(pTrack->getBpm(), Qt::UserRole);
        row_data.insert(COLUMN_BPM, item);

        item = new QStandardItem(pTrack->getKeyText());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_KEY, item);

        item = new QStandardItem(pTrack->getType());
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_TYPE, item);

        item = new QStandardItem(pTrack->getBitrateText());
        item->setToolTip(item->text());
        item->setData(pTrack->getBitrate(), Qt::UserRole);
        row_data.insert(COLUMN_BITRATE, item);

        QString location = pTrack->getLocation();
        QString nativeLocation = QDir::toNativeSeparators(location);
        item = new QStandardItem(nativeLocation);
        item->setToolTip(nativeLocation);
        item->setData(location, Qt::UserRole);
        row_data.insert(COLUMN_NATIVELOCATION, item);

        QDateTime modifiedTime = pTrack->getFileModifiedTime().toLocalTime();
        item = new QStandardItem(modifiedTime.toString(Qt::DefaultLocaleShortDate));
        item->setToolTip(item->text());
        item->setData(modifiedTime, Qt::UserRole);
        row_data.insert(COLUMN_FILE_MODIFIED_TIME, item);

        QDateTime creationTime = pTrack->getFileCreationTime().toLocalTime();
        item = new QStandardItem(creationTime.toString(Qt::DefaultLocaleShortDate));
        item->setToolTip(item->text());
        item->setData(creationTime, Qt::UserRole);
        row_data.insert(COLUMN_FILE_CREATION_TIME, item);

        const mixxx::ReplayGain replayGain(pTrack->getReplayGain());
        item = new QStandardItem(
                mixxx::ReplayGain::ratioToString(replayGain.getRatio()));
        item->setToolTip(item->text());
        item->setData(item->text(), Qt::UserRole);
        row_data.insert(COLUMN_REPLAYGAIN, item);

        rows.append(row_data);
        ++row;
        // If 10 tracks have been analyzed, send it to GUI
        // Will limit GUI freezing
        if (row % 10 == 0) {
            // this is a blocking operation
            emit(rowsAppended(rows, thisModelObserver));
            qDebug() << "Append " << rows.count() << " from " << filepath;
            rows.clear();
        }
        // Sleep additionally for 10ms which prevents us from GUI freezes
        msleep(20);
    }
    emit(rowsAppended(rows, thisModelObserver));
    qDebug() << "Append last " << rows.count();
}
std::string terrama2::core::DataStoragerTiff::replaceMask(const std::string& mask,
    std::shared_ptr<te::dt::DateTime> timestamp,
    terrama2::core::DataSetPtr dataSet) const
{
  if(!timestamp.get())
    return mask;

  long year = 0;
  long month = 0;
  long day = 0;
  long hour = 0;
  long minutes = 0;
  long seconds = 0;

  if(timestamp->getDateTimeType() == te::dt::TIME_INSTANT)
  {
    auto dateTime = std::dynamic_pointer_cast<te::dt::TimeInstant>(timestamp);
    //invalid date type
    if(dateTime->getTimeInstant().is_not_a_date_time())
      return mask;


    auto date = dateTime->getDate();
    year = date.getYear();
    month = date.getMonth().as_number();
    day = date.getDay().as_number();

    auto time = dateTime->getTime();
    hour = time.getHours();
    minutes = time.getMinutes();
    seconds = time.getSeconds();
  }
  else if(timestamp->getDateTimeType() == te::dt::TIME_INSTANT_TZ)
  {
    auto dateTime = std::dynamic_pointer_cast<te::dt::TimeInstantTZ>(timestamp);
    auto boostLocalTime = dateTime->getTimeInstantTZ();
    //invalid date type
    if(boostLocalTime.is_not_a_date_time())
      return mask;

    std::string timezone;
    try
    {
      //get dataset timezone
      timezone = getTimezone(dataSet);
    }
    catch(const terrama2::core::UndefinedTagException&)
    {
      //if no timezone is set use UTC
      timezone = "UTC+00";
    }

    boost::local_time::time_zone_ptr zone(new boost::local_time::posix_time_zone(timezone));
    auto localTime = boostLocalTime.local_time_in(zone);
    auto date = localTime.date();
    year = date.year();
    month = date.month().as_number();
    day = date.day();

    auto time = localTime.time_of_day();
    hour = time.hours();
    minutes = time.minutes();
    seconds = time.seconds();
  }
  else
  {
    //This method expects a valid Date/Time, other formats are not valid.
    QString errMsg = QObject::tr("Unknown date format.");
    TERRAMA2_LOG_ERROR() << errMsg;
    throw terrama2::core::DataAccessorException() << ErrorDescription(errMsg);
  }

  //replace wildcards in mask
  std::string fileName = mask;
  size_t pos = fileName.find("yyyy");
  if(pos != std::string::npos)
    fileName.replace(pos, 4, zeroPadNumber(year, 4));

  pos = fileName.find("yy");
  if(pos != std::string::npos)
    fileName.replace(pos, 2, zeroPadNumber(year, 2));

  pos = fileName.find("MM");
  if(pos != std::string::npos)
    fileName.replace(pos, 2, zeroPadNumber(month, 2));

  pos = fileName.find("dd");
  if(pos != std::string::npos)
    fileName.replace(pos, 2, zeroPadNumber(day, 2));

  pos = fileName.find("hh");
  if(pos != std::string::npos)
    fileName.replace(pos, 2, zeroPadNumber(hour, 2));

  pos = fileName.find("mm");
  if(pos != std::string::npos)
    fileName.replace(pos, 2, zeroPadNumber(minutes, 2));

  pos = fileName.find("ss");
  if(pos != std::string::npos)
    fileName.replace(pos, 2, zeroPadNumber(seconds, 2));

  //if no extension in the mask, add extension
  pos = fileName.find(".tif");
  if(pos != std::string::npos)
    fileName += ".tif";
  return fileName;
}
Exemple #22
0
int main(void)
{
	int ID = 0; // ID associated with the person. starts at invalid value
	char email[100]; // email address of user
	char *roomSize; // Size of the desired room
	int month = 0; // month from 1-12. starts at invalid value
	int day = 0; // day from 1-31. starts at invalid value.
	int year = 0; // month from 2014 up. starts at invalid value.
	int useTime[2] = {-1, -1}; // start and end time in 24 hour format. starts at invalid value.
	int loggedIn = 0; // Whether the user has entered their ID, username
	bool sub = false; // wilingness to substitute
	char output[MAX_STRING*10]; // final output of the Request

	// Enter details to proceed
	printf("Please log in to proceed. Enter your 6 digit ID: ");
	while (loggedIn == 0) {
		ID = getID();
		buf[0] = '\0'; // reset buffer
		getEmail(email);
		buf[0] = '\0'; // reset buffer
		loggedIn = logIn();
		buf[0] = '\0'; // reset buffer
	} 
	
	// Get the year the user would like to book for.
	printf("Would you like to book for this calendar year? (Y/N): ");
	while (year == 0) {
	    year = getYear();
	    buf[0] = '\0'; // reset buffer
	}

	// Get the month the user would like to book for.
	printf("Would you like to book for this month in %i? (Y/N): ", year);
	while ((month < 1) || (month > 12)) {
	    month = getMonth(year);
	    buf[0] = '\0'; // reset buffer
	}

	// Get the day the user would like to book for. Dynamicly change valid days in getDay
	printf("What day would you like to book for? ");
	while (day == 0) {
	    day = getDay(month, year);
	    buf[0] = '\0'; // reset buffer
	}

	// Get the time the user will use the room.
	printf("What time would you like to start using the room? (24 hour): ");
	while (useTime[0] == -1) {
		getTime(useTime, day, month, year);
		buf[0] = '\0'; // reset buffer
	}

	// Get the room size the user would like to book
	printf("What is the size of the room you are looking to reserve? (\"small\", \"standard\", or \"very large\"): ");
    roomSize = getRoomSize();
    strcat (roomSize, "\0"); // add end of string character
    buf[0] = '\0'; // reset buffer

    printf("Would you be willing to take a larger room if there is no %s room available? (Y/N): ", roomSize);
    buf[0] = '\0'; // reset buffer
	fgets(buf, MAX_STRING, stdin);
	strcat (buf, "\0"); // add end of string character

	// willingness to substitute
	if ((buf[0] == 'y') || (buf[0] == 'Y')) {
		sub = true;
	}

	else {
		while ((buf[0] != 'n') || (buf[0] == 'N')) {
			printf("\nIncorrect input. Please answer with \'Y\' or \'N\': ");
			buf[0] = '\0'; // reset buffer
			fgets(buf, MAX_STRING, stdin);
			strcat (buf, "\0"); // add end of string character
		}
	}

	printf("\n\nBooking %i (%s) for a %s room on %i/%i/%i from %i to %i...", ID, email, roomSize, month, day, year, useTime[0], useTime[1]);
	sprintf(output, "%i,%i,%i,%i,%i,%s,%d,%i,%i,%s", month, day, year, useTime[0], useTime[1], roomSize, sub, ID, loggedIn, email);
	
	FILE *f = fopen("file.txt", "w");
	if (f == NULL)
	{
	  printf("Error opening file!\n");
	  exit(1);
	}
	
	// write to file where handler can process it
	fprintf(f, "%s\n", output);

	printf("Press enter to continue...\n");
	getchar();

	return 0;
}
/*
 * In principle, plot over the last "time_plot" hours (0 to N).
 * If time_plot < 0, do 3 plots: all data, 12 hours and 24 hours. For CPU efficiency in the Raspberry Pi
 */
void PlotFibreMonSwitch(int do_time_plot = 0, int width = 1400, int height = 900) { // Plot over the last "time_plot" hours
  int time_plot_array[3] = {0, 24, 12};
  float fontsize = 0.045;
  const char filename[200] = "MergedLog.txt";
  const char file_fibremap[200] = "fibremap.txt";
  int nfibres = FIBRES;
  float **fibres_values_temp;  // Ptx, Prx, Attenuation, Attenuator, Temperatures
  char **fibres_names_temp;
  int time_plot = 0;    // Avoid breaking things
  if (do_time_plot > 0) {
    time_plot = do_time_plot;
  }
  
  char title[FIBRES][20];
  
  TTree *data;
  TTree *fibremap;
  TTree *fibres_values = new TTree("Fibres values", "Fibres values");

  fibres_values_temp = (float**)calloc(nfibres, sizeof(float*));
  fibres_names_temp = (char**)calloc(nfibres, sizeof(char*));
  for (int j = 0; j < nfibres; j++) {
    fibres_values_temp[j] = (float*)calloc(5, sizeof(float));
    fibres_names_temp[j] = (char*)calloc(100, sizeof(char));
  }

  // Data from the fibremap file
  char fromSw[100], toSw[100], fibrename[100], fibrename_val[100];
  int fibre, fromPort, toPort, fibre_idx;
  float attenuator;
  
  fibremap = new TTree("Fibre mapping", "Fibre mapping");
  fibremap->ReadFile(file_fibremap, "fibre/I:fromSw/C:fromPort/I:toSw/C:toPort/I:fibrename/C:attenuator/F");
  fibremap->SetBranchAddress("fibre", &fibre);
  fibremap->SetBranchAddress("fromSw", fromSw);
  fibremap->SetBranchAddress("fromPort", &fromPort);
  fibremap->SetBranchAddress("toSw", toSw);
  fibremap->SetBranchAddress("toPort", &toPort);
  fibremap->SetBranchAddress("fibrename", fibrename);
  fibremap->SetBranchAddress("attenuator", &attenuator);
  
  nfibres = fibremap->GetEntries();
  

  // Data for the destination TTree containing each fibre attenuation (and the rest)
  float x, att, Ptx, Prx ,Ptx_fibreval, Prx_fibreval, temperature_val;
  char titletemp[50];
  TBranch *branch_fibre = fibres_values->Branch("fibre_idx", &fibre_idx, "fibre_idx/I");
  TBranch *branch_fibrename = fibres_values->Branch("fibrename_val", fibrename_val, "fibrename_val/C");
  TBranch *branch_time = fibres_values->Branch("x", &x, "x/F");
  TBranch *branch_att = fibres_values->Branch("Ptx_fibreval", &Ptx_fibreval, "Ptx_fibreval/F");
  TBranch *branch_temperature = fibres_values->Branch("temperature_val", &temperature_val, "temperature_val/F");
  TBranch *branch_Ptx = fibres_values->Branch("Prx_fibreval", &Prx_fibreval, "Prx_fibreval/F");
  TBranch *branch_Prx = fibres_values->Branch("Attenuation", &att, "Att/F");
  
  cout << "Got " << nfibres << " fibres mapped" << endl;
  
  // Load logging data
  data = new TTree("Fibre data", "Fibre data");
  char date[200], month[20], day[20], time[20], hostname[100], t2[20];
  float temp, voltage, current, Ptx, Prx;
  data->ReadFile(filename, "month/C:day:time:hostname:date:t2:temp/F:voltage:current:Ptx:Prx");
  data->SetBranchAddress("date", date);
  data->SetBranchAddress("month", month);
  data->SetBranchAddress("day", day);
  data->SetBranchAddress("time", time);
  data->SetBranchAddress("hostname", hostname);
  data->SetBranchAddress("t2", t2);
  data->SetBranchAddress("temp", &temp);
  data->SetBranchAddress("voltage", &voltage);
  data->SetBranchAddress("current", &current);
  data->SetBranchAddress("Ptx", &Ptx);
  data->SetBranchAddress("Prx", &Prx);
  
  int datalen = data->GetEntries();
  int time_entries = datalen/nfibres;
  
  // Get timestamps for beginning and end of log
  data->GetEntry(0);
  int time0 = getTimestamp(date, time);
  data->GetEntry(datalen-1);
  int timeN = getTimestamp(date, time);
  
  time_entries = (timeN - time0)/60/INTERVAL + 1;
  
  // Process data and do mapping
  int pos = 0;
  int line_time = 0;
  int thisfibre = 0;
  for (int pos = 0; pos < datalen; pos++) {
    data->GetEntry(pos);
    if (line_time != (getTimestamp(date, time) - time0)/60/INTERVAL) {
      thisfibre = 0;
      for (int k = 0; k < nfibres; k++) {
        fibres_values_temp[k][2] = fibres_values_temp[k][0] - fibres_values_temp[k][1] - fibres_values_temp[k][3];
        
        x = (float)line_time*INTERVAL*60; // *INTERVAL*60;
        
        strcpy(fibrename_val, fibres_names_temp[k]);
        Ptx_fibreval = fibres_values_temp[k][0];
        Prx_fibreval = fibres_values_temp[k][1];
        temperature_val = fibres_values_temp[k][4];
        att = fibres_values_temp[k][2];
        fibre_idx = k;
        // Save TTree element
        fibres_values->Fill();
      }
      line_time = (getTimestamp(date, time) - time0)/60/INTERVAL;
    }
    char hostname_switch[100];
    int port_switch = -1;
    char *tok;
    
    tok = strtok(hostname, ":");
    if (tok != NULL) {
      strcpy(hostname_switch, tok);
      tok = strtok(NULL, ":");
      if (tok != NULL) {
        port_switch = atoi(tok);
      }
    }
    
    // Find hostname and port in the fibre maps 
    int idx_tx = -1;
    int idx_rx = -1;
    for (int k = 0; k < nfibres; k++) {
      fibremap->GetEntry(k);
      if ((strstr(hostname, fromSw) != NULL) && ((port_switch == -1) || (port_switch == fromPort))) {
        idx_tx = k;
        strcpy(fibres_names_temp[k], fibrename);
        fibres_values_temp[idx_tx][3] = attenuator;
      }
      if ((strstr(hostname, toSw) != NULL) && ((port_switch == -1) || (port_switch == toPort))) {
        idx_rx = k;
      }
    }
    fibres_values_temp[idx_tx][0] = Ptx;
    fibres_values_temp[idx_tx][4] = temp;
    fibres_values_temp[idx_rx][1] = Prx;
    
    thisfibre++;
  }

  // Plot
  TGraph **Attenuation;
  TGraph **TxPower, **RxPower, **Temperature;
  TLegend *att_legend = new TLegend(0.85, 0.85, 0.99, 0.99);
  TLegend *temperature_legend = new TLegend(0.85, 0.85, 0.99, 0.99);
  TLegend *txpower_legend = new TLegend(0.85, 0.85, 0.99, 0.99);
  TLegend *rxpower_legend = new TLegend(0.85, 0.85, 0.99, 0.99);
  float **y_val, **x_val, **txpower_val, **rxpower_val, max_att, min_att, max_txpower, min_txpower, max_rxpower, min_rxpower, **temp_val, max_temp, min_temp;
  char **fibrenames;
  
  min_att = 1e9;
  max_att = -1;
  min_rxpower = 1e9;
  max_rxpower = -1e9;
  min_txpower = 1e9;
  max_txpower = -1e9;
  min_temp = 1e9;
  max_temp = -1e9;

  y_val = (float**)calloc(nfibres, sizeof(float*));
  x_val = (float**)calloc(nfibres, sizeof(float*));
  temp_val = (float**)calloc(nfibres, sizeof(float*));
  txpower_val = (float**)calloc(nfibres, sizeof(float*));
  rxpower_val = (float**)calloc(nfibres, sizeof(float*));
  fibrenames = (char**)calloc(nfibres, sizeof(char*));
  for (int i = 0; i < nfibres; i++) {
    y_val[i] = (float*)calloc(time_entries, sizeof(float));
    x_val[i] = (float*)calloc(time_entries, sizeof(float));
    for (int j = 0; j < time_entries; j++) {
      x_val[i][j] = -1;
    }
    temp_val[i] = (float*)calloc(time_entries, sizeof(float));
    txpower_val[i] = (float*)calloc(time_entries, sizeof(float));
    rxpower_val[i] = (float*)calloc(time_entries, sizeof(float));
    fibrenames[i] = (char*)calloc(time_entries, sizeof(char));
  }

  Attenuation = (TGraph**)calloc(nfibres, sizeof(TGraph*));
  Temperature = (TGraph**)calloc(nfibres, sizeof(TGraph*));
  TxPower = (TGraph**)calloc(nfibres, sizeof(TGraph*));
  RxPower = (TGraph**)calloc(nfibres, sizeof(TGraph*));
  int nentries = fibres_values->GetEntries();
  // Get data from TTree into the arrays
  for (int k = 0; k < nentries; k++) {
    fibres_values->GetEntry(k);
    x_val[(int)fibre_idx][(int)x/INTERVAL/60] = x + INTERVAL*60;
    y_val[(int)fibre_idx][(int)x/INTERVAL/60] = att;
    temp_val[(int)fibre_idx][(int)x/INTERVAL/60] = temperature_val;
    txpower_val[(int)fibre_idx][(int)x/INTERVAL/60] = Ptx_fibreval;
    rxpower_val[(int)fibre_idx][(int)x/INTERVAL/60] = Prx_fibreval;
    strcpy(fibrenames[fibre_idx], fibrename_val);
  }
  /* 
   * Create all TGraphs and TLegends
   */
  for (int i = 0; i < nfibres; i++) {
    // Fix null values
    for (int j = 0; j < time_entries; j++) {
      if (x_val[i][j] < 0) {
        x_val[i][j] = x_val[i][j - 1] + INTERVAL*60;
        y_val[i][j] = y_val[i][j - 1];
        temp_val[i][j] = temp_val[i][j - 1];
        txpower_val[i][j] = txpower_val[i][j - 1];
        rxpower_val[i][j] = rxpower_val[i][j - 1];
      }
      // If using time_plot, zoom in only in the interesting interval
      if ((time_plot == 0) || (j + time_plot*60/INTERVAL > time_entries)) {
        if (max_att < y_val[i][j])
          max_att = y_val[i][j];
        if (min_att > y_val[i][j])
          min_att = y_val[i][j];
        if (max_txpower < txpower_val[i][j])
          max_txpower = txpower_val[i][j];
        if (min_txpower > txpower_val[i][j])
          min_txpower = txpower_val[i][j];
        if (max_rxpower < rxpower_val[i][j])
          max_rxpower = rxpower_val[i][j];
        if (min_rxpower > rxpower_val[i][j])
          min_rxpower = rxpower_val[i][j];
        if (max_temp < temp_val[i][j])
          max_temp = temp_val[i][j];
        if (min_temp > temp_val[i][j])
          min_temp = temp_val[i][j];
      }
    }
    Attenuation[i] = new TGraph(time_entries, x_val[i], y_val[i]);
    Temperature[i] = new TGraph(time_entries, x_val[i], temp_val[i]);
    TxPower[i] = new TGraph(time_entries, x_val[i], txpower_val[i]);
    RxPower[i] = new TGraph(time_entries, x_val[i], rxpower_val[i]);
    att_legend->AddEntry(Attenuation[i], fibrenames[i], "LP");
    temperature_legend->AddEntry(Attenuation[i], fibrenames[i], "LP");
    txpower_legend->AddEntry(Attenuation[i], fibrenames[i], "LP");
    rxpower_legend->AddEntry(Attenuation[i], fibrenames[i], "LP");
  }

  // X axis reference for zooming in the last N hours intervals
  int rangeinit = (time_entries*INTERVAL - time_plot*60)*60;
  int rangeend = INTERVAL*60*(time_entries + 5*time_plot/12);   // Variable spacing depending on the number of hours, to make room for the legend

  // Time reference for the plots X axis
  data->GetEntry(0);
  char date1[20], date2[20];
  char time1[20], time2[20];
  sprintf(date1, date);
  sprintf(time1, time);
  data->GetEntry(datalen - 1);
  sprintf(date2, date);
  sprintf(time2, time);
  TDatime T0(getYear(date1), getMonth(date1), getDay(date1), getHour(time1), getMinute(time1) - INTERVAL, 00);
  int X0 = T0.Convert();
  gStyle->SetTimeOffset(X0);
  TDatime T1(getYear(date1), getMonth(date1), getDay(date1), getHour(time1), getMinute(time1), 00);
  int X1 = T1.Convert()-X0;
  TDatime T2(getYear(date2), getMonth(date2), getDay(date2), getHour(time2), getMinute(time2), 00);
  int X2 = T2.Convert()-X0 + INTERVAL*60;       // Move the lines to the left to leave some space for the legend
  
  /*
   * Attenuation plot
   */
  TCanvas *att_can = new TCanvas("C_att", "Attenuation", width, height);

  for (int i = 0; i < nfibres; i++) {
    Attenuation[i]->Draw(i==0?"AL":"L,same");
    Attenuation[i]->SetLineColor(i + 1);
    Attenuation[i]->SetLineWidth(2);
  }
  Attenuation[0]->GetYaxis()->SetRangeUser(floor(min_att*.95), ceil(max_att*1.05));
  if (time_plot > 0) {
    Attenuation[0]->GetXaxis()->SetRangeUser(rangeinit, rangeend);
  }
  Attenuation[0]->GetYaxis()->SetTitle("Attenuation [dB]");
  Attenuation[0]->GetXaxis()->SetTitle("");
  Attenuation[0]->SetTitle("Fibres attenuation");
  Attenuation[0]->GetXaxis()->SetTimeFormat("#splitline{%d/%m}{%H:%M}");
  Attenuation[0]->GetXaxis()->SetTimeDisplay(1);
  Attenuation[0]->GetXaxis()->SetLabelOffset(0.03);
  
  att_legend->Draw();
  
  // Output to file
  char filename[200];
  if (time_plot > 0) {
    sprintf(filename, "attenuation_%d_hours.png", time_plot);
  }
  else {
    sprintf(filename, "attenuation.png");
  }
  att_can->Print(filename);
  
  if (do_time_plot < 0) {
    for (int i = 1; i < 3; i++) {
      sprintf(filename, "attenuation_%d_hours.png", time_plot_array[i]);
      
      int rangeinit = (time_entries*INTERVAL - time_plot_array[i]*60)*60;
      int rangeend = INTERVAL*60*(time_entries + 5*time_plot_array[i]/12);
      Attenuation[0]->GetXaxis()->SetRangeUser(rangeinit, rangeend);
      float thisattmax = -1.;
      float thisattmin = 1000.;
      for (int j = 0; j < time_entries; j++) {
        for (int k = 0; k < nfibres; k++) {
          if (j + time_plot_array[i]*60/INTERVAL > time_entries) {
            if (y_val[k][j] > thisattmax)
              thisattmax = y_val[k][j];
            if (y_val[k][j] < thisattmin)
              thisattmin = y_val[k][j];
          }
        }
      }
      Attenuation[0]->GetYaxis()->SetRangeUser(floor(thisattmin*.95), ceil(thisattmax*1.05));
      
      att_can->Print(filename);
    }
  }
  
  /*
   * Transmitted power plot
   */
  TCanvas *txpower_can = new TCanvas("TxPower", "TxPower", width, height);
  
  for (int i = 0; i < nfibres; i++) {
    TxPower[i]->Draw(i==0?"AL":"L,same");
    TxPower[i]->SetLineColor(i + 1);
    TxPower[i]->SetLineWidth(2);
  }
  TxPower[0]->GetYaxis()->SetRangeUser((ceil(min_txpower) - 1), (floor(max_txpower) + 1));
  if (time_plot > 0) {
    TxPower[0]->GetXaxis()->SetRangeUser(rangeinit, rangeend); 
  }
  TxPower[0]->GetYaxis()->SetTitle("TxPower [dBm]");
  TxPower[0]->GetXaxis()->SetTitle("");
  TxPower[0]->SetTitle("SFP Transmitted Power");
  TxPower[0]->GetXaxis()->SetTimeFormat("#splitline{%d/%m}{%H:%M}");
  TxPower[0]->GetXaxis()->SetTimeDisplay(1);
  TxPower[0]->GetXaxis()->SetLabelOffset(0.03);
  txpower_legend->Draw();
  
  if (time_plot > 0) {
    sprintf(filename, "txpower_%d_hours.png", time_plot);
  }
  else {
    sprintf(filename, "txpower.png");
  }
  txpower_can->Print(filename);
  if (do_time_plot < 0) {
    for (int i = 1; i < 3; i++) {
      sprintf(filename, "txpower_%d_hours.png", time_plot_array[i]);
      
      int rangeinit = (time_entries*INTERVAL - time_plot_array[i]*60)*60;
      int rangeend = INTERVAL*60*(time_entries + 5*time_plot_array[i]/12);
      TxPower[0]->GetXaxis()->SetRangeUser(rangeinit, rangeend);
      float thistxpmax = -1000.;
      float thistxpmin = 1000.;
      for (int j = 0; j < time_entries; j++) {
        for (int k = 0; k < nfibres; k++) {
          if (j + time_plot_array[i]*60/INTERVAL > time_entries) {
            if (txpower_val[k][j] > thistxpmax)
              thistxpmax = txpower_val[k][j];
            if (txpower_val[k][j] < thistxpmin)
              thistxpmin = txpower_val[k][j];
          }
        }
      }
      TxPower[0]->GetYaxis()->SetRangeUser((ceil(thistxpmin) - 1), (floor(thistxpmax) + 1));
      
      txpower_can->Print(filename);
    }
  }
  
  
  
  /*
   * Received power plot
   */
  TCanvas *rxpower_can = new TCanvas("RxPower", "RxPower", width, height);
  
  for (int i = 0; i < nfibres; i++) {
    RxPower[i]->Draw(i==0?"AL":"L,same");
    RxPower[i]->SetLineColor(i + 1);
    RxPower[i]->SetLineWidth(2);
  }
  RxPower[0]->GetYaxis()->SetRangeUser((ceil(min_rxpower) - 1), (floor(max_rxpower) + 1));
  if (time_plot > 0) {
    RxPower[0]->GetXaxis()->SetRangeUser(rangeinit, rangeend);
  }
  RxPower[0]->GetYaxis()->SetTitle("RxPower [dBm]");
  RxPower[0]->GetXaxis()->SetTitle("");
  RxPower[0]->SetTitle("SFP Received Power");
  RxPower[0]->GetXaxis()->SetTimeFormat("#splitline{%d/%m}{%H:%M}");
  RxPower[0]->GetXaxis()->SetTimeDisplay(1);
  RxPower[0]->GetXaxis()->SetLabelOffset(0.03);
  rxpower_legend->Draw();
  
  if (time_plot > 0) {
    sprintf(filename, "rxpower_%d_hours.png", time_plot);
  }
  else {
    sprintf(filename, "rxpower.png");
  }
  rxpower_can->Print(filename);
  if (do_time_plot < 0) {
    for (int i = 1; i < 3; i++) {
      sprintf(filename, "rxpower_%d_hours.png", time_plot_array[i]);
      
      int rangeinit = (time_entries*INTERVAL - time_plot_array[i]*60)*60;
      int rangeend = INTERVAL*60*(time_entries + 5*time_plot_array[i]/12);
      RxPower[0]->GetXaxis()->SetRangeUser(rangeinit, rangeend);
      float thisrxpmax = -1000.;
      float thisrxpmin = 1000.;
      for (int j = 0; j < time_entries; j++) {
        for (int k = 0; k < nfibres; k++) {
          if (j + time_plot_array[i]*60/INTERVAL > time_entries) {
            if (rxpower_val[k][j] > thisrxpmax)
              thisrxpmax = rxpower_val[k][j];
            if (rxpower_val[k][j] < thisrxpmin)
              thisrxpmin = rxpower_val[k][j];
          }
        }
      }
      
      RxPower[0]->GetYaxis()->SetRangeUser((ceil(thisrxpmin) - 1), (floor(thisrxpmax) + 1));
      
      rxpower_can->Print(filename);
    }
  }
  
   
  /*
   * Temperature plot
   */
  TCanvas *temperature_can = new TCanvas("Temperature", "Temperature", width, height);
  
  for (int i = 0; i < nfibres; i++) {
    Temperature[i]->Draw(i==0?"AL":"L,same");
    Temperature[i]->SetLineColor(i + 1);
    Temperature[i]->SetLineWidth(2);
  }
  Temperature[0]->GetYaxis()->SetRangeUser((ceil(min_temp) - 1), (floor(max_temp) + 1));
  if (time_plot > 0) {
    Temperature[0]->GetXaxis()->SetRangeUser(rangeinit, rangeend);
  }
  Temperature[0]->GetYaxis()->SetTitle("Temperature [^{o}C]");
  Temperature[0]->GetXaxis()->SetTitle("");
  Temperature[0]->SetTitle("SFP Temperature");
  Temperature[0]->GetXaxis()->SetTimeFormat("#splitline{%d/%m}{%H:%M}");
  Temperature[0]->GetXaxis()->SetTimeDisplay(1);
  Temperature[0]->GetXaxis()->SetLabelOffset(0.03);
  temperature_legend->Draw();
  
  if (time_plot > 0) {
    sprintf(filename, "temperature_%d_hours.png", time_plot);
  }
  else {
    sprintf(filename, "temperature.png");
  }
  temperature_can->Print(filename);
  if (do_time_plot < 0) {
    for (int i = 1; i < 3; i++) {
      sprintf(filename, "temperature_%d_hours.png", time_plot_array[i]);
      
      int rangeinit = (time_entries*INTERVAL - time_plot_array[i]*60)*60;
      int rangeend = INTERVAL*60*(time_entries + 5*time_plot_array[i]/12);
      Temperature[0]->GetXaxis()->SetRangeUser(rangeinit, rangeend);
      float thistempmax = -1.;
      float thistempmin = 1000.;
      for (int j = 0; j < time_entries; j++) {
        for (int k = 0; k < nfibres; k++) {
          if (j + time_plot_array[i]*60/INTERVAL > time_entries) {
            if (temp_val[k][j] > thistempmax)
              thistempmax = temp_val[k][j];
            if (temp_val[k][j] < thistempmin)
              thistempmin = temp_val[k][j];
          }
        }
      }
      
      Temperature[0]->GetYaxis()->SetRangeUser((ceil(thistempmin) - 1), (floor(thistempmax) + 1));
      
      temperature_can->Print(filename);
    }
  }
  

  // Free Willy
  free(fibres_values_temp);
  free(fibres_names_temp);
  
}
Exemple #24
0
	int									getAge()								{ return getYear() - _birthYear; }
Exemple #25
0
int rspfLocalTm::getShortYear()const
{
   return (getYear()%100);
}