示例#1
0
int CUtlBuffer::VaScanf( const char* pFmt, va_list list )
{
	Assert( pFmt );
	if ( m_Error || !IsText() )
		return 0;
	
	int numScanned = 0;
	int nLength;
	char c;
	char* pEnd;
	while ( c = *pFmt++ )
	{
		// Stop if we hit the end of the buffer
		if ( m_Get >= TellMaxPut() )
		{
			m_Error |= GET_OVERFLOW;
			break;
		}

		switch (c)
		{
		case ' ':
			// eat all whitespace
			EatWhiteSpace();
			break;

		case '%':
			{
				// Conversion character... try to convert baby!
				char type = *pFmt++;
				if (type == 0)
					return numScanned;

				switch(type)
				{
				case 'c':
					{
						char* ch = va_arg( list, char * );
						if ( CheckPeekGet( 0, sizeof(char) ) )
						{
							*ch = *(const char*)PeekGet();
							++m_Get;
						}
						else
						{
							*ch = 0;
							return numScanned;
						}
					}
				break;

				case 'i':
				case 'd':
					{
						int* i = va_arg( list, int * );

						// NOTE: This is not bullet-proof; it assumes numbers are < 128 characters
						nLength = 128;
						if ( !CheckArbitraryPeekGet( 0, nLength ) )
						{
							*i = 0;
							return numScanned;
						}

						*i = strtol( (char*)PeekGet(), &pEnd, 10 );
						int nBytesRead = (int)( pEnd - (char*)PeekGet() );
						if ( nBytesRead == 0 )
							return numScanned;
						m_Get += nBytesRead;
					}
					break;
				
				case 'x':
					{
						int* i = va_arg( list, int * );

						// NOTE: This is not bullet-proof; it assumes numbers are < 128 characters
						nLength = 128;
						if ( !CheckArbitraryPeekGet( 0, nLength ) )
						{
							*i = 0;
							return numScanned;
						}

						*i = strtol( (char*)PeekGet(), &pEnd, 16 );
						int nBytesRead = (int)( pEnd - (char*)PeekGet() );
						if ( nBytesRead == 0 )
							return numScanned;
						m_Get += nBytesRead;
					}
					break;
					
				case 'u':
					{
						unsigned int* u = va_arg( list, unsigned int *);

						// NOTE: This is not bullet-proof; it assumes numbers are < 128 characters
						nLength = 128;
						if ( !CheckArbitraryPeekGet( 0, nLength ) )
						{
							*u = 0;
							return numScanned;
						}

						*u = strtoul( (char*)PeekGet(), &pEnd, 10 );
						int nBytesRead = (int)( pEnd - (char*)PeekGet() );
						if ( nBytesRead == 0 )
							return numScanned;
						m_Get += nBytesRead;
					}
					break;
					
				case 'f':
					{
						float* f = va_arg( list, float *);

						// NOTE: This is not bullet-proof; it assumes numbers are < 128 characters
						nLength = 128;
						if ( !CheckArbitraryPeekGet( 0, nLength ) )
						{
							*f = 0.0f;
							return numScanned;
						}

						*f = (float)strtod( (char*)PeekGet(), &pEnd );
						int nBytesRead = (int)( pEnd - (char*)PeekGet() );
						if ( nBytesRead == 0 )
							return numScanned;
						m_Get += nBytesRead;
					}
					break;
					
				case 's':
					{
						char* s = va_arg( list, char * );
						GetString( s );
					}
					break;

				default:
					{
						// unimplemented scanf type
						Assert(0);
						return numScanned;
					}
					break;
				}

				++numScanned;
			}
			break;

		default:
			{
				// Here we have to match the format string character
				// against what's in the buffer or we're done.
				if ( !CheckPeekGet( 0, sizeof(char) ) )
					return numScanned;

				if ( c != *(const char*)PeekGet() )
					return numScanned;

				++m_Get;
			}
		}
	}
	return numScanned;
}
template<> bool str2val< double >( const string& s, double& ret )
{
	// cerr << "in str2val< double >\n";
	ret = strtod( s.c_str(), 0 );
	return 1;
}
示例#3
0
文件: fun.c 项目: code4tots/fun
int extractNumber(char **stringPointer, Token *token) {
  char *start = *stringPointer;
  token->type = TOKEN_TYPE_NUM;
  token->value.number = strtod(start, stringPointer);
  return start < *stringPointer;
}
示例#4
0
static BOOL CALLBACK options_appearance_dialog_handler(HWND hwnd,
		UINT msg, WPARAM wparam, LPARAM lParam)
{
	int len;
	char *temp, number[6];
	HWND sub;

	LOG_WIN_MSG(hwnd, msg, wparam, lParam);

	switch (msg) {
	case WM_INITDIALOG:
		sub = GetDlgItem(hwnd, IDC_PREFS_FONTDEF);
		SendMessage(sub, CB_ADDSTRING, 0, (LPARAM)"Sans serif");
		SendMessage(sub, CB_ADDSTRING, 0, (LPARAM)"Serif");
		SendMessage(sub, CB_ADDSTRING, 0, (LPARAM)"Monospace");
		SendMessage(sub, CB_ADDSTRING, 0, (LPARAM)"Cursive");
		SendMessage(sub, CB_ADDSTRING, 0, (LPARAM)"Fantasy");
		SendMessage(sub, CB_SETCURSEL,
			    (WPARAM) (nsoption_int(font_default) - 1), 0);

		if ((nsoption_charp(font_sans) != NULL) &&
		    (nsoption_charp(font_sans)[0] != '\0')) {
			sub = GetDlgItem(hwnd, IDC_PREFS_SANS);
			SendMessage(sub, WM_SETTEXT, 0,
				    (LPARAM)nsoption_charp(font_sans));
		}
		if ((nsoption_charp(font_serif) != NULL) &&
		    (nsoption_charp(font_serif)[0] != '\0')) {
			sub = GetDlgItem(hwnd, IDC_PREFS_SERIF);
			SendMessage(sub, WM_SETTEXT, 0,
				    (LPARAM)nsoption_charp(font_serif));
		}
		if ((nsoption_charp(font_mono) != NULL) &&
		    (nsoption_charp(font_mono)[0] != '\0')) {
			sub = GetDlgItem(hwnd, IDC_PREFS_MONO);
			SendMessage(sub, WM_SETTEXT, 0,
				    (LPARAM)nsoption_charp(font_mono));
		}
		if ((nsoption_charp(font_cursive) != NULL) &&
		    (nsoption_charp(font_cursive)[0] != '\0')) {
			sub = GetDlgItem(hwnd, IDC_PREFS_CURSIVE);
			SendMessage(sub, WM_SETTEXT, 0,
				    (LPARAM)nsoption_charp(font_cursive));
		}
		if ((nsoption_charp(font_fantasy) != NULL) &&
		    (nsoption_charp(font_fantasy)[0] != '\0')) {
			sub = GetDlgItem(hwnd, IDC_PREFS_FANTASY);
			SendMessage(sub, WM_SETTEXT, 0,
				    (LPARAM)nsoption_charp(font_fantasy));
		}
		if (nsoption_int(font_min_size) != 0) {
			sub = GetDlgItem(hwnd, IDC_PREFS_FONT_MINSIZE);
			snprintf(number, 6, "%.1f", nsoption_int(font_min_size) / 10.0);
			SendMessage(sub, WM_SETTEXT, 0, (LPARAM)number);
		}
		if (nsoption_int(font_size) != 0) {
			sub = GetDlgItem(hwnd, IDC_PREFS_FONT_SIZE);
			snprintf(number, 6, "%.1f", nsoption_int(font_size) / 10.0);
			SendMessage(sub, WM_SETTEXT, 0, (LPARAM)number);
		}
		if (nsoption_int(max_fetchers) != 0) {
			sub = GetDlgItem(hwnd, IDC_PREFS_FETCHERS);
			snprintf(number, 6, "%d", nsoption_int(max_fetchers));
			SendMessage(sub, WM_SETTEXT, 0, (LPARAM)number);
		}
		if (nsoption_int(max_fetchers_per_host) != 0) {
			sub = GetDlgItem(hwnd, IDC_PREFS_FETCH_HOST);
			snprintf(number, 6, "%d",
				 nsoption_int(max_fetchers_per_host));
			SendMessage(sub, WM_SETTEXT, 0, (LPARAM)number);
		}
		if (nsoption_int(max_cached_fetch_handles) != 0) {
			sub = GetDlgItem(hwnd, IDC_PREFS_FETCH_HANDLES);
			snprintf(number, 6, "%d",
				 nsoption_int(max_cached_fetch_handles));
			SendMessage(sub, WM_SETTEXT, 0, (LPARAM)number);
		}


		/* animation */
		sub = GetDlgItem(hwnd, IDC_PREFS_NOANIMATION);
		SendMessage(sub, BM_SETCHECK, (WPARAM)((nsoption_bool(animate_images))
				       ? BST_UNCHECKED : BST_CHECKED),	0);

		if (nsoption_int(minimum_gif_delay) != 0) {
			sub = GetDlgItem(hwnd, IDC_PREFS_ANIMATIONDELAY);
			snprintf(number, 6, "%.1f", nsoption_int(minimum_gif_delay) /
				 100.0);
			SendMessage(sub, WM_SETTEXT, 0, (LPARAM)number);
		}
		break;

	case WM_NOTIFY:
		switch (((NMHDR FAR *)lParam)->code) {
		case PSN_APPLY:
			sub = GetDlgItem(hwnd, IDC_PREFS_FONT_SIZE);
			len = SendMessage(sub, WM_GETTEXTLENGTH, 0, 0);
			temp = malloc(len + 1);
			if (temp != NULL) {
				SendMessage(sub, WM_GETTEXT, (WPARAM)
					    (len + 1), (LPARAM) temp);
				nsoption_int(font_size) = (int)
					(10 * strtod(temp, NULL));
				free(temp);
			}

			sub = GetDlgItem(hwnd, IDC_PREFS_FONT_MINSIZE);
			len = SendMessage(sub, WM_GETTEXTLENGTH, 0, 0);
			temp = malloc(len + 1);
			if (temp != NULL) {
				SendMessage(sub, WM_GETTEXT, (WPARAM)
					    (len + 1), (LPARAM) temp);
				nsoption_set_int(font_min_size, 
						 (int)(10 * strtod(temp, NULL)));
				free(temp);
			}

			/* animation */
			nsoption_set_bool(animate_images, 
					  (IsDlgButtonChecked(hwnd, IDC_PREFS_NOANIMATION) == BST_CHECKED) ? true : false);


			sub = GetDlgItem(hwnd, IDC_PREFS_ANIMATIONDELAY);
			len = SendMessage(sub, WM_GETTEXTLENGTH, 0, 0);
			temp = malloc(len + 1);
			if (temp != NULL) {
				SendMessage(sub, WM_GETTEXT, (WPARAM)
					    (len + 1), (LPARAM) temp);
				nsoption_set_int(minimum_gif_delay,
						 (int)(100 * strtod(temp, NULL)));
				free(temp);
			}

			break;

		case UDN_DELTAPOS: {
			NMUPDOWN *ud = (NMUPDOWN *)lParam;
			switch(((NMHDR *)lParam)->idFrom) {
			case IDC_PREFS_FONT_SIZE_SPIN:
				change_spinner(GetDlgItem(hwnd, IDC_PREFS_FONT_SIZE), 0.1  * ud->iDelta, 1.0, 50.0);
				return TRUE;

			case IDC_PREFS_FONT_MINSIZE_SPIN:
				change_spinner(GetDlgItem(hwnd, IDC_PREFS_FONT_MINSIZE), 0.1  * ud->iDelta, 1.0, 50.0);
				return TRUE;

			case IDC_PREFS_ANIMATIONDELAY_SPIN:
				change_spinner(GetDlgItem(hwnd, IDC_PREFS_ANIMATIONDELAY), 0.1  * ud->iDelta, 0.1, 100.0);
				return TRUE;
				
			}
		}
			break;
		}


	case WM_COMMAND:
		LOG(("WM_COMMAND Identifier 0x%x",LOWORD(wparam)));

		switch(LOWORD(wparam)) {
		case IDC_PREFS_PROXYTYPE:
			sub = GetDlgItem(hwnd, IDC_PREFS_PROXYTYPE);
			nsoption_set_int(http_proxy_auth,
					 SendMessage(sub, CB_GETCURSEL, 0, 0) - 1);
			nsoption_set_bool(http_proxy,
					  (nsoption_int(http_proxy_auth) != -1));
			nsoption_set_int(http_proxy_auth,  
					 nsoption_int(http_proxy_auth) + 
					 (nsoption_bool(http_proxy)) ? 0 : 1);
			break;

		case IDC_PREFS_SANS: {
			CHOOSEFONT *cf = nsws_prefs_font_prepare(FF_SWISS, hwnd);
			if (cf == NULL) {
				break;
			}

			if (ChooseFont(cf) == TRUE) {
				nsoption_set_charp(font_sans, 
						   strdup(cf->lpLogFont->lfFaceName));
			}

			free(cf->lpLogFont);
			free(cf);
			if ((nsoption_charp(font_sans) != NULL) &&
			    (nsoption_charp(font_sans)[0] != '\0')) {
				sub = GetDlgItem(hwnd, IDC_PREFS_SANS);
				SendMessage(sub, WM_SETTEXT, 0,
					    (LPARAM)nsoption_charp(font_sans));
			}
			break;
		}

		case IDC_PREFS_SERIF: {
			CHOOSEFONT *cf = nsws_prefs_font_prepare(FF_ROMAN, hwnd);
			if (cf == NULL) {
				break;
			}

			if (ChooseFont(cf) == TRUE) {
				nsoption_set_charp(font_serif,
						   strdup(cf->lpLogFont->lfFaceName));
			}

			free(cf->lpLogFont);
			free(cf);
			if ((nsoption_charp(font_serif) != NULL) &&
			    (nsoption_charp(font_serif)[0] != '\0')) {
				sub = GetDlgItem(hwnd, IDC_PREFS_SERIF);
				SendMessage(sub, WM_SETTEXT, 0,
					    (LPARAM)nsoption_charp(font_serif));
			}
			break;
		}

		case IDC_PREFS_MONO: {
			CHOOSEFONT *cf = nsws_prefs_font_prepare(FF_MODERN, hwnd);
			if (cf == NULL) {
				break;
			}

			if (ChooseFont(cf) == TRUE) {
				nsoption_set_charp(font_mono,
						   strdup(cf->lpLogFont->lfFaceName));
			}

			free(cf->lpLogFont);
			free(cf);

			if ((nsoption_charp(font_mono) != NULL) &&
			    (nsoption_charp(font_mono)[0] != '\0')) {
				sub = GetDlgItem(hwnd, IDC_PREFS_MONO);
				SendMessage(sub, WM_SETTEXT, 0,
					    (LPARAM)nsoption_charp(font_mono));
			}
			break;
		}

		case IDC_PREFS_CURSIVE: {
			CHOOSEFONT *cf = nsws_prefs_font_prepare(FF_SCRIPT, hwnd);
			if (cf == NULL) {
				break;
			}

			if (ChooseFont(cf) == TRUE) {
				nsoption_set_charp(font_cursive,
						   strdup(cf->lpLogFont->lfFaceName));
			}
			free(cf->lpLogFont);
			free(cf);
			if ((nsoption_charp(font_cursive) != NULL) &&
			    (nsoption_charp(font_cursive)[0] != '\0')) {
				sub = GetDlgItem(hwnd, IDC_PREFS_CURSIVE);
				SendMessage(sub, WM_SETTEXT, 0,
					    (LPARAM)nsoption_charp(font_cursive));
			}
			break;
		}

		case IDC_PREFS_FANTASY: {
			CHOOSEFONT *cf = nsws_prefs_font_prepare(FF_DECORATIVE, hwnd);
			if (cf == NULL) {
				break;
			}

			if (ChooseFont(cf) == TRUE) {
				nsoption_set_charp(font_fantasy,
						   strdup(cf->lpLogFont->lfFaceName));
			}
			free(cf->lpLogFont);
			free(cf);
			if ((nsoption_charp(font_fantasy) != NULL) &&
			    (nsoption_charp(font_fantasy)[0] != '\0')) {
				sub = GetDlgItem(hwnd, IDC_PREFS_FANTASY);
				SendMessage(sub, WM_SETTEXT, 0,
					    (LPARAM)nsoption_charp(font_fantasy));
			}
			break;
		}

		case IDC_PREFS_FONTDEF: 
			sub = GetDlgItem(hwnd, IDC_PREFS_FONTDEF);
			nsoption_set_int(font_default,
					 SendMessage(sub, CB_GETCURSEL, 0, 0) + 1);
			break;
		
		}
		break;

	}
	return FALSE;
}
示例#5
0
static int ParseSizeString(const char *size, double *res)
{
#define MAX_SUBSTRINGS 30
    int pcre_exec_ret;
    int r;
    int ov[MAX_SUBSTRINGS];
    int retval = 0;
    char str[128];
    char str2[128];

    *res = 0;

    pcre_exec_ret = pcre_exec(parse_regex, parse_regex_study, size, strlen(size), 0, 0,
                    ov, MAX_SUBSTRINGS);
    if (!(pcre_exec_ret == 2 || pcre_exec_ret == 3)) {
        SCLogError(SC_ERR_PCRE_MATCH, "invalid size argument - %s. Valid size "
                   "argument should be in the format - \n"
                   "xxx <- indicates it is just bytes\n"
                   "xxxkb or xxxKb or xxxKB or xxxkB <- indicates kilobytes\n"
                   "xxxmb or xxxMb or xxxMB or xxxmB <- indicates megabytes\n"
                   "xxxgb or xxxGb or xxxGB or xxxgB <- indicates gigabytes.\n",
                   size);
        retval = -2;
        goto end;
    }

    r = pcre_copy_substring((char *)size, ov, MAX_SUBSTRINGS, 1,
                             str, sizeof(str));
    if (r < 0) {
        SCLogError(SC_ERR_PCRE_GET_SUBSTRING, "pcre_copy_substring failed");
        retval = -2;
        goto end;
    }

    char *endptr, *str_ptr = str;
    errno = 0;
    *res = strtod(str_ptr, &endptr);
    if (errno == ERANGE) {
        SCLogError(SC_ERR_NUMERIC_VALUE_ERANGE, "Numeric value out of range");
        retval = -1;
        goto end;
    } else if (endptr == str_ptr) {
        SCLogError(SC_ERR_INVALID_NUMERIC_VALUE, "Invalid numeric value");
        retval = -1;
        goto end;
    }

    if (pcre_exec_ret == 3) {
        r = pcre_copy_substring((char *)size, ov, MAX_SUBSTRINGS, 2,
                                 str2, sizeof(str2));
        if (r < 0) {
            SCLogError(SC_ERR_PCRE_GET_SUBSTRING, "pcre_copy_substring failed");
            retval = -2;
            goto end;
        }

        if (strcasecmp(str2, "kb") == 0) {
            *res *= 1024;
        } else if (strcasecmp(str2, "mb") == 0) {
            *res *= 1024 * 1024;
        } else if (strcasecmp(str2, "gb") == 0) {
            *res *= 1024 * 1024 * 1024;
        } else {
            /* not possible */
            BUG_ON(1);
        }
    }

    retval = 0;
end:
    return retval;
}
int main( int argc , char *argv[] )
{
   double val , p , p1=0.0,p2=0.0,p3=0.0 ;
   double vbot,vtop,vdel ;
   int code , iarg=1 , doq=0 , dod=0 , doi=0 , doz=0 , doh=0 ;

   /*-- print some help for the pitiful user --*/

   if( argc < 3 || strstr(argv[1],"help") != NULL ){
    int ii ;
    printf("\n") ;
    printf("Demo program for computing NIfTI statistical functions.\n") ;
    printf("Usage: nifti_stats [-q|-d|-1|-z] val CODE [p1 p2 p3]\n") ;
    printf(" val can be a single number or in the form bot:top:step.\n") ;
    printf(" default ==> output p = Prob(statistic < val).\n") ;
    printf("  -q     ==> output is 1-p.\n") ;
    printf("  -d     ==> output is density.\n") ;
    printf("  -1     ==> output is x such that Prob(statistic < x) = val.\n") ;
    printf("  -z     ==> output is z such that Normal cdf(z) = p(val).\n") ;
    printf("  -h     ==> output is z such that 1/2-Normal cdf(z) = p(val).\n");
    printf(" Allowable CODEs:\n") ;
    for( ii=NIFTI_FIRST_STATCODE ; ii <= NIFTI_LAST_STATCODE ; ii++ ){
     printf("  %-10s",inam[ii]); if((ii-NIFTI_FIRST_STATCODE)%6==5)printf("\n");
    }
    printf("\n") ;
    printf(" Following CODE are distributional parameters, as needed.\n");
    printf("\n") ;
    printf("Results are written to stdout, 1 number per output line.\n") ;
    printf("Example (piping output into AFNI program 1dplot):\n") ;
    printf(" nifti_stats -d 0:4:.001 INVGAUSS 1 3 | 1dplot -dx 0.001 -stdin\n");
    printf("\n") ;
    printf("Author - RW Cox - SSCC/NIMH/NIH/DHHS/USA/EARTH - March 2004\n") ;
    printf("\n") ;
    exit(0) ;
   }

   /*-- check first arg to see if it is an output option;
        if so, set the appropriate output flag to determine what to compute --*/

        if( strcmp(argv[iarg],"-q") == 0 ){ doq = 1 ; iarg++ ; }
   else if( strcmp(argv[iarg],"-d") == 0 ){ dod = 1 ; iarg++ ; }
   else if( strcmp(argv[iarg],"-1") == 0 ){ doi = 1 ; iarg++ ; }
   else if( strcmp(argv[iarg],"-z") == 0 ){ doz = 1 ; iarg++ ; }
   else if( strcmp(argv[iarg],"-h") == 0 ){ doh = 1 ; iarg++ ; }

   /*-- get the value(s) to process --*/

   vbot=vtop=vdel = 0.0 ;
   sscanf( argv[iarg++] , "%lf:%lf:%lf" , &vbot,&vtop,&vdel ) ;
   if( vbot >= vtop ) vdel = 0.0 ;
   if( vdel <= 0.0  ) vtop = vbot ;

   /*-- decode the CODE into the integer signifying the distribution --*/

   code = nifti_intent_code(argv[iarg++]) ;
     if( code < 0 ){ fprintf(stderr,"illegal code=%s\n",argv[iarg-1]); exit(1); }

   /*-- get the parameters, if present (defaults are 0) --*/

   if( argc > iarg ) p1 = strtod(argv[iarg++],NULL) ;
   if( argc > iarg ) p2 = strtod(argv[iarg++],NULL) ;
   if( argc > iarg ) p3 = strtod(argv[iarg++],NULL) ;

   /*-- loop over input value(s), compute output, write to stdout --*/

   for( val=vbot ; val <= vtop ; val += vdel ){
     if( doq )                                        /* output = 1-cdf */
       p = nifti_stat2rcdf( val , code,p1,p2,p3 ) ;
     else if( dod )                                   /* output = density */
       p = 1000.0*( nifti_stat2cdf(val+.001,code,p1,p2,p3)
                   -nifti_stat2cdf(val     ,code,p1,p2,p3)) ;
     else if( doi )                                   /* output = inverse */
       p = nifti_cdf2stat( val , code,p1,p2,p3 ) ;
     else if( doz )                                   /* output = z score */
       p = nifti_stat2zscore( val , code,p1,p2,p3 ) ;
     else if( doh )                                   /* output = halfz score */
       p = nifti_stat2hzscore( val , code,p1,p2,p3 ) ;
     else                                              /* output = cdf */
       p = nifti_stat2cdf( val , code,p1,p2,p3 ) ;

     printf("%.9g\n",p) ;
     if( vdel <= 0.0 ) break ;  /* the case of just 1 value */
   }

   /*-- terminus est --*/

   exit(0) ;
}
void read_problem(const char *filename)
{
	int elements, max_index, inst_max_index, i, j;
	FILE *fp = fopen(filename,"r");
	char *endptr;
	char *idx, *val, *label;

	if(fp == NULL)
	{
		fprintf(stderr,"can't open input file %s\n",filename);
		exit(1);
	}

	prob.l = 0;
	elements = 0;

	max_line_len = 1024;
	line = Malloc(char,max_line_len);
	while(readline(fp)!=NULL)
	{
		char *p = strtok(line," \t"); // label

		// features
		while(1)
		{
			p = strtok(NULL," \t");
			if(p == NULL || *p == '\n') // check '\n' as ' ' may be after the last feature
				break;
			++elements;
		}
		++elements;
		++prob.l;
	}
	rewind(fp);

	prob.y = Malloc(double,prob.l);
	prob.x = Malloc(struct svm_node *,prob.l);
	x_space = Malloc(struct svm_node,elements);

	max_index = 0;
	j=0;
	for(i=0;i<prob.l;i++)
	{
		inst_max_index = -1; // strtol gives 0 if wrong format, and precomputed kernel has <index> start from 0
		readline(fp);
		prob.x[i] = &x_space[j];
		label = strtok(line," \t\n");
		if(label == NULL) // empty line
			exit_input_error(i+1);

		prob.y[i] = strtod(label,&endptr);
		if(endptr == label || *endptr != '\0')
			exit_input_error(i+1);

		while(1)
		{
			idx = strtok(NULL,":");
			val = strtok(NULL," \t");

			if(val == NULL)
				break;

			errno = 0;
			x_space[j].index = (int) strtol(idx,&endptr,10);
			if(endptr == idx || errno != 0 || *endptr != '\0' || x_space[j].index <= inst_max_index)
				exit_input_error(i+1);
			else
				inst_max_index = x_space[j].index;

			errno = 0;
			x_space[j].value = strtod(val,&endptr);
			if(endptr == val || errno != 0 || (*endptr != '\0' && !isspace(*endptr)))
				exit_input_error(i+1);

			++j;
		}

		if(inst_max_index > max_index)
			max_index = inst_max_index;
		x_space[j++].index = -1;
	}

	if(param.gamma == 0 && max_index > 0)
		param.gamma = 1.0/max_index;

	if(param.kernel_type == PRECOMPUTED)
		for(i=0;i<prob.l;i++)
		{
			if (prob.x[i][0].index != 0)
			{
				fprintf(stderr,"Wrong input format: first column must be 0:sample_serial_number\n");
				exit(1);
			}
			if ((int)prob.x[i][0].value <= 0 || (int)prob.x[i][0].value > max_index)
			{
				fprintf(stderr,"Wrong input format: sample_serial_number out of range\n");
				exit(1);
			}
		}

	fclose(fp);
}
示例#8
0
int gmx_wheel(int argc, char *argv[])
{
    const char     *desc[] = {
        "[THISMODULE] plots a helical wheel representation of your sequence.",
        "The input sequence is in the [REF].dat[ref] file where the first line contains",
        "the number of residues and each consecutive line contains a residue "
        "name."
    };
    output_env_t    oenv;
    static real     rot0  = 0;
    static gmx_bool bNum  = TRUE;
    static char    *title = NULL;
    static int      r0    = 1;
    t_pargs         pa [] = {
        { "-r0",  FALSE, etINT, {&r0},
          "The first residue number in the sequence" },
        { "-rot0", FALSE, etREAL, {&rot0},
          "Rotate around an angle initially (90 degrees makes sense)" },
        { "-T",   FALSE, etSTR, {&title},
          "Plot a title in the center of the wheel (must be shorter than 10 characters, or it will overwrite the wheel)" },
        { "-nn",  FALSE, etBOOL, {&bNum},
          "Toggle numbers" }
    };
    t_filenm        fnm[] = {
        { efDAT, "-f", NULL,  ffREAD  },
        { efEPS, "-o", NULL,  ffWRITE }
    };
#define NFILE asize(fnm)

    int    i, nres;
    char **resnm;

    if (!parse_common_args(&argc, argv, 0, NFILE, fnm, asize(pa), pa,
                           asize(desc), desc, 0, NULL, &oenv))
    {
        return 0;
    }

    for (i = 1; (i < argc); i++)
    {
        if (std::strcmp(argv[i], "-r0") == 0)
        {
            r0 = std::strtol(argv[++i], NULL, 10);
            fprintf(stderr, "First residue is %d\n", r0);
        }
        else if (std::strcmp(argv[i], "-rot0") == 0)
        {
            rot0 = strtod(argv[++i], NULL);
            fprintf(stderr, "Initial rotation is %g\n", rot0);
        }
        else if (std::strcmp(argv[i], "-T") == 0)
        {
            title = gmx_strdup(argv[++i]);
            fprintf(stderr, "Title will be '%s'\n", title);
        }
        else if (std::strcmp(argv[i], "-nn") == 0)
        {
            bNum = FALSE;
            fprintf(stderr, "No residue numbers\n");
        }
        else
        {
            gmx_fatal(FARGS, "Incorrect usage of option %s", argv[i]);
        }
    }

    nres = get_lines(ftp2fn(efDAT, NFILE, fnm), &resnm);
    if (bNum)
    {
        wheel(ftp2fn(efEPS, NFILE, fnm), nres, resnm, r0, rot0, title);
    }
    else
    {
        wheel2(ftp2fn(efEPS, NFILE, fnm), nres, resnm, rot0, title);
    }

    return 0;
}
double QDecSingle::toDouble() const
{
  char str[MaxStrSize] = {0};
  decSingleToString(&m_data, str);
  return strtod(str, 0);
}
示例#10
0
文件: geod.c 项目: Maasik/proj.4
	static void	/* file processing function */
process(FILE *fid) {
	char line[MAXLINE+3], *s;

	for (;;) {
		++emess_dat.File_line;
		if (!(s = fgets(line, MAXLINE, fid)))
			break;
		if (!strchr(s, '\n')) { /* overlong line */
			int c;
			strcat(s, "\n");
			/* gobble up to newline */
			while ((c = fgetc(fid)) != EOF && c != '\n') ;
		}
		if (*s == tag) {
			fputs(line, stdout);
			continue;
		}
		phi1 = dmstor(s, &s);
		lam1 = dmstor(s, &s);
		if (inverse) {
			phi2 = dmstor(s, &s);
			lam2 = dmstor(s, &s);
			geod_inv();
		} else {
			al12 = dmstor(s, &s);
			geod_S = strtod(s, &s) * to_meter;
			geod_pre();
			geod_for();
		}
		if (!*s && (s > line)) --s; /* assumed we gobbled \n */
		if (pos_azi) {
			if (al12 < 0.) al12 += M_TWOPI;
			if (al21 < 0.) al21 += M_TWOPI;
		}
		if (fullout) {
			printLL(phi1, lam1); TAB;
			printLL(phi2, lam2); TAB;
			if (oform) {
				(void)printf(oform, al12 * RAD_TO_DEG); TAB;
				(void)printf(oform, al21 * RAD_TO_DEG); TAB;
				(void)printf(osform, geod_S * fr_meter);
			}  else {
				(void)fputs(rtodms(pline, al12, 0, 0), stdout); TAB;
				(void)fputs(rtodms(pline, al21, 0, 0), stdout); TAB;
				(void)printf(osform, geod_S * fr_meter);
			}
		} else if (inverse)
			if (oform) {
				(void)printf(oform, al12 * RAD_TO_DEG); TAB;
				(void)printf(oform, al21 * RAD_TO_DEG); TAB;
				(void)printf(osform, geod_S * fr_meter);
			} else {
				(void)fputs(rtodms(pline, al12, 0, 0), stdout); TAB;
				(void)fputs(rtodms(pline, al21, 0, 0), stdout); TAB;
				(void)printf(osform, geod_S * fr_meter);
			}
		else {
			printLL(phi2, lam2); TAB;
			if (oform)
				(void)printf(oform, al21 * RAD_TO_DEG);
			else
				(void)fputs(rtodms(pline, al21, 0, 0), stdout);
		}
		(void)fputs(s, stdout);
	}
}
示例#11
0
文件: store.c 项目: kwirk/systemd
void log_sample(int sample, struct list_sample_data **ptr) {
        static int vmstat;
        static int schedstat;
        char buf[4096];
        char key[256];
        char val[256];
        char rt[256];
        char wt[256];
        char *m;
        int c;
        int p;
        int mod;
        static int e_fd;
        ssize_t s;
        ssize_t n;
        struct dirent *ent;
        int fd;
        struct list_sample_data *sampledata;
        struct ps_sched_struct *ps_prev = NULL;



        sampledata = *ptr;

        /* all the per-process stuff goes here */
        if (!proc) {
                /* find all processes */
                proc = opendir("/proc");
                if (!proc)
                        return;
                procfd = dirfd(proc);
        } else {
                rewinddir(proc);
        }

        if (!vmstat) {
                /* block stuff */
                vmstat = openat(procfd, "vmstat", O_RDONLY);
                if (vmstat == -1) {
                        perror("open /proc/vmstat");
                        exit (EXIT_FAILURE);
                }
        }

        n = pread(vmstat, buf, sizeof(buf) - 1, 0);
        if (n <= 0) {
                close(vmstat);
                return;
        }
        buf[n] = '\0';

        m = buf;
        while (m) {
                if (sscanf(m, "%s %s", key, val) < 2)
                        goto vmstat_next;
                if (streq(key, "pgpgin"))
                        sampledata->blockstat.bi = atoi(val);
                if (streq(key, "pgpgout")) {
                        sampledata->blockstat.bo = atoi(val);
                        break;
                }
vmstat_next:
                m = bufgetline(m);
                if (!m)
                        break;
        }

        if (!schedstat) {
                /* overall CPU utilization */
                schedstat = openat(procfd, "schedstat", O_RDONLY);
                if (schedstat == -1) {
                        perror("open /proc/schedstat");
                        exit (EXIT_FAILURE);
                }
        }

        n = pread(schedstat, buf, sizeof(buf) - 1, 0);
        if (n <= 0) {
                close(schedstat);
                return;
        }
        buf[n] = '\0';

        m = buf;
        while (m) {
                if (sscanf(m, "%s %*s %*s %*s %*s %*s %*s %s %s", key, rt, wt) < 3)
                        goto schedstat_next;

                if (strstr(key, "cpu")) {
                        c = atoi((const char*)(key+3));
                        if (c > MAXCPUS)
                                /* Oops, we only have room for MAXCPUS data */
                                break;
                        sampledata->runtime[c] = atoll(rt);
                        sampledata->waittime[c] = atoll(wt);

                        if (c == cpus)
                                cpus = c + 1;
                }
schedstat_next:
                m = bufgetline(m);
                if (!m)
                        break;
        }

        if (arg_entropy) {
                if (!e_fd) {
                        e_fd = openat(procfd, "sys/kernel/random/entropy_avail", O_RDONLY);
                }

                if (e_fd) {
                        n = pread(e_fd, buf, sizeof(buf) - 1, 0);
                        if (n > 0) {
                                buf[n] = '\0';
                                sampledata->entropy_avail = atoi(buf);
                        }
                }
        }

        while ((ent = readdir(proc)) != NULL) {
                char filename[PATH_MAX];
                int pid;
                struct ps_struct *ps;

                if ((ent->d_name[0] < '0') || (ent->d_name[0] > '9'))
                        continue;

                pid = atoi(ent->d_name);

                if (pid >= MAXPIDS)
                        continue;

                ps = ps_first;
                while (ps->next_ps) {
                        ps = ps->next_ps;
                        if (ps->pid == pid)
                                break;
                }

                /* end of our LL? then append a new record */
                if (ps->pid != pid) {
                        _cleanup_fclose_ FILE *st = NULL;
                        char t[32];
                        struct ps_struct *parent;

                        ps->next_ps = calloc(1, sizeof(struct ps_struct));
                        if (!ps->next_ps) {
                                perror("calloc(ps_struct)");
                                exit (EXIT_FAILURE);
                        }
                        ps = ps->next_ps;
                        ps->pid = pid;

                        ps->sample = calloc(1, sizeof(struct ps_sched_struct));
                        if (!ps->sample) {
                                perror("calloc(ps_struct)");
                                exit (EXIT_FAILURE);
                        }
                        ps->sample->sampledata = sampledata;

                        pscount++;

                        /* mark our first sample */
                        ps->first = ps->sample;
                        ps->sample->runtime = atoll(rt);
                        ps->sample->waittime = atoll(wt);

                        /* get name, start time */
                        if (!ps->sched) {
                                sprintf(filename, "%d/sched", pid);
                                ps->sched = openat(procfd, filename, O_RDONLY);
                                if (ps->sched == -1)
                                        continue;
                        }

                        s = pread(ps->sched, buf, sizeof(buf) - 1, 0);
                        if (s <= 0) {
                                close(ps->sched);
                                continue;
                        }
                        buf[s] = '\0';

                        if (!sscanf(buf, "%s %*s %*s", key))
                                continue;

                        strscpy(ps->name, sizeof(ps->name), key);

                        /* cmdline */
                        if (arg_show_cmdline)
                                pid_cmdline_strscpy(ps->name, sizeof(ps->name), pid);

                        /* discard line 2 */
                        m = bufgetline(buf);
                        if (!m)
                                continue;

                        m = bufgetline(m);
                        if (!m)
                                continue;

                        if (!sscanf(m, "%*s %*s %s", t))
                                continue;

                        ps->starttime = strtod(t, NULL) / 1000.0;

                        /* ppid */
                        sprintf(filename, "%d/stat", pid);
                        fd = openat(procfd, filename, O_RDONLY);
                        st = fdopen(fd, "r");
                        if (!st)
                                continue;
                        if (!fscanf(st, "%*s %*s %*s %i", &p)) {
                                continue;
                        }
                        ps->ppid = p;

                        /*
                         * setup child pointers
                         *
                         * these are used to paint the tree coherently later
                         * each parent has a LL of children, and a LL of siblings
                         */
                        if (pid == 1)
                                continue; /* nothing to do for init atm */

                        /* kthreadd has ppid=0, which breaks our tree ordering */
                        if (ps->ppid == 0)
                                ps->ppid = 1;

                        parent = ps_first;
                        while ((parent->next_ps && parent->pid != ps->ppid))
                                parent = parent->next_ps;

                        if ((!parent) || (parent->pid != ps->ppid)) {
                                /* orphan */
                                ps->ppid = 1;
                                parent = ps_first->next_ps;
                        }

                        ps->parent = parent;

                        if (!parent->children) {
                                /* it's the first child */
                                parent->children = ps;
                        } else {
                                /* walk all children and append */
                                struct ps_struct *children;
                                children = parent->children;
                                while (children->next)
                                        children = children->next;
                                children->next = ps;
                        }
                }

                /* else -> found pid, append data in ps */

                /* below here is all continuous logging parts - we get here on every
                 * iteration */

                /* rt, wt */
                if (!ps->schedstat) {
                        sprintf(filename, "%d/schedstat", pid);
                        ps->schedstat = openat(procfd, filename, O_RDONLY);
                        if (ps->schedstat == -1)
                                continue;
                }
                s = pread(ps->schedstat, buf, sizeof(buf) - 1, 0);
                if (s <= 0) {
                        /* clean up our file descriptors - assume that the process exited */
                        close(ps->schedstat);
                        if (ps->sched)
                                close(ps->sched);
                        //if (ps->smaps)
                        //        fclose(ps->smaps);
                        continue;
                }
                buf[s] = '\0';

                if (!sscanf(buf, "%s %s %*s", rt, wt))
                        continue;

                ps->sample->next = calloc(1, sizeof(struct ps_sched_struct));
                if (!ps->sample) {
                        perror("calloc(ps_struct)");
                        exit (EXIT_FAILURE);
                }
                ps->sample->next->prev = ps->sample;
                ps->sample = ps->sample->next;
                ps->last = ps->sample;
                ps->sample->runtime = atoll(rt);
                ps->sample->waittime = atoll(wt);
                ps->sample->sampledata = sampledata;
                ps->sample->ps_new = ps;
                if (ps_prev) {
                        ps_prev->cross = ps->sample;
                }
                ps_prev = ps->sample;
                ps->total = (ps->last->runtime - ps->first->runtime)
                            / 1000000000.0;

                if (!arg_pss)
                        goto catch_rename;

                /* Pss */
                if (!ps->smaps) {
                        sprintf(filename, "%d/smaps", pid);
                        fd = openat(procfd, filename, O_RDONLY);
                        ps->smaps = fdopen(fd, "r");
                        if (!ps->smaps)
                                continue;
                        setvbuf(ps->smaps, smaps_buf, _IOFBF, sizeof(smaps_buf));
                }
                else {
                        rewind(ps->smaps);
                }
                /* test to see if we need to skip another field */
                if (skip == 0) {
                        if (fgets(buf, sizeof(buf), ps->smaps) == NULL) {
                                continue;
                        }
                        if (fread(buf, 1, 28 * 15, ps->smaps) != (28 * 15)) {
                                continue;
                        }
                        if (buf[392] == 'V') {
                                skip = 2;
                        }
                        else {
                                skip = 1;
                        }
                        rewind(ps->smaps);
                }
                while (1) {
                        int pss_kb;

                        /* skip one line, this contains the object mapped. */
                        if (fgets(buf, sizeof(buf), ps->smaps) == NULL) {
                                break;
                        }
                        /* then there's a 28 char 14 line block */
                        if (fread(buf, 1, 28 * 14, ps->smaps) != 28 * 14) {
                                break;
                        }
                        pss_kb = atoi(&buf[61]);
                        ps->sample->pss += pss_kb;

                        /* skip one more line if this is a newer kernel */
                        if (skip == 2) {
                               if (fgets(buf, sizeof(buf), ps->smaps) == NULL)
                                       break;
                        }
                }
                if (ps->sample->pss > ps->pss_max)
                        ps->pss_max = ps->sample->pss;

catch_rename:
                /* catch process rename, try to randomize time */
                mod = (arg_hz < 4.0) ? 4.0 : (arg_hz / 4.0);
                if (((samples - ps->pid) + pid) % (int)(mod) == 0) {

                        /* re-fetch name */
                        /* get name, start time */
                        if (!ps->sched) {
                                sprintf(filename, "%d/sched", pid);
                                ps->sched = openat(procfd, filename, O_RDONLY);
                                if (ps->sched == -1)
                                        continue;
                        }
                        s = pread(ps->sched, buf, sizeof(buf) - 1, 0);
                        if (s <= 0) {
                                /* clean up file descriptors */
                                close(ps->sched);
                                if (ps->schedstat)
                                        close(ps->schedstat);
                                //if (ps->smaps)
                                //        fclose(ps->smaps);
                                continue;
                        }
                        buf[s] = '\0';

                        if (!sscanf(buf, "%s %*s %*s", key))
                                continue;

                        strscpy(ps->name, sizeof(ps->name), key);

                        /* cmdline */
                        if (arg_show_cmdline)
                                pid_cmdline_strscpy(ps->name, sizeof(ps->name), pid);
                }
        }
}
示例#12
0
static int
startElement_METRICS(void *data, const char *el, const char **attr)
{
   xmldata_t *xmldata = (xmldata_t *)data;
   struct xml_tag *xt;
   struct type_tag *tt;
   datum_t *hash_datum = NULL;
   datum_t *rdatum;
   datum_t hashkey, hashval;
   const char *name = NULL;
   const char *metricval = NULL;
   const char *metricnum = NULL;
   const char *type = NULL;
   int i;
   hash_t *summary;
   Metric_t *metric;

   /* In non-scalable mode, we do not process summary data. */
   if (!gmetad_config.scalable_mode) return 0;
   
   /* Get name for hash key, and val/type for summaries. */
   for(i = 0; attr[i]; i+=2)
      {
         xt = in_xml_list(attr[i], strlen(attr[i]));
         if (!xt) continue;

         switch (xt->tag)
            {
               case NAME_TAG:
                  name = attr[i+1];
                  hashkey.data = (void*) name;
                  hashkey.size =  strlen(name) + 1;
                  break;
               case TYPE_TAG:
                  type = attr[i+1];
                  break;
               case SUM_TAG:
                  metricval = attr[i+1];
                  break;
               case NUM_TAG:
                  metricnum = attr[i+1];
               default:
                  break;
            }
      }

   summary = xmldata->source.metric_summary;
   hash_datum = hash_lookup(&hashkey, summary);
   if (!hash_datum)
      {
         metric = &(xmldata->metric);
         memset((void*) metric, 0, sizeof(*metric));
         fillmetric(attr, metric, type);
      }
   else
      {
         memcpy(&xmldata->metric, hash_datum->data, hash_datum->size);
         datum_free(hash_datum);
         metric = &(xmldata->metric);

         tt = in_type_list(type, strlen(type));
         if (!tt) return 0;
         switch (tt->type)
               {
                  case INT:
                  case UINT:
                  case FLOAT:
                     metric->val.d += (double)
                             strtod(metricval, (char**) NULL);
                     break;
                  default:
                     break;
               }
            metric->num += atoi(metricnum);
         }

   /* Update metric in summary table. */
   hashval.size = sizeof(*metric) - GMETAD_FRAMESIZE + metric->stringslen;
   hashval.data = (void*) metric;

   summary = xmldata->source.metric_summary;
   rdatum = hash_insert(&hashkey, &hashval, summary);
   if (!rdatum) {
      err_msg("Could not insert %s metric", name);
      return 1;
   }
   return 0;
}
示例#13
0
/* Populates a Metric_t structure from a list of XML metric attribute strings.
 * We need the type string here because we cannot be sure it comes before
 * the metric value in the attribute list.
 */
static void
fillmetric(const char** attr, Metric_t *metric, const char* type)
{
   int i;
   /* INV: always points to the next free byte in metric.strings buffer. */
   int edge = 0;
   struct type_tag *tt;
   struct xml_tag *xt;
   char *metricval, *p;

   /* For old versions of gmond. */
   metric->slope = -1;

   for(i = 0; attr[i] ; i+=2)
      {
         /* Only process the XML tags that gmetad is interested in */
         xt = in_xml_list (attr[i], strlen(attr[i]));
         if (!xt)
            continue;

         switch( xt->tag )
            {
               case SUM_TAG:
               case VAL_TAG:
                  metricval = (char*) attr[i+1];

                  tt = in_type_list(type, strlen(type));
                  if (!tt) return;

                  switch (tt->type)
                     {
                        case INT:
                        case TIMESTAMP:
                        case UINT:
                        case FLOAT:
                           metric->val.d = (double)
                                   strtod(metricval, (char**) NULL);
                           p = strrchr(metricval, '.');
                           if (p) metric->precision = (short int) strlen(p+1);
                           break;
                        case STRING:
                           /* We store string values in the 'valstr' field. */
                           break;
                     }
                  metric->valstr = addstring(metric->strings, &edge, metricval);
                  break;
               case TYPE_TAG:
                  metric->type = addstring(metric->strings, &edge, attr[i+1]);
                  break;
               case UNITS_TAG:
                  metric->units = addstring(metric->strings, &edge, attr[i+1]);
                  break;
               case TN_TAG:
                  metric->tn = atoi(attr[i+1]);
                  break;
               case TMAX_TAG:
                  metric->tmax = atoi(attr[i+1]);
                  break;
               case DMAX_TAG:
                  metric->dmax = atoi(attr[i+1]);
                  break;
               case SLOPE_TAG:
                  metric->slope = addstring(metric->strings, &edge, attr[i+1]);
                  break;
               case SOURCE_TAG:
                  metric->source = addstring(metric->strings, &edge, attr[i+1]);
                  break;
               case NUM_TAG:
                  metric->num = atoi(attr[i+1]);
                  break;
               default:
                  break;
            }
      }
      metric->stringslen = edge;
      
      /* We are ok with growing metric values b/c we write to a full-sized
       * buffer in xmldata. */
}
示例#14
0
static int
startElement_METRIC(void *data, const char *el, const char **attr)
{
   xmldata_t *xmldata = (xmldata_t *)data;
   ganglia_slope_t slope = GANGLIA_SLOPE_UNSPECIFIED;
   struct xml_tag *xt;
   struct type_tag *tt;
   datum_t *hash_datum = NULL;
   datum_t *rdatum;
   datum_t hashkey, hashval;
   const char *name = NULL;
   const char *metricval = NULL;
   const char *type = NULL;
   int do_summary;
   int i, edge, carbon_ret;
   hash_t *summary;
   Metric_t *metric;

   if (!xmldata->host_alive ) return 0;

   /* Get name for hash key, and val/type for summaries. */
   for(i = 0; attr[i]; i+=2)
      {
         xt = in_xml_list(attr[i], strlen(attr[i]));
         if (!xt) continue;

         switch (xt->tag)
            {
               case NAME_TAG:
                  name = attr[i+1];
                  hashkey.data = (void*) name;
                  hashkey.size =  strlen(name) + 1;
                  break;
               case VAL_TAG:
                  metricval = attr[i+1];
                  break;
               case TYPE_TAG:
                  type = attr[i+1];
                  break;
               case SLOPE_TAG:
                  slope = cstr_to_slope(attr[i+1]);
               default:
                  break;
            }
      }

   metric = &(xmldata->metric);
   memset((void*) metric, 0, sizeof(*metric));

   /* Summarize all numeric metrics */
   do_summary = 0;
   tt = in_type_list(type, strlen(type));
   if (!tt) return 0;

   if (tt->type==INT || tt->type==UINT || tt->type==FLOAT)
      do_summary = 1;

   /* Only keep metric details if we are the authority on this cluster. */
   if (authority_mode(xmldata))
      {
         /* Save the data to a round robin database if the data source is alive
          */
         fillmetric(attr, metric, type);
	 if (metric->dmax && metric->tn > metric->dmax)
            return 0;

         if (do_summary && !xmldata->ds->dead && !xmldata->rval)
            {
                  debug_msg("Updating host %s, metric %s", 
                                  xmldata->hostname, name);
                  if ( gmetad_config.write_rrds == 1 )
                     xmldata->rval = write_data_to_rrd(xmldata->sourcename,
                        xmldata->hostname, name, metricval, NULL,
                        xmldata->ds->step, xmldata->source.localtime, slope);
		  if (gmetad_config.carbon_server) // if the user has specified a carbon server, send the metric to carbon as well
                     carbon_ret=write_data_to_carbon(xmldata->sourcename, xmldata->hostname, name, metricval,xmldata->source.localtime);
            }
         metric->id = METRIC_NODE;
         metric->report_start = metric_report_start;
         metric->report_end = metric_report_end;


         edge = metric->stringslen;
         metric->name = addstring(metric->strings, &edge, name);
         metric->stringslen = edge;

         /* Set local idea of T0. */
         metric->t0 = xmldata->now;
         metric->t0.tv_sec -= metric->tn;

         /* Trim metric structure to the correct length. */
         hashval.size = sizeof(*metric) - GMETAD_FRAMESIZE + metric->stringslen;
         hashval.data = (void*) metric;

         /* Update full metric in cluster host table. */
         rdatum = hash_insert(&hashkey, &hashval, xmldata->host.metrics);
         if (!rdatum)
            {
               err_msg("Could not insert %s metric", name);
            }
      }

   /* Always update summary for numeric metrics. */
   if (do_summary)
      {
         summary = xmldata->source.metric_summary;
         hash_datum = hash_lookup(&hashkey, summary);
         if (!hash_datum)
            {
               if (!authority_mode(xmldata))
                  {
                     metric = &(xmldata->metric);
                     memset((void*) metric, 0, sizeof(*metric));
                     fillmetric(attr, metric, type);
                  }
               /* else we have already filled in the metric above. */
            }
         else
            {
               memcpy(&xmldata->metric, hash_datum->data, hash_datum->size);
               datum_free(hash_datum);
               metric = &(xmldata->metric);

               switch (tt->type)
                  {
                     case INT:
                     case UINT:
                     case FLOAT:
                        metric->val.d += (double)
                                strtod(metricval, (char**) NULL);
                        break;
                     default:
                        break;
                  }
            }

         metric->num++;
         metric->t0 = xmldata->now; /* tell cleanup thread we are using this */

         /* Trim metric structure to the correct length. Tricky. */
         hashval.size = sizeof(*metric) - GMETAD_FRAMESIZE + metric->stringslen;
         hashval.data = (void*) metric;

         /* Update metric in summary table. */
         rdatum = hash_insert(&hashkey, &hashval, summary);
         if (!rdatum) err_msg("Could not insert %s metric", name);
      }
   return 0;
}
示例#15
0
accept_languages * parse_accept_languages(char * acceptlang) {
	char *	langdup;	/* Duplicate of accept language for parsing */
	accept_languages	*langs = NULL;
	char *	langtok;	/* Language token (language + locality + q value) */
	char *	saveptr;	/* Save state of tokenization */
	char *	qdelim;		/* location of the delimiter ';q=' */
	char *	localitydelim;	/* Delimiter for locality specifier */
	int		x;
	char *	stp;

	/* If the browser did not pass an HTTP_ACCEPT_LANGUAGE variable, there
		is not much we can do */
	if(NULL == acceptlang) {
		return NULL;
		}

	/* Duplicate the browser supplied HTTP_ACCEPT_LANGUAGE variable */
	if(NULL == (langdup = strdup(acceptlang))) {
		printf("Unable to allocate memory for langdup\n");
		return NULL;
		}

	/* Initialize the structure to contain the parsed HTTP_ACCEPT_LANGUAGE
		information */
	if(NULL == (langs = malloc(sizeof(accept_languages)))) {
		printf("Unable to allocate memory for langs\n");
		free(langdup);
		return NULL;
		}
	langs->count = 0;
	langs->languages = (accept_language **)NULL;

	/* Tokenize the HTTP_ACCEPT_LANGUAGE string */
	langtok = strtok_r(langdup, ",", &saveptr);
	while(langtok != NULL) {
		/* Bump the count and allocate memory for structures */
		langs->count++;
		if(NULL == langs->languages) {
			/* Adding first language */
			if(NULL == (langs->languages =
			                malloc(langs->count * sizeof(accept_language *)))) {
				printf("Unable to allocate memory for first language\n");
				langs->count--;
				free_accept_languages(langs);
				free(langdup);
				return NULL;
				}
			}
		else {
			/* Adding additional language */
			if(NULL == (langs->languages = realloc(langs->languages,
			                                       langs->count * sizeof(accept_language *)))) {
				printf("Unable to allocate memory for additional language\n");
				langs->count--;
				free_accept_languages(langs);
				free(langdup);
				return NULL;
				}
			}
		if(NULL == (langs->languages[ langs->count - 1] =
		                malloc(sizeof(accept_language)))) {
			printf("Unable to allocate memory for language\n");
			langs->count--;
			free_accept_languages(langs);
			free(langdup);
			return NULL;
			}
		langs->languages[ langs->count - 1]->language = (char *)NULL;
		langs->languages[ langs->count - 1]->locality = (char *)NULL;
		langs->languages[ langs->count - 1]->q = 1.0;

		/* Check to see if there is a q value */
		qdelim = strstr(langtok, ACCEPT_LANGUAGE_Q_DELIMITER);

		if(NULL != qdelim) {	/* found a q value */
			langs->languages[ langs->count - 1]->q =
			    strtod(qdelim + strlen(ACCEPT_LANGUAGE_Q_DELIMITER), NULL);
			langtok[ qdelim - langtok] = '\0';
			}

		/* Check to see if there is a locality specifier */
		if(NULL == (localitydelim = strchr(langtok, '-'))) {
			localitydelim = strchr(langtok, '_');
			}

		if(NULL != localitydelim) {
			/* We have a locality delimiter, so copy it */
			if(NULL == (langs->languages[ langs->count - 1]->locality =
			                strdup(localitydelim + 1))) {
				printf("Unable to allocate memory for locality '%s'\n",
				       langtok);
				free_accept_languages(langs);
				free(langdup);
				return NULL;
				}

			/* Ensure it is upper case */
			for(x = 0, stp = langs->languages[ langs->count - 1]->locality;
			        x < strlen(langs->languages[ langs->count - 1]->locality);
			        x++, stp++) {
				*stp = toupper(*stp);
				}

			/* Then null out the delimiter so the language copy works */
			*localitydelim = '\0';
			}
		if(NULL == (langs->languages[ langs->count - 1]->language =
		                strdup(langtok))) {
			printf("Unable to allocate memory for language '%s'\n",
			       langtok);
			free_accept_languages(langs);
			free(langdup);
			return NULL;
			}

		/* Get the next language token */
		langtok = strtok_r(NULL, ",", &saveptr);
		}

	free(langdup);
	return langs;
	}
示例#16
0
文件: nxjson.c 项目: CowanSM/ejdb
static char* parse_value(nx_json* parent, const char* key, char* p, nx_json_unicode_encoder encoder) {
  nx_json* js;
  while (1) {
    switch (*p) {
      case '\0':
        NX_JSON_REPORT_ERROR("unexpected end of text", p);
        return 0; // error
      case ' ': case '\t': case '\n': case '\r':
      case ',':
        // skip
        p++;
        break;
      case '{':
        js=create_json(NX_JSON_OBJECT, key, parent);
        p++;
        while (1) {
          const char* new_key;
          p=parse_key(&new_key, p, encoder);
          if (!p) return 0; // error
          if (*p=='}') return p+1; // end of object
          p=parse_value(js, new_key, p, encoder);
          if (!p) return 0; // error
        }
      case '[':
        js=create_json(NX_JSON_ARRAY, key, parent);
        p++;
        while (1) {
          p=parse_value(js, 0, p, encoder);
          if (!p) return 0; // error
          if (*p==']') return p+1; // end of array
        }
      case ']':
        return p;
      case '"':
        p++;
        js=create_json(NX_JSON_STRING, key, parent);
        js->text_value=unescape_string(p, &p, encoder);
        if (!js->text_value) return 0; // propagate error
        return p;
      case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
        {
          js=create_json(NX_JSON_INTEGER, key, parent);
          char* pe;
          js->int_value=strtol(p, &pe, 0);
          if (pe==p) {
            NX_JSON_REPORT_ERROR("invalid number", p);
            return 0; // error
          }
          if (*pe=='.' || *pe=='e' || *pe=='E') { // double value
            js->type=NX_JSON_DOUBLE;
            js->dbl_value=strtod(p, &pe);
            if (pe==p) {
              NX_JSON_REPORT_ERROR("invalid number", p);
              return 0; // error
            }
          }
          else {
            js->dbl_value=js->int_value;
          }
          return pe;
        }
      case 't':
        if (!strncmp(p, "true", 4)) {
          js=create_json(NX_JSON_BOOL, key, parent);
          js->int_value=1;
          return p+4;
        }
        NX_JSON_REPORT_ERROR("unexpected chars", p);
        return 0; // error
      case 'f':
        if (!strncmp(p, "false", 5)) {
          js=create_json(NX_JSON_BOOL, key, parent);
          js->int_value=0;
          return p+5;
        }
        NX_JSON_REPORT_ERROR("unexpected chars", p);
        return 0; // error
      case 'n':
        if (!strncmp(p, "null", 4)) {
          create_json(NX_JSON_NULL, key, parent);
          return p+4;
        }
        NX_JSON_REPORT_ERROR("unexpected chars", p);
        return 0; // error
      case '/': // comment
        if (p[1]=='/') { // line comment
          char* ps=p;
          p=strchr(p+2, '\n');
          if (!p) {
            NX_JSON_REPORT_ERROR("endless comment", ps);
            return 0; // error
          }
          p++;
        }
        else if (p[1]=='*') { // block comment
          p=skip_block_comment(p+2);
          if (!p) return 0;
        }
        else {
          NX_JSON_REPORT_ERROR("unexpected chars", p);
          return 0; // error
        }
        break;
      default:
        NX_JSON_REPORT_ERROR("unexpected chars", p);
        return 0; // error
    }
  }
}
示例#17
0
int main(int argc, char **argv)
{
    /* Set some default behaviors. */

    const char *i = "rect";
    const char *o = "rect";
    const char *p = "rgss";
    const char *f = "linear";

    float rot[3] = { 0.f, 0.f, 0.f };

    int n = 1024;
    int c;

    /* Parse the command line options. */

    while ((c = getopt(argc, argv, "i:o:p:n:f:x:y:z:")) != -1)
        switch (c)
        {
            case 'i': i      = optarg;               break;
            case 'o': o      = optarg;               break;
            case 'p': p      = optarg;               break;
            case 'f': f      = optarg;               break;
            case 'x': rot[0] = strtod(optarg, 0);    break;
            case 'y': rot[1] = strtod(optarg, 0);    break;
            case 'z': rot[2] = strtod(optarg, 0);    break;
            case 'n': n      = strtol(optarg, 0, 0); break;

            default: return usage(argv[0]);
        }

    int      num = 1;
    image   *src = 0;
    image   *dst = 0;
    image   *tmp = 0;
    to_img   img;
    to_env   env;
    filter   fil;

    /* Select the sampler. */

    if      (!strcmp(f, "linear"))  fil = filter_linear;
    else if (!strcmp(f, "nearest")) fil = filter_nearest;
    else return usage(argv[0]);

    /* Read the input image. */

    if (optind + 2 <= argc)
    {
        if      (!strcmp(i, "cube"))
        {
            tmp = image_reader(argv[optind], 6);
            src = image_border(tmp);
            img = cube_to_img;
        }
        else if (!strcmp(i, "dome"))
        {
            src = image_reader(argv[optind], 1);
            img = dome_to_img;
        }
        else if (!strcmp(i, "hemi"))
        {
            src = image_reader(argv[optind], 1);
            img = hemi_to_img;
        }
        else if (!strcmp(i, "ball"))
        {
            src = image_reader(argv[optind], 1);
            img = ball_to_img;
        }
        else if (!strcmp(i, "rect"))
        {
            src = image_reader(argv[optind], 1);
            img = rect_to_img;
        }
        else return usage(argv[0]);
    }
    else return usage(argv[0]);

    /* Prepare the output image. */

    if (src)
    {
        if      (!strcmp(o, "cube"))
        {
            dst = image_alloc((num = 6), n, n, src->c, src->b, src->s);
            env = cube_to_env;
        }
        else if (!strcmp(o, "dome"))
        {
            dst = image_alloc((num = 1), n, n, src->c, src->b, src->s);
            env = dome_to_env;
        }
        else if (!strcmp(o, "hemi"))
        {
            dst = image_alloc((num = 1), n, n, src->c, src->b, src->s);
            env = hemi_to_env;
        }
        else if (!strcmp(o, "ball"))
        {
            dst = image_alloc((num = 1), n, n, src->c, src->b, src->s);
            env = ball_to_env;
        }
        else if (!strcmp(o, "rect"))
        {
            dst = image_alloc((num = 1), n, 2 * n, src->c, src->b, src->s);
            env = rect_to_env;
        }
        else return usage(argv[0]);
    }

    /* Perform the remapping using the selected pattern. */

    if (src && dst)
    {
        if      (!strcmp(p, "cent"))
            process(src, dst, &cent_pattern, rot, fil, img, env, num);

        else if (!strcmp(p, "rgss"))
            process(src, dst, &rgss_pattern, rot, fil, img, env, num);

        else if (!strcmp(p, "box2"))
            process(src, dst, &box2_pattern, rot, fil, img, env, num);

        else if (!strcmp(p, "box3"))
            process(src, dst, &box3_pattern, rot, fil, img, env, num);

        else if (!strcmp(p, "box4"))
            process(src, dst, &box4_pattern, rot, fil, img, env, num);

        else return usage(argv[0]);

        /* Write the output. */

        image_writer(argv[optind + 1], dst, num);
    }

    return 0;
}
static config_err_t
_decode_value_raw (ipmi_sensors_config_state_data_t *state_data,
                   const char *threshold_input,
                   uint8_t *threshold_raw)
{
  int8_t r_exponent, b_exponent;
  int16_t m, b;
  uint8_t linearization, analog_data_format;
  config_err_t rv = CONFIG_ERR_FATAL_ERROR;
  config_err_t ret;
  double threshold_value;
  char *ptr;

  assert (state_data);
  assert (threshold_input);
  assert (threshold_raw);

  if ((ret = _get_sdr_decoding_data (state_data,
                                     &r_exponent,
                                     &b_exponent,
                                     &m,
                                     &b,
                                     &linearization,
                                     &analog_data_format)) != CONFIG_ERR_SUCCESS)
    {
      rv = ret;
      goto cleanup;
    }

  errno = 0;
  threshold_value = strtod (threshold_input, &ptr);
  if (errno
      || ptr[0] != '\0')
    {
      pstdout_fprintf (state_data->pstate,
		       stderr,
		       "Invalid input: %s\n",
		       threshold_input);
      /* fatal error, should have been validated earlier */
      goto cleanup;
    }

  if (ipmi_sensor_decode_raw_value (r_exponent,
                                    b_exponent,
                                    m,
                                    b,
                                    linearization,
                                    analog_data_format,
                                    threshold_value,
                                    threshold_raw) < 0)
    {
      pstdout_fprintf (state_data->pstate,
		       stderr,
		       "ipmi_sensor_decode_raw_value: %s\n",
		       strerror (errno));
      goto cleanup;
    }

  rv = CONFIG_ERR_SUCCESS;
 cleanup:
  return (rv);
}
示例#19
0
yajl_status
yajl_do_parse(yajl_handle hand, const unsigned char * jsonText,
              size_t jsonTextLen)
{
    yajl_tok tok;
    const unsigned char * buf;
    size_t bufLen;
    size_t * offset = &(hand->bytesConsumed);

    *offset = 0;

  around_again:
    switch (yajl_bs_current(hand->stateStack)) {
        case yajl_state_parse_complete:
            if (hand->flags & yajl_allow_multiple_values) {
                yajl_bs_set(hand->stateStack, yajl_state_got_value);
                goto around_again;
            }
            if (!(hand->flags & yajl_allow_trailing_garbage)) {
                if (*offset != jsonTextLen) {
                    tok = yajl_lex_lex(hand->lexer, jsonText, jsonTextLen,
                                       offset, &buf, &bufLen);
                    if (tok != yajl_tok_eof) {
                        yajl_bs_set(hand->stateStack, yajl_state_parse_error);
                        hand->parseError = "trailing garbage";
                    }
                    goto around_again;
                }
            }
            return yajl_status_ok;
        case yajl_state_lexical_error:
        case yajl_state_parse_error:
            return yajl_status_error;
        case yajl_state_start:
        case yajl_state_got_value:
        case yajl_state_map_need_val:
        case yajl_state_array_need_val:
        case yajl_state_array_start:  {
            /* for arrays and maps, we advance the state for this
             * depth, then push the state of the next depth.
             * If an error occurs during the parsing of the nesting
             * enitity, the state at this level will not matter.
             * a state that needs pushing will be anything other
             * than state_start */

            yajl_state stateToPush = yajl_state_start;

            tok = yajl_lex_lex(hand->lexer, jsonText, jsonTextLen,
                               offset, &buf, &bufLen);

            switch (tok) {
                case yajl_tok_eof:
                    return yajl_status_ok;
                case yajl_tok_error:
                    yajl_bs_set(hand->stateStack, yajl_state_lexical_error);
                    goto around_again;
                case yajl_tok_string:
                    if (hand->callbacks && hand->callbacks->yajl_string) {
                        _CC_CHK(hand->callbacks->yajl_string(hand->ctx,
                                                             buf, bufLen));
                    }
                    break;
                case yajl_tok_string_with_escapes:
                    if (hand->callbacks && hand->callbacks->yajl_string) {
                        yajl_buf_clear(hand->decodeBuf);
                        yajl_string_decode(hand->decodeBuf, buf, bufLen);
                        _CC_CHK(hand->callbacks->yajl_string(
                                    hand->ctx, yajl_buf_data(hand->decodeBuf),
                                    yajl_buf_len(hand->decodeBuf)));
                    }
                    break;
                case yajl_tok_bool:
                    if (hand->callbacks && hand->callbacks->yajl_boolean) {
                        _CC_CHK(hand->callbacks->yajl_boolean(hand->ctx,
                                                              *buf == 't'));
                    }
                    break;
                case yajl_tok_null:
                    if (hand->callbacks && hand->callbacks->yajl_null) {
                        _CC_CHK(hand->callbacks->yajl_null(hand->ctx));
                    }
                    break;
                case yajl_tok_left_bracket:
                    if (hand->callbacks && hand->callbacks->yajl_start_map) {
                        _CC_CHK(hand->callbacks->yajl_start_map(hand->ctx));
                    }
                    stateToPush = yajl_state_map_start;
                    break;
                case yajl_tok_left_brace:
                    if (hand->callbacks && hand->callbacks->yajl_start_array) {
                        _CC_CHK(hand->callbacks->yajl_start_array(hand->ctx));
                    }
                    stateToPush = yajl_state_array_start;
                    break;
                case yajl_tok_integer:
                    if (hand->callbacks) {
                        if (hand->callbacks->yajl_number) {
                            _CC_CHK(hand->callbacks->yajl_number(
                                        hand->ctx,(const char *) buf, bufLen));
                        } else if (hand->callbacks->yajl_integer) {
                            int64_t i = 0;
                            errno = 0;
                            i = yajl_parse_integer(buf, (unsigned int)bufLen);
                            if ((i == INT64_MIN || i == INT64_MAX) &&
                                errno == ERANGE)
                            {
                                yajl_bs_set(hand->stateStack,
                                            yajl_state_parse_error);
                                hand->parseError = "integer overflow" ;
                                /* try to restore error offset */
                                if (*offset >= bufLen) *offset -= bufLen;
                                else *offset = 0;
                                goto around_again;
                            }
                            _CC_CHK(hand->callbacks->yajl_integer(hand->ctx,
                                                                  i));
                        }
                    }
                    break;
                case yajl_tok_double:
                    if (hand->callbacks) {
                        if (hand->callbacks->yajl_number) {
                            _CC_CHK(hand->callbacks->yajl_number(
                                        hand->ctx, (const char *) buf, bufLen));
                        } else if (hand->callbacks->yajl_double) {
                            double d = 0.0;
                            yajl_buf_clear(hand->decodeBuf);
                            yajl_buf_append(hand->decodeBuf, buf, bufLen);
                            buf = yajl_buf_data(hand->decodeBuf);
                            errno = 0;
                            d = strtod((char *) buf, NULL);
                            if ((d == HUGE_VAL || d == -HUGE_VAL) &&
                                errno == ERANGE)
                            {
                                yajl_bs_set(hand->stateStack,
                                            yajl_state_parse_error);
                                hand->parseError = "numeric (floating point) "
                                    "overflow";
                                /* try to restore error offset */
                                if (*offset >= bufLen) *offset -= bufLen;
                                else *offset = 0;
                                goto around_again;
                            }
                            _CC_CHK(hand->callbacks->yajl_double(hand->ctx,
                                                                 d));
                        }
                    }
                    break;
                case yajl_tok_right_brace: {
                    if (yajl_bs_current(hand->stateStack) ==
                        yajl_state_array_start)
                    {
                        if (hand->callbacks &&
                            hand->callbacks->yajl_end_array)
                        {
                            _CC_CHK(hand->callbacks->yajl_end_array(hand->ctx));
                        }
                        yajl_bs_pop(hand->stateStack);
                        goto around_again;
                    }
                    /* intentional fall-through */
                }
                case yajl_tok_colon:
                case yajl_tok_comma:
                case yajl_tok_right_bracket:
                    yajl_bs_set(hand->stateStack, yajl_state_parse_error);
                    hand->parseError =
                        "unallowed token at this point in JSON text";
                    goto around_again;
                default:
                    yajl_bs_set(hand->stateStack, yajl_state_parse_error);
                    hand->parseError = "invalid token, internal error";
                    goto around_again;
            }
            /* got a value.  transition depends on the state we're in. */
            {
                yajl_state s = yajl_bs_current(hand->stateStack);
                if (s == yajl_state_start || s == yajl_state_got_value) {
                    yajl_bs_set(hand->stateStack, yajl_state_parse_complete);
                } else if (s == yajl_state_map_need_val) {
                    yajl_bs_set(hand->stateStack, yajl_state_map_got_val);
                } else {
                    yajl_bs_set(hand->stateStack, yajl_state_array_got_val);
                }
            }
            if (stateToPush != yajl_state_start) {
                yajl_bs_push(hand->stateStack, stateToPush);
            }

            goto around_again;
        }
        case yajl_state_map_start:
        case yajl_state_map_need_key: {
            /* only difference between these two states is that in
             * start '}' is valid, whereas in need_key, we've parsed
             * a comma, and a string key _must_ follow */
            tok = yajl_lex_lex(hand->lexer, jsonText, jsonTextLen,
                               offset, &buf, &bufLen);
            switch (tok) {
                case yajl_tok_eof:
                    return yajl_status_ok;
                case yajl_tok_error:
                    yajl_bs_set(hand->stateStack, yajl_state_lexical_error);
                    goto around_again;
                case yajl_tok_string_with_escapes:
                    if (hand->callbacks && hand->callbacks->yajl_map_key) {
                        yajl_buf_clear(hand->decodeBuf);
                        yajl_string_decode(hand->decodeBuf, buf, bufLen);
                        buf = yajl_buf_data(hand->decodeBuf);
                        bufLen = yajl_buf_len(hand->decodeBuf);
                    }
                    /* intentional fall-through */
                case yajl_tok_string:
                    if (hand->callbacks && hand->callbacks->yajl_map_key) {
                        _CC_CHK(hand->callbacks->yajl_map_key(hand->ctx, buf,
                                                              bufLen));
                    }
                    yajl_bs_set(hand->stateStack, yajl_state_map_sep);
                    goto around_again;
                case yajl_tok_right_bracket:
                    if (yajl_bs_current(hand->stateStack) ==
                        yajl_state_map_start)
                    {
                        if (hand->callbacks && hand->callbacks->yajl_end_map) {
                            _CC_CHK(hand->callbacks->yajl_end_map(hand->ctx));
                        }
                        yajl_bs_pop(hand->stateStack);
                        goto around_again;
                    }
                default:
                    yajl_bs_set(hand->stateStack, yajl_state_parse_error);
                    hand->parseError =
                        "invalid object key (must be a string)";
                    goto around_again;
            }
        }
        case yajl_state_map_sep: {
            tok = yajl_lex_lex(hand->lexer, jsonText, jsonTextLen,
                               offset, &buf, &bufLen);
            switch (tok) {
                case yajl_tok_colon:
                    yajl_bs_set(hand->stateStack, yajl_state_map_need_val);
                    goto around_again;
                case yajl_tok_eof:
                    return yajl_status_ok;
                case yajl_tok_error:
                    yajl_bs_set(hand->stateStack, yajl_state_lexical_error);
                    goto around_again;
                default:
                    yajl_bs_set(hand->stateStack, yajl_state_parse_error);
                    hand->parseError = "object key and value must "
                        "be separated by a colon (':')";
                    goto around_again;
            }
        }
        case yajl_state_map_got_val: {
            tok = yajl_lex_lex(hand->lexer, jsonText, jsonTextLen,
                               offset, &buf, &bufLen);
            switch (tok) {
                case yajl_tok_right_bracket:
                    if (hand->callbacks && hand->callbacks->yajl_end_map) {
                        _CC_CHK(hand->callbacks->yajl_end_map(hand->ctx));
                    }
                    yajl_bs_pop(hand->stateStack);
                    goto around_again;
                case yajl_tok_comma:
                    yajl_bs_set(hand->stateStack, yajl_state_map_need_key);
                    goto around_again;
                case yajl_tok_eof:
                    return yajl_status_ok;
                case yajl_tok_error:
                    yajl_bs_set(hand->stateStack, yajl_state_lexical_error);
                    goto around_again;
                default:
                    yajl_bs_set(hand->stateStack, yajl_state_parse_error);
                    hand->parseError = "after key and value, inside map, "
                                       "I expect ',' or '}'";
                    /* try to restore error offset */
                    if (*offset >= bufLen) *offset -= bufLen;
                    else *offset = 0;
                    goto around_again;
            }
        }
        case yajl_state_array_got_val: {
            tok = yajl_lex_lex(hand->lexer, jsonText, jsonTextLen,
                               offset, &buf, &bufLen);
            switch (tok) {
                case yajl_tok_right_brace:
                    if (hand->callbacks && hand->callbacks->yajl_end_array) {
                        _CC_CHK(hand->callbacks->yajl_end_array(hand->ctx));
                    }
                    yajl_bs_pop(hand->stateStack);
                    goto around_again;
                case yajl_tok_comma:
                    yajl_bs_set(hand->stateStack, yajl_state_array_need_val);
                    goto around_again;
                case yajl_tok_eof:
                    return yajl_status_ok;
                case yajl_tok_error:
                    yajl_bs_set(hand->stateStack, yajl_state_lexical_error);
                    goto around_again;
                default:
                    yajl_bs_set(hand->stateStack, yajl_state_parse_error);
                    hand->parseError =
                        "after array element, I expect ',' or ']'";
                    goto around_again;
            }
        }
    }

    abort();
    return yajl_status_error;
}
示例#20
0
int main(int argc, char *argv[])
{
	int sockfd;
	struct sigaction act;
	char fname[BUFSIZE], timestr[BUFSIZE], buf[BUFSIZE];
	char stringbuffer[50][BUFSIZE];
	int i;
	time_t now;

	char *str, *ptr, *pEnd;
	double rf_level;

	struct tm *loctime;

	struct stat statbuf;

	FILE *f;

	/* cgi variables */
	int postsize;

	/* print html headers */ 
	printf("Content-Type: text/html;charset=iso-8859-1\n\n");
	printf("<html><head>\n");
	printf("<style type=\"text/css\">");
	printf(" p { margin: 0; padding: 0;}");
	printf(" h1 { font-size: 120%; padding: 0; margin-bottom: 0; } ");
	printf(" form { float:left } ");
	printf(" hr { clear: both } ");
	printf(" </style>");
	/* printf("<meta http-equiv=\"refresh\" content=\"5\">"); */
	printf("</head><body>\n");

	/* get post data */
	str = getenv("CONTENT_LENGTH");
	if (str!=NULL) postsize = atoi(str);
	else postsize=0;
	fgets(buf, postsize+1, stdin);
	ptr=buf;
	while (((*ptr)!='=')&&((*ptr)!='\0')) {
		ptr++;
	}
	if (*ptr!='\0') ptr++;

	/* setup variables */

	/* setup signal handler */
	act.sa_handler = sig_alrm;
	act.sa_flags = 0;
	sigaction(SIGALRM, &act, 0);
	
	/* check it's valid float and greater than 0 */
	errno = 0;
	rf_level = strtod(ptr, &pEnd);

	/* parameter was given, so send it to weather station */
	//printf("%s", ptr);


	if (strstr(ptr, "reset") != NULL) {

		/* Parameter was reset command */

		/* connect */
		if ((sockfd = connect_ip(SERVER_IP, SERVER_PORT)) == -1) {
			return -1;
		}

		/* generate parameter string */
		snprintf(buf, sizeof(buf), "%s", MSG_RESET, ptr);

		/* send parameters to server */
		if (send_data(sockfd, buf, sizeof(buf)) != 0) {
			return -1;
		}

		close(sockfd);

		sleep(5);

		printf("Reset successful!");

	} else if (rf_level > 0) {

		/* Parameter was RF trigger level */

		/* connect */
		if ((sockfd = connect_ip(SERVER_IP, SERVER_PORT)) == -1) {
			return -1;
		}

		/* generate parameter string */
		snprintf(buf, sizeof(buf), "%s;%s\r\n", MSG_SET_PARAMS, ptr);

		/* send parameters to server */
		if (send_data(sockfd, buf, sizeof(buf)) != 0) {
			return -1;
		}

		close(sockfd);

		sleep(1);

		printf("Level set succesfully!");
	}

	/* fail connection on timeout */
	alarm(FAILTIME);

	if ((sockfd = connect_ip(SERVER_IP, SERVER_PORT)) == -1) {
		return 1;
	}

	/* start talking to server */
	if (get_data(sockfd, buf, sizeof(buf), MSG_GET_PARAMS) <= 0) {
		return 1;
	}

	close(sockfd);

	rf_level = strtod(buf, &pEnd);

	/* clear interrupt */
	alarm(0);

	/* Page title */
	printf("<h1>Weather Station Configuration Tool</h1>");
	printf("<p>Version 1.0, Copyright (C) 2007 Mikko Vatanen\n</p><hr>");
	
	/* Parameter form */
	printf("<form method=\"post\" action=\"/cgi-bin/conftool\">\n");
	printf("<label>RF Trigger Level: </label>");
	printf("<input type=\"text\" name=\"level\" value=\"%2.2f\">\n", rf_level);
	printf("<input type=\"submit\" value=\"Set level\">\n");
	printf("</form>\n");

	/* Reset form */
	printf("<form method=\"post\" action=\"/cgi-bin/conftool\">\n");
	printf("<input type=\"hidden\" name=\"level\" value=\"reset\">\n");
	printf("&nbsp;&nbsp;&nbsp;&nbsp;<input type=\"submit\" value=\"Reset WStation\">\n");
	printf("</form>");

	/* Refresh data */
	printf("<form method=\"post\" action=\"/cgi-bin/conftool\">\n");
	printf("<input type=\"hidden\" name=\"level\" value=\"\">\n");
	printf("&nbsp;&nbsp;&nbsp;&nbsp;<input type=\"submit\" value=\"Refresh page\">\n");
	printf("</form>");

	printf("<br><hr>");

	/* tail newest data file */

	now = time(NULL);
	loctime = localtime(&now);

	strftime(timestr, sizeof(timestr), "%F", loctime);
	sprintf(fname, "/home/wwwadmin/htdocs/saa/%s/%s.%s", DATADIR, timestr, FILEEXT);
	printf("<b>%s</b><br><pre>", fname);

	stat(fname, &statbuf);

	if ((f = fopen(fname, "r")) != NULL) {

		i = 0;

		if (fseek(f, statbuf.st_size - 40 * 65, SEEK_SET ) == 0) {

			/* ignore partial line first */
			fgets(buf, sizeof(buf), f);

			/* store data for reverse order */
			while (fgets(buf, sizeof(buf), f) != NULL && i < 40) {
				strncpy(stringbuffer[i++], buf, BUFSIZE);
			}	
		}

		fclose(f);

	}

	/* Print data in reverse order */
	while ( i >= 0 ) {
		printf("%s", stringbuffer[i--]);
	}

	printf("</pre>\n");

	/* print html footer */
	printf("</body></html>\n");

	return 0;
}
示例#21
0
/*
** Read a variable. On error put nil on stack.
** LUA interface:
**			variable = read ([format])
**
** O formato pode ter um dos seguintes especificadores:
**
**	s ou S -> para string
**	f ou F, g ou G, e ou E -> para reais
**	i ou I -> para inteiros
**
**	Estes especificadores podem vir seguidos de numero que representa
**	o numero de campos a serem lidos.
*/
static void io_read (void)
{
 lua_Object o = lua_getparam (1);
 if (o == NULL || !lua_isstring(o))	/* free format */
 {
  int c;
  char s[256];
  while (isspace(c=fgetc(in)))
   ;
  if (c == '\"')
  {
   int c, n=0;
   while((c = fgetc(in)) != '\"')
   {
    if (c == EOF)
    {
     lua_pushnil ();
     return;
    }
    s[n++] = c;
   }
   s[n] = 0;
  }
  else if (c == '\'')
  {
   int c, n=0;
   while((c = fgetc(in)) != '\'')
   {
    if (c == EOF)
    {
     lua_pushnil ();
     return;
    }
    s[n++] = c;
   }
   s[n] = 0;
  }
  else
  {
   char *ptr;
   double d;
   ungetc (c, in);
   if (fscanf (in, "%s", s) != 1)
   {
    lua_pushnil ();
    return;
   }
   d = strtod (s, &ptr);
   if (!(*ptr))
   {
    lua_pushnumber (d);
    return;
   }
  }
  lua_pushstring (s);
  return;
 }
 else				/* formatted */
 {
  char *e = lua_getstring(o);
  char t;
  int  m=0;
  while (isspace(*e)) e++;
  t = *e++;
  while (isdigit(*e))
   m = m*10 + (*e++ - '0');
  
  if (m > 0)
  {
   char f[80];
   char s[256];
   sprintf (f, "%%%ds", m);
   if (fgets (s, m, in) == NULL)
   {
    lua_pushnil();
    return;
   }
   else
   {
    if (s[strlen(s)-1] == '\n')
     s[strlen(s)-1] = 0;
   }
   switch (tolower(t))
   {
    case 'i':
    {
     long int l;
     sscanf (s, "%ld", &l);
     lua_pushnumber(l);
    }
    break;
    case 'f': case 'g': case 'e':
    {
     float f;
     sscanf (s, "%f", &f);
     lua_pushnumber(f);
    }
    break;
    default: 
     lua_pushstring(s); 
    break;
   }
  }
  else
  {
   switch (tolower(t))
   {
    case 'i':
    {
     long int l;
     if (fscanf (in, "%ld", &l) == EOF)
       lua_pushnil();
       else lua_pushnumber(l);
    }
    break;
    case 'f': case 'g': case 'e':
    {
     float f;
     if (fscanf (in, "%f", &f) == EOF)
       lua_pushnil();
       else lua_pushnumber(f);
    }
    break;
    default: 
    {
     char s[256];
     if (fscanf (in, "%s", s) == EOF)
       lua_pushnil();
       else lua_pushstring(s);
    }
    break;
   }
  }
 }
}
示例#22
0
sch_resource_t
res_to_num(char *res_str, struct resource_type *type)
{
    sch_resource_t count = SCHD_INFINITY;	/* convert string resource to numeric */
    sch_resource_t count2 = SCHD_INFINITY;	/* convert string resource to numeric */
    char *endp;				/* used for strtol() */
    char *endp2;				/* used for strtol() */
    long multiplier = 1;			/* multiplier to count */
    int is_size = 0;			/* resource value is a size type */
    int is_time = 0;			/* resource value is a time spec */

    if (res_str == NULL)
        return SCHD_INFINITY;

    if (!strcasecmp(ATR_TRUE, res_str)) {
        if (type != NULL) {
            type->is_boolean = 1;
            type->is_non_consumable = 1;
        }
        count = 1;
    }
    else if (!strcasecmp(ATR_FALSE, res_str)) {
        if (type != NULL) {
            type->is_boolean = 1;
            type->is_non_consumable = 1;
        }
        count = 0;
    }
    else if (!is_num(res_str)) {
        if (type != NULL) {
            type->is_string = 1;
            type->is_non_consumable = 1;
        }
        count = SCHD_INFINITY;
    }
    else {
        count = (sch_resource_t) strtod(res_str, &endp);

        if (*endp == ':') { /* time resource -> convert to seconds */
            count2 = (sch_resource_t) strtod(endp+1, &endp2);
            if (*endp2 == ':') { /* form of HH:MM:SS */
                count *= 3600;
                count += count2 * 60;
                count += strtol(endp2 + 1, &endp, 10);
                if (*endp != '\0')
                    count = SCHD_INFINITY;
            }
            else			 { /* form of MM:SS */
                count *= 60;
                count += count2;
            }
            multiplier = 1;
            is_time = 1;
        }
        else if (*endp == 'k' || *endp == 'K') {
            multiplier = 1;
            is_size = 1;
        }
        else if (*endp == 'm' || *endp == 'M') {
            multiplier = MEGATOKILO;
            is_size = 1;
        }
        else if (*endp == 'g' || *endp == 'G') {
            multiplier = GIGATOKILO;
            is_size = 1;
        }
        else if (*endp == 't' || *endp == 'T') {
            multiplier = TERATOKILO;
            is_size = 1;
        }
        else if (*endp == 'b' || *endp == 'B') {
            count = ceil(count / KILO);
            multiplier = 1;
            is_size = 1;
        }
        else if (*endp == 'w') {
            count = ceil(count / KILO);
            multiplier = SIZEOF_WORD;
            is_size = 1;
        }
        else	/* catch all */
            multiplier = 1;

        if (*endp != '\0' && *(endp + 1) == 'w')
            multiplier *= SIZEOF_WORD;

        if (type != NULL) {
            type->is_consumable = 1;
            if (is_size  )
                type->is_size = 1;
            else if (is_time)
                type->is_time = 1;
            else
                type->is_num = 1;
        }
    }

    return count * multiplier;
}
示例#23
0
void CGPSSubcrible::OnRevGpsMsg(long ILongID,char strgps[],long lenth)
{
	  //获得字符数组
		char *pchar = new char[ lenth + 1];
		char *pdate = new char[5];
		
		memcpy(pchar,strgps,lenth);
		
		*(pchar + lenth) = '\0';

 		char *tok;
 		char *p[50] = {0};
 		char seps[] = ",";
 	    int i = 0;
 	    
		char *stopstr;
 		
 		//获得字符串数组
 	    tok = strtok(pchar,seps);
 		while( tok != NULL && i < 50)
 		{	
 			p[i] = new char[strlen(tok) + 1];
 		    strcpy(p[i],tok);
 	        tok = strtok( NULL,seps);
 			
 			i++;
 		}
 	    
 		if ( i < 10 )
 		{
 			//清除数组指针
 	       for(int j = 0; j<i; j++)
		   {
 	          delete p[j];
		   }
 	
 		   delete pchar;
 		   delete pdate;
		   
		    return;
 		}
 	
		GPS_Info info = {0};
//		const int TIGER_COORDINATE_UNIT = 1000000;

 		info.latidude = strtod(p[0],&stopstr);
//		info.latidude /= TIGER_COORDINATE_UNIT;
//		info.latidude -= 90;

 		info.longitude = strtod(p[1],&stopstr);
//		info.longitude /= TIGER_COORDINATE_UNIT;
//		info.longitude -= 180;

 		info.speed     = strtod(p[2],&stopstr);
 		info.height    = strtod(p[3],&stopstr);
 		info.angle     = strtod(p[4],&stopstr);
 	
 	     strncpy(pdate,p[5],4);
 	     *(pdate+4) = '\0';
 	     info.revTime.dwYear = strtol(pdate,&stopstr,10);
 	  
 	     strncpy(pdate,p[5]+4,2);
 	     *(pdate+2) = '\0';
 	     info.revTime.dwMonth = strtol(pdate,&stopstr,10);
 	   
 	     strncpy(pdate,p[5]+6,2);
 	     *(pdate+2) = '\0';
 	     info.revTime.dwDay = strtol(pdate,&stopstr,10);
 	      
 	
 	     strncpy(pdate,p[5]+8,2);
 	     *(pdate+2) = '\0';
 	     info.revTime.dwHour = strtol(pdate,&stopstr,10);
 	
 	     strncpy(pdate,p[5]+10,2);
 	     *(pdate+2) = '\0';
 	     info.revTime.dwMinute = strtol(pdate,&stopstr,10);
 	
 	     strncpy(pdate,p[5]+12,2);
 	     *(pdate+2) = '\0';
 	     info.revTime.dwSecond = strtol(pdate,&stopstr,10);
 	     
 	
 		 info.antennaState = (p[6][0] == '1');
 		 info.orientationState = (p[7][0] == '1');
 		 info.starCount = strtol(p[8],&stopstr,10);
 		 
		 //清除数组指针
 	     for(int j = 0; j<i; j++)
		 {
 	        delete p[j];
		 }
 	
 		 delete pchar;
 		 delete pdate;

 		 if(m_RecievCallBack != NULL)
 		 {
 			 m_RecievCallBack(ILongID,info,m_dwuserdata);
 		 }
 	
}
示例#24
0
文件: atof.c 项目: 6305-LAB/OS-kernel
double atof(const char *s)
{
	return strtod(s, (const char **) NULL);
}
示例#25
0
void do_predict(FILE *input, FILE *output)
{
	int correct = 0;
	int total = 0;
	double error = 0;
	double sump = 0, sumt = 0, sumpp = 0, sumtt = 0, sumpt = 0;

	int nr_class=get_nr_class(model_);
	double *prob_estimates=NULL;
	int j, n;
	int nr_feature=get_nr_feature(model_);
	if(model_->bias>=0)
		n=nr_feature+1;
	else
		n=nr_feature;

	if(flag_predict_probability)
	{
		int *labels;

		if(!check_probability_model(model_))
		{
			fprintf(stderr, "probability output is only supported for logistic regression\n");
			exit(1);
		}

		labels=(int *) malloc(nr_class*sizeof(int));
		get_labels(model_,labels);
		prob_estimates = (double *) malloc(nr_class*sizeof(double));
		fprintf(output,"labels");
		for(j=0;j<nr_class;j++)
			fprintf(output," %d",labels[j]);
		fprintf(output,"\n");
		free(labels);
	}

	max_line_len = 1024;
	line = (char *)malloc(max_line_len*sizeof(char));
	while(readline(input) != NULL)
	{
		int i = 0;
		double target_label, predict_label;
		char *idx, *val, *label, *endptr;
		int inst_max_index = 0; // strtol gives 0 if wrong format

		label = strtok(line," \t\n");
		if(label == NULL) // empty line
			exit_input_error(total+1);

		target_label = strtod(label,&endptr);
		if(endptr == label || *endptr != '\0')
			exit_input_error(total+1);

		while(1)
		{
			if(i>=max_nr_attr-2)	// need one more for index = -1
			{
				max_nr_attr *= 2;
				x = (struct feature_node *) realloc(x,max_nr_attr*sizeof(struct feature_node));
			}

			idx = strtok(NULL,":");
			val = strtok(NULL," \t");

			if(val == NULL)
				break;
			errno = 0;
			x[i].index = (int) strtol(idx,&endptr,10);
			if(endptr == idx || errno != 0 || *endptr != '\0' || x[i].index <= inst_max_index)
				exit_input_error(total+1);
			else
				inst_max_index = x[i].index;

			errno = 0;
			x[i].value = strtod(val,&endptr);
			if(endptr == val || errno != 0 || (*endptr != '\0' && !isspace(*endptr)))
				exit_input_error(total+1);

			// feature indices larger than those in training are not used
			if(x[i].index <= nr_feature)
				++i;
		}

		if(model_->bias>=0)
		{
			x[i].index = n;
			x[i].value = model_->bias;
			i++;
		}
		x[i].index = -1;

		if(flag_predict_probability)
		{
			int j;
			predict_label = predict_probability(model_,x,prob_estimates);
			fprintf(output,"%g",predict_label);
			for(j=0;j<model_->nr_class;j++)
				fprintf(output," %g",prob_estimates[j]);
			fprintf(output,"\n");
		}
		else
		{
			predict_label = predict(model_,x);
			fprintf(output,"%g\n",predict_label);
		}

		if(predict_label == target_label)
			++correct;
		error += (predict_label-target_label)*(predict_label-target_label);
		sump += predict_label;
		sumt += target_label;
		sumpp += predict_label*predict_label;
		sumtt += target_label*target_label;
		sumpt += predict_label*target_label;
		++total;
	}
	if(model_->param.solver_type==L2R_L2LOSS_SVR ||
	   model_->param.solver_type==L2R_L1LOSS_SVR_DUAL ||
	   model_->param.solver_type==L2R_L2LOSS_SVR_DUAL)
	{
		info("Mean squared error = %g (regression)\n",error/total);
		info("Squared correlation coefficient = %g (regression)\n",
			((total*sumpt-sump*sumt)*(total*sumpt-sump*sumt))/
			((total*sumpp-sump*sump)*(total*sumtt-sumt*sumt))
			);
	}
	else
		info("Accuracy = %g%% (%d/%d)\n",(double) correct/total*100,correct,total);
	if(flag_predict_probability)
		free(prob_estimates);
}
示例#26
0
/* process command-line arguments */
static int
process_arguments (int argc, char **argv)
{
	int c;
	int escape = 0;
	char *temp;

	int option = 0;
	static struct option longopts[] = {
		{"hostname", required_argument, 0, 'H'},
		{"critical", required_argument, 0, 'c'},
		{"warning", required_argument, 0, 'w'},
		{"critical-codes", required_argument, 0, 'C'},
		{"warning-codes", required_argument, 0, 'W'},
		{"timeout", required_argument, 0, 't'},
		{"protocol", required_argument, 0, 'P'}, /* FIXME: Unhandled */
		{"port", required_argument, 0, 'p'},
		{"escape", no_argument, 0, 'E'},
		{"all", no_argument, 0, 'A'},
		{"send", required_argument, 0, 's'},
		{"expect", required_argument, 0, 'e'},
		{"maxbytes", required_argument, 0, 'm'},
		{"quit", required_argument, 0, 'q'},
		{"jail", no_argument, 0, 'j'},
		{"delay", required_argument, 0, 'd'},
		{"refuse", required_argument, 0, 'r'},
		{"mismatch", required_argument, 0, 'M'},
		{"use-ipv4", no_argument, 0, '4'},
		{"use-ipv6", no_argument, 0, '6'},
		{"verbose", no_argument, 0, 'v'},
		{"version", no_argument, 0, 'V'},
		{"help", no_argument, 0, 'h'},
		{"ssl", no_argument, 0, 'S'},
		{"certificate", required_argument, 0, 'D'},
		{0, 0, 0, 0}
	};

	if (argc < 2)
		usage4 (_("No arguments found"));

	/* backwards compatibility */
	for (c = 1; c < argc; c++) {
		if (strcmp ("-to", argv[c]) == 0)
			strcpy (argv[c], "-t");
		else if (strcmp ("-wt", argv[c]) == 0)
			strcpy (argv[c], "-w");
		else if (strcmp ("-ct", argv[c]) == 0)
			strcpy (argv[c], "-c");
	}

	if (!is_option (argv[1])) {
		server_address = argv[1];
		argv[1] = argv[0];
		argv = &argv[1];
		argc--;
	}

	while (1) {
		c = getopt_long (argc, argv, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:",
		                 longopts, &option);

		if (c == -1 || c == EOF || c == 1)
			break;

		switch (c) {
		case '?':                 /* print short usage statement if args not parsable */
			usage5 ();
		case 'h':                 /* help */
			print_help ();
			exit (STATE_OK);
		case 'V':                 /* version */
			print_revision (progname, NP_VERSION);
			exit (STATE_OK);
		case 'v':                 /* verbose mode */
			flags |= FLAG_VERBOSE;
			break;
		case '4':
			address_family = AF_INET;
			break;
		case '6':
#ifdef USE_IPV6
			address_family = AF_INET6;
#else
			usage4 (_("IPv6 support not available"));
#endif
			break;
		case 'H':                 /* hostname */
			server_address = optarg;
			break;
		case 'c':                 /* critical */
			critical_time = strtod (optarg, NULL);
			flags |= FLAG_TIME_CRIT;
			break;
		case 'j':		  /* hide output */
			flags |= FLAG_HIDE_OUTPUT;
			break;
		case 'w':                 /* warning */
			warning_time = strtod (optarg, NULL);
			flags |= FLAG_TIME_WARN;
			break;
		case 'C':
			crit_codes = realloc (crit_codes, ++crit_codes_count);
			crit_codes[crit_codes_count - 1] = optarg;
			break;
		case 'W':
			warn_codes = realloc (warn_codes, ++warn_codes_count);
			warn_codes[warn_codes_count - 1] = optarg;
			break;
		case 't':                 /* timeout */
			if (!is_intpos (optarg))
				usage4 (_("Timeout interval must be a positive integer"));
			else
				socket_timeout = atoi (optarg);
			break;
		case 'p':                 /* port */
			if (!is_intpos (optarg))
				usage4 (_("Port must be a positive integer"));
			else
				server_port = atoi (optarg);
			break;
		case 'E':
			escape = 1;
			break;
		case 's':
			if (escape)
				server_send = np_escaped_string(optarg);
			else
				xasprintf(&server_send, "%s", optarg);
			break;
		case 'e': /* expect string (may be repeated) */
			flags &= ~FLAG_EXACT_MATCH;
			if (server_expect_count == 0)
				server_expect = malloc (sizeof (char *) * (++server_expect_count));
			else
				server_expect = realloc (server_expect, sizeof (char *) * (++server_expect_count));
			server_expect[server_expect_count - 1] = optarg;
			break;
		case 'm':
			if (!is_intpos (optarg))
				usage4 (_("Maxbytes must be a positive integer"));
			else
				maxbytes = strtol (optarg, NULL, 0);
			break;
		case 'q':
			if (escape)
				server_quit = np_escaped_string(optarg);
			else
				xasprintf(&server_quit, "%s\r\n", optarg);
			break;
		case 'r':
			if (!strncmp(optarg,"ok",2))
				econn_refuse_state = STATE_OK;
			else if (!strncmp(optarg,"warn",4))
				econn_refuse_state = STATE_WARNING;
			else if (!strncmp(optarg,"crit",4))
				econn_refuse_state = STATE_CRITICAL;
			else
				usage4 (_("Refuse must be one of ok, warn, crit"));
			break;
		case 'M':
			if (!strncmp(optarg,"ok",2))
				expect_mismatch_state = STATE_OK;
			else if (!strncmp(optarg,"warn",4))
				expect_mismatch_state = STATE_WARNING;
			else if (!strncmp(optarg,"crit",4))
				expect_mismatch_state = STATE_CRITICAL;
			else
				usage4 (_("Mismatch must be one of ok, warn, crit"));
			break;
		case 'd':
			if (is_intpos (optarg))
				delay = atoi (optarg);
			else
				usage4 (_("Delay must be a positive integer"));
			break;
		case 'D': /* Check SSL cert validity - days 'til certificate expiration */
#ifdef HAVE_SSL
#  ifdef USE_OPENSSL /* XXX */
			if ((temp=strchr(optarg,','))!=NULL) {
			    *temp='\0';
			    if (!is_intnonneg (optarg))
                               usage2 (_("Invalid certificate expiration period"), optarg);				 days_till_exp_warn = atoi(optarg);
			    *temp=',';
			    temp++;
			    if (!is_intnonneg (temp))
				usage2 (_("Invalid certificate expiration period"), temp);
			    days_till_exp_crit = atoi (temp);
			}
			else {
			    days_till_exp_crit=0;
			    if (!is_intnonneg (optarg))
				usage2 (_("Invalid certificate expiration period"), optarg);
			    days_till_exp_warn = atoi (optarg);
			}
			check_cert = TRUE;
			flags |= FLAG_SSL;
			break;
#  endif /* USE_OPENSSL */
#endif
			/* fallthrough if we don't have ssl */
		case 'S':
#ifdef HAVE_SSL
			flags |= FLAG_SSL;
#else
			die (STATE_UNKNOWN, _("Invalid option - SSL is not available"));
#endif
			break;
		case 'A':
			flags |= FLAG_MATCH_ALL;
			break;
		}
	}

	if (server_address == NULL)
		usage4 (_("You must provide a server address"));
	else if (server_address[0] != '/' && is_host (server_address) == FALSE)
		die (STATE_CRITICAL, "%s %s - %s: %s\n", SERVICE, state_text(STATE_CRITICAL), _("Invalid hostname, address or socket"), server_address);

	return TRUE;
}
int main(int argc, char *argv[])
{
    Ecore_Evas *ee;
    Evas_Object *bridge, *img;
    const char *opt, *input, *output, *params;
    int r = 0, w = -1, h = -1, err;
    double scale = -1.0;

    if (argc < 4) {
        fprintf(stderr,
                "Usage:\n"
                "\t%s <percentage%%|WxH|w=W|h=H> <input> <output>"
                " [save-params]\n"
                "where save-params is evas supported parameters, like:\n"
                "\tquality=85\n"
                "\tcompress=9\n",
                argv[0]);
        return 1;
    }

    opt = argv[1];
    input = argv[2];
    output = argv[3];
    params = argv[4];

    if (strncasecmp(opt, "w=", 2) == 0) {
        char *end = NULL;
        w = strtol(opt + 2, &end, 10);
        if (!end || *end != '\0') {
            fprintf(stderr, "ERROR: invalid decimal integer '%s'\n",
                    opt + 2);
            return 1;
        } else if (w < 1) {
            fprintf(stderr, "ERROR: invalid width %d, must be >= 1\n", w);
            return 1;
        }
    } else if (strncasecmp(opt, "h=", 2) == 0) {
        char *end = NULL;
        h = strtol(opt + 2, &end, 10);
        if (!end || *end != '\0') {
            fprintf(stderr, "ERROR: invalid decimal integer '%s'\n",
                    opt + 2);
            return 1;
        } else if (h < 1) {
            fprintf(stderr, "ERROR: invalid height %d, must be >= 1\n", h);
            return 1;
        }
    } else if (strchr(opt, '%')) {
        char *end = NULL;
        scale = strtod(opt, &end);
        if (!end || *end != '%') {
            fprintf(stderr, "ERROR: invalid percentual '%s'\n", opt);
            return 1;
        } else if (scale <= 0.0) {
            fprintf(stderr, "ERROR: invalid percentual %g, must be > 0.0\n",
                    scale);
            return 1;
        }
        scale /= 100.0;
    } else if (strchr(opt, 'x')) {
        if (sscanf(opt, "%dx%d", &w, &h) != 2) {
            fprintf(stderr, "ERROR: invalid size format '%s'\n", opt);
            return 1;
        } else if (w < 1) {
            fprintf(stderr, "ERROR: invalid width %d, must be >= 1\n", w);
            return 1;
        } else {
            fprintf(stderr, "ERROR: invalid height %d, must be >= 1\n", h);
            return 1;
        }
    } else {
        fprintf(stderr,
                "ERROR: first parameter must be in format:\n"
                "\tpercentage%%    - example: 10%%\n"
                "\tWxH            - example: 1024x768\n"
                "\tw=W            - example: w=1024\n"
                "\th=H            - example: h=768\n"
                "But '%s' was used!\n",
                opt);
        return 1;
    }

    ecore_evas_init();
    evas_init();

    ee = ecore_evas_buffer_new(1, 1);
    bridge = ecore_evas_object_image_new(ee);
    img = evas_object_image_add(ecore_evas_object_evas_get(bridge));
    evas_object_image_smooth_scale_set(img, EINA_TRUE);

    if (w > 0 && h > 0)
        evas_object_image_load_size_set(img, w, h);

    evas_object_image_file_set(img, input, NULL);
    err = evas_object_image_load_error_get(img);
    if (err != EVAS_LOAD_ERROR_NONE) {
        const char *msg = evas_load_error_str(err);
        fprintf(stderr, "ERROR: could not load '%s': %s\n", input, msg);
        r = 1;
        goto end;
    }

    if (w < 1 || h < 1) {
        int iw, ih;
        evas_object_image_size_get(img, &iw, &ih);

        if (iw < 0 || ih < 0) {
            fprintf(stderr, "ERROR: invalid source image size %dx%d (%s)\n",
                    iw, ih, input);
            goto end;
        }

        if (scale > 0) {
            w = ceil(iw * scale);
            h = ceil(ih * scale);
        } else if (w < 1)
            w = ceil(iw * (double)h / (double)ih);
        else if (h < 1)
            h = ceil(ih * (double)w / (double)iw);

        if (iw != w && ih != h)
            evas_object_image_load_size_set(img, w, h);
    }

    printf("output: %s, size: %dx%d, alpha: %s, params: %s\n",
           output, w, h,
           evas_object_image_alpha_get(img) ? "yes" : "no",
           params ? params : "<none>");

    evas_object_image_fill_set(img, 0, 0, w, h);
    evas_object_resize(img, w, h);
    evas_object_show(img);

    evas_object_image_alpha_set(bridge, evas_object_image_alpha_get(img));
    evas_object_image_size_set(bridge, w, h);
    ecore_evas_manual_render(ecore_evas_object_ecore_evas_get(bridge));

    evas_object_image_save(bridge, output, NULL, params);

  end:
    evas_object_del(img);
    evas_object_del(bridge);
    ecore_evas_free(ee);

    evas_shutdown();
    ecore_evas_shutdown();

    return r;
}
示例#28
0
void readData(double *adLookUp, char* szDataFile, t_Flows* ptFlows, t_Params *ptParams)
{
  char szLine[MAX_LINE_LENGTH];
  char *szTok;
  int nN = 0, nM = 0;
  double *adData = NULL;
  double *adF    = NULL;
  int    *anF    = NULL;
  int    *anLengths = NULL;
  char *pcError = NULL;
  int i = 0, j = 0, nE = 0;
  FILE *ifp = NULL;

  ifp = fopen(szDataFile, "r");

  if(ifp){
    /*read header line*/
    fgets(szLine, MAX_LINE_LENGTH, ifp);
    /*get read number*/
    szTok = strtok(szLine, DELIM);
    nN = strtol(szTok,&pcError, 10);
    if(*pcError != '\0')
      goto formatError;

    /*get flow number*/
    szTok = strtok(NULL,DELIM);
    nM = strtol(szTok,&pcError, 10);
    if(*pcError != '\0')
      goto formatError;
    
    adData = (double *) malloc(nN*nM*sizeof(double));
    if(!adData)
      goto memoryError;

    adF = (double *) malloc(nN*nM*sizeof(double));
    if(!adF)
      goto memoryError;

    anF = (int *) malloc(nN*nM*sizeof(int));
    if(!anF)
      goto memoryError;

    anLengths = (int *) malloc(nN*sizeof(int));
    if(!anLengths)
      goto memoryError;

    for(i = 0; i < nN; i++){
      fgets(szLine, MAX_LINE_LENGTH, ifp);
      
      szTok = strtok(szLine, DELIM);

      if(ptParams->bNoIndex == FALSE){ 
	szTok = strtok(NULL, DELIM);
      }

      anLengths[i] = strtol(szTok, &pcError,10);
      if(*pcError != '\0')
	goto formatError;
    
      nE = anLengths[i] % 4;
      anLengths[i] -= nE;
          printf("%d %d %d %d\n",i, anLengths[i], nE, nM);
      for(j = 0; j < anLengths[i]; j++){
	double dF = 0.0;

	szTok = strtok(NULL, DELIM);
	dF = strtod(szTok, &pcError);
	//	printf("%d %s %f\n",j, szTok,dF);
	if(dF >= 9.99){
	  //fprintf(stderr,"%d %d %f too large max flow 9.99\n",i,j,dF);
	  dF = 9.99;
	  fflush(stderr);
	}

	adData[i*nM + j] = dF;
	anF[i*nM + j] =  (int) floor((dF + DELTA)/PRECISION);
	if(anF[i*nM + j] < 0){
	  anF[i*nM + j] = 0;
	}
	if(anF[i*nM + j] > BINS - 1){
	  anF[i*nM + j] = BINS - 1;
	}

	adF[i*nM + j] = distM1(adLookUp, dF);
	
	if(*pcError != '\0')
	  goto formatError;
      }

      for(; j < nM; j++){
	double dF = 0.0;
	adData[i*nM + j] = dF;
	anF[i*nM + j] =  (int) floor((dF + DELTA)/PRECISION);
	adF[i*nM + j] = distM1(adLookUp, dF);
	
      }
    }

    fclose(ifp);
  }
  else{
    printf("Failed to open file %s in readData\n",szDataFile);
    fflush(stderr);
    exit(EXIT_FAILURE);
  }

  ptFlows->anLengths = anLengths;
  ptFlows->adData    = adData;
  ptFlows->adF       = adF;
  ptFlows->anF       = anF;
  ptFlows->nN = nN; ptFlows->nM = nM;
  return;
 memoryError:
  fprintf(stderr, "Failed allocating memory in readData\n");
  fflush(stderr);
  exit(EXIT_FAILURE);

 formatError:
  fprintf(stderr, "Incorrect input format error\n");
  fflush(stderr);
  exit(EXIT_FAILURE);
}
示例#29
0
int VDScriptInterpreter::Token() {
	static char hexdig[]="0123456789ABCDEF";
	char *s,c;

	if (tokhold) {
		int t = tokhold;
		tokhold = 0;
		return t;
	}

	do {
		c=*tokstr++;
	} while(c && isspace((unsigned char)c));

	if (!c) {
		--tokstr;

		return 0;
	}

	// C++ style comment?

	if (c=='/')
		if (tokstr[0]=='/') {
			while(*tokstr) ++tokstr;

			return 0;		// C++ comment
		} else
			return '/';

	// string?

	if (c=='"') {
		const char *s = tokstr;
		char *t;
		long len_adjust=0;

		while((c=*tokstr++) && c!='"') {
			if (c=='\\') {
				c = *tokstr++;
				if (!c) SCRIPT_ERROR(PARSE_ERROR);
				else {
					if (c=='x') {
						if (!isxdigit((unsigned char)tokstr[0]) || !isxdigit((unsigned char)tokstr[1]))
							SCRIPT_ERROR(PARSE_ERROR);
						tokstr+=2;
						len_adjust += 2;
					}
					++len_adjust;
				}
			}
		}

		tokslit = strheap.Allocate(tokstr - s - 1 - len_adjust);
		t = *tokslit;
		while(s<tokstr-1) {
			int val;

			c = *s++;

			if (c=='\\')
				switch(c=*s++) {
				case 'a': *t++='\a'; break;
				case 'b': *t++='\b'; break;
				case 'f': *t++='\f'; break;
				case 'n': *t++='\n'; break;
				case 'r': *t++='\r'; break;
				case 't': *t++='\t'; break;
				case 'v': *t++='\v'; break;
				case 'x':
					val = strchr(hexdig,toupper(s[0]))-hexdig;
					val = (val<<4) | (strchr(hexdig,toupper(s[1]))-hexdig);
					*t++ = val;
					s += 2;
					break;
				default:
					*t++ = c;
				}
			else
				*t++ = c;
		}
		*t=0;

		if (!c) --tokstr;

		return TOK_STRING;
	}

	// unescaped string?
	if ((c=='u' || c=='U') && *tokstr == '"') {
		const char *s = ++tokstr;

		while((c=*tokstr++) && c != '"')
			;

		if (!c) {
			--tokstr;
			SCRIPT_ERROR(PARSE_ERROR);
		}

		size_t len = tokstr - s - 1;

		const VDStringA strA(VDTextWToU8(VDTextAToW(s, len)));

		len = strA.size();

		tokslit = strheap.Allocate(len);
		memcpy(*tokslit, strA.data(), len);
		(*tokslit)[len] = 0;

		return TOK_STRING;
	}

	// look for variable/keyword

	if (isIdentFirstChar(c)) {
		s = szIdent;

		*s++ = c;
		while(isIdentNextChar(c = *tokstr++)) {
			if (s>=szIdent + MAX_IDENT_CHARS)
				SCRIPT_ERROR(IDENT_TOO_LONG);

			*s++ = c;
		}

		--tokstr;
		*s=0;

		if (!strcmp(szIdent, "declare"))
			return TOK_DECLARE;
		else if (!strcmp(szIdent, "true"))
			return TOK_TRUE;
		else if (!strcmp(szIdent, "false"))
			return TOK_FALSE;
		else if (!strcmp(szIdent, "int"))
			return TOK_INT;
		else if (!strcmp(szIdent, "long"))
			return TOK_LONG;
		else if (!strcmp(szIdent, "double"))
			return TOK_DOUBLE;

		return TOK_IDENT;
	}

	// test for number: decimal (123), octal (0123), or hexadecimal (0x123)

	if (isdigit((unsigned char)c)) {
		sint64 v = 0;

		if (c=='0' && tokstr[0] == 'x') {

			// hex (base 16)
			++tokstr;

			while(isxdigit((unsigned char)(c = *tokstr++))) {
				v = v*16 + (strchr(hexdig, toupper(c))-hexdig);
			}

		} else if (c=='0' && isdigit((unsigned char)tokstr[0])) {
			// octal (base 8)
			while((c=*tokstr++)>='0' && c<='7')
				v = v*8 + (c-'0');
		} else {
			// check for float
			const char *s = tokstr;
			while(*s) {
				if (*s == '.' || *s == 'e' || *s == 'E') {
					// It's a float -- parse and return.

					--tokstr;
					tokdval = strtod(tokstr, (char **)&tokstr);
					return TOK_DBLVAL;
				}

				if (!isdigit((unsigned char)*s))
					break;
				++s;
			}

			// decimal
			v = (c-'0');
			while(isdigit((unsigned char)(c=*tokstr++)))
				v = v*10 + (c-'0');
		}
		--tokstr;

		if (v > 0x7FFFFFFF) {
			toklval = v;
			return TOK_LONGVAL;
		} else {
			tokival = (int)v;
			return TOK_INTVAL;
		}
	}

	// test for symbols:
	//
	//	charset:	+-*/<>=!&|^[]~;%(),
	//	solitary:	+-*/<>=!&|^[]~;%(),
	//	extra:		!= <= >= == && ||
	//
	//	the '/' is handled above for comment handling

	if (c=='!')
		if (tokstr[0] == '=') { ++tokstr; return TOK_NOTEQ;  } else return '!';

	if (c=='<')
		if (tokstr[0] == '=') { ++tokstr; return TOK_LESSEQ; } else return '<';

	if (c=='>')
		if (tokstr[0] == '=') { ++tokstr; return TOK_GRTREQ; } else return '>';

	if (c=='=')
		if (tokstr[0] == '=') { ++tokstr; return TOK_EQUALS; } else return '=';

	if (c=='&')
		if (tokstr[0] == '&') { ++tokstr; return TOK_AND;    } else return '&';

	if (c=='|')
		if (tokstr[0] == '|') { ++tokstr; return TOK_OR;     } else return '|';

	if (strchr("+-*^[]~;%(),.",c))
		return c;

	SCRIPT_ERROR(PARSE_ERROR);
}
示例#30
0
文件: IoSeq.c 项目: Akiyah/io
double IoSeq_asDouble(IoSeq *self)
{
	return strtod((char *)UArray_bytes(DATA(self)), NULL);
}