示例#1
0
bool ErrorHandling::checkAddInput(vector<string>& input)
{	
	bool value = true;
	
	int inputNotGiven = 0;
	for(int counter = 0; counter < input.size() - 1; counter++)
	{
		if(input[counter] == "")
				++inputNotGiven;
	}
			
	if(inputNotGiven == 3)
	{
		cout << "\nInvalid input as no event detail has been mentioned.\n"; 
		performLogging("Invalid input as no event detail has been mentioned.");
		value = false;
	}

	if(value)
	{
		if(!checkDate(input[1]))
			value = false;

		if(!checkTime(input[2]))
			value = false;
	}
	return value;
}
示例#2
0
/* verifier
return value: -438: You should send a 438-reply.
			-437: You should send a 437-reply.
			-436: You should send a 436-reply.
			-428: You should send a 428-reply.
			-3: Error verifying Date header field.
			-2: Authentication service is not authoritative.
			-1: An error occured.
			1: verification OK
*/
static int verifier_(struct sip_msg* msg, char* str1, char* str2)
{
	char identityHF[MAX_IDENTITY] = "\0";
	X509 * cert = NULL;
	int retval = -1;
	STACK_OF(X509) * certchain = NULL;

	/* parse all headers */
	if (parse_headers(msg, HDR_EOH_F, 0)!=0) {
		LM_ERR("failed to parse headers\n");
		return -1;
	}

	retval = getIdentityHF(identityHF, msg);
	switch(retval)
	{
		case 0:
			/* Identity header field does not exist */
			return -428;
		case -1:
			LM_ERR("getIdentityHF failed\n");
			return -1;
	}

	if(!getCert(&cert, &certchain, msg))
	{
		return -436;
	}

	if(!validateCert(cert, certchain))
	{
		X509_free(cert);
		sk_X509_pop_free(certchain, X509_free);
		return -437;
	}
	sk_X509_pop_free(certchain, X509_free);

	if(!checkAuthority(cert, msg))
	{
		X509_free(cert);
		return -2;
	}

	if(!checkSign(cert, identityHF, msg))
	{
		X509_free(cert);
		return -438;
	}

	if(!checkDate(cert, msg))
	{
		X509_free(cert);
		return -3;
	}

	X509_free(cert);
	return 1;
}
示例#3
0
// 스케줄 입력
void insertSchedule(int scheduleCount) {
	int year, month, day;
	char schedule[100];
	while (1) {
		printf("입력 : ");
		scanf("%d %d %d", &year, &month, &day);
		getchar();
		fgets(schedule, sizeof(schedule), stdin);
		removeEnterInFgetsString(schedule);

		// 날짜 제대로 입력했는지 확인
		if (checkDate(year, month, day)) {
			break;
		}
	}
	printf("출력 : %d년 %d월 %d일 %s\n", year, month, day, schedule);

	// 일정 겹치는지 확인
	int overwrite = 1;
	for (int i = 0; i < scheduleCount; i++) {
		// 겹침
		if (mScheduleYear[i] == year && mScheduleMonth[i] == month && mScheduleDay[i] == day) {
			char answer;
			printf("해당 날짜에 이미 일정이 있습니다. 덮어 씌우시겠습니까? (Y or N)");
			getchar();
			answer = getchar();
			// 덮어씌우기
			if (answer == 'Y' || answer == 'y') {
				scheduleCount = i;
				overwrite = 1;
			}
			// 되돌아가기
			else
				overwrite = 0;
			break;
		}
	}

	// 덮어쓰지 않겠다면 처음으로 돌아감
	if (!overwrite)
		return;

	printf("count = %d\n", scheduleCount);
	mScheduleYear[scheduleCount] = year;
	mScheduleMonth[scheduleCount] = month;
	mScheduleDay[scheduleCount] = day;
	if (mScheduleCount == scheduleCount)
		mScheduleCount++;

	printf("일정을 추가하였습니다.\n");
	printf("아무키나 입력하세요.......");
	getchar();
	system("clear");
}
示例#4
0
void getYear() {
  int iYear,iMonth,iDay;
  printf("\nPlease input data as [yyyy mm dd] :\n");
  fgets(buf, BUFFER_SIZE, stdin);
  sscanf(buf, "%d %d %d", &iYear, &iMonth, &iDay);

  if (!checkDate(iYear,iMonth,iDay)) {
    printf("Input date is invalid!\n\n");
    return;
  }
  saveData(DATE, iYear, iMonth, iDay);
}
int LogicDetailParser::findDate(Task& task, string text){
	int day, month, year;
	day = month = year = NOTSTATED;

	if(parserDate(text, day, month, year)){
		if(year < YEARCHECK)
			year += TWOTHOUSAND;
		if(checkDate(day, month, year)){
			setTaskDate(task, day, month, year);
			return FOUND;
		}
		else
			return ERROR;
	}
	return NOTFOUND;
}
void XDateEdit::setDate(const QDate &pDate, bool pAnnounce)
{
  if (DEBUG)
    qDebug("%s::setDate(%s, %d) with _currentDate %s, _allowNull %d",
           qPrintable(parent() ? parent()->objectName() : objectName()),
           qPrintable(pDate.toString()), pAnnounce,
           qPrintable(_currentDate.toString()), _allowNull);

  if (pDate.isNull())
    setNull();
  else
  {
    if(!pAnnounce)
    {
      if(determineIfStd() && (_siteId != -1))
        return checkDate(pDate);
    }
    else
    {
      pAnnounce = (pDate != _currentDate);
    }
    _currentDate = pDate;
    _valid = _currentDate.isValid();
    _parsed = _valid;

    if (DEBUG)
      qDebug("%s::setDate() setting text",
             qPrintable(parent() ? parent()->objectName() : objectName()));
    if ((_allowNull) && (_currentDate == _nullDate))
      setText(_nullString);
    else
      setText(formatDate(pDate));
    if (DEBUG)
      qDebug("%s::setDate() done setting text",
             qPrintable(parent() ? parent()->objectName() : objectName()));
  }

  if (pAnnounce)
  {
    if (DEBUG)
      qDebug("%s::setDate() emitting newDate(%s)",
             qPrintable(parent() ? parent()->objectName() : objectName()),
             qPrintable(_currentDate.toString()));
    emit newDate(_currentDate);
  }
}
示例#7
0
bool ErrorHandling::checkSearchInput(vector<string> input)
{
	bool value = true;

	if(input[1] != "")
	{
		if(!checkDate(input[1]))
		value = false;
	}
 
	if(input[2] != "")
	{
		if(!checkTime(input[2]))
		value = false;
	}

	return value;
}
示例#8
0
double SunPosition::dateToJulian( Date inputDate)
{	
	// check date
	if( checkDate(inputDate) )
	{
		printf ("INVALID DATE: %i %i %i %i %i %i\n",inputDate.year,inputDate.month,inputDate.day,inputDate.hour,inputDate.minute,inputDate.second);
		return -1;
	}
	
	// Fliegel and van Flandern (1968) Algorithm
	
	int jd = inputDate.day-32075+1461*(inputDate.year+4800+(inputDate.month-14)/12)/4+367*(inputDate.month-2-(inputDate.month-14)/12*12) /12-3*((inputDate.year+4900+(inputDate.month-14)/12)/100)/4;
	double result = (double)jd + (double)inputDate.hour/24.0 + (double)inputDate.minute/(24.0*60.0) + (double)inputDate.second/(24.0*3600.0);
	
	//printf("julianDate= %f   %i %i %i %i %i %i\n",result,inputDate.year,inputDate.month,inputDate.day,inputDate.hour,inputDate.minute,inputDate.second);
	
	return result;
}
示例#9
0
void find(int flag, int cur_add_day)
{
    FILE *input;

    struct event giorti;
    int max_day, flag1=0;
    int mera, minas, etos;
    int verbose=0;      /* when NOT called by the user (-f parameter) the */
    /* user must not see the results of the search    */

    mera = current_day+cur_add_day;
    minas = current_month;
    etos = current_year;

    if (flag == 0)
    {
        verbose = 1;

#ifndef NO_GUI
        hideMainWindowGUI();
#endif

        do
        {
            flag = 0;
#ifndef NO_GUI
            auto_close_flag = 1;
            getDateForFindGUI(&mera, &minas);
#else
            minas= getDateCLI("month");
            mera = getDateCLI("day");
#endif
            flag = checkDate(mera, minas, current_year);
            if (flag == 1)
            {

#ifndef NO_GUI
                invalidDateMsgGUI();
#else
                fprintf(stderr, _("Please try again.\n"));
#endif

            }
        }
        while (flag == 1);
    }

    while ((max_day=monthDays(minas, etos)) < mera)
    {
        mera-=max_day;
        minas++;
        if (minas > 12)
        {
            minas = 1;
            etos++;
        }
    }

    if (no_database != 'p' && no_database != 'a')
    {
        readFile(personal, mera, minas);
    }

    if (no_database != 'i' && no_database != 'a')
    {
        readFile(internat, mera, minas);
    }

    input = fopen(database, "rb");    /* Flawfinder: ignore */
    if (!input)
    {
        if (flag == 0 && quiet == 1 )
        {
            fprintf(stderr, _("Could not locate database file with name <%s>.\n"), database);
        }
        return;
    }

    flag = 0;

    /* search the database from the beginning till the date we search is bigger*/
    /* than database's readed month+2 (because database is sorted and the max */
    /* celebration which depends on east is 56 days after) */
    while (!feof(input) && flag1==0)
    {
        flag1 = 0;
        fread(&giorti, sizeof(struct event), 1, input);

        /* if a celebration depends an the easter day change it's day/month */
        checkKiniti(giorti.kiniti, &giorti.mera, &giorti.minas, giorti.onoma);

        if (!feof(input))
        {
            if (minas == giorti.minas)
            {
                if (mera == giorti.mera)
                {
                    print(giorti);
                    flag = 1;
                }
            }
            if (minas+2 < giorti.minas)
            {
                flag1 = 1;
            }
        }
    }

    fclose(input);

#ifndef NO_GUI
    insertResultIntoLabelGUI();
    strncpy(label_str, "", labelBUFFER);
#endif

    /* If called with the -f parameter print the "no results" message */
    if (verbose == 1 && flag == 0)
    {
#ifndef NO_GUI
        strncpy(label_str, _("\nSearch returned no results.\n\n"), labelBUFFER);
        insertResultIntoLabelGUI();
#else
        fprintf(stdout, _("\nSearch returned no results.\n\n"));
#endif
    }
}
//controll the program navigation
void Soccer_league::start(string str)
{

	while(!str.substr(0,1).compare(" "))
		str=str.substr(1,str.length());

	if (str.length()<1)return;
	//if there is a user file to read and he inserted before lunce the program


	//getting the next action/request fron the user
inputerror: //getline(cin,str);
	//real input because i change it to lower case and without spaces
	string realInput = str;
	/*all the matches will be without spaces and with lower case*/
	str.erase( std::remove(str.begin(),str.end(),' '), str.end() );
	std::transform(str.begin(), str.end(), str.begin(), ::tolower);

	//check if str starts with '.' it should be a regex
	if (str.substr(0,1).compare(".")==0||str.substr(0,1).compare(",")==0||str.substr(0,1).compare("/")==0)
	{
		goto inputerror;
	}
	if (str.compare("help")==0)
	{

	}
	// statments
	if (str.compare("showleague")==0)
	{
		printLeagueTabel(_team);
	}
	//display the team names
	else if (str.compare("showteams")==0)
	{
		cout<<"Team Name"<<endl;
		cout<<"-----------"<<endl;
		for (int i=0 ; i< _team.size();i++)
		{
			cout<<_team[i]->get_teamName()<<endl;
		}

	}
	//display a specific game
	else if (str.substr(0,4).compare("show")==0 && (str.length()-4)>=2 && realInput.substr(0,5).compare("show ")==0 && realInput.substr(0,5).compare("Show ")==0)
	{
		//split the string into 2 parts each one of then is a team name
		str = str.substr(4,str.length());
		int locationInLine=0;
		string splited,home,guest;
		for (int i=0 ; i < realInput.length(); i++)
		{
			string temp = realInput.substr(i,1);
			if (realInput.length()>(i+4) && realInput.at(i)==' ' && realInput.at(i+1)=='-' && realInput.at(i+2)==' ')
			{
				home=splited;
				locationInLine+=i+3;
				guest=realInput.substr(locationInLine,realInput.length());
				splited.clear();
				break;
			}
			splited.append(temp);
		}
		home = home.substr(5,home.length()-1);
		//search the requested game in reverse order to get the latest game
		for (int i=_game.size()-1; i >= 0 ; i--)
		{
			if (home.compare(_game[i]->get_home())==0 && guest.compare(_game[i]->get_guest().substr(0,(_game[i]->get_guest().length())))==0)
			{
				cout<<getGameDetails(i,_game)<<endl;
				break;
			}
		}
	}



	//check if we have date elements like . , / and it start with game namber
	else if (str.find("game")!= std::string::npos&&(str.find(".")!= std::string::npos || str.find(",")!= std::string::npos || str.find("/")!= std::string::npos))
	{
		//delete the word 'game' from the input string and keep only the number
		int gameNumber=0;
		if(str.substr(5,6).compare(",") || str.substr(5,6).compare("."))
			gameNumber = atoi(str.substr(4,5).c_str());
		string strGame=str.substr(6,str.length());
		//finally check if the input is date
		Date* date = (checkDate(strGame));
		for (int i=0; i< _game.size(); i++)
		{
			Date* d = _game[i]->get_date();
			if (*d==*date && _game[i]->get_round() == gameNumber)
			{
				//display the asks games
				cout<<getGameDetails(i,_game)<<endl;
			}
		}
		cout<<endl;
	}

	//access allow only if you are the manager
	if (str.substr(0,5).compare("admin")==0)
	{
		//remove the admin word from the beginning and keep the left string
		string strAdmin = str.substr(5,str.length());

		if (strAdmin.substr(0,7).compare("addgame")==0)
		{
			//close the ream registeration
			if(_isOpen==1 )
			{
				_dateBase->get_file()<<("START")<<endl;
				_dateBase->get_file()<<("END")<<endl;
				_isOpen=0;
			}

			int location= realInput.find("game");
			string newGame = realInput.substr(location+4,realInput.length());
			//check if the game is correct by names and game number and act.
			addGame(newGame,_dateBase->get_file(),_game);
			//_game.push_back(new Game(newGame));
			//writeToFileinTheEnd(newGame);
			interpretGamesToTeamsStatus(_team,_game.at(_game.size()-1));
			string output = "user add a new game ";
			output+=newGame;
			writeToOUTPUTfile(output,_dateBase->get_output());
		}
		//register teams
		if (strAdmin.substr(0,13).compare("registerteams")==0)
		{

			if(_isOpen==1)
			{
				string newTeam;int check=1;
				vector<string> vec;
				//save my list in vector to comper with the input string
				for (int i=0;i<_team.size();i++)
				{
					vec.push_back(_team[i]->get_teamName());
				}
				//cout<<"insert team names: "<<endl;
				//check is the inset team is not exist and exit when ; insert
				while (!newTeam.compare(";")==0)
				{

					getline (cin,newTeam);
					for (int i=0;i<vec.size();i++)
					{
						if(newTeam.compare(vec[i])==0)
						{
							cout<<"team "<<newTeam<< " is already registered"<<endl;
							check=0;
						}
					}
					if (check==1 && !newTeam.compare(";")==0)
					{
						writeToFileinTheEnd(newTeam,_dateBase->get_file());
						string output = "user add a new team ";
						output+=newTeam;
						writeToOUTPUTfile(output,_dateBase->get_output());
						_team.push_back(new Team(newTeam));
					}
					check=1;
				}
				cout<< "Teams was added"<<endl;
			}
			else
			{
				cout<<"cannot add new teams because the league is already started"<<endl;
			}
		}
		//update team name
		if (strAdmin.substr(0,17).compare("correctionreplace")==0)
		{
			int location = realInput.find("replace");
			realInput = realInput.substr(location+8,realInput.length());
			//seperate the old team name and new team name
			int locationInLine=0;
			string splited,oldTeam,newTeam;
			string temp = realInput;
			oldTeam = temp.substr(0,realInput.find("by")-1);
			newTeam = temp.substr(realInput.find("by ")+3,temp.length());

			/*for (int i=0 ; i < realInput.length(); i++)
			{
			string temp = realInput.substr(i,1);
			if (realInput.length()>(i+4) && realInput.at(i)==' ' && realInput.at(i+1)=='-' && realInput.at(i+2)==' ')
			{
			oldTeam=splited;
			locationInLine+=i+3;
			newTeam=realInput.substr(locationInLine,realInput.length());
			splited.clear();
			break;
			}
			splited.append(temp);
			}*/

			//update team name into the data base
			replace_line_in_file(oldTeam , newTeam, _dateBase->get_file(), _team , _game);
			string output = "user replace team name ";
			output+= oldTeam;
			output+=" to ";
			output+=newTeam;
			writeToOUTPUTfile(output,_dateBase->get_output());
			//cout<< "Team name updated"<<endl;
		}
		if (strAdmin.substr(0,14).compare("correctiongame")==0)
		{
			strAdmin = strAdmin.substr(strAdmin.find("game")+4,strAdmin.length());
			string gameNumber = strAdmin.substr(0,1);
			string sdate = strAdmin.substr(2,strAdmin.length());
			Date* date = checkDate(strAdmin.substr(2,strAdmin.length()));
			updateGame(gameNumber, sdate,_dateBase->get_file(),_team,_game);
		}
		if (strAdmin.substr(0,16).compare("correctiondelete")==0)
		{
			if(_isOpen)
			{
				int location = realInput.find("delete");
				string teamToRemove = realInput.substr(location+7,realInput.length());
				removeLine(teamToRemove,_dateBase->get_file());
				for (int i=0; i<_team.size();i++)
				{
					if (_team[i]->get_teamName().compare(teamToRemove)==0)
					{
						_team.erase(_team.begin()+i);
						string output = "user delete team ";
						output+= teamToRemove;
						writeToOUTPUTfile(output,_dateBase->get_output());
						break;
					}
				}
			}
			else cout<<"cannot delete team because the league is already started"<<endl;

		}
		if (strAdmin.substr(0,10).compare("correction")==0 && strAdmin.find('-') != std::string::npos )
		{
			realInput = realInput.substr(realInput.find("correction")+11,realInput.length());
			int locationInLine=0;
			string splited,home,guest;
			string temp = realInput;
			for (int i=0 ; i < realInput.length(); i++)
			{
				string temp = realInput.substr(i,1);
				if (realInput.length()>(i+4) && realInput.at(i)==' ' && realInput.at(i+1)=='-' && realInput.at(i+2)==' ')
				{
					home=splited;
					locationInLine+=i+3;
					guest=realInput.substr(locationInLine,realInput.length());
					splited.clear();
					break;
				}
				splited.append(temp);
			}
			string score;
			for (int i=0 ; i < guest.length(); i++)
			{
				string temp = guest.substr(i,1);
				try{
					if (guest.length()>(i+4) && atoi(temp.c_str())>0)
					{
						score = guest;
						guest=splited.substr(0,splited.length()-1);
						locationInLine+=i;
						score=score.substr(guest.length()+1,score.length());
						splited.clear();
						break;
					}
				}
				catch(exception e){};
				splited.append(temp);
			}
			updateGameDetails(home,guest,score,_dateBase->get_file(),_team,_game);
			interpretGamesToTeamsStatus(_team,_game.at(_game.size()-1));

		}
	}
	if (str.compare("exit")==0)
	{
		_dateBase->get_file().close();
		return;
	}

}
示例#11
0
文件: curses.c 项目: bsdcpp/mylib
int main(int argc ,char * argv[])
{
    char cmd_line[COMMAND_LEN];
    char cp[2],busi_type[10];
    int busi_flag;
    int fd;
    memset(busi_type,0,10);
    memset(cmd_line,0,COMMAND_LEN);

    initscr();  /*启动curses 模式*/
    noecho(); /*用户所敲的输入无所回应,保持沉默*/

    do
    {
        clear();
        move(10,0);
        refresh();
        printf("\r请选择要处理的业务: ");	  
        move(12,0);
        refresh();
        printf("\r请输入(1->ISP;2->VOC):");
        refresh();    
        keyboard_input(cp);
    } while ( strcmp(cp,"1")!=0 && strcmp(cp,"2")!=0);
    busi_flag=atoi(cp);
    sprintf(cmd_line,"%s %s ","/LJCJ_FS2/USERS/ycl01/voc_isp/bin",cp);

    do
    {
        clear();
        move(10,0);
        refresh();
        printf("\r请选择要处理的数据源:");	  
        move(12,0);
        refresh();
        printf("\r请输入(1->正式数据;2->预估数据):");
        refresh();    
        keyboard_input(cp);
    }while ( strcmp(cp,"1")!=0 && strcmp(cp,"2")!=0);
    strcat(cmd_line,cp);

    if (busi_flag==1)
    {
        fd=0;
        do /*输入日期,并要求格式正确*/
        {
            clear();
            move(10,0);
            refresh();
            if (fd > 0) printf("\rISP月份格式不正确,重新输入!请输入要处理的文件月份!(yyyymm):");
            else        printf("\r请输入要处理的文件月份!(yyyymm):");
            refresh();
            keyboard_input(checkmon);
            fd++;
        }while (checkMon(checkmon)==false);
        strcat(cmd_line," ");
        strcat(cmd_line,checkmon);
    }
    else
    {
        fd=0;
        do /*输入起始日期,并要求格式正确*/
        {
            clear();
            move(10,0);
            refresh();
            if (fd > 0) printf("\rVOC日期格式不正确,重新输入!请输入要处理的文件起始日期!(yyyymmdd):");
            else        printf("\r请输入要处理的文件起始日期!(yyyymmdd):");
            refresh();
            keyboard_input(checkdate);
            fd++;
        }while (checkDate(checkdate)==false);
        strcat(cmd_line," ");
        strcat(cmd_line,checkdate);	  
    }

    do /*输入起始日期,并要求格式正确*/
    {
        clear();
        move(10,0);
        refresh();
        printf("\r请输入要处理的业务:");
        refresh();  
        keyboard_input(busi_type);
    }while(0);
    strcat(cmd_line," ");
    strcat(cmd_line,busi_type);	  
    printf("%s\n",cmd_line);
    endwin(); /*关闭curses 模式*/

}
示例#12
0
int main( int argc, char ** argv )
{
  KLocale::setMainCatalogue("kdelibs");
  KApplication a( argc, argv, "klocaletest" );

  KGlobal::locale()->setLanguage(QString::fromLatin1("en_US"));
  KGlobal::locale()->setCountry(QString::fromLatin1("C"));
  KGlobal::locale()->setThousandsSeparator(QString::fromLatin1(","));

  QString formatted;
  formatted = KGlobal::locale()->formatNumber( 70 ); check("formatNumber(70)",formatted,"70.00");
  formatted = KGlobal::locale()->formatNumber( 70, 0 ); check("formatNumber(70, 0)",formatted,"70");
  formatted = KGlobal::locale()->formatNumber( 70.2 ); check("formatNumber(70.2)",formatted,"70.20");
  formatted = KGlobal::locale()->formatNumber( 70.24 ); check("formatNumber(70.24)",formatted,"70.24");
  formatted = KGlobal::locale()->formatNumber( 70.245 ); check("formatNumber(70.245)",formatted,"70.25"); /*rounded*/
  formatted = KGlobal::locale()->formatNumber(1234567.89123456789,8); check("formatNumber(1234567.89123456789,8)",formatted,"1,234,567.89123457");

  formatted = KGlobal::locale()->formatNumber("70"); check("formatNumber(\"70\")",formatted,"70.00");
  formatted = KGlobal::locale()->formatNumber("70", true, 2); check("formatNumber(\"70\", true, 2)",formatted,"70.00");
  formatted = KGlobal::locale()->formatNumber("70", true, 0); check("formatNumber(\"70\", true, 0)",formatted,"70");
  formatted = KGlobal::locale()->formatNumber("70.9123", true, 0); check("formatNumber(\"70.9123\", true, 0)",formatted,"71"); /* rounded */
  formatted = KGlobal::locale()->formatNumber("-70.2", true, 2); check("formatNumber(\"-70.2\", true, 2)",formatted,"-70.20");
  formatted = KGlobal::locale()->formatNumber("+70.24", true, 2); check("formatNumber(\"+70.24\", true, 2)",formatted,"70.24");
  formatted = KGlobal::locale()->formatNumber("70.245", true, 2); check("formatNumber(\"70.245\", true, 2)",formatted,"70.25"); /*rounded*/
  formatted = KGlobal::locale()->formatNumber("99.996", true, 2); check("formatNumber(\"99.996\", true, 2)",formatted,"100.00"); /*rounded*/
  formatted = KGlobal::locale()->formatNumber("12345678901234567.89123456789", false, 0); check("formatNumber(\"12345678901234567.89123456789\", false, 0)",formatted,"12,345,678,901,234,567.89123456789");



  double num;
  bool ok;
  num = KGlobal::locale()->readNumber( "12,1", &ok ); check("readNumber(12,1)",ok?"yes":"no","no");
  num = KGlobal::locale()->readNumber( "12,100", &ok ); check("readNumber(12,100)",ok?"yes":"no","yes");
  num = KGlobal::locale()->readNumber( "12,100000,000", &ok ); check("readNumber(12,100000,000)",ok?"yes":"no","no");
  num = KGlobal::locale()->readNumber( "12,100000000", &ok ); check("readNumber(12,100000000)",ok?"yes":"no","no");
  num = KGlobal::locale()->readNumber( "12,100000,000", &ok ); check("readNumber(12,100000,000)",ok?"yes":"no","no");
  num = KGlobal::locale()->readNumber( "12,,100,000", &ok ); check("readNumber(12,,100,000)",ok?"yes":"no","no");
  num = KGlobal::locale()->readNumber( "12,1000,000", &ok ); check("readNumber(12,1000,000)",ok?"yes":"no","no");
  num = KGlobal::locale()->readNumber( "12,0000000,000", &ok ); check("readNumber(12,0000000,000)",ok?"yes":"no","no");
  num = KGlobal::locale()->readNumber( "12,0000000", &ok ); check("readNumber(12,0000000)",ok?"yes":"no","no");
  num = KGlobal::locale()->readNumber( "12,146,131.12", &ok ); check("readNumber(12,146,131.12)",ok?"yes":"no","yes");
  num = KGlobal::locale()->readNumber( "1.12345678912", &ok );
        qDebug( "%s", QString::number( num, 'g', 12 ).latin1() ); // warning this is the only way to see all decimals
        check("readNumber(1.12345678912)",ok && num==1.12345678912?"yes":"no","yes");
  // bug 95511
  KLocale locale(*KGlobal::locale());
  locale.setCurrencySymbol("$$");
  num = locale.readMoney("1,234,567.89$$", &ok);
  check("readMoney(1,234,567.89$$)",ok?"yes":"no","yes");
  num = locale.readMoney("-1,234,567.89$$", &ok);
  check("readMoney(-1,234,567.89$$)",ok?"yes":"no","yes");

  QDate date;
  date.setYMD( 2002, 5, 3 );
  checkDate("readDate( 3, 5, 2002 )",date,KGlobal::locale()->readDate( KGlobal::locale()->formatDate( date ) ) );
  date = QDate::currentDate();
  checkDate("readDate( QDate::currentDate() )",date,KGlobal::locale()->readDate( KGlobal::locale()->formatDate( date ) ) );

  QTime time;
  time = KGlobal::locale()->readTime( "11:22:33", &ok );
  check("readTime(\"11:22:33\")", (ok && time == QTime(11, 22, 33)) ?
        "yes" : "no", "yes");
  time = KGlobal::locale()->readTime( "11:22", &ok );
  check("readTime(\"11:22\")", (ok && time == QTime(11, 22, 0)) ?
        "yes" : "no", "yes");
  time = KGlobal::locale()->readTime( "foo", &ok );
  check("readTime(\"foo\")", (!ok && !time.isValid()) ?
        "invalid" : "valid", "invalid");

  time = KGlobal::locale()->readTime( "11:22:33", KLocale::WithoutSeconds, &ok );
  check("readTime(\"11:22:33\", WithoutSeconds)", (!ok && !time.isValid()) ?
        "invalid" : "valid", "invalid");
  time = KGlobal::locale()->readTime( "11:22", KLocale::WithoutSeconds, &ok );
  check("readTime(\"11:22\", WithoutSeconds)", (ok && time == QTime(11, 22, 0)) ?
        "yes" : "no", "yes");

  KGlobal::locale()->setTimeFormat( "%H:%M %p" );
  time = QTime( 0, 22, 33 );
  QString timeStr = KGlobal::locale()->formatTime( time, true /*seconds*/, false /*duration*/ );
  check("formatTime(\"0:22\", as time)", timeStr, "00:22 am" );
  timeStr = KGlobal::locale()->formatTime( time, true /*seconds*/, true /*duration*/ );
  check("formatTime(\"0:22\", as duration)", timeStr, "00:22" );

  kdDebug() << "setLanguage C\n";
  KGlobal::locale()->setLanguage(QString::fromLatin1("C"));
  kdDebug() << "C: " << i18n("yes") << " " << i18n("QAccel", "Space") << endl;

  kdDebug() << "setLanguage de\n";
  KGlobal::locale()->setLanguage(QString::fromLatin1("de"));
  kdDebug() << "de: " << i18n("yes") << " " << i18n("QAccel", "Space") << endl;


  Test m;
  a.setMainWidget( &m );
  m.show();

  return a.exec();
}
示例#13
0
// Main Function
int main()
{


    char file_name[20];
    int counterHit;
    int counterUnique;
    int option;
    char IP[IP_LENGHT];
    char link[LINK_LENGHT];
    char date[10];        // Date typed by the user
    int day;
    int month;
    int year;
    Hit hits[200];
    int i;
    int j;
    int aux = 0;
    char linkName[LINK_LENGHT];
    char startDate[11];  //Date typed by the user used in the range
    char finishDate[11]; //Date typed by the user used in the range
    vector <string> links;


    cout << "Enter the name of the file to load:" << endl;
    cin >> file_name;
    // Open File hits.txt
    FILE *input;
    input = fopen(file_name,"r");

    if(input == NULL)
    {
        //Error Message
        printf("Error Reading File");
        return 1;
    }
    cout << "Loading  hits.txt \n\n\n" << endl;

    while(fscanf(input,"%s %s %s\n",IP,link,date) != EOF)
    {
        // Split date in a valid format and separate into integers
        sscanf(date, "%2d/%2d/%4d", &month, &day, &year);

        if (strlen(date)!=10)
        {
            cout << "Found a record with an invalid date format (not mm/dd/yyyy)...\n" << endl;
            cout << "ignoring entry" << endl;
        }
        else if (! checkDate(month, day, year))
        {
            cout << "Found a record with an invalid date ... ignoring entry \n" << endl;
        }
        else
        {
            // Setting values to the objects
            hits[aux].setIp(IP);
            hits[aux].setLink(link);
            hits[aux].setDay(day);
            hits[aux].setMonth(month);
            hits[aux].setYear(year);
            aux++;
        }
    }

    // Main Menu
    cout << "Please select a menu option: \n";
    cout << "1)Link Information in date range \n";
    cout << "2)Information about all links \n";
    cout << "3)Quit the program \n";
    cout << "Option (1,2,3): ";
    cin >> option;
    cout <<"\n";
    cout <<"\n";

    switch (option)
    {

    case 1:
        cout << "Enter a link name: " <<endl;
        cin >> linkName;
        cout <<"\n";

        cout << "Enter a start date: " <<endl;
        cin >> startDate;
        cout <<"\n";

        cout << "Enter a finish date:" <<endl;
        cin >> finishDate;
        cout <<"\n";


        checkDateRange(hits, linkName, startDate, finishDate, counterHit, counterUnique);

        cout <<"Link:  "<< linkName <<endl;
        cout <<"Total Hits: "<< counterHit <<endl;
        cout <<"Unique:     "<<counterUnique<<endl;
        cout <<"Returning:  "<<counterHit - counterUnique<<endl;
        break;

    case 2:

        cout << "     Link Name            Unique Visits  Return Visits  Total Visits" << endl;
        cout << "------------------------  -------------  -------------  ------------" << endl;

        for(int i = 0; i < hits->getCounter() ; i++ ){

            if(! vectorHas(hits[i].getLink(), links)){
                links.push_back(hits[i].getLink());
                checkDateRange(hits, hits[i].getLink(), "01/01/1000", "01/12/2100", counterHit, counterUnique);
                printf("%-24s         %-8d       %-9d    %d \n",hits[i].getLink(), counterUnique, counterHit - counterUnique, counterHit  );
            }
        }
        break;
    case 3:
        cout <<"\n";
        cout << "Program terminating normally...";
        cout <<"\n";
        return 0;

    default:
        cout << "Invalid Entry" << endl;
        return 1;
    }
}
Settings::BirthdayPage::BirthdayPage(QWidget* parent) : QWidget(parent)
{
    QVBoxLayout* mainLayout = new QVBoxLayout(this);

    QHBoxLayout* dataLayout = new QHBoxLayout;
    mainLayout->addLayout(dataLayout);

    QVBoxLayout* itemsLayout = new QVBoxLayout;
    dataLayout->addLayout(itemsLayout);

    QHBoxLayout* itemsHeaderLayout = new QHBoxLayout;
    itemsLayout->addLayout(itemsHeaderLayout);

    QLabel* categoryText = new QLabel(i18n("Category:"));
    itemsHeaderLayout->addWidget(categoryText);

    m_categoryBox = new QComboBox;
    itemsHeaderLayout->addWidget(m_categoryBox);
    connect(m_categoryBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeCategory(int)));

    m_filter = new QLineEdit;
    m_filter->setPlaceholderText(i18n("Filter (Alt+f)"));
    itemsHeaderLayout->addWidget(m_filter);
    connect(m_filter, SIGNAL(textChanged(QString)), this, SLOT(resetCategory()));
    new QShortcut(Qt::AltModifier + Qt::Key_F, m_filter, SLOT(setFocus()));

    m_dataView = new QTableWidget;
    m_dataView->setColumnCount(2);
    m_dataView->verticalHeader()->hide();
    m_dataView->setShowGrid(false);
    itemsLayout->addWidget(m_dataView);
    connect(m_dataView, SIGNAL(cellActivated(int,int)), this, SLOT(editDate(int,int)));

    QVBoxLayout* calendarLayout = new QVBoxLayout;
    dataLayout->addLayout(calendarLayout);

    calendarLayout->addStretch();

    m_birthdayOfLabel = new QLabel;
    calendarLayout->addWidget(m_birthdayOfLabel);

    m_dateInput = new QLineEdit;
    calendarLayout->addWidget(m_dateInput);
    connect(m_dateInput, SIGNAL(textEdited(QString)), this, SLOT(parseDate(QString)));
    connect(m_dateInput, SIGNAL(editingFinished()), this, SLOT(checkDate()));

    m_locale = KGlobal::locale();
    m_calendar = new QCalendarWidget;
    switch (m_locale->weekStartDay()) {
    case 1: m_calendar->setFirstDayOfWeek(Qt::Monday); break;
    case 2: m_calendar->setFirstDayOfWeek(Qt::Tuesday); break;
    case 3: m_calendar->setFirstDayOfWeek(Qt::Wednesday); break;
    case 4: m_calendar->setFirstDayOfWeek(Qt::Thursday); break;
    case 5: m_calendar->setFirstDayOfWeek(Qt::Friday); break;
    case 6: m_calendar->setFirstDayOfWeek(Qt::Saturday); break;
    case 7: m_calendar->setFirstDayOfWeek(Qt::Sunday); break;
    }
    calendarLayout->addWidget(m_calendar);
    connect(m_calendar, SIGNAL(clicked(QDate)), this, SLOT(setDate(QDate)));

    m_unsetButton = new QPushButton(i18n("Remove birthday"));
    calendarLayout->addWidget(m_unsetButton);
    connect(m_unsetButton, SIGNAL(clicked()), this, SLOT(removeDate()));

    calendarLayout->addStretch();

    QLabel* info = new QLabel(i18n("Set the date of birth for items (say people) here, "
                                   "and then see their age when viewing the images."));
    mainLayout->addWidget(info);

    m_noDateString = QString::fromUtf8("---");
    m_boldFont.setBold(true);

    disableCalendar();
}
void XDateEdit::parseDate()
{
  QString dateString = text().trimmed();
  bool    isNumeric;

  if (DEBUG)
    qDebug("%s::parseDate() with dateString %s, _currentDate %s, _allowNull %d",
           qPrintable(parent() ? parent()->objectName() : objectName()),
           qPrintable(dateString),
           qPrintable(_currentDate.toString()), _allowNull);

#ifdef GUIClient_h
  QDate today = ofmgThis->dbDate();
#else
  QDate today = QDate::currentDate();
#endif

  if (_parsed)
  {
    if (DEBUG)
      qDebug("%s::parseDate() looks like we've already parsed this string",
             qPrintable(parent() ? parent()->objectName() : objectName()));
    return;
  }

  _valid = false;

  if (dateString.contains(QRegExp("[0-9]+[-][0-9]+"))) //user enters hyphens instead of slashes
  {
    dateString.replace("-", "/");
  }

  if (dateString == _nullString || dateString.isEmpty())
    setNull();

  else if (dateString == "0")                           // today
    checkDate(today);

  else if (dateString.contains(QRegExp("^[+-][0-9]+"))) // offset from today
  {
    int offset = dateString.toInt(&isNumeric);
    if (isNumeric)
      checkDate(today.addDays(offset));
  }

  else if (dateString[0] == '#')                        // julian day
  {
    int offset = dateString.right(dateString.length() - 1).toInt(&isNumeric);
    if (isNumeric) {
      if (offset < 0)
        checkDate(QDate(today.year(), 12, 31).addDays(offset + 1));
      else
        checkDate(QDate(today.year(), 1, 1).addDays(offset - 1));
    }
  }

  else if (dateString.contains(QRegExp("^[0-9][0-9]?$"))) // date in month
  {
    int offset = dateString.toInt(&isNumeric, 10);
    if (isNumeric)
    {
      if (offset > today.daysInMonth())
        offset = today.daysInMonth();
 
      checkDate(QDate(today.year(), today.month(), 1).addDays(offset - 1));
    }
  }

  else                                                  // interpret with locale
  {
    QString dateFormatStr = QLocale().dateFormat(QLocale::ShortFormat);
    if (DEBUG)
      qDebug("%s::parseDate() trying to parse with %s",
             qPrintable(parent() ? parent()->objectName() : objectName()),
             qPrintable(dateFormatStr));

    QDate tmp = QDate::fromString(dateString, dateFormatStr);
    bool twodigitformat = !(dateFormatStr.indexOf(QRegExp("y{4}")) >= 0);
    if (tmp.isValid())
    {
      if (twodigitformat && tmp.year() < 1950) // Qt docs say 2-digit years are 1900-based so
      {
        qDebug("%s::parseDate() found valid 2-digit year %d",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               tmp.year());
        tmp = tmp.addYears(100); // add backwards-compat with pre-3.0 DLineEdit
        qDebug("%s::parseDate() altered year to %d",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               tmp.year());
      }
    }
    else if (twodigitformat)
    {
      // try 4 digits, ignoring the possibility of '-literals in the format str
      dateFormatStr.replace(QRegExp("y{2}"), "yyyy");
      if (DEBUG)
        qDebug("%s::parseDate() rewriting 2-digit year format string to %s",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               qPrintable(dateFormatStr));
      tmp = QDate::fromString(dateString, dateFormatStr);

      if (tmp.isValid())
      {
        if (tmp.year() < 10)
          tmp = tmp.addYears(today.year() - today.year() % 100);
        if (DEBUG)
          qDebug("%s::parseDate() after changing to 4-digit year, year = %d",
                 qPrintable(parent() ? parent()->objectName() : objectName()),
                 tmp.year());
      }
      else if (DEBUG)
        qDebug("%s::parseDate() after changing to 4-digit year, date still isn't valid",
               qPrintable(parent() ? parent()->objectName() : objectName()));

    }
    else
    {
      // try 2 digits, ignoring the possibility of '-literals in the format str
      dateFormatStr.replace(QRegExp("y{4}"), "yy");
      if (DEBUG)
        qDebug("%s::parseDate() rewriting 4-digit year format string to %s",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               qPrintable(dateFormatStr));
      tmp = QDate::fromString(dateString, dateFormatStr);
      if (tmp.isValid() && tmp.year() < 1950) // Qt docs say 2-digit years are 1900-based so
      {
        qDebug("%s::parseDate() found valid 2-digit year %d",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               tmp.year());
        tmp = tmp.addYears(100); // add backwards-compat with pre-3.0 DLineEdit
        qDebug("%s::parseDate() altered year to %d",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               tmp.year());
      }
    }
    if(!tmp.isValid())
    {
      // still no match -- we will decompose the format and input and
      // build a date based on that information
      QRegExp rx("(\\d+)");
      QRegExp rx2("(m+|y+|d+)");
      rx2.setCaseSensitivity(Qt::CaseInsensitive);
      QStringList numberList;
      QStringList formatList;
      int pos = 0;
      while ((pos = rx.indexIn(dateString, pos)) != -1)
      {
        numberList << rx.cap(1);
        pos += rx.matchedLength();
      }
      pos = 0;
      while((pos = rx2.indexIn(dateFormatStr, pos)) != -1)
      {
        formatList << rx2.cap(1);
        pos += rx2.matchedLength();
      }

      if (DEBUG)
        qDebug("%s::parseDate() aligning numberList %s with formatList %s",
               qPrintable(parent() ? parent()->objectName() : objectName()),
               qPrintable(numberList.join(":")), qPrintable(formatList.join(":")));

      // if we don't have exactly 3 and the numberList is not 2 or 3 then don't bother
      if(formatList.size() == 3 && (numberList.size() == 2 || numberList.size() == 3))
      {
        int year = today.year();
        int day = -1;
        int month = -1;

        pos = 0;
        for (int i = 0; i < formatList.size(); ++i)
        {
          QChar ch = formatList.at(i).toLower().at(0);
          if(ch == 'y' && numberList.size() == 3)
          {
            year = numberList.at(pos).toInt();
            pos++;
          }
          else if(ch == 'm')
          {
            month = numberList.at(pos).toInt();
            pos++;
          }
          else if(ch == 'd')
          {
            day = numberList.at(pos).toInt();
            pos++;
          }
        }

        // if single digit year, move it to the current century
        if (year < 10)
          year += today.year() - today.year() % 100;

        if(day > 0 && month > 0 && year > 0)
          tmp = QDate(year, month, day);
      }
      else if(formatList.size() == 3 && numberList.size() == 1)
      {
        QString ns = numberList.at(0);
        bool isNumber = false;
        (void)ns.toInt(&isNumber);
        if(isNumber && (ns.length() == 6 || ns.length() == 8))
        {
          int year = today.year();
          int day = -1;
          int month = -1;

          pos = 0;
          for (int i = 0; i < formatList.size(); ++i)
          {
            QChar ch = formatList.at(i).toLower().at(0);
            if(ch == 'y')
            {
              if(ns.length() == 8)
              {
                year = ns.mid(pos, 4).toInt();
                pos+=4;
              }
              else
              {
                year = ns.mid(pos, 2).toInt(&isNumber);
                pos+=2;
                if(isNumber)
                {
                  if(year < 50)
                    year += 2000;
                  else
                    year += 1900;
                }
              }
            }
            else if(ch == 'm')
            {
              month = ns.mid(pos, 2).toInt();
              pos+=2;
            }
            else if(ch == 'd')
            {
              day = ns.mid(pos, 2).toInt();
              pos+=2;
            }
          }

          if(day > 0 && month > 0 && year > 0)
            tmp = QDate(year, month, day);
        }
      }
    }

    checkDate(QDate(tmp.year(), tmp.month(), tmp.day()));
  }

  if (!_valid)
    setText("");

  _parsed = true;
}
SpecialOrderEditor::SpecialOrderEditor( QWidget *parent, bool newOne )
: KDialog( parent )
{
    m_modelAssigned = false;
    priceEach   = 0;
    paymentEach = 0;
    
    groupInfo.isAvailable = true;
    groupInfo.cost  = 0;
    groupInfo.price = 0;
    groupInfo.count = 0;
    groupInfo.name  = "";

    ui = new SpecialOrderUI( this );
    setMainWidget( ui );
    setCaption( i18n("Special Orders") );
    setButtons( KDialog::Ok|KDialog::Cancel );

    //Set Validators for input boxes
    ui->editAddQty->setValidator(new QDoubleValidator(0.00, 999999999999.99, 3, ui->editAddQty));

    ui->editQty->setValue(1);
    ui->editAddQty->setText("1.00");

    connect( ui->editQty, SIGNAL(editingFinished()), this, SLOT(calculateCost()));
    connect( ui->editQty, SIGNAL(valueChanged(int)), this, SLOT(calculateCost()));

    connect( ui->editQty, SIGNAL(editingFinished()), this, SLOT(checkFieldsState()));
    connect( ui->editPayment, SIGNAL(valueChanged(double)), this, SLOT(checkFieldsState()));
    

    connect( ui->editFilter, SIGNAL(textEdited ( const QString &)), SLOT(applyFilter(const QString &)) );
    connect( ui->btnAdd,    SIGNAL(clicked()), SLOT(addItem()) );
    connect( ui->editAddQty,    SIGNAL(returnPressed()), SLOT(addItem()) );
    connect( ui->btnRemove, SIGNAL(clicked()), SLOT(removeItem()) );
    connect( ui->groupView, SIGNAL(itemDoubleClicked(QTableWidgetItem*)), SLOT(itemDoubleClicked(QTableWidgetItem*)) );

    connect( ui->deliveryDT, SIGNAL(valueChanged(QDateTime)), this, SLOT(checkDate(QDateTime)) );

    connect( ui->editNotes, SIGNAL(textChanged()), SLOT(updateNoteLength()) );

    //for now, when creating a s.o. the status cannot be modified. It can be when edited.
    if (newOne) {
      dateTime         = QDateTime::currentDateTime();
      ui->deliveryDT->setDateTime(QDateTime::currentDateTime().addDays(1));
    }

    //tip
    QString path = KStandardDirs::locate("appdata", "styles/");
    path = path+"tip.svg";
    qtyTip   = new MibitTip(this, ui->editQty, path, DesktopIcon("dialog-warning",32) );
    path = KStandardDirs::locate("appdata", "styles/")+"rotated_tip.svg";
    groupTip = new MibitTip(this, ui->groupView, path, DesktopIcon("dialog-warning",32), tpAbove );

    path = KStandardDirs::locate("appdata", "styles/");
    path = path+"floating_bottom.svg";
    newClientPanel = new MibitFloatPanel(this, path, Top);
    newClientPanel->setSize(550,250);
    newClientPanel->addWidget(ui->frameClient);
    newClientPanel->setMode(pmManual);
    newClientPanel->setHiddenTotally(true);
    ui->editClientName->setEmptyMessage(i18n("Enter client name here..."));
    ui->editClientPhone->setEmptyMessage(i18n("Enter client phone here..."));
    ui->editClientCell->setEmptyMessage(i18n("Enter client cell phone here..."));

    connect( ui->btnNewClient, SIGNAL(clicked()), newClientPanel, SLOT(showPanel() ));
    connect( ui->btnNewClient, SIGNAL(clicked()), this, SLOT(enableCreateClient() ));
    connect( ui->btnClientCancel, SIGNAL(clicked()), newClientPanel, SLOT(hidePanel()));
    connect( ui->btnClientAdd, SIGNAL(clicked()), this, SLOT(createClient()));
    connect( ui->editClientName, SIGNAL(textEdited(const QString &)), this, SLOT(checkValidInfo()) );
    connect( ui->editClientAddress, SIGNAL(textChanged()), this, SLOT(checkValidInfo()) );
    connect( ui->editClientPhone, SIGNAL(textEdited(const QString &)), this, SLOT(checkValidInfo()) );
    connect( ui->editClientCell, SIGNAL(textEdited(const QString &)), this, SLOT(checkValidInfo()) );

    setDefaultButton(KDialog::None);
    ui->btnFilter->setDefault(true);
    ui->btnFilter->hide(); //hack to dont have a default OK or Cancel button

    ui->clientsCombo->setFocus();
    enableButtonOk(false);
}
示例#17
0
// Function to check the hits of a link inside a date range.
void checkDateRange(Hit hits[], char* link, char* StartDate, char* FinishDate, int &counterHit, int &counterUnique)
{
    int dayS;
    int monthS;
    int yearS;
    int dayF;
    int monthF;
    int yearF;
    counterHit = 0;
    counterUnique = 0;
    int counterEquals = 0;

    sscanf(StartDate,"%2d/%2d/%4d", &monthS, &dayS, &yearS);
    sscanf(FinishDate,"%2d/%2d/%4d", &monthF, &dayF, &yearF);

        if (strlen(StartDate)!=10 || strlen(FinishDate)!=10 )
        {
            cout << "Invalid date ...\n" << endl;
        }
        else if (! checkDate(monthS, dayS, yearS && ! checkDate(monthF, dayF, yearF)))
        {
            cout << "Invalid date ... \n" << endl;
        }
        else{

    for(int i = 0; i < hits->getCounter() ; i++ )
    {
        if ((hits[i].getYear() >= yearS && hits[i].getYear() <= yearF) && (strcmp(hits[i].getLink(),link)==0))
        {

            if (hits[i].getMonth() >= monthS && hits[i].getMonth() <= monthF )
            {
                if (hits[i].getDay() >= dayS && hits[i].getDay() <= dayF)
                    counterHit++;
                counterEquals = 0;

                for(int j=0; j < hits->getCounter(); j++)
                {
                    int m = strcmp(hits[i].getIp(),hits[j].getIp());
                    int n = strcmp(hits[i].getLink(),hits[j].getLink());

                    if((m == 0 && n==0) && j>i)
                    {
                        if (hits[j].getYear() >= yearS && hits[j].getYear() <= yearF)
                        {
                            if (hits[j].getMonth() >= monthS && hits[j].getMonth() <= monthF )
                            {
                                if (hits[j].getDay() >= dayS && hits[j].getDay() <= dayF)
                                {
                                    counterEquals++;
                                }
                            }
                        }
                    }
                }

                if(counterEquals == 0) counterUnique++;
            }
        }
      }
    }






}
示例#18
0
文件: Order.c 项目: vsctiago/LP_EpR
void setOrderExpectedDeliveryDate(Order *orders, int pos) {
    do {
        setDate(&orders[pos].expectedDeliveryDate, O_MSG_EXPECTED_DELIVERY_DATE);
    } while(checkDate(&orders[pos].expectedDeliveryDate, &orders[pos].approvalDate) == false);
}
示例#19
0
// update the dive and return the notes field, stripped of the HTML junk
void QMLManager::commitChanges(QString diveId, QString date, QString location, QString gps, QString duration, QString depth,
			       QString airtemp, QString watertemp, QString suit, QString buddy, QString diveMaster, QString weight, QString notes,
			       QString startpressure, QString endpressure, QString gasmix)
{
	struct dive *d = get_dive_by_uniq_id(diveId.toInt());
	DiveObjectHelper *myDive = new DiveObjectHelper(d);

	// notes comes back as rich text - let's convert this into plain text
	QTextDocument doc;
	doc.setHtml(notes);
	notes = doc.toPlainText();

	if (!d) {
		qDebug() << "don't touch this... no dive";
		return;
	}
	bool diveChanged = false;
	bool needResort = false;

	diveChanged = needResort = checkDate(myDive, d, date);

	diveChanged |= checkLocation(myDive, d, location, gps);

	diveChanged |= checkDuration(myDive, d, duration);

	diveChanged |= checkDepth(myDive, d, depth);

	if (myDive->airTemp() != airtemp) {
		diveChanged = true;
		d->airtemp.mkelvin = parseTemperatureToMkelvin(airtemp);
	}
	if (myDive->waterTemp() != watertemp) {
		diveChanged = true;
		d->watertemp.mkelvin = parseTemperatureToMkelvin(watertemp);
	}
	// not sure what we'd do if there was more than one weight system
	// defined - for now just ignore that case
	if (weightsystem_none((void *)&d->weightsystem[1])) {
		if (myDive->sumWeight() != weight) {
			diveChanged = true;
			d->weightsystem[0].weight.grams = parseWeightToGrams(weight);
		}
	}
	// start and end pressures for first cylinder only
	if (myDive->startPressure() != startpressure || myDive->endPressure() != endpressure) {
		diveChanged = true;
		d->cylinder[0].start.mbar = parsePressureToMbar(startpressure);
		d->cylinder[0].end.mbar = parsePressureToMbar(endpressure);
		if (d->cylinder[0].end.mbar > d->cylinder[0].start.mbar)
			d->cylinder[0].end.mbar = d->cylinder[0].start.mbar;
	}
	// gasmix for first cylinder
	if (myDive->firstGas() != gasmix) {
		int o2 = parseGasMixO2(gasmix);
		int he = parseGasMixHE(gasmix);
		// the QML code SHOULD only accept valid gas mixes, but just to make sure
		if (o2 >= 0 && o2 <= 1000 &&
		    he >= 0 && he <= 1000 &&
		    o2 + he <= 1000) {
			diveChanged = true;
			d->cylinder[0].gasmix.o2.permille = o2;
			d->cylinder[0].gasmix.he.permille = he;
		}
	}
	if (myDive->suit() != suit) {
		diveChanged = true;
		free(d->suit);
		d->suit = strdup(qPrintable(suit));
	}
	if (myDive->buddy() != buddy) {
		diveChanged = true;
		free(d->buddy);
		d->buddy = strdup(qPrintable(buddy));
	}
	if (myDive->divemaster() != diveMaster) {
		diveChanged = true;
		free(d->divemaster);
		d->divemaster = strdup(qPrintable(diveMaster));
	}
	if (myDive->notes() != notes) {
		diveChanged = true;
		free(d->notes);
		d->notes = strdup(qPrintable(notes));
	}
	// now that we have it all figured out, let's see what we need
	// to update
	DiveListModel *dm = DiveListModel::instance();
	int oldModelIdx = dm->getDiveIdx(d->id);
	int oldIdx = get_idx_by_uniq_id(d->id);
	if (needResort) {
		// we know that the only thing that might happen in a resort is that
		// this one dive moves to a different spot in the dive list
		sort_table(&dive_table);
		int newIdx = get_idx_by_uniq_id(d->id);
		if (newIdx != oldIdx) {
			DiveListModel::instance()->removeDive(oldModelIdx);
			DiveListModel::instance()->insertDive(oldModelIdx - (newIdx - oldIdx), myDive);
			diveChanged = false; // because we already modified things
		}
	}
	if (diveChanged) {
		if (d->maxdepth.mm == d->dc.maxdepth.mm &&
		    d->maxdepth.mm > 0 &&
		    same_string(d->dc.model, "manually added dive") &&
		    d->dc.samples == 0) {
			// so we have depth > 0, a manually added dive and no samples
			// let's create an actual profile so the desktop version can work it
			// first clear out the mean depth (or the fake_dc() function tries
			// to be too clever
			d->meandepth.mm = d->dc.meandepth.mm = 0;
			d->dc = *fake_dc(&d->dc, true);
		}
		DiveListModel::instance()->updateDive(oldModelIdx, d);
		invalidate_dive_cache(d);
		mark_divelist_changed(true);
	}
	if (diveChanged || needResort)
		changesNeedSaving();
}
示例#20
0
void Hachmei::on_birthdayDate_dateChanged(const QDate &date)
{
	ui->byDateButton->setEnabled(checkDate());
	ui->goldNumber->setEnabled(checkDate() && checkName());
}
示例#21
0
void Hachmei::on_surname_textChanged(const QString &arg1)
{
	ui->surname->setText(firstLetterUppercase(ui->surname->text()));
	ui->byName->setEnabled(checkName());
	ui->goldNumber->setEnabled(checkDate() && checkName());
}
示例#22
0
int main(void){
	
	bPriLev=PRI_MAIN;
	
	tTime.bDay=7;
	tTime.bMonth=8;
	tTime.bYear=11;
	
	
	
	_init();
	
	while(1) { /* Infinite Loop */
		switch(bState){

/*--------------------------------------------------------------------------------------------------*/
			case STATE_IDLE:
				switch(bBtn){
					case NO_BTN:
						if(bTimeColonToToggle){ toggleTimeColon(); bTimeColonToToggle=0; }
						refreshQuote();
						bFirst=1;
						
						break;
					case BTN_A:
					case BTN_B:
					case BTN_C:
					case BTN_A_LONG:
					case BTN_B_LONG:
						START_BACKLIGHT();
						bBtn=NO_BTN;
						break;
					case BTN_C_LONG:
						bState = STATE_MENU;
						BACKLIGHT_ON();
						bBtn=NO_BTN;
						break;
					default:
						break;
				}
				break;
				
/*--------------------------------------------------------------------------------------------------*/				
			case STATE_MENU:
				switch(bBtn){
					case NO_BTN:
						if(bSelectionMenuChanged || bFirst){
							bFirst=0;
							bSelectionMenuChanged=0;
							LCDWriteStringXY(0,0,"-");
							LCDWriteStringXY(1,0, options[bSelectionMenu]);
							LCDWriteStringXY(0,1," ");
							LCDWriteStringXY(1,1, options[bSelectionMenu+1]);
						}
						break;
					
					case BTN_A:
						bSelectionMenu++;
						bSelectionMenu %= NUMBER_OF_OPTIONS;
						bSelectionMenuChanged=1;
						bBtn=NO_BTN;
						break;
					
					case BTN_B:
						if(bSelectionMenu>0) bSelectionMenu--;
						else bSelectionMenu=(NUMBER_OF_OPTIONS-1);
						bSelectionMenu %= NUMBER_OF_OPTIONS;
						bSelectionMenuChanged=1;
						bBtn=NO_BTN;
						break;
					
					case BTN_C:
						switch(bSelectionMenu){
							case SEL_DATE:
								bState = STATE_EDIT_DATE;
								bBtn = NO_BTN;
								break;
							case SEL_TIME:
								bState = STATE_EDIT_TIME;
								bBtn = NO_BTN;
								break;
							case SEL_TIMEZONE:
								bState = STATE_EDIT_TIMEZONE;
								bBtn = NO_BTN;
								break;
							default:
								break;
						}
						bFirst=1;
						break;
					
					case BTN_C_LONG:
						bState = STATE_IDLE;
						bBtn=NO_BTN;
						BACKLIGHT_OFF();
						START_BACKLIGHT();
						
						LCD_RESET();
						
						bSelectionMenu=0;
						bDateChanged=1;		// Appena rientro in idle stampo le quote
						bTimeChanged=1;
						bTempChanged=1;
						break;
					
					default:
						break;
				}				
				break;
			
/*--------------------------------------------------------------------------------------------------*/			
			case STATE_EDIT_DATE:
				switch(bBtn){
					case NO_BTN:
						if(bFirst){
							bFirst=0;
							LCDClear();
							tTimeEditing = tTime;
							sprintf(str, "%02d/%02d/%02d", tTimeEditing.bDay, tTimeEditing.bMonth, tTimeEditing.bYear);
							LCDWriteStringXY(0,0, "Editing date:");
							LCDWriteStringXY(3,1, str);
							LCDCmd(0x0f);	// set blinking cursor
							LCD_CURSOR_LEFT_N(8);
						}
						break;
					case BTN_A:
						bBtn = NO_BTN;
						changeEditDate(bSelectionDate, BTN_A);
						sprintf(str, "%02d/%02d/%02d", tTimeEditing.bDay, tTimeEditing.bMonth, tTimeEditing.bYear);
						LCDWriteStringXY(3,1,str);
						LCD_CURSOR_LEFT_N(8-bSelectionDate);
						break;
					case BTN_B:
						bBtn = NO_BTN;
						changeEditDate(bSelectionDate, BTN_B);
						sprintf(str, "%02d/%02d/%02d", tTimeEditing.bDay, tTimeEditing.bMonth, tTimeEditing.bYear);
						LCDWriteStringXY(3,1,str);
						LCD_CURSOR_LEFT_N(8-bSelectionDate);
						break;
					case BTN_C:
						if(bSelectionDate<7){ LCD_CURSOR_RIGHT_N(1); bSelectionDate++; }
						else{ bSelectionDate=0; LCD_CURSOR_LEFT_N(7); }
						// eseguo il controllo della data solo se passo da giorno a mese e da mese a anno
						if(bSelectionDate==2 || bSelectionDate==5){
							LCD_CURSOR_RIGHT_N(1);
							bSelectionDate++;
							if(checkDate(&tTimeEditing, aDays)){
								sprintf(str, "%02d/%02d/%02d", tTimeEditing.bDay, tTimeEditing.bMonth, tTimeEditing.bYear);
								LCDWriteStringXY(3,1,str);
								LCD_CURSOR_LEFT_N(8-bSelectionDate);
							}
						}
						bBtn = NO_BTN;
						break;
					case BTN_C_LONG:
						bState=STATE_EDIT_DATE_CONFIRM;
						bBtn=NO_BTN;
						bFirst=1;
						break;
					default:
						break;
				}
				break;

/*--------------------------------------------------------------------------------------------------*/
				case STATE_EDIT_DATE_CONFIRM:
					switch(bBtn){
						case NO_BTN:
							if(bFirst){ 
								LCDWriteStringXY(0,0, "Confermi? Si/No");
								LCD_CURSOR_LEFT_N(5);
								bFirst=0;
								bSelectionDate=0;
							}
							if(bSelectionDateChanged){
								if(bSelectionDate==0){ LCD_SET_CURSOR_POSITION(10); }
								else{ LCD_SET_CURSOR_POSITION(13); }
								bSelectionDateChanged=0;
							}
							break;
						
						case BTN_C:
							bSelectionDate = (bSelectionDate == 0)?1:0;
							bSelectionDateChanged=1;
							bBtn=NO_BTN;
							break;
						
						case BTN_C_LONG:
							if(bSelectionDate){
								bState = STATE_MENU;
								bSelectionDate=0;
							}else{
								tTime.bDay = tTimeEditing.bDay;
								tTime.bMonth = tTimeEditing.bMonth;
								tTime.bYear = tTimeEditing.bYear;
								bState = STATE_MENU;
								LCD_RESET();
							}
							bBtn = NO_BTN;
							bFirst=1;
							break;
						default: break;
					}
				break;

/*--------------------------------------------------------------------------------------------------*/
			case STATE_EDIT_TIME:
					switch(bBtn){
						case NO_BTN:
							if(bFirst){
								bFirst=0;
								LCDClear();
								tTimeEditing = tTime;
								sprintf(str, "%02d:%02d:%02d", tTimeEditing.bHour, tTimeEditing.bMin, tTimeEditing.bSec);
								LCDWriteStringXY(0,0, "Editing time:");
								LCDWriteStringXY(3,1, str);
								LCDCmd(0x0f);	// set blinking cursor
								LCD_CURSOR_LEFT_N(8);
							}
							break;
						case BTN_A:
							bBtn = NO_BTN;
							changeEditTime(bSelectionTime, BTN_A);
							sprintf(str, "%02d:%02d:%02d", tTimeEditing.bHour, tTimeEditing.bMin, tTimeEditing.bSec);
							LCDWriteStringXY(3,1,str);
							LCD_CURSOR_LEFT_N(8-bSelectionTime);
							break;
						case BTN_B:
							bBtn = NO_BTN;
							changeEditTime(bSelectionTime, BTN_B);
							sprintf(str, "%02d:%02d:%02d", tTimeEditing.bHour, tTimeEditing.bMin, tTimeEditing.bSec);
							LCDWriteStringXY(3,1,str);
							LCD_CURSOR_LEFT_N(8-bSelectionTime);
							break;
						case BTN_C:
							if(bSelectionTime<7){ LCDCmd(0x14); bSelectionTime++; }
							else{ bSelectionTime=0; LCD_CURSOR_LEFT_N(7); }
							if(bSelectionTime==2 || bSelectionTime==5){ LCDCmd(0x14); bSelectionTime++; }
							bBtn = NO_BTN;
							break;
						case BTN_C_LONG:
							bState=STATE_EDIT_TIME_CONFIRM;
							bBtn=NO_BTN;
							bFirst=1;
							break;
						default:
							break;
					}
				break;

/*--------------------------------------------------------------------------------------------------*/
			case STATE_EDIT_TIME_CONFIRM:
					switch(bBtn){
						case NO_BTN:
							if(bFirst){ 
								LCDWriteStringXY(0,0, "Confermi? Si/No");
								LCD_CURSOR_LEFT_N(5);
								bFirst=0;
								bSelectionTime=0;
							}
							if(bSelectionTimeChanged){
								if(bSelectionTime==0){ LCD_SET_CURSOR_POSITION(10); }
								else{ LCD_SET_CURSOR_POSITION(13); }
								bSelectionTimeChanged=0;
							}
							break;
						
						case BTN_C:
							bSelectionTime = (bSelectionTime == 0)?1:0;
							bSelectionTimeChanged=1;
							bBtn=NO_BTN;
							break;
						
						case BTN_C_LONG:
							if(bSelectionTime){
								bState = STATE_MENU;
								bSelectionTime=0;
							}else{
								tTime.bSec = tTimeEditing.bSec;
								tTime.bMin = tTimeEditing.bMin;
								tTime.bHour = tTimeEditing.bHour;
								bState = STATE_MENU;
								LCD_RESET();
							}
							bBtn = NO_BTN;
							bFirst=1;
							break;
						default: break;
					}
				break;
				
/*--------------------------------------------------------------------------------------------------*/
			case STATE_EDIT_TIMEZONE:
				switch(bBtn){
					case NO_BTN:
						if(bFirst){
							bFirst=0;
							LCDClear();
							LCDWriteStringXY(0,0, "Edit timezone:");
							LCDWriteStringXY(0,1,"1=");
							
						}
						break;
					default:
						break;
				}
				break;
			default:
				break;
		}
	}	
}
示例#23
0
//=============================================================================
// Validate the given input string.
//=============================================================================
QValidator::State CDateValidator::validate (QString &input, int &pos) const
{
  int pos1, pos2;

  //---------------------------------------------------------------------------
  //  If input is empty it is Intermediate.
  //---------------------------------------------------------------------------
  if (input.isEmpty())
    return Intermediate;

  //---------------------------------------------------------------------------
  //  All characters besides numbers and dots are invalid.
  //---------------------------------------------------------------------------
  if (input.find (QRegExp ("[^0-9.]")) != -1)
    return Invalid;

  //---------------------------------------------------------------------------
  //  Check how many dots are in the string.
  //---------------------------------------------------------------------------
  switch (input.contains ('.'))
  {
  	//-------------------------------------------------------------------------
  	//  The input string is interpreted as a day.
  	//-------------------------------------------------------------------------
    case 0:
      //-----------------------------------------------------------------------
      //  Check the parts of the date string for correctness.
      //-----------------------------------------------------------------------
      if (checkDate (false, input) == false)
        return Invalid;

      break;

    //-------------------------------------------------------------------------
    //  The input string is interpreted as a day and a month.
    //-------------------------------------------------------------------------
    case 1:
      pos1 = input.find ('.');

      //-----------------------------------------------------------------------
      //  If the last character is a dot, it's OK.
      //-----------------------------------------------------------------------
      if ((input.at (input.length() - 1) == '.') && (input.length() != 1))
      {
        if (checkDate (true, input.left (pos1)) == false)
          return Invalid;
        else
          return Acceptable;
      }

      //-----------------------------------------------------------------------
      //  Check the parts of the date string for correctness.
      //-----------------------------------------------------------------------
      if (checkDate (false, input.left (pos1), input.mid  (pos1 + 1)) == false)
        return Invalid;
      
      break;

    //-------------------------------------------------------------------------
    //  The input string is interpreted as a day, a month and a year.
    //-------------------------------------------------------------------------
    case 2:
      pos1 = input.find ('.');
      pos2 = input.findRev('.');

      //-----------------------------------------------------------------------
      //  Two dots at the end are not allowed.
      //-----------------------------------------------------------------------
      if (input.mid (input.length() - 2) == "..")
        return Invalid;

      //-----------------------------------------------------------------------
      //  If the last character is a dot, it's OK.
      //-----------------------------------------------------------------------
      if (input.at (input.length() - 1) == '.')
      {
        if (checkDate (true, input.left (pos1), 
                       input.mid  (pos1 + 1, pos2 - pos1 - 1)) == false)
          return Invalid;
        else
          return Acceptable;
      }

      //-----------------------------------------------------------------------
      //  Check the parts of the date string for correctness.
      //-----------------------------------------------------------------------
      if (checkDate (false, input.left (pos1),
                     input.mid  (pos1 + 1, pos2 - pos1 - 1),
                     input.mid (pos2 + 1)) == false)
        return Invalid;

      break;

    default:
      return Invalid;
  }
  
  return Acceptable;
}
示例#24
0
int main()
{
  checkDate(0, 3, 14);          // invalid year
  checkDate(1997, 0, 12);       // invalid month
  checkDate(1998, 13, 1);       // invalid month
  checkDate(97, 1, 12);         // invalid year
  checkDate(1999, 2, 29);       // invalid day
  checkDate(1900, 2, 29);       // invalid day

  Date empty(0, 0, 0);
  cout <<"empty: \"" <<empty.ToString() <<"\"\n";
  Date empty2(ChrString(""));
  cout <<"empty2: \"" <<empty2.ToString() <<"\"\n";

  Date d1 = ChrString("20000101");
  Date d2(2000, 3, 1);
  cout <<"Day of week for d1:" <<d1.ToString() <<" == "
       <<DayText[d1.DayOfWeek()] <<endl;
  cout <<"Day of week for d2:" <<d2.ToString() <<" == "
       <<DayText[d2.DayOfWeek()] <<endl;

  Date p1(1996, 2, 29);
  Date p2("20000229");

  cout <<"p1 == " <<p1.ToString() <<endl;
  cout <<"p2 == " <<p2.ToString() <<endl;

  DateStuff::Duration d = p1.AgeBetween(p2);
  cout <<"Duration between p1 and p2: "
       <<d._Year <<" years, "
       <<d._Month <<" months, "
       <<d._Day <<" days\n";

  DateStuff::Duration dd = p1.AgeBetween(d2);
  cout <<"Duration between p1 and d2 (20000301): "
       <<dd._Year <<" years, "
       <<dd._Month <<" months, "
       <<dd._Day <<" days\n";

  if (p1 < p2)
  {
    p1.AddDays(d._Day);
    p1.AddMonths(d._Month);
    p1.AddYears(d._Year);
  }
  else if (p1 > p2)
  {
    p2.AddDays(d._Day);
    p2.AddMonths(d._Month);
    p2.AddYears(d._Year);
  }

  cout <<"p1 == p2 (after adding Duration(p1,p2)): "
       <<((p1 == p2) ? "Yes":"No") <<endl;

  FullDate today;
  Date f(today);
  cout <<"Today: " <<f.ToString() <<endl;
  f.AddWeekDays(2);
  cout <<" +2 weekdays: " <<f.ToString() <<endl;
  f.AddWeekDays(10);
  cout <<" +10 weekdays: " <<f.ToString() <<endl;
  f.AddWeekDays(30);
  cout <<" +30 weekdays: " <<f.ToString() <<endl;
  f.SubtractWeekDays(30);
  cout <<" -30 weekdays: " <<f.ToString() <<endl;
  f.SubtractWeekDays(10);
  cout <<" -10 weekdays: " <<f.ToString() <<endl;
  f.SubtractWeekDays(2);
  cout <<" -2 weekdays: " <<f.ToString() <<endl;

  cout <<"WeekdaysBetween 12/11/96 and 12/13/96: "
       <<Date(1996, 12, 11).WeekDaysBetween(Date(1996, 12, 13))
       <<endl;
  cout <<"WeekdaysBetween 12/13/96 and 12/27/96: "
       <<Date(1996, 12, 13).WeekDaysBetween(Date(1996, 12, 27))
       <<endl;
  cout <<"WeekdaysBetween 12/27/96 and 2/7/97: "
       <<Date(1996, 12, 27).WeekDaysBetween(Date(1997, 2, 7))
       <<endl;

  FullDate f1(d1), f2(d2);
  DateStuff::Duration f12 = f2 - f1;
  cout <<"d1 - d1 == "
       <<f12._Year <<" years, "
       <<f12._Month <<" months, "
       <<f12._Day <<" days\n";
}